1 // Copyright (C) 2007-2024 CEA, EDF, OPEN CASCADE
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_QuadToTriaAdaptor.cxx
22 // Created : Wen May 07 16:37:07 2008
23 // Author : Sergey KUUL (skl)
25 #include "StdMeshers_QuadToTriaAdaptor.hxx"
27 #include "SMDS_IteratorOnIterators.hxx"
28 #include "SMDS_SetIterator.hxx"
29 #include "SMDS_VolumeTool.hxx"
30 #include "SMESHDS_GroupBase.hxx"
31 #include "SMESHDS_Mesh.hxx"
32 #include "SMESH_Algo.hxx"
33 #include "SMESH_Group.hxx"
34 #include "SMESH_Mesh.hxx"
35 #include "SMESH_MeshAlgos.hxx"
36 #include "SMESH_MesherHelper.hxx"
37 #include "SMESH_subMesh.hxx"
39 #include <IntAna_IntConicQuad.hxx>
40 #include <IntAna_Quadric.hxx>
41 #include <TColgp_Array1OfPnt.hxx>
42 #include <TColgp_Array1OfVec.hxx>
43 #include <TColgp_SequenceOfPnt.hxx>
44 #include <TopExp_Explorer.hxx>
46 #include <TopoDS_Iterator.hxx>
50 #include "utilities.h"
58 enum EQuadNature { NOT_QUAD, QUAD, DEGEN_QUAD, PYRAM_APEX = 4, TRIA_APEX = 0 };
60 // std-like iterator used to get coordinates of nodes of mesh element
61 typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
63 //================================================================================
65 * \brief Return ID of pyramid base face, for debug
67 //================================================================================
69 int getFaceID(const SMDS_MeshElement* pyram)
72 if ( const SMDS_MeshElement* f = SMDS_Mesh::FindFace( pyram->GetNode(0),
82 //================================================================================
84 * \brief Return true if two nodes of triangles are equal
86 //================================================================================
88 bool EqualTriangles(const SMDS_MeshElement* F1,const SMDS_MeshElement* F2)
91 ( F1->GetNode(1)==F2->GetNode(2) && F1->GetNode(2)==F2->GetNode(1) ) ||
92 ( F1->GetNode(1)==F2->GetNode(1) && F1->GetNode(2)==F2->GetNode(2) );
94 //================================================================================
96 * \brief Return true if two adjacent pyramids are too close one to another
97 * so that a tetrahedron to built between them would have too poor quality
99 //================================================================================
101 bool TooCloseAdjacent( const SMDS_MeshElement* PrmI,
102 const SMDS_MeshElement* PrmJ,
105 const SMDS_MeshNode* nApexI = PrmI->GetNode(4);
106 const SMDS_MeshNode* nApexJ = PrmJ->GetNode(4);
107 if ( nApexI == nApexJ ||
108 nApexI->getshapeId() != nApexJ->getshapeId() )
111 // Find two common base nodes and their indices within PrmI and PrmJ
112 const SMDS_MeshNode* baseNodes[2] = { 0,0 };
113 int baseNodesIndI[2], baseNodesIndJ[2];
114 for ( int i = 0; i < 4 ; ++i )
116 int j = PrmJ->GetNodeIndex( PrmI->GetNode(i));
119 int ind = baseNodes[0] ? 1:0;
120 if ( baseNodes[ ind ])
121 return false; // pyramids with a common base face
122 baseNodes [ ind ] = PrmI->GetNode(i);
123 baseNodesIndI[ ind ] = i;
124 baseNodesIndJ[ ind ] = j;
127 if ( !baseNodes[1] ) return false; // not adjacent
129 // Get normals of triangles sharing baseNodes
130 gp_XYZ apexI = SMESH_TNodeXYZ( nApexI );
131 gp_XYZ apexJ = SMESH_TNodeXYZ( nApexJ );
132 gp_XYZ base1 = SMESH_TNodeXYZ( baseNodes[0]);
133 gp_XYZ base2 = SMESH_TNodeXYZ( baseNodes[1]);
134 gp_Vec baseVec( base1, base2 );
135 gp_Vec baI( base1, apexI );
136 gp_Vec baJ( base1, apexJ );
137 gp_Vec nI = baseVec.Crossed( baI );
138 gp_Vec nJ = baseVec.Crossed( baJ );
140 // Check angle between normals
141 double angle = nI.Angle( nJ );
142 bool tooClose = ( angle < 15. * M_PI / 180. );
144 // Check if pyramids collide
145 if ( !tooClose && ( baI * baJ > 0 ) && ( nI * nJ > 0 ))
147 // find out if nI points outside of PrmI or inside
148 int dInd = baseNodesIndI[1] - baseNodesIndI[0];
149 bool isOutI = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
151 // find out sign of projection of baI to nJ
152 double proj = baI * nJ;
154 tooClose = ( isOutI ? proj > 0 : proj < 0 );
157 // Check if PrmI and PrmJ are in same domain
158 if ( tooClose && !hasShape )
160 // check order of baseNodes within pyramids, it must be opposite
162 dInd = baseNodesIndI[1] - baseNodesIndI[0];
163 bool isOutI = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
164 dInd = baseNodesIndJ[1] - baseNodesIndJ[0];
165 bool isOutJ = ( abs(dInd)==1 ) ? dInd < 0 : dInd > 0;
166 if ( isOutJ == isOutI )
167 return false; // other domain
169 // direct both normals outside pyramid
170 ( isOutI ? nJ : nI ).Reverse();
172 // check absence of a face separating domains between pyramids
173 TIDSortedElemSet emptySet, avoidSet;
175 while ( const SMDS_MeshElement* f =
176 SMESH_MeshAlgos::FindFaceInSet( baseNodes[0], baseNodes[1],
177 emptySet, avoidSet, &i1, &i2 ))
179 avoidSet.insert( f );
181 // face node other than baseNodes
182 int otherNodeInd = 0;
183 while ( otherNodeInd == i1 || otherNodeInd == i2 ) otherNodeInd++;
184 const SMDS_MeshNode* otherFaceNode = f->GetNode( otherNodeInd );
186 if ( otherFaceNode == nApexI || otherFaceNode == nApexJ )
187 continue; // f is a temporary triangle
189 // check if f is a base face of either of pyramids
190 if ( f->NbCornerNodes() == 4 &&
191 ( PrmI->GetNodeIndex( otherFaceNode ) >= 0 ||
192 PrmJ->GetNodeIndex( otherFaceNode ) >= 0 ))
193 continue; // f is a base quadrangle
195 // check projections of face direction (baOFN) to triangle normals (nI and nJ)
196 gp_Vec baOFN( base2, SMESH_TNodeXYZ( otherFaceNode ));
197 if ( nI * baOFN > 0 && nJ * baOFN > 0 &&
198 baI* baOFN > 0 && baJ* baOFN > 0 ) // issue 0023212
200 tooClose = false; // f is between pyramids
209 //================================================================================
211 * \brief Move medium nodes of merged quadratic pyramids
213 //================================================================================
215 void UpdateQuadraticPyramids(const set<const SMDS_MeshNode*>& commonApex,
216 SMESHDS_Mesh* meshDS)
218 typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TStdElemIterator;
219 TStdElemIterator itEnd;
221 // shift of node index to get medium nodes between the 4 base nodes and the apex
222 const int base2MediumShift = 9;
224 set<const SMDS_MeshNode*>::const_iterator nIt = commonApex.begin();
225 for ( ; nIt != commonApex.end(); ++nIt )
227 SMESH_TNodeXYZ apex( *nIt );
229 vector< const SMDS_MeshElement* > pyrams // pyramids sharing the apex node
230 ( TStdElemIterator( apex._node->GetInverseElementIterator( SMDSAbs_Volume )), itEnd );
232 // Select medium nodes to keep and medium nodes to remove
234 typedef map < const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
235 TN2NMap base2medium; // to keep
236 vector< const SMDS_MeshNode* > nodesToRemove;
238 for ( unsigned i = 0; i < pyrams.size(); ++i )
239 for ( int baseIndex = 0; baseIndex < PYRAM_APEX; ++baseIndex )
241 SMESH_TNodeXYZ base = pyrams[i]->GetNode( baseIndex );
242 const SMDS_MeshNode* medium = pyrams[i]->GetNode( baseIndex + base2MediumShift );
243 TN2NMap::iterator b2m = base2medium.insert( make_pair( base._node, medium )).first;
244 if ( b2m->second != medium )
246 nodesToRemove.push_back( medium );
250 // move the kept medium node
251 gp_XYZ newXYZ = 0.5 * ( apex + base );
252 meshDS->MoveNode( medium, newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
256 // Within pyramids, replace nodes to remove by nodes to keep
258 for ( unsigned i = 0; i < pyrams.size(); ++i )
260 vector< const SMDS_MeshNode* > nodes( pyrams[i]->begin_nodes(),
261 pyrams[i]->end_nodes() );
262 for ( int baseIndex = 0; baseIndex < PYRAM_APEX; ++baseIndex )
264 const SMDS_MeshNode* base = pyrams[i]->GetNode( baseIndex );
265 nodes[ baseIndex + base2MediumShift ] = base2medium[ base ];
267 meshDS->ChangeElementNodes( pyrams[i], &nodes[0], nodes.size());
270 // Remove the replaced nodes
272 if ( !nodesToRemove.empty() )
274 SMESHDS_SubMesh * sm = meshDS->MeshElements( nodesToRemove[0]->getshapeId() );
275 for ( unsigned i = 0; i < nodesToRemove.size(); ++i )
276 meshDS->RemoveFreeNode( nodesToRemove[i], sm, /*fromGroups=*/false);
282 //================================================================================
284 * \brief Store an error about overlapping faces
286 //================================================================================
288 bool overlapError( SMESH_Mesh& mesh,
289 const SMDS_MeshElement* face1,
290 const SMDS_MeshElement* face2,
291 const TopoDS_Shape& shape = TopoDS_Shape())
293 if ( !face1 || !face2 ) return false;
296 msg << "face " << face1->GetID() << " overlaps face " << face2->GetID();
298 SMESH_subMesh * sm = 0;
299 if ( shape.IsNull() )
301 sm = mesh.GetSubMesh( mesh.GetShapeToMesh() );
303 else if ( shape.ShapeType() >= TopAbs_SOLID )
305 sm = mesh.GetSubMesh( shape );
309 TopoDS_Iterator it ( shape );
311 sm = mesh.GetSubMesh( it.Value() );
315 SMESH_ComputeErrorPtr& err = sm->GetComputeError();
316 if ( !err || err->IsOK() )
318 SMESH_BadInputElements* badElems =
319 new SMESH_BadInputElements( mesh.GetMeshDS(),COMPERR_BAD_INPUT_MESH, msg, sm->GetAlgo() );
320 badElems->add( face1 );
321 badElems->add( face2 );
322 err.reset( badElems );
326 return false; // == "algo fails"
329 //================================================================================
331 * \brief Check if a face is in a SOLID
333 //================================================================================
335 bool isInSolid( vector<const SMDS_MeshNode*> & faceNodes,
340 return true; // NOT_QUAD
341 for ( int i = 0; i < nbNodes; ++i )
343 int shapeID = faceNodes[i]->GetShapeID();
344 if ( shapeID == solidID )
347 faceNodes.resize( nbNodes );
348 std::vector<const SMDS_MeshElement*> vols;
349 SMDS_Mesh::GetElementsByNodes( faceNodes, vols, SMDSAbs_Volume );
350 bool inSolid = false;
351 for ( size_t i = 0; i < vols.size() && !inSolid; ++i )
353 int shapeID = vols[i]->GetShapeID();
354 inSolid = ( shapeID == solidID );
356 faceNodes.push_back( faceNodes[0] );
361 //================================================================================
363 * \brief Merge the two pyramids (i.e. fuse their apex) and others already merged with them
365 //================================================================================
367 void StdMeshers_QuadToTriaAdaptor::MergePiramids( const SMDS_MeshElement* PrmI,
368 const SMDS_MeshElement* PrmJ,
369 set<const SMDS_MeshNode*> & nodesToMove)
371 const SMDS_MeshNode* Nrem = PrmJ->GetNode(4); // node to remove
372 //int nbJ = Nrem->NbInverseElements( SMDSAbs_Volume );
373 SMESH_TNodeXYZ Pj( Nrem );
375 // an apex node to make common to all merged pyramids
376 SMDS_MeshNode* CommonNode = const_cast<SMDS_MeshNode*>(PrmI->GetNode(4));
377 if ( CommonNode == Nrem ) return; // already merged
378 //int nbI = CommonNode->NbInverseElements( SMDSAbs_Volume );
379 SMESH_TNodeXYZ Pi( CommonNode );
380 // gp_XYZ Pnew = /*( nbI*Pi + nbJ*Pj ) / (nbI+nbJ);*/ 0.5 * ( Pi + Pj );
382 SMDS_VolumeTool volumeTool;
383 double pyrad1Vol = 0.0;
384 double pyrad2Vol = 0.0;
385 // To get the pyramids vols
386 if ( volumeTool.Set( PrmI ) )
387 pyrad1Vol = volumeTool.GetSize();
388 if ( volumeTool.Set( PrmJ ) )
389 pyrad2Vol = volumeTool.GetSize();
391 typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > elemIterator;
392 elemIterator iteratorsEnd;
394 vector< const SMDS_MeshElement* > associatedElementsI ( elemIterator( CommonNode->GetInverseElementIterator(SMDSAbs_Volume)), iteratorsEnd);
395 if ( associatedElementsI.size() > 1 )
396 for ( size_t i = 0; i < associatedElementsI.size(); ++i )
398 const SMDS_MeshElement* element = associatedElementsI[i];
399 if ( element != PrmI && volumeTool.Set( element ) )
400 pyrad1Vol += volumeTool.GetSize();
402 vector< const SMDS_MeshElement* > associatedElementsJ ( elemIterator( Nrem->GetInverseElementIterator(SMDSAbs_Volume)), iteratorsEnd);
403 if ( associatedElementsJ.size() > 1 )
404 for ( size_t i = 0; i < associatedElementsJ.size(); ++i )
406 const SMDS_MeshElement* element = associatedElementsJ[i];
407 if ( element != PrmJ && volumeTool.Set( element ) )
408 pyrad2Vol += volumeTool.GetSize(); //associatedVolPyramid->GetSize();
411 double totalVol = pyrad1Vol + pyrad2Vol;
412 // The new Apex can't be computed based in an arithmetic median,
413 // Geometric mediam is considered to be better
414 // gp_XYZ Pnew = /*( nbI*Pi + nbJ*Pj ) / (nbI+nbJ);*/ 0.5 * ( Pi + Pj );
415 ASSERT( totalVol > 0. );
416 gp_XYZ Pnew = Pi * pyrad1Vol/totalVol + Pj * pyrad2Vol/totalVol;
418 CommonNode->setXYZ( Pnew.X(), Pnew.Y(), Pnew.Z() );
420 nodesToMove.insert( CommonNode );
421 nodesToMove.erase ( Nrem );
423 //cout << "MergePiramids F" << getFaceID( PrmI ) << " - F" << getFaceID( PrmJ ) << endl;
425 typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TStdElemIterator;
426 TStdElemIterator itEnd;
428 typedef std::map< const SMDS_MeshNode*, const SMDS_MeshNode* > TNNMap;
429 TNNMap mediumReplaceMap;
431 // find and remove coincided faces of merged pyramids
432 vector< const SMDS_MeshElement* > inverseElems
433 // copy inverse elements to avoid iteration on changing container
434 ( TStdElemIterator( CommonNode->GetInverseElementIterator(SMDSAbs_Face)), itEnd);
435 for ( size_t i = 0; i < inverseElems.size(); ++i )
437 const SMDS_MeshElement* FI = inverseElems[i];
438 const SMDS_MeshElement* FJEqual = 0;
439 SMDS_ElemIteratorPtr triItJ = Nrem->GetInverseElementIterator(SMDSAbs_Face);
440 while ( !FJEqual && triItJ->more() )
442 const SMDS_MeshElement* FJ = triItJ->next();
443 if ( EqualTriangles( FJ, FI ))
448 if ( FJEqual->NbNodes() == 6 ) // find medium nodes to replace
450 mediumReplaceMap.insert( std::make_pair( FJEqual->GetNode(3), FI->GetNode(5) ));
451 mediumReplaceMap.insert( std::make_pair( FJEqual->GetNode(5), FI->GetNode(3) ));
453 removeTmpElement( FI );
454 removeTmpElement( FJEqual );
455 myRemovedTrias.insert( FI );
456 myRemovedTrias.insert( FJEqual );
460 // set the common apex node to pyramids and triangles merged with J
461 vector< const SMDS_MeshNode* > nodes;
462 inverseElems.assign( TStdElemIterator( Nrem->GetInverseElementIterator()), itEnd );
463 for ( size_t i = 0; i < inverseElems.size(); ++i )
465 const SMDS_MeshElement* elem = inverseElems[i];
466 nodes.assign( elem->begin_nodes(), elem->end_nodes() );
467 nodes[ elem->GetType() == SMDSAbs_Volume ? PYRAM_APEX : TRIA_APEX ] = CommonNode;
468 if ( !mediumReplaceMap.empty() )
469 for ( size_t iN = elem->NbCornerNodes(); iN < nodes.size(); ++iN )
471 TNNMap::iterator n2n = mediumReplaceMap.find( nodes[iN] );
472 if ( n2n != mediumReplaceMap.end() )
473 nodes[iN] = n2n->second;
475 GetMeshDS()->ChangeElementNodes( elem, &nodes[0], nodes.size());
477 ASSERT( Nrem->NbInverseElements() == 0 );
478 GetMeshDS()->RemoveFreeNode( Nrem,
479 GetMeshDS()->MeshElements( Nrem->getshapeId()),
480 /*fromGroups=*/false);
481 if ( !mediumReplaceMap.empty() )
482 for ( TNNMap::iterator n2n = mediumReplaceMap.begin(); n2n != mediumReplaceMap.end(); ++n2n )
484 const SMDS_MeshNode* remNode = n2n->first;
485 if ( !remNode->IsNull() && remNode->NbInverseElements() == 0 )
486 GetMeshDS()->RemoveFreeNode( remNode, 0, /*fromGroups=*/false);
491 //================================================================================
493 * \brief Merges adjacent pyramids
495 //================================================================================
497 void StdMeshers_QuadToTriaAdaptor::MergeAdjacent(const SMDS_MeshElement* PrmI,
498 set<const SMDS_MeshNode*>& nodesToMove,
499 const bool isRecursion)
501 TIDSortedElemSet adjacentPyrams;
502 bool mergedPyrams = false;
503 for ( int k = 0; k < 4; k++ ) // loop on 4 base nodes of PrmI
505 const SMDS_MeshNode* n = PrmI->GetNode(k);
506 SMDS_ElemIteratorPtr vIt = n->GetInverseElementIterator( SMDSAbs_Volume );
507 while ( vIt->more() )
509 const SMDS_MeshElement* PrmJ = vIt->next();
510 if ( PrmJ == PrmI || PrmJ->NbCornerNodes() != 5 || !adjacentPyrams.insert( PrmJ ).second )
512 if ( TooCloseAdjacent( PrmI, PrmJ, GetMesh()->HasShapeToMesh() ))
514 MergePiramids( PrmI, PrmJ, nodesToMove );
516 // container of inverse elements can change
517 // vIt = n->GetInverseElementIterator( SMDSAbs_Volume ); -- iterator re-implemented
521 if ( mergedPyrams && !isRecursion )
523 TIDSortedElemSet::iterator prm;
524 for (prm = adjacentPyrams.begin(); prm != adjacentPyrams.end(); ++prm)
525 MergeAdjacent( *prm, nodesToMove, true );
530 //================================================================================
532 * \brief Decrease height of a given or adjacent pyramids if height difference
534 * \param [in] pyram - a pyramid to treat
535 * \param [inout] h2 - pyramid's square height
536 * \return bool - true if the height changes
538 //================================================================================
540 bool StdMeshers_QuadToTriaAdaptor::DecreaseHeightDifference( const SMDS_MeshElement* thePyram,
543 const double allowedFactor2 = 2. * 2.;
546 myNodes[0] = thePyram->GetNode( 3 );
547 for ( int i = 0; i < 4; ++i )
549 myNodes[1] = thePyram->GetNode( i );
550 SMDS_Mesh::GetElementsByNodes( myNodes, myAdjPyrams, SMDSAbs_Volume );
551 myNodes[0] = myNodes[1];
553 for ( const SMDS_MeshElement* pyramAdj : myAdjPyrams )
555 if ( pyramAdj == thePyram )
557 if ( !myPyramHeight2.IsBound( pyramAdj ))
559 double h2Adj = Abs( myPyramHeight2( pyramAdj ));
560 double h2 = Abs( theH2 );
563 if ( h2 * allowedFactor2 < h2Adj )
565 // bind negative value to allow finding pyramids whose height must change
566 myPyramHeight2.Bind( pyramAdj, - h2 * allowedFactor2 );
572 if ( h2Adj * allowedFactor2 < h2 )
574 // bind negative value to allow finding pyramids whose height must change
575 myPyramHeight2.Bind( thePyram, - h2Adj * allowedFactor2 );
585 //================================================================================
589 //================================================================================
591 StdMeshers_QuadToTriaAdaptor::StdMeshers_QuadToTriaAdaptor():
596 //================================================================================
600 //================================================================================
602 StdMeshers_QuadToTriaAdaptor::~StdMeshers_QuadToTriaAdaptor()
604 // temporary faces are deleted by ~SMESH_ProxyMesh()
605 if ( myElemSearcher ) delete myElemSearcher;
609 //=======================================================================
610 //function : FindBestPoint
611 //purpose : Return a point P laying on the line (PC,V) so that triangle
612 // (P, P1, P2) to be equilateral as much as possible
613 // V - normal to (P1,P2,PC)
614 //=======================================================================
616 static gp_Pnt FindBestPoint(const gp_Pnt& P1, const gp_Pnt& P2,
617 const gp_Pnt& PC, const gp_Vec& V,
622 const double a2 = P1.SquareDistance(P2);
623 const double b2 = P1.SquareDistance(PC);
624 const double c2 = P2.SquareDistance(PC);
625 if ( a2 < ( b2 + Sqrt( 4 * b2 * c2 ) + c2 ) / 4 ) // ( a < (b+c)/2 )
628 // find shift along V in order a to became equal to (b+c)/2
629 const double Vsize = V.Magnitude();
630 if ( fabs( Vsize ) > std::numeric_limits<double>::min() )
632 shift = sqrt( a2 + (b2-c2)*(b2-c2)/16/a2 - (b2+c2)/2 );
633 Pbest.ChangeCoord() += shift * V.XYZ() / Vsize;
639 //=======================================================================
640 //function : HasIntersection3
641 //purpose : Find intersection point between a triangle (P1,P2,P3)
642 // and a segment [PC,P]
643 //=======================================================================
645 static bool HasIntersection3(const gp_Pnt& P, const gp_Pnt& PC, gp_Pnt& Pint,
646 const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3)
648 const double EPSILON = 1e-6;
649 double segLen = P.Distance( PC );
651 gp_XYZ orig = PC.XYZ();
652 gp_XYZ dir = ( P.XYZ() - PC.XYZ() ) / segLen;
653 gp_XYZ vert0 = P1.XYZ();
654 gp_XYZ vert1 = P2.XYZ();
655 gp_XYZ vert2 = P3.XYZ();
657 gp_XYZ edge1 = vert1 - vert0;
658 gp_XYZ edge2 = vert2 - vert0;
660 /* begin calculating determinant - also used to calculate U parameter */
661 gp_XYZ pvec = dir ^ edge2;
663 /* if determinant is near zero, ray lies in plane of triangle */
664 double det = edge1 * pvec;
666 const double ANGL_EPSILON = 1e-12;
667 if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
670 /* calculate distance from vert0 to ray origin */
671 gp_XYZ tvec = orig - vert0;
673 /* calculate U parameter and test bounds */
674 double u = ( tvec * pvec ) / det;
675 //if (u < 0.0 || u > 1.0)
676 if (u < -EPSILON || u > 1.0 + EPSILON)
679 /* prepare to test V parameter */
680 gp_XYZ qvec = tvec ^ edge1;
682 /* calculate V parameter and test bounds */
683 double v = (dir * qvec) / det;
684 //if ( v < 0.0 || u + v > 1.0 )
685 if ( v < -EPSILON || u + v > 1.0 + EPSILON)
688 /* calculate t, ray intersects triangle */
689 double t = (edge2 * qvec) / det;
691 Pint = orig + dir * t;
693 bool hasInt = ( t > 0. && t < segLen );
695 if ( hasInt && det < EPSILON ) // t is inaccurate, additionally check
697 gp_XYZ triNorm = edge1 ^ edge2;
698 gp_XYZ int0vec = Pint.XYZ() - vert0;
699 gp_XYZ in = triNorm ^ edge1; // dir inside triangle from edge1
700 double dot = int0vec * in;
701 if ( dot < 0 && dot / triNorm.Modulus() < -EPSILON )
703 in = edge2 ^ triNorm;
705 if ( dot < 0 && dot / triNorm.Modulus() < -EPSILON )
707 gp_XYZ int1vec = Pint.XYZ() - vert1;
708 in = triNorm ^ ( vert2 - vert1 );
710 if ( dot < 0 && dot / triNorm.Modulus() < -EPSILON )
716 //=======================================================================
717 //function : HasIntersection
718 //purpose : Auxiliary for CheckIntersection()
719 //=======================================================================
721 static bool HasIntersection(const gp_Pnt& P, const gp_Pnt& PC, gp_Pnt& Pint,
722 TColgp_SequenceOfPnt& aContour)
724 if ( aContour.Length() == 3 ) {
725 return HasIntersection3( P, PC, Pint, aContour(1), aContour(2), aContour(3) );
729 if( (aContour(1).SquareDistance(aContour(2)) > 1.e-12) &&
730 (aContour(1).SquareDistance(aContour(3)) > 1.e-12) &&
731 (aContour(2).SquareDistance(aContour(3)) > 1.e-12) ) {
732 check = HasIntersection3( P, PC, Pint, aContour(1), aContour(2), aContour(3) );
734 if(check) return true;
735 if( (aContour(1).SquareDistance(aContour(4)) > 1.e-12) &&
736 (aContour(1).SquareDistance(aContour(3)) > 1.e-12) &&
737 (aContour(4).SquareDistance(aContour(3)) > 1.e-12) ) {
738 check = HasIntersection3( P, PC, Pint, aContour(1), aContour(3), aContour(4) );
740 if(check) return true;
746 //================================================================================
748 * \brief Return allowed height of a pyramid
749 * \param Papex - optimal pyramid apex
750 * \param PC - gravity center of a quadrangle
751 * \param PN - four nodes of the quadrangle
752 * \param aMesh - mesh
753 * \param NotCheckedFace - the quadrangle face
754 * \param Shape - the shape being meshed
755 * \retval false if mesh invalidity detected
757 //================================================================================
759 bool StdMeshers_QuadToTriaAdaptor::LimitHeight (gp_Pnt& Papex,
761 const TColgp_Array1OfPnt& PN,
762 const vector<const SMDS_MeshNode*>& FNodes,
764 const SMDS_MeshElement* NotCheckedFace,
765 const bool UseApexRay,
766 const TopoDS_Shape& Shape)
768 if ( !myElemSearcher )
769 myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *aMesh.GetMeshDS() );
770 SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>(myElemSearcher);
772 // Find intersection of faces with (P,PC) segment elongated 3 times
774 double height = Papex.Distance( PC );
775 gp_Ax1 line( PC, gp_Vec( PC, Papex ));
777 vector< const SMDS_MeshElement* > suspectFaces;
778 TColgp_SequenceOfPnt aContour;
782 double idealHeight = height;
783 const SMDS_MeshElement* intFace = 0;
785 // find intersection closest to PC
786 Ptest = PC.XYZ() + line.Direction().XYZ() * height * 3;
788 searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectFaces );
789 for ( size_t iF = 0; iF < suspectFaces.size(); ++iF )
791 const SMDS_MeshElement* face = suspectFaces[iF];
792 if ( face == NotCheckedFace ) continue;
795 for ( int i = 0, nb = face->NbCornerNodes(); i < nb; ++i )
796 aContour.Append( SMESH_TNodeXYZ( face->GetNode(i) ));
798 if ( HasIntersection( Ptest, PC, Pint, aContour ))
800 double dInt = PC.Distance( Pint ) / 3.;
808 if ( height < 1e-2 * idealHeight && intFace )
809 return overlapError( aMesh, NotCheckedFace, intFace, Shape );
812 // Find faces intersecting triangular facets of the pyramid (issue 23212)
814 gp_XYZ center = PC.XYZ() + line.Direction().XYZ() * height * 0.5;
815 double diameter = Max( PN(1).Distance(PN(3)), PN(2).Distance(PN(4)));
816 suspectFaces.clear();
817 searcher->GetElementsInSphere( center, diameter * 0.6, SMDSAbs_Face, suspectFaces);
819 const double upShift = 1.5;
820 Ptest = PC.XYZ() + line.Direction().XYZ() * height * upShift; // tmp apex
822 for ( size_t iF = 0; iF < suspectFaces.size(); ++iF )
824 const SMDS_MeshElement* face = suspectFaces[iF];
825 if ( face == NotCheckedFace ) continue;
826 if ( face->GetNodeIndex( FNodes[0] ) >= 0 ||
827 face->GetNodeIndex( FNodes[1] ) >= 0 ||
828 face->GetNodeIndex( FNodes[2] ) >= 0 ||
829 face->GetNodeIndex( FNodes[3] ) >= 0 )
830 continue; // neighbor face of the quadrangle
832 // limit height using points of intersection of face links with pyramid facets
833 int nbN = face->NbCornerNodes();
834 gp_Pnt P1 = SMESH_TNodeXYZ( face->GetNode( nbN-1 )); // 1st link end
835 for ( int i = 0; i < nbN; ++i )
837 gp_Pnt P2 = SMESH_TNodeXYZ( face->GetNode(i) ); // 2nd link end
839 for ( int iN = 1; iN <= 4; ++iN ) // loop on pyramid facets
841 if ( HasIntersection3( P1, P2, Pint, PN(iN), PN(iN+1), Ptest ))
843 height = Min( height, gp_Vec( PC, Pint ) * line.Direction() );
844 //Ptest = PC.XYZ() + line.Direction().XYZ() * height * upShift; // new tmp apex
851 Papex = PC.XYZ() + line.Direction().XYZ() * height;
856 //================================================================================
858 * \brief Retrieve data of the given face
859 * \param PN - coordinates of face nodes
860 * \param VN - cross products of vectors (PC-PN(i)) ^ (PC-PN(i+1))
861 * \param FNodes - face nodes
862 * \param PC - gravity center of nodes
863 * \param VNorm - face normal (sum of VN)
864 * \param volumes - two volumes sharing the given face, the first is in VNorm direction
865 * \retval int - 0 if given face is not quad,
866 * 1 if given face is quad,
867 * 2 if given face is degenerate quad (two nodes are coincided)
869 //================================================================================
871 int StdMeshers_QuadToTriaAdaptor::Preparation(const SMDS_MeshElement* face,
872 TColgp_Array1OfPnt& PN,
873 TColgp_Array1OfVec& VN,
874 vector<const SMDS_MeshNode*>& FNodes,
877 const SMDS_MeshElement** volumes)
879 if( face->NbCornerNodes() != 4 )
885 gp_XYZ xyzC(0., 0., 0.);
886 for ( i = 0; i < 4; ++i )
888 gp_XYZ p = SMESH_TNodeXYZ( FNodes[i] = face->GetNode(i) );
889 PN.SetValue( i+1, p );
897 for ( i = 1; i < 4; i++ )
901 if( PN(i).Distance(PN(j)) < 1.e-6 )
913 list< const SMDS_MeshNode* >::iterator itdg = myDegNodes.begin();
914 const SMDS_MeshNode* DegNode = 0;
915 for(; itdg!=myDegNodes.end(); itdg++) {
916 const SMDS_MeshNode* N = (*itdg);
917 gp_Pnt Ptmp(N->X(),N->Y(),N->Z());
918 if(Pdeg.Distance(Ptmp)<1.e-6) {
924 DegNode = FNodes[i-1];
925 myDegNodes.push_back(DegNode);
928 FNodes[i-1] = DegNode;
931 PN.SetValue(i,PN.Value(i+1));
932 FNodes[i-1] = FNodes[i];
937 PN.SetValue(nbp+1,PN(1));
938 FNodes[nbp] = FNodes[0];
940 // find normal direction
941 gp_Vec V1(PC,PN(nbp));
943 VNorm = V1.Crossed(V2);
944 VN.SetValue(nbp,VNorm);
945 for(i=1; i<nbp; i++) {
946 V1 = gp_Vec(PC,PN(i));
947 V2 = gp_Vec(PC,PN(i+1));
948 gp_Vec Vtmp = V1.Crossed(V2);
953 // find volumes sharing the face
956 volumes[0] = volumes[1] = 0;
957 SMDS_ElemIteratorPtr vIt = FNodes[0]->GetInverseElementIterator( SMDSAbs_Volume );
958 while ( vIt->more() )
960 const SMDS_MeshElement* vol = vIt->next();
961 bool volSharesAllNodes = true;
962 for ( int i = 1; i < face->NbNodes() && volSharesAllNodes; ++i )
963 volSharesAllNodes = ( vol->GetNodeIndex( FNodes[i] ) >= 0 );
964 if ( volSharesAllNodes )
965 volumes[ volumes[0] ? 1 : 0 ] = vol;
966 // we could additionally check that vol has all FNodes in its one face using SMDS_VolumeTool
968 // define volume position relating to the face normal
972 SMDS_ElemIteratorPtr nodeIt = volumes[0]->nodesIterator();
974 volGC = accumulate( TXyzIterator(nodeIt), TXyzIterator(), volGC ) / volumes[0]->NbNodes();
976 if ( VNorm * gp_Vec( PC, volGC ) < 0 )
977 swap( volumes[0], volumes[1] );
981 return hasdeg ? DEGEN_QUAD : QUAD;
985 //=======================================================================
988 //=======================================================================
990 bool StdMeshers_QuadToTriaAdaptor::Compute(SMESH_Mesh& aMesh,
991 const TopoDS_Shape& aShape,
992 SMESH_ProxyMesh* aProxyMesh)
994 SMESH_ProxyMesh::setMesh( aMesh );
996 if ( aShape.ShapeType() != TopAbs_SOLID )
1001 vector<const SMDS_MeshElement*> myPyramids;
1003 const SMESHDS_SubMesh * aSubMeshDSFace;
1004 SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
1005 SMESH_MesherHelper helper1(aMesh);
1006 helper1.IsQuadraticSubMesh(aShape);
1008 if ( myElemSearcher ) delete myElemSearcher;
1009 vector< SMDS_ElemIteratorPtr > itVec;
1012 itVec.push_back( aProxyMesh->GetFaces( aShape ));
1016 for ( TopExp_Explorer exp(aShape,TopAbs_FACE); exp.More(); exp.Next() )
1017 if (( aSubMeshDSFace = meshDS->MeshElements( exp.Current() )))
1018 itVec.push_back( aSubMeshDSFace->GetElements() );
1021 SMDS_IteratorOnIterators< const SMDS_MeshElement*, vector< SMDS_ElemIteratorPtr > > TIter;
1022 SMDS_ElemIteratorPtr faceIt( new TIter( itVec ));
1023 myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *meshDS, faceIt );
1025 TColgp_Array1OfPnt PN(1,5);
1026 TColgp_Array1OfVec VN(1,4);
1027 vector<const SMDS_MeshNode*> FNodes(5);
1030 const int solidID = meshDS->ShapeToIndex( aShape );
1032 for ( TopExp_Explorer exp(aShape,TopAbs_FACE); exp.More(); exp.Next() )
1034 const TopoDS_Shape& aShapeFace = exp.Current();
1036 aSubMeshDSFace = aProxyMesh->GetSubMesh( aShapeFace );
1038 aSubMeshDSFace = meshDS->MeshElements( aShapeFace );
1039 if ( !aSubMeshDSFace )
1042 vector<const SMDS_MeshElement*> trias, quads;
1043 bool hasNewTrias = false;
1045 const bool toCheckFaceInSolid =
1046 aProxyMesh ? aProxyMesh->HasPrismsOnTwoSides( meshDS->MeshElements( aShapeFace )) : false;
1047 if ( toCheckFaceInSolid && !dynamic_cast< const SMESH_ProxyMesh::SubMesh* >( aSubMeshDSFace ))
1048 continue; // no room for pyramids as prisms are on both sides
1051 bool isRevGlob = false;
1052 SMESH_MesherHelper helper2( aMesh );
1053 PShapeIteratorPtr sIt = helper2.GetAncestors( aShapeFace, aMesh, aShape.ShapeType() );
1054 while ( const TopoDS_Shape * solid = sIt->next() )
1055 if ( !solid->IsSame( aShape ))
1057 isRevGlob = helper2.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
1058 if ( toCheckFaceInSolid )
1059 helper2.IsQuadraticSubMesh( *solid );
1063 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
1064 while ( iteratorElem->more() ) // loop on elements on a geometrical face
1066 const SMDS_MeshElement* face = iteratorElem->next();
1068 // preparation step to get face info
1069 int stat = Preparation( face, PN, VN, FNodes, PC, VNorm );
1071 bool isRev = isRevGlob;
1072 SMESH_MesherHelper* helper = &helper1;
1073 if ( toCheckFaceInSolid && !isInSolid( FNodes, face->NbCornerNodes(), solidID ))
1083 trias.push_back( face );
1089 // add triangles to result map
1090 SMDS_MeshFace* NewFace;
1091 helper->SetElementsOnShape( false );
1093 NewFace = helper->AddFace( FNodes[0], FNodes[1], FNodes[2] );
1095 NewFace = helper->AddFace( FNodes[0], FNodes[2], FNodes[1] );
1096 storeTmpElement( NewFace );
1097 trias.push_back ( NewFace );
1098 quads.push_back( face );
1105 if(!isRev) VNorm.Reverse();
1106 //double xc = 0., yc = 0., zc = 0.;
1107 double h, hMin = Precision::Infinite();
1113 Pbest = FindBestPoint(PN(i), PN(i+1), PC, VN(i).Reversed(), h);
1115 Pbest = FindBestPoint(PN(i), PN(i+1), PC, VN(i), h);
1116 if ( 0 < h && h < hMin )
1122 //gp_Pnt PCbest(xc/4., yc/4., zc/4.);
1125 double height = PCbest.Distance(PC);
1126 if ( height < 1.e-6 ) {
1127 // create new PCbest using a bit shift along VNorm
1128 PCbest = PC.XYZ() + VNorm.XYZ() * 0.001;
1131 // check possible intersection with other faces
1132 if ( !LimitHeight( PCbest, PC, PN, FNodes, aMesh, face, /*UseApexRay=*/true, aShape ))
1135 // create node at PCbest
1136 helper->SetElementsOnShape( true );
1137 SMDS_MeshNode* NewNode = helper->AddNode( PCbest.X(), PCbest.Y(), PCbest.Z() );
1140 SMDS_MeshVolume* aPyram;
1142 aPyram = helper->AddVolume( FNodes[0], FNodes[3], FNodes[2], FNodes[1], NewNode );
1144 aPyram = helper->AddVolume( FNodes[0], FNodes[1], FNodes[2], FNodes[3], NewNode );
1145 myPyramids.push_back(aPyram);
1146 //cout << "F" << face->GetID() << " - V" << aPyram->GetID() << endl;
1148 myPyramHeight2.Bind( aPyram, PCbest.SquareDistance( PC ));
1150 // add triangles to result map
1151 helper->SetElementsOnShape( false );
1152 for ( i = 0; i < 4; i++ )
1154 trias.push_back ( helper->AddFace( NewNode, FNodes[i], FNodes[i+1] ));
1155 storeTmpElement( trias.back() );
1158 quads.push_back( face );
1164 } // switch ( stat )
1165 } // end loop on elements on a face submesh
1167 bool sourceSubMeshIsProxy = false;
1170 // move proxy sub-mesh from other proxy mesh to this
1171 sourceSubMeshIsProxy = takeProxySubMesh( aShapeFace, aProxyMesh );
1172 // move also tmp elements added in mesh
1173 takeTmpElemsInMesh( aProxyMesh );
1177 SMESH_ProxyMesh::SubMesh* prxSubMesh = getProxySubMesh( aShapeFace );
1178 prxSubMesh->ChangeElements( trias.begin(), trias.end() );
1180 // delete tmp quadrangles removed from aProxyMesh
1181 if ( sourceSubMeshIsProxy )
1183 for ( unsigned i = 0; i < quads.size(); ++i )
1184 removeTmpElement( quads[i] );
1186 delete myElemSearcher;
1188 SMESH_MeshAlgos::GetElementSearcher( *meshDS, aProxyMesh->GetFaces(aShape));
1192 } // end for(TopExp_Explorer exp(aShape,TopAbs_FACE);exp.More();exp.Next()) {
1194 return Compute2ndPart(aMesh, myPyramids);
1197 //================================================================================
1199 * \brief Computes pyramids in mesh with no shape
1201 //================================================================================
1203 bool StdMeshers_QuadToTriaAdaptor::Compute(SMESH_Mesh& aMesh)
1205 SMESH_ProxyMesh::setMesh( aMesh );
1206 SMESH_ProxyMesh::_allowedTypes.push_back( SMDSEntity_Triangle );
1207 SMESH_ProxyMesh::_allowedTypes.push_back( SMDSEntity_Quad_Triangle );
1208 if ( aMesh.NbQuadrangles() < 1 )
1211 // find if there is a group of faces identified as skin faces, with normal going outside the volume
1212 std::string groupName = "skinFaces";
1213 SMESHDS_GroupBase* groupDS = 0;
1214 SMESH_Mesh::GroupIteratorPtr groupIt = aMesh.GetGroups();
1215 while ( groupIt->more() )
1218 SMESH_Group * group = groupIt->next();
1219 if ( !group ) continue;
1220 groupDS = group->GetGroupDS();
1221 if ( !groupDS || groupDS->IsEmpty() )
1226 if (groupDS->GetType() != SMDSAbs_Face)
1231 std::string grpName = group->GetName();
1232 if (grpName == groupName)
1240 const bool toFindVolumes = aMesh.NbVolumes() > 0;
1242 vector<const SMDS_MeshElement*> myPyramids;
1243 SMESH_MesherHelper helper(aMesh);
1244 helper.IsQuadraticSubMesh(aMesh.GetShapeToMesh());
1246 SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
1247 SMESH_ProxyMesh::SubMesh* prxSubMesh = getProxySubMesh();
1249 if ( !myElemSearcher )
1250 myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *meshDS );
1251 SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>( myElemSearcher );
1252 SMESHUtils::Deleter<SMESH_ElementSearcher>
1253 volSearcher( SMESH_MeshAlgos::GetElementSearcher( *meshDS ));
1254 vector< const SMDS_MeshElement* > suspectFaces, foundVolumes;
1256 TColgp_Array1OfPnt PN(1,5);
1257 TColgp_Array1OfVec VN(1,4);
1258 vector<const SMDS_MeshNode*> FNodes(5);
1259 TColgp_SequenceOfPnt aContour;
1261 SMDS_FaceIteratorPtr fIt = meshDS->facesIterator();
1264 const SMDS_MeshElement* face = fIt->next();
1265 if ( !face ) continue;
1266 // retrieve needed information about a face
1269 const SMDS_MeshElement* volumes[2];
1270 int what = Preparation( face, PN, VN, FNodes, PC, VNorm, volumes );
1271 if ( what == NOT_QUAD )
1273 if ( volumes[0] && volumes[1] )
1274 continue; // face is shared by two volumes - no room for a pyramid
1276 if ( what == DEGEN_QUAD )
1279 // add a triangle to the proxy mesh
1280 SMDS_MeshFace* NewFace;
1282 // check orientation
1283 double tmp = PN(1).Distance(PN(2)) + PN(2).Distance(PN(3));
1284 // far points in VNorm direction
1285 gp_Pnt Ptmp1 = PC.XYZ() + VNorm.XYZ() * tmp * 1.e6;
1286 gp_Pnt Ptmp2 = PC.XYZ() - VNorm.XYZ() * tmp * 1.e6;
1287 // check intersection for Ptmp1 and Ptmp2
1291 double dist1 = RealLast();
1292 double dist2 = RealLast();
1295 gp_Ax1 line( PC, VNorm );
1296 vector< const SMDS_MeshElement* > suspectFaces;
1297 searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectFaces);
1299 for ( size_t iF = 0; iF < suspectFaces.size(); ++iF ) {
1300 const SMDS_MeshElement* F = suspectFaces[iF];
1301 if ( F == face ) continue;
1303 for ( int i = 0; i < 4; ++i )
1304 aContour.Append( SMESH_TNodeXYZ( F->GetNode(i) ));
1306 if ( !volumes[0] && HasIntersection( Ptmp1, PC, PPP, aContour )) {
1308 double tmp = PC.Distance(PPP);
1309 if ( tmp < dist1 ) {
1314 if ( !volumes[1] && HasIntersection( Ptmp2, PC, PPP, aContour )) {
1316 double tmp = PC.Distance(PPP);
1317 if ( tmp < dist2 ) {
1324 if( IsOK1 && !IsOK2 ) {
1325 // using existed direction
1327 else if( !IsOK1 && IsOK2 ) {
1328 // using opposite direction
1331 else { // IsOK1 && IsOK2
1332 double tmp1 = PC.Distance(Pres1);
1333 double tmp2 = PC.Distance(Pres2);
1335 // using existed direction
1338 // using opposite direction
1342 helper.SetElementsOnShape( false );
1344 NewFace = helper.AddFace( FNodes[0], FNodes[1], FNodes[2] );
1346 NewFace = helper.AddFace( FNodes[0], FNodes[2], FNodes[1] );
1347 storeTmpElement( NewFace );
1348 prxSubMesh->AddElement( NewFace );
1352 // -----------------------------------
1353 // Case of non-degenerated quadrangle
1354 // -----------------------------------
1356 // Find pyramid peak
1358 gp_XYZ PCbest = PC.XYZ();//(0., 0., 0.); // pyramid peak
1359 double h, hMin = Precision::Infinite();
1361 for ( ; i <= 4; i++ ) {
1362 gp_Pnt Pbest = FindBestPoint(PN(i), PN(i+1), PC, VN(i), h);
1363 if ( 0 < h && h < hMin )
1365 PCbest = Pbest.XYZ();
1368 //PCbest += Pbest.XYZ();
1372 double height = PC.Distance(PCbest); // pyramid height to precise
1373 if ( height < 1.e-6 ) {
1374 // create new PCbest using a bit shift along VNorm
1375 PCbest = PC.XYZ() + VNorm.XYZ() * 0.001;
1376 height = PC.Distance(PCbest);
1377 if ( height < std::numeric_limits<double>::min() )
1378 return false; // batterfly element
1381 // Restrict pyramid height by intersection with other faces
1383 gp_Vec tmpDir(PC,PCbest); tmpDir.Normalize();
1384 double tmp = PN(1).Distance(PN(3)) + PN(2).Distance(PN(4));
1385 // far points: in (PC, PCbest) direction and vice-versa
1386 gp_Pnt farPnt[2] = { PC.XYZ() + tmpDir.XYZ() * tmp * 1.e6,
1387 PC.XYZ() - tmpDir.XYZ() * tmp * 1.e6 };
1388 // check intersection for farPnt1 and farPnt2
1389 bool intersected[2] = { false, false };
1390 double dist2int [2] = { RealLast(), RealLast() };
1392 int intFaceInd [2] = { 0, 0 };
1394 if ( toFindVolumes && 0 ) // non-conformal mesh is not suitable for any mesher so far
1396 // there are volumes in the mesh, in a non-conformal mesh a neighbor
1397 // volume can be not found yet
1398 for ( int isRev = 0; isRev < 2; ++isRev )
1400 if ( volumes[isRev] ) continue;
1401 gp_Pnt testPnt = PC.XYZ() + tmpDir.XYZ() * height * ( isRev ? -0.1: 0.1 );
1402 foundVolumes.clear();
1403 if ( volSearcher->FindElementsByPoint( testPnt, SMDSAbs_Volume, foundVolumes ))
1404 volumes[isRev] = foundVolumes[0];
1406 if ( volumes[0] && volumes[1] )
1407 continue; // no room for a pyramid
1410 gp_Ax1 line( PC, tmpDir );
1411 suspectFaces.clear();
1412 searcher->GetElementsNearLine( line, SMDSAbs_Face, suspectFaces);
1414 for ( size_t iF = 0; iF < suspectFaces.size(); ++iF )
1416 const SMDS_MeshElement* F = suspectFaces[iF];
1417 if ( F == face ) continue;
1419 int nbN = F->NbCornerNodes();
1420 for ( i = 0; i < nbN; ++i )
1421 aContour.Append( SMESH_TNodeXYZ( F->GetNode(i) ));
1423 for ( int isRev = 0; isRev < 2; ++isRev )
1425 if( !volumes[isRev] && HasIntersection( farPnt[isRev], PC, intP, aContour ))
1427 double d = PC.Distance( intP );
1428 if ( d < dist2int[isRev] )
1430 intersected[isRev] = true;
1431 intPnt [isRev] = intP;
1432 dist2int [isRev] = d;
1433 intFaceInd [isRev] = iF;
1439 // if the face belong to the group of skinFaces, do not build a pyramid outside
1440 if ( groupDS && groupDS->Contains(face) )
1442 intersected[0] = false;
1444 else if ( intersected[0] && intersected[1] ) // check if one of pyramids is in a hole
1446 gp_Pnt P ( PC.XYZ() + tmpDir.XYZ() * 0.5 * dist2int[0] );
1447 if ( searcher->GetPointState( P ) == TopAbs_OUT )
1448 intersected[0] = false;
1451 P = ( PC.XYZ() - tmpDir.XYZ() * 0.5 * dist2int[1] );
1452 if ( searcher->GetPointState( P ) == TopAbs_OUT )
1453 intersected[1] = false;
1457 // Create one or two pyramids
1459 for ( int isRev = 0; isRev < 2; ++isRev )
1461 if ( !intersected[isRev] ) continue;
1462 double pyramidH = Min( height, dist2int[isRev]/3. );
1463 gp_Pnt Papex = PC.XYZ() + tmpDir.XYZ() * (isRev ? -pyramidH : pyramidH);
1464 if ( pyramidH < 1e-2 * height )
1465 return overlapError( aMesh, face, suspectFaces[ intFaceInd[isRev] ] );
1467 if ( !LimitHeight( Papex, PC, PN, FNodes, aMesh, face, /*UseApexRay=*/false ))
1470 // create node for Papex
1471 helper.SetElementsOnShape( true );
1472 SMDS_MeshNode* NewNode = helper.AddNode( Papex.X(), Papex.Y(), Papex.Z() );
1475 SMDS_MeshVolume* aPyram;
1477 aPyram = helper.AddVolume( FNodes[0], FNodes[1], FNodes[2], FNodes[3], NewNode );
1479 aPyram = helper.AddVolume( FNodes[0], FNodes[3], FNodes[2], FNodes[1], NewNode );
1480 myPyramids.push_back(aPyram);
1482 //myPyramHeight2.Bind( aPyram, Papex.SquareDistance( PC ));
1484 // add triangles to result map
1485 helper.SetElementsOnShape( false );
1486 for ( i = 0; i < 4; i++) {
1487 SMDS_MeshFace* NewFace;
1489 NewFace = helper.AddFace( NewNode, FNodes[i], FNodes[i+1] );
1491 NewFace = helper.AddFace( NewNode, FNodes[i+1], FNodes[i] );
1492 storeTmpElement( NewFace );
1493 prxSubMesh->AddElement( NewFace );
1496 } // end loop on all faces
1498 return Compute2ndPart(aMesh, myPyramids);
1501 //================================================================================
1503 * \brief Update created pyramids and faces to avoid their intersection
1505 //================================================================================
1507 bool StdMeshers_QuadToTriaAdaptor::Compute2ndPart(SMESH_Mesh& aMesh,
1508 const vector<const SMDS_MeshElement*>& myPyramids)
1510 if ( myPyramids.empty() )
1513 SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
1515 //int myShapeID = myPyramids[0]->GetNode(4)->getshapeId();
1517 SMDS_ElemIteratorPtr
1518 pyramIt( new SMDS_ElementVectorIterator( myPyramids.begin(), myPyramids.end() ));
1519 if ( myElemSearcher ) delete myElemSearcher;
1520 myElemSearcher = SMESH_MeshAlgos::GetElementSearcher( *meshDS, pyramIt );
1522 SMESH_ElementSearcher* searcher = const_cast<SMESH_ElementSearcher*>( myElemSearcher );
1524 set<const SMDS_MeshNode*> nodesToMove;
1526 // check adjacent pyramids
1528 // for ( i = 0; i < myPyramids.size(); ++i )
1530 // const SMDS_MeshElement* PrmI = myPyramids[i];
1531 // MergeAdjacent( PrmI, nodesToMove );
1534 // Fix adjacent pyramids whose heights differ too much
1537 bool modifHeight = true;
1538 typedef NCollection_DataMap< const SMDS_MeshElement*, double >::Iterator TPyramToH2Iter;
1539 while ( modifHeight )
1541 modifHeight = false;
1542 for ( TPyramToH2Iter pyramToH2( myPyramHeight2 ); pyramToH2.More(); pyramToH2.Next() )
1543 modifHeight |= DecreaseHeightDifference( pyramToH2.Key(), pyramToH2.Value() );
1545 for ( TPyramToH2Iter pyramToH2( myPyramHeight2 ); pyramToH2.More(); pyramToH2.Next() )
1547 if ( pyramToH2.Value() > 0 )
1548 continue; // not changed
1549 const double h = Sqrt( - pyramToH2.Value() );
1550 const SMDS_MeshElement* pyram = pyramToH2.Key();
1551 SMESH_NodeXYZ Papex = pyram->GetNode( PYRAM_APEX );
1553 for ( int i = 0; i < 4; ++i )
1554 PC += SMESH_NodeXYZ( pyram->GetNode( i ));
1556 gp_Vec V( PC, Papex );
1557 gp_Pnt newApex = gp_Pnt( PC ).Translated( h * V.Normalized() );
1558 meshDS->MoveNode( Papex.Node(), newApex.X(), newApex.Y(), newApex.Z() );
1561 // iterate on all new pyramids
1562 vector< const SMDS_MeshElement* > suspectPyrams;
1563 for ( i = 0; i < myPyramids.size(); ++i )
1565 const SMDS_MeshElement* PrmI = myPyramids[i];
1566 const SMDS_MeshNode* apexI = PrmI->GetNode( PYRAM_APEX );
1568 // compare PrmI with all the rest pyramids
1570 // collect adjacent pyramids and nodes coordinates of PrmI
1571 set<const SMDS_MeshElement*> checkedPyrams;
1573 for ( k = 0; k < 5; k++ )
1575 const SMDS_MeshNode* n = PrmI->GetNode(k);
1576 PsI[k] = SMESH_TNodeXYZ( n );
1577 SMDS_ElemIteratorPtr vIt = n->GetInverseElementIterator( SMDSAbs_Volume );
1578 while ( vIt->more() )
1580 const SMDS_MeshElement* PrmJ = vIt->next();
1581 if ( SMESH_MeshAlgos::NbCommonNodes( PrmI, PrmJ ) > 1 )
1582 checkedPyrams.insert( PrmJ );
1586 // get pyramids to check
1587 gp_XYZ PC = ( PsI[0].XYZ() + PsI[1].XYZ() + PsI[2].XYZ() + PsI[3].XYZ() ) / 4.;
1588 gp_XYZ ray = PsI[4].XYZ() - PC;
1589 gp_XYZ center = PC + 0.5 * ray;
1590 double diameter = Max( PsI[0].Distance(PsI[2]), PsI[1].Distance(PsI[3]));
1591 suspectPyrams.clear();
1592 searcher->GetElementsInSphere( center, diameter * 0.6, SMDSAbs_Volume, suspectPyrams);
1594 // check intersection with distant pyramids
1595 for ( j = 0; j < suspectPyrams.size(); ++j )
1597 const SMDS_MeshElement* PrmJ = suspectPyrams[j];
1600 if ( apexI == PrmJ->GetNode( PYRAM_APEX ))
1601 continue; // pyramids PrmI and PrmJ already merged
1602 if ( !checkedPyrams.insert( PrmJ ).second )
1603 continue; // already checked
1606 for ( k = 0; k < 5; k++ )
1607 PsJ[k] = SMESH_TNodeXYZ( PrmJ->GetNode(k) );
1609 if ( ray * ( PsJ[4].XYZ() - PC ) < 0. )
1610 continue; // PrmJ is below PrmI
1612 for ( k = 0; k < 4; k++ ) // loop on 4 base nodes of PrmI
1616 for ( k = 0; k < 4 && !hasInt; k++ )
1618 gp_Vec Vtmp( PsI[k], PsI[ PYRAM_APEX ]);
1619 gp_Pnt Pshift = PsI[k].XYZ() + Vtmp.XYZ() * 0.01; // base node moved a bit to apex
1621 ( HasIntersection3( Pshift, PsI[4], Pint, PsJ[0], PsJ[1], PsJ[PYRAM_APEX]) ||
1622 HasIntersection3( Pshift, PsI[4], Pint, PsJ[1], PsJ[2], PsJ[PYRAM_APEX]) ||
1623 HasIntersection3( Pshift, PsI[4], Pint, PsJ[2], PsJ[3], PsJ[PYRAM_APEX]) ||
1624 HasIntersection3( Pshift, PsI[4], Pint, PsJ[3], PsJ[0], PsJ[PYRAM_APEX]) );
1626 for ( k = 0; k < 4 && !hasInt; k++ )
1628 gp_Vec Vtmp( PsJ[k], PsJ[ PYRAM_APEX ]);
1629 gp_Pnt Pshift = PsJ[k].XYZ() + Vtmp.XYZ() * 0.01;
1631 ( HasIntersection3( Pshift, PsJ[4], Pint, PsI[0], PsI[1], PsI[PYRAM_APEX]) ||
1632 HasIntersection3( Pshift, PsJ[4], Pint, PsI[1], PsI[2], PsI[PYRAM_APEX]) ||
1633 HasIntersection3( Pshift, PsJ[4], Pint, PsI[2], PsI[3], PsI[PYRAM_APEX]) ||
1634 HasIntersection3( Pshift, PsJ[4], Pint, PsI[3], PsI[0], PsI[PYRAM_APEX]) );
1639 // count common nodes of base faces of two pyramids
1641 for ( k = 0; k < 4; k++ )
1642 nbc += int ( PrmI->GetNodeIndex( PrmJ->GetNode(k) ) >= 0 );
1645 continue; // pyrams have a common base face
1649 // Merge the two pyramids and others already merged with them
1650 MergePiramids( PrmI, PrmJ, nodesToMove );
1654 // decrease height of pyramids
1655 gp_XYZ PCi(0,0,0), PCj(0,0,0);
1656 for ( k = 0; k < 4; k++ ) {
1657 PCi += PsI[k].XYZ();
1658 PCj += PsJ[k].XYZ();
1661 gp_Vec VN1(PCi,PsI[4]);
1662 gp_Vec VN2(PCj,PsJ[4]);
1663 gp_Vec VI1(PCi,Pint);
1664 gp_Vec VI2(PCj,Pint);
1665 double ang1 = fabs(VN1.Angle(VI1));
1666 double ang2 = fabs(VN2.Angle(VI2));
1667 double coef1 = 0.5 - (( ang1 < M_PI/3. ) ? cos(ang1)*0.25 : 0 );
1668 double coef2 = 0.5 - (( ang2 < M_PI/3. ) ? cos(ang2)*0.25 : 0 ); // cos(ang2) ?
1669 // double coef2 = 0.5;
1671 // coef2 -= cos(ang1)*0.25;
1675 SMDS_MeshNode* aNode1 = const_cast<SMDS_MeshNode*>( apexI );
1676 aNode1->setXYZ( PCi.X()+VN1.X(), PCi.Y()+VN1.Y(), PCi.Z()+VN1.Z() );
1677 SMDS_MeshNode* aNode2 = const_cast<SMDS_MeshNode*>(PrmJ->GetNode( PYRAM_APEX ));
1678 aNode2->setXYZ( PCj.X()+VN2.X(), PCj.Y()+VN2.Y(), PCj.Z()+VN2.Z() );
1679 nodesToMove.insert( aNode1 );
1680 nodesToMove.insert( aNode2 );
1681 //cout << "Limit H F" << getFaceID( PrmI ) << " - F" << getFaceID( PrmJ ) << endl;
1683 // fix intersections that can appear after apex movement
1684 //MergeAdjacent( PrmI, nodesToMove );
1685 //MergeAdjacent( PrmJ, nodesToMove );
1687 apexI = PrmI->GetNode( PYRAM_APEX ); // apexI can be removed by merge
1690 } // loop on 4 base nodes of PrmI
1691 } // loop on suspectPyrams
1693 } // loop on all pyramids
1695 //smIdType nbNodes = aMesh.NbNodes();
1696 for ( i = 0; i < myPyramids.size(); ++i )
1698 const SMDS_MeshElement* PrmI = myPyramids[i];
1699 MergeAdjacent( PrmI, nodesToMove );
1702 if( !nodesToMove.empty() && !meshDS->IsEmbeddedMode() )
1704 set<const SMDS_MeshNode*>::iterator n = nodesToMove.begin();
1705 for ( ; n != nodesToMove.end(); ++n )
1706 meshDS->MoveNode( *n, (*n)->X(), (*n)->Y(), (*n)->Z() );
1709 // move medium nodes of merged quadratic pyramids
1710 if ( myPyramids[0]->IsQuadratic() )
1711 UpdateQuadraticPyramids( nodesToMove, GetMeshDS() );
1713 // erase removed triangles from the proxy mesh
1714 if ( !myRemovedTrias.empty() )
1716 for ( int i = 0; i <= meshDS->MaxShapeIndex(); ++i )
1717 if ( SMESH_ProxyMesh::SubMesh* sm = findProxySubMesh(i))
1719 vector<const SMDS_MeshElement *> faces;
1720 faces.reserve( sm->NbElements() );
1721 SMDS_ElemIteratorPtr fIt = sm->GetElements();
1722 while ( fIt->more() )
1724 const SMDS_MeshElement* tria = fIt->next();
1725 set<const SMDS_MeshElement*>::iterator rmTria = myRemovedTrias.find( tria );
1726 if ( rmTria != myRemovedTrias.end() )
1727 myRemovedTrias.erase( rmTria );
1729 faces.push_back( tria );
1731 sm->ChangeElements( faces.begin(), faces.end() );
1737 delete myElemSearcher;