1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #include <Standard_Stream.hxx>
25 #include <GEOMUtils.hxx>
27 #include <Basics_OCCTVersion.hxx>
29 #include <utilities.h>
31 #include <Utils_ExceptHandlers.hxx>
34 #include <BRepMesh_IncrementalMesh.hxx>
36 #include <BRepExtrema_DistShapeShape.hxx>
38 #include <BRep_Builder.hxx>
39 #include <BRep_Tool.hxx>
40 #include <BRepBndLib.hxx>
41 #include <BRepGProp.hxx>
42 #include <BRepTools.hxx>
44 #include <BRepClass3d_SolidClassifier.hxx>
46 #include <BRepBuilderAPI_MakeFace.hxx>
48 #include <Bnd_Box.hxx>
53 #include <TopoDS_Edge.hxx>
54 #include <TopoDS_Face.hxx>
55 #include <TopoDS_Shape.hxx>
56 #include <TopoDS_Vertex.hxx>
57 #include <TopoDS_Compound.hxx>
58 #include <TopoDS_Iterator.hxx>
59 #include <TopExp_Explorer.hxx>
60 #include <TopTools_MapOfShape.hxx>
61 #include <TopTools_ListOfShape.hxx>
62 #include <TopTools_ListIteratorOfListOfShape.hxx>
63 #include <TopTools_Array1OfShape.hxx>
65 #include <Geom_Circle.hxx>
66 #include <Geom_Surface.hxx>
67 #include <Geom_Plane.hxx>
68 #include <Geom_SphericalSurface.hxx>
69 #include <Geom_ToroidalSurface.hxx>
70 #include <Geom_RectangularTrimmedSurface.hxx>
72 #include <GeomLProp_CLProps.hxx>
73 #include <GeomLProp_SLProps.hxx>
75 #include <GProp_GProps.hxx>
76 #include <GProp_PrincipalProps.hxx>
78 #include <TColStd_Array1OfReal.hxx>
83 #include <ShapeAnalysis.hxx>
84 #include <ShapeFix_Shape.hxx>
86 #include <ProjLib.hxx>
92 #include <Standard_Failure.hxx>
93 #include <Standard_NullObject.hxx>
94 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
96 #define STD_SORT_ALGO 1
101 * This function constructs and returns modified shape from the original one
102 * for singular cases. It is used for the method GetMinDistanceSingular.
104 * \param theShape the original shape
105 * \param theModifiedShape output parameter. The modified shape.
106 * \param theAddDist output parameter. The added distance for modified shape.
107 * \retval true if the shape is modified; false otherwise.
111 Standard_Boolean ModifyShape(const TopoDS_Shape &theShape,
112 TopoDS_Shape &theModifiedShape,
113 Standard_Real &theAddDist)
115 Standard_Boolean isModified = Standard_False;
116 TopExp_Explorer anExp;
120 theModifiedShape.Nullify();
122 for ( anExp.Init( theShape, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
124 theModifiedShape = anExp.Current();
127 TopoDS_Shape sh = theShape;
128 while(sh.ShapeType()==TopAbs_COMPOUND) {
129 TopoDS_Iterator it(sh);
132 Handle(Geom_Surface) S = BRep_Tool::Surface(TopoDS::Face(theModifiedShape));
133 if( S->IsKind(STANDARD_TYPE(Geom_SphericalSurface)) ||
134 S->IsKind(STANDARD_TYPE(Geom_ToroidalSurface)) ||
136 const Standard_Boolean isShell =
137 (sh.ShapeType()==TopAbs_SHELL || sh.ShapeType()==TopAbs_FACE);
139 if( isShell || S->IsUPeriodic() ) {
140 // non solid case or any periodic surface (Mantis 22454).
142 // changes for 0020677: EDF 1219 GEOM: MinDistance gives 0 instead of 20.88
143 //S->Bounds(U1,U2,V1,V2); changed by
144 ShapeAnalysis::GetFaceUVBounds(TopoDS::Face(theModifiedShape),U1,U2,V1,V2);
145 // end of changes for 020677 (dmv)
146 Handle(Geom_RectangularTrimmedSurface) TrS1 =
147 new Geom_RectangularTrimmedSurface(S,U1,(U1+U2)/2.,V1,V2);
148 Handle(Geom_RectangularTrimmedSurface) TrS2 =
149 new Geom_RectangularTrimmedSurface(S,(U1+U2)/2.,U2,V1,V2);
152 TopoDS_Shape aMShape;
155 B.MakeCompound(TopoDS::Compound(aMShape));
157 B.MakeShell(TopoDS::Shell(aMShape));
160 B.MakeFace(F1,TrS1,1.e-7);
162 B.MakeFace(F2,TrS2,1.e-7);
164 Handle(ShapeFix_Shape) sfs = new ShapeFix_Shape;
167 // The original shape is a solid.
171 B.Add(aSolid, aMShape);
176 sfs->SetPrecision(1.e-6);
177 sfs->SetMaxTolerance(1.0);
179 theModifiedShape = sfs->Shape();
180 isModified = Standard_True;
183 if( S->IsKind(STANDARD_TYPE(Geom_SphericalSurface)) ) {
184 Handle(Geom_SphericalSurface) SS = Handle(Geom_SphericalSurface)::DownCast(S);
185 gp_Pnt PC = SS->Location();
188 B.MakeVertex(V,PC,1.e-7);
189 theModifiedShape = V;
190 theAddDist = SS->Radius();
191 isModified = Standard_True;
194 Handle(Geom_ToroidalSurface) TS = Handle(Geom_ToroidalSurface)::DownCast(S);
195 gp_Ax3 ax3 = TS->Position();
196 Handle(Geom_Circle) C = new Geom_Circle(ax3.Ax2(),TS->MajorRadius());
199 B.MakeEdge(E,C,1.e-7);
200 theModifiedShape = E;
201 theAddDist = TS->MinorRadius();
202 isModified = Standard_True;
206 theModifiedShape = theShape;
210 theModifiedShape = theShape;
215 //=======================================================================
216 //function : ShapeToDouble
217 //purpose : used by CompareShapes::operator()
218 //=======================================================================
219 std::pair<double, double> ShapeToDouble (const TopoDS_Shape& S, bool isOldSorting)
221 // Computing of CentreOfMass
225 if (S.ShapeType() == TopAbs_VERTEX) {
226 GPoint = BRep_Tool::Pnt(TopoDS::Vertex(S));
227 Len = (double)S.Orientation();
231 // BEGIN: fix for Mantis issue 0020842
233 BRepGProp::LinearProperties(S, GPr);
236 if (S.ShapeType() == TopAbs_EDGE || S.ShapeType() == TopAbs_WIRE) {
237 BRepGProp::LinearProperties(S, GPr);
239 else if (S.ShapeType() == TopAbs_FACE || S.ShapeType() == TopAbs_SHELL) {
240 BRepGProp::SurfaceProperties(S, GPr);
243 BRepGProp::VolumeProperties(S, GPr);
246 // END: fix for Mantis issue 0020842
247 GPoint = GPr.CentreOfMass();
251 double dMidXYZ = GPoint.X() * 999.0 + GPoint.Y() * 99.0 + GPoint.Z() * 0.9;
252 return std::make_pair(dMidXYZ, Len);
255 void parseWard( const GEOMUtils::LevelsList &theLevelList, std::string &treeStr )
257 treeStr.append( "{" );
258 for( GEOMUtils::LevelsList::const_iterator j = theLevelList.begin();
259 j != theLevelList.end(); ++j ) {
260 if ( j != theLevelList.begin() ) {
261 treeStr.append( ";" );
263 GEOMUtils::LevelInfo level = (*j);
264 GEOMUtils::LevelInfo::iterator upIter;
265 for ( upIter = level.begin(); upIter != level.end(); ++upIter ) {
266 if ( upIter != level.begin() ) {
267 treeStr.append( "," );
269 treeStr.append( upIter->first );
270 for ( std::vector<std::string>::iterator k = upIter->second.begin(); k != upIter->second.end(); ++k ) {
271 treeStr.append( "_" );
272 treeStr.append( *k );
276 treeStr.append( "}" );
279 GEOMUtils::LevelsList parseWard( const std::string& theData, std::size_t& theCursor )
281 std::size_t indexStart = theData.find( "{", theCursor ) + 1;
282 std::size_t indexEnd = theData.find( "}", indexStart );
284 std::string ward = theData.substr( indexStart, indexEnd - indexStart );
285 std::stringstream ss(ward);
287 std::vector<std::string> levelsListStr;
288 while ( std::getline( ss, substr, ';' ) ) {
289 if ( !substr.empty() )
290 levelsListStr.push_back( substr );
292 GEOMUtils::LevelsList levelsListData;
293 for( int level = 0; level < levelsListStr.size(); level++ ) {
294 std::vector<std::string> namesListStr;
295 std::stringstream ss1( levelsListStr[level] );
296 while ( std::getline( ss1, substr, ',' ) ) {
297 if ( !substr.empty() )
298 namesListStr.push_back( substr );
300 GEOMUtils::LevelInfo levelInfoData;
301 for( int node = 0; node < namesListStr.size(); node++ ) {
302 std::vector<std::string> linksListStr;
303 std::stringstream ss2( namesListStr[node] );
304 while ( std::getline( ss2, substr, '_' ) ) {
305 if ( !substr.empty() )
306 linksListStr.push_back( substr );
308 std::string nodeItem = linksListStr[0];
309 if( !nodeItem.empty() ) {
310 GEOMUtils::NodeLinks linksListData;
311 for( int link = 1; link < linksListStr.size(); link++ ) {
312 std::string linkItem = linksListStr[link];
313 linksListData.push_back( linkItem );
315 levelInfoData[nodeItem] = linksListData;
318 levelsListData.push_back(levelInfoData);
321 theCursor = indexEnd + 1;
322 return levelsListData;
327 //=======================================================================
328 //function : GetPosition
330 //=======================================================================
331 gp_Ax3 GEOMUtils::GetPosition (const TopoDS_Shape& theShape)
335 if (theShape.IsNull())
339 aResult.Transform(theShape.Location().Transformation());
340 if (theShape.ShapeType() == TopAbs_FACE) {
341 Handle(Geom_Surface) aGS = BRep_Tool::Surface(TopoDS::Face(theShape));
342 if (!aGS.IsNull() && aGS->IsKind(STANDARD_TYPE(Geom_Plane))) {
343 Handle(Geom_Plane) aGPlane = Handle(Geom_Plane)::DownCast(aGS);
344 gp_Pln aPln = aGPlane->Pln();
345 aResult = aPln.Position();
346 // In case of reverse orinetation of the face invert the plane normal
347 // (the face's normal does not mathc the plane's normal in this case)
348 if(theShape.Orientation() == TopAbs_REVERSED)
350 gp_Dir Vx = aResult.XDirection();
351 gp_Dir N = aResult.Direction().Mirrored(Vx);
352 gp_Pnt P = aResult.Location();
353 aResult = gp_Ax3(P, N, Vx);
361 TopAbs_ShapeEnum aShType = theShape.ShapeType();
363 if (aShType == TopAbs_VERTEX) {
364 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(theShape));
367 if (aShType == TopAbs_COMPOUND) {
368 aShType = GetTypeOfSimplePart(theShape);
371 GProp_GProps aSystem;
372 if (aShType == TopAbs_EDGE || aShType == TopAbs_WIRE)
373 BRepGProp::LinearProperties(theShape, aSystem);
374 else if (aShType == TopAbs_FACE || aShType == TopAbs_SHELL)
375 BRepGProp::SurfaceProperties(theShape, aSystem);
377 BRepGProp::VolumeProperties(theShape, aSystem);
379 aPnt = aSystem.CentreOfMass();
382 aResult.SetLocation(aPnt);
387 //=======================================================================
388 //function : GetVector
390 //=======================================================================
391 gp_Vec GEOMUtils::GetVector (const TopoDS_Shape& theShape,
392 Standard_Boolean doConsiderOrientation)
394 if (theShape.IsNull())
395 Standard_NullObject::Raise("Null shape is given for a vector");
397 if (theShape.ShapeType() != TopAbs_EDGE)
398 Standard_TypeMismatch::Raise("Invalid shape is given, must be a vector or an edge");
400 TopoDS_Edge anE = TopoDS::Edge(theShape);
402 TopoDS_Vertex V1, V2;
403 TopExp::Vertices(anE, V1, V2, doConsiderOrientation);
405 if (V1.IsNull() || V2.IsNull())
406 Standard_NullObject::Raise("Invalid edge is given, it must have two points");
408 gp_Vec aV (BRep_Tool::Pnt(V1), BRep_Tool::Pnt(V2));
409 if (aV.Magnitude() < gp::Resolution()) {
410 Standard_ConstructionError::Raise("Vector of zero length is given");
416 //=======================================================================
417 //function : CompareShapes::operator()
418 //purpose : used by std::sort(), called from SortShapes()
419 //=======================================================================
420 bool GEOMUtils::CompareShapes::operator() (const TopoDS_Shape& theShape1,
421 const TopoDS_Shape& theShape2)
423 if (!myMap.IsBound(theShape1)) {
424 myMap.Bind(theShape1, ShapeToDouble(theShape1, myIsOldSorting));
427 if (!myMap.IsBound(theShape2)) {
428 myMap.Bind(theShape2, ShapeToDouble(theShape2, myIsOldSorting));
431 std::pair<double, double> val1 = myMap.Find(theShape1);
432 std::pair<double, double> val2 = myMap.Find(theShape2);
434 double tol = Precision::Confusion();
435 bool exchange = Standard_False;
437 double dMidXYZ = val1.first - val2.first;
438 if (dMidXYZ >= tol) {
439 exchange = Standard_True;
441 else if (Abs(dMidXYZ) < tol) {
442 double dLength = val1.second - val2.second;
443 if (dLength >= tol) {
444 exchange = Standard_True;
446 else if (Abs(dLength) < tol && theShape1.ShapeType() <= TopAbs_FACE) {
448 // equal values possible on shapes such as two halves of a sphere and
449 // a membrane inside the sphere
451 BRepBndLib::Add(theShape1, box1);
452 if (!box1.IsVoid()) {
453 BRepBndLib::Add(theShape2, box2);
454 Standard_Real dSquareExtent = box1.SquareExtent() - box2.SquareExtent();
455 if (dSquareExtent >= tol) {
456 exchange = Standard_True;
458 else if (Abs(dSquareExtent) < tol) {
459 Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax, val1, val2;
460 box1.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
461 val1 = (aXmin+aXmax)*999.0 + (aYmin+aYmax)*99.0 + (aZmin+aZmax)*0.9;
462 box2.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
463 val2 = (aXmin+aXmax)*999.0 + (aYmin+aYmax)*99.0 + (aZmin+aZmax)*0.9;
464 if ((val1 - val2) >= tol) {
465 exchange = Standard_True;
472 //return val1 < val2;
476 //=======================================================================
477 //function : SortShapes
479 //=======================================================================
480 void GEOMUtils::SortShapes (TopTools_ListOfShape& SL,
481 const Standard_Boolean isOldSorting)
484 std::vector<TopoDS_Shape> aShapesVec;
485 aShapesVec.reserve(SL.Extent());
487 TopTools_ListIteratorOfListOfShape it (SL);
488 for (; it.More(); it.Next()) {
489 aShapesVec.push_back(it.Value());
493 CompareShapes shComp (isOldSorting);
494 std::stable_sort(aShapesVec.begin(), aShapesVec.end(), shComp);
495 //std::sort(aShapesVec.begin(), aShapesVec.end(), shComp);
497 std::vector<TopoDS_Shape>::const_iterator anIter = aShapesVec.begin();
498 for (; anIter != aShapesVec.end(); ++anIter) {
502 // old implementation
503 Standard_Integer MaxShapes = SL.Extent();
504 TopTools_Array1OfShape aShapes (1,MaxShapes);
505 TColStd_Array1OfInteger OrderInd(1,MaxShapes);
506 TColStd_Array1OfReal MidXYZ (1,MaxShapes); //X,Y,Z;
507 TColStd_Array1OfReal Length (1,MaxShapes); //X,Y,Z;
509 // Computing of CentreOfMass
510 Standard_Integer Index;
513 TopTools_ListIteratorOfListOfShape it(SL);
514 for (Index=1; it.More(); Index++)
516 TopoDS_Shape S = it.Value();
517 SL.Remove( it ); // == it.Next()
519 OrderInd.SetValue (Index, Index);
520 if (S.ShapeType() == TopAbs_VERTEX) {
521 GPoint = BRep_Tool::Pnt( TopoDS::Vertex( S ));
522 Length.SetValue( Index, (Standard_Real) S.Orientation());
525 // BEGIN: fix for Mantis issue 0020842
527 BRepGProp::LinearProperties (S, GPr);
530 if (S.ShapeType() == TopAbs_EDGE || S.ShapeType() == TopAbs_WIRE) {
531 BRepGProp::LinearProperties (S, GPr);
533 else if (S.ShapeType() == TopAbs_FACE || S.ShapeType() == TopAbs_SHELL) {
534 BRepGProp::SurfaceProperties(S, GPr);
537 BRepGProp::VolumeProperties(S, GPr);
540 // END: fix for Mantis issue 0020842
541 GPoint = GPr.CentreOfMass();
542 Length.SetValue(Index, GPr.Mass());
544 MidXYZ.SetValue(Index, GPoint.X()*999.0 + GPoint.Y()*99.0 + GPoint.Z()*0.9);
545 //cout << Index << " L: " << Length(Index) << "CG: " << MidXYZ(Index) << endl;
549 Standard_Integer aTemp;
550 Standard_Boolean exchange, Sort = Standard_True;
551 Standard_Real tol = Precision::Confusion();
554 Sort = Standard_False;
555 for (Index=1; Index < MaxShapes; Index++)
557 exchange = Standard_False;
558 Standard_Real dMidXYZ = MidXYZ(OrderInd(Index)) - MidXYZ(OrderInd(Index+1));
559 Standard_Real dLength = Length(OrderInd(Index)) - Length(OrderInd(Index+1));
560 if ( dMidXYZ >= tol ) {
561 // cout << "MidXYZ: " << MidXYZ(OrderInd(Index))<< " > " <<MidXYZ(OrderInd(Index+1))
562 // << " d: " << dMidXYZ << endl;
563 exchange = Standard_True;
565 else if ( Abs(dMidXYZ) < tol && dLength >= tol ) {
566 // cout << "Length: " << Length(OrderInd(Index))<< " > " <<Length(OrderInd(Index+1))
567 // << " d: " << dLength << endl;
568 exchange = Standard_True;
570 else if ( Abs(dMidXYZ) < tol && Abs(dLength) < tol &&
571 aShapes(OrderInd(Index)).ShapeType() <= TopAbs_FACE) {
573 // equal values possible on shapes such as two halves of a sphere and
574 // a membrane inside the sphere
576 BRepBndLib::Add( aShapes( OrderInd(Index) ), box1 );
577 if ( box1.IsVoid() ) continue;
578 BRepBndLib::Add( aShapes( OrderInd(Index+1) ), box2 );
579 Standard_Real dSquareExtent = box1.SquareExtent() - box2.SquareExtent();
580 if ( dSquareExtent >= tol ) {
581 // cout << "SquareExtent: " << box1.SquareExtent()<<" > "<<box2.SquareExtent() << endl;
582 exchange = Standard_True;
584 else if ( Abs(dSquareExtent) < tol ) {
585 Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax, val1, val2;
586 box1.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
587 val1 = (aXmin+aXmax)*999 + (aYmin+aYmax)*99 + (aZmin+aZmax)*0.9;
588 box2.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
589 val2 = (aXmin+aXmax)*999 + (aYmin+aYmax)*99 + (aZmin+aZmax)*0.9;
590 //exchange = val1 > val2;
591 if ((val1 - val2) >= tol) {
592 exchange = Standard_True;
594 //cout << "box: " << val1<<" > "<<val2 << endl;
600 // cout << "exchange " << Index << " & " << Index+1 << endl;
601 aTemp = OrderInd(Index);
602 OrderInd(Index) = OrderInd(Index+1);
603 OrderInd(Index+1) = aTemp;
604 Sort = Standard_True;
609 for (Index=1; Index <= MaxShapes; Index++)
610 SL.Append( aShapes( OrderInd(Index) ));
614 //=======================================================================
615 //function : CompsolidToCompound
617 //=======================================================================
618 TopoDS_Shape GEOMUtils::CompsolidToCompound (const TopoDS_Shape& theCompsolid)
620 if (theCompsolid.ShapeType() != TopAbs_COMPSOLID) {
624 TopoDS_Compound aCompound;
626 B.MakeCompound(aCompound);
628 TopTools_MapOfShape mapShape;
629 TopoDS_Iterator It (theCompsolid, Standard_True, Standard_True);
631 for (; It.More(); It.Next()) {
632 TopoDS_Shape aShape_i = It.Value();
633 if (mapShape.Add(aShape_i)) {
634 B.Add(aCompound, aShape_i);
641 //=======================================================================
642 //function : AddSimpleShapes
644 //=======================================================================
645 void GEOMUtils::AddSimpleShapes (const TopoDS_Shape& theShape, TopTools_ListOfShape& theList)
647 if (theShape.ShapeType() != TopAbs_COMPOUND &&
648 theShape.ShapeType() != TopAbs_COMPSOLID) {
649 theList.Append(theShape);
653 TopTools_MapOfShape mapShape;
654 TopoDS_Iterator It (theShape, Standard_True, Standard_True);
656 for (; It.More(); It.Next()) {
657 TopoDS_Shape aShape_i = It.Value();
658 if (mapShape.Add(aShape_i)) {
659 if (aShape_i.ShapeType() == TopAbs_COMPOUND ||
660 aShape_i.ShapeType() == TopAbs_COMPSOLID) {
661 AddSimpleShapes(aShape_i, theList);
663 theList.Append(aShape_i);
669 //=======================================================================
670 //function : CheckTriangulation
672 //=======================================================================
673 bool GEOMUtils::CheckTriangulation (const TopoDS_Shape& aShape)
675 bool isTriangulation = true;
677 TopExp_Explorer exp (aShape, TopAbs_FACE);
680 TopLoc_Location aTopLoc;
681 Handle(Poly_Triangulation) aTRF;
682 aTRF = BRep_Tool::Triangulation(TopoDS::Face(exp.Current()), aTopLoc);
684 isTriangulation = false;
687 else // no faces, try edges
689 TopExp_Explorer expe (aShape, TopAbs_EDGE);
693 TopLoc_Location aLoc;
694 Handle(Poly_Polygon3D) aPE = BRep_Tool::Polygon3D(TopoDS::Edge(expe.Current()), aLoc);
696 isTriangulation = false;
700 if (!isTriangulation) {
701 // calculate deflection
702 Standard_Real aDeviationCoefficient = 0.001;
705 BRepBndLib::Add(aShape, B);
706 Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
707 B.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
709 Standard_Real dx = aXmax - aXmin, dy = aYmax - aYmin, dz = aZmax - aZmin;
710 Standard_Real aDeflection = Max(Max(dx, dy), dz) * aDeviationCoefficient * 4;
711 Standard_Real aHLRAngle = 0.349066;
713 BRepMesh_IncrementalMesh Inc (aShape, aDeflection, Standard_False, aHLRAngle);
719 //=======================================================================
720 //function : GetTypeOfSimplePart
722 //=======================================================================
723 TopAbs_ShapeEnum GEOMUtils::GetTypeOfSimplePart (const TopoDS_Shape& theShape)
725 TopAbs_ShapeEnum aType = theShape.ShapeType();
726 if (aType == TopAbs_VERTEX) return TopAbs_VERTEX;
727 else if (aType == TopAbs_EDGE || aType == TopAbs_WIRE) return TopAbs_EDGE;
728 else if (aType == TopAbs_FACE || aType == TopAbs_SHELL) return TopAbs_FACE;
729 else if (aType == TopAbs_SOLID || aType == TopAbs_COMPSOLID) return TopAbs_SOLID;
730 else if (aType == TopAbs_COMPOUND) {
731 // Only the iType of the first shape in the compound is taken into account
732 TopoDS_Iterator It (theShape, Standard_False, Standard_False);
734 return GetTypeOfSimplePart(It.Value());
740 //=======================================================================
741 //function : GetEdgeNearPoint
743 //=======================================================================
744 TopoDS_Shape GEOMUtils::GetEdgeNearPoint (const TopoDS_Shape& theShape,
745 const TopoDS_Vertex& thePoint)
747 TopoDS_Shape aResult;
749 // 1. Explode the shape on edges
750 TopTools_MapOfShape mapShape;
751 Standard_Integer nbEdges = 0;
752 TopExp_Explorer exp (theShape, TopAbs_EDGE);
753 for (; exp.More(); exp.Next()) {
754 if (mapShape.Add(exp.Current())) {
760 Standard_NullObject::Raise("Given shape contains no edges");
763 Standard_Integer ind = 1;
764 TopTools_Array1OfShape anEdges (1, nbEdges);
765 TColStd_Array1OfReal aDistances (1, nbEdges);
766 for (exp.Init(theShape, TopAbs_EDGE); exp.More(); exp.Next()) {
767 if (mapShape.Add(exp.Current())) {
768 TopoDS_Shape anEdge = exp.Current();
769 anEdges(ind) = anEdge;
771 // 2. Classify the point relatively each edge
772 BRepExtrema_DistShapeShape aDistTool (thePoint, anEdges(ind));
773 if (!aDistTool.IsDone())
774 Standard_ConstructionError::Raise("Cannot find a distance from the given point to one of edges");
776 aDistances(ind) = aDistTool.Value();
781 // 3. Define edge, having minimum distance to the point
782 Standard_Real nearest = RealLast(), nbFound = 0;
783 Standard_Real prec = Precision::Confusion();
784 for (ind = 1; ind <= nbEdges; ind++) {
785 if (Abs(aDistances(ind) - nearest) < prec) {
788 else if (aDistances(ind) < nearest) {
789 nearest = aDistances(ind);
790 aResult = anEdges(ind);
797 Standard_ConstructionError::Raise("Multiple edges near the given point are found");
799 else if (nbFound == 0) {
800 Standard_ConstructionError::Raise("There are no edges near the given point");
808 //=======================================================================
809 //function : PreciseBoundingBox
811 //=======================================================================
812 Standard_Boolean GEOMUtils::PreciseBoundingBox
813 (const TopoDS_Shape &theShape, Bnd_Box &theBox)
815 Standard_Real aBound[6];
817 theBox.Get(aBound[0], aBound[2], aBound[4], aBound[1], aBound[3], aBound[5]);
820 const gp_Pnt aMid(0.5*(aBound[1] + aBound[0]), // XMid
821 0.5*(aBound[3] + aBound[2]), // YMid
822 0.5*(aBound[5] + aBound[4])); // ZMid
823 const gp_XYZ aSize(aBound[1] - aBound[0], // DX
824 aBound[3] - aBound[2], // DY
825 aBound[5] - aBound[4]); // DZ
826 const gp_Pnt aPnt[6] =
828 gp_Pnt(aBound[0] - (aBound[1] - aBound[0]), aMid.Y(), aMid.Z()), // XMin
829 gp_Pnt(aBound[1] + (aBound[1] - aBound[0]), aMid.Y(), aMid.Z()), // XMax
830 gp_Pnt(aMid.X(), aBound[2] - (aBound[3] - aBound[2]), aMid.Z()), // YMin
831 gp_Pnt(aMid.X(), aBound[3] + (aBound[3] - aBound[2]), aMid.Z()), // YMax
832 gp_Pnt(aMid.X(), aMid.Y(), aBound[4] - (aBound[5] - aBound[4])), // ZMin
833 gp_Pnt(aMid.X(), aMid.Y(), aBound[5] + (aBound[5] - aBound[4])) // ZMax
835 const gp_Dir aDir[3] = { gp::DX(), gp::DY(), gp::DZ() };
836 const Standard_Real aPlnSize[3] =
838 0.5*Max(aSize.Y(), aSize.Z()), // XMin, XMax planes
839 0.5*Max(aSize.X(), aSize.Z()), // YMin, YMax planes
840 0.5*Max(aSize.X(), aSize.Y()) // ZMin, ZMax planes
844 for (i = 0; i < 6; i++) {
845 const Standard_Integer iHalf = i/2;
846 const gp_Pln aPln(aPnt[i], aDir[iHalf]);
847 BRepBuilderAPI_MakeFace aMkFace(aPln, -aPlnSize[iHalf], aPlnSize[iHalf],
848 -aPlnSize[iHalf], aPlnSize[iHalf]);
850 if (!aMkFace.IsDone()) {
851 return Standard_False;
854 TopoDS_Shape aFace = aMkFace.Shape();
856 // Get minimal distance between planar face and shape.
857 Standard_Real aMinDist =
858 GEOMUtils::GetMinDistance(aFace, theShape, aPMin[0], aPMin[1]);
861 return Standard_False;
864 aBound[i] = aPMin[1].Coord(iHalf + 1);
867 // Update Bounding box with the new values.
869 theBox.Update(aBound[0], aBound[2], aBound[4], aBound[1], aBound[3], aBound[5]);
871 return Standard_True;
874 //=======================================================================
875 //function : GetMinDistanceSingular
877 //=======================================================================
878 double GEOMUtils::GetMinDistanceSingular(const TopoDS_Shape& aSh1,
879 const TopoDS_Shape& aSh2,
880 gp_Pnt& Ptmp1, gp_Pnt& Ptmp2)
884 Standard_Real AddDist1 = 0.;
885 Standard_Real AddDist2 = 0.;
886 Standard_Boolean IsChange1 = ModifyShape(aSh1, tmpSh1, AddDist1);
887 Standard_Boolean IsChange2 = ModifyShape(aSh2, tmpSh2, AddDist2);
889 if( !IsChange1 && !IsChange2 )
892 BRepExtrema_DistShapeShape dst(tmpSh1,tmpSh2);
894 double MinDist = 1.e9;
895 gp_Pnt PMin1, PMin2, P1, P2;
896 for (int i = 1; i <= dst.NbSolution(); i++) {
897 P1 = dst.PointOnShape1(i);
898 P2 = dst.PointOnShape2(i);
899 Standard_Real Dist = P1.Distance(P2);
900 if (MinDist > Dist) {
911 gp_Dir aDir(gp_Vec(PMin1,PMin2));
912 if( MinDist > (AddDist1+AddDist2) ) {
913 Ptmp1 = gp_Pnt( PMin1.X() + aDir.X()*AddDist1,
914 PMin1.Y() + aDir.Y()*AddDist1,
915 PMin1.Z() + aDir.Z()*AddDist1 );
916 Ptmp2 = gp_Pnt( PMin2.X() - aDir.X()*AddDist2,
917 PMin2.Y() - aDir.Y()*AddDist2,
918 PMin2.Z() - aDir.Z()*AddDist2 );
919 return (MinDist - AddDist1 - AddDist2);
923 Ptmp1 = gp_Pnt( PMin1.X() + aDir.X()*AddDist1,
924 PMin1.Y() + aDir.Y()*AddDist1,
925 PMin1.Z() + aDir.Z()*AddDist1 );
929 Ptmp2 = gp_Pnt( PMin2.X() - aDir.X()*AddDist2,
930 PMin2.Y() - aDir.Y()*AddDist2,
931 PMin2.Z() - aDir.Z()*AddDist2 );
936 double res = MinDist - AddDist1 - AddDist2;
937 if(res<0.) res = 0.0;
943 //=======================================================================
944 //function : GetMinDistance
946 //=======================================================================
947 Standard_Real GEOMUtils::GetMinDistance
948 (const TopoDS_Shape& theShape1,
949 const TopoDS_Shape& theShape2,
950 gp_Pnt& thePnt1, gp_Pnt& thePnt2)
952 Standard_Real aResult = 1.e9;
954 // Issue 0020231: A min distance bug with torus and vertex.
955 // Make GetMinDistance() return zero if a sole VERTEX is inside any of SOLIDs
957 // which of shapes consists of only one vertex?
958 TopExp_Explorer exp1(theShape1,TopAbs_VERTEX), exp2(theShape2,TopAbs_VERTEX);
959 TopoDS_Shape V1 = exp1.More() ? exp1.Current() : TopoDS_Shape();
960 TopoDS_Shape V2 = exp2.More() ? exp2.Current() : TopoDS_Shape();
961 exp1.Next(); exp2.Next();
962 if ( exp1.More() ) V1.Nullify();
963 if ( exp2.More() ) V2.Nullify();
964 // vertex and container of solids
965 TopoDS_Shape V = V1.IsNull() ? V2 : V1;
966 TopoDS_Shape S = V1.IsNull() ? theShape1 : theShape2;
968 // classify vertex against solids
969 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( V ) );
970 for ( exp1.Init( S, TopAbs_SOLID ); exp1.More(); exp1.Next() ) {
971 BRepClass3d_SolidClassifier classifier( exp1.Current(), p, 1e-6);
972 if ( classifier.State() == TopAbs_IN ) {
982 // additional workaround for bugs 19899, 19908 and 19910 from Mantis
983 double dist = GEOMUtils::GetMinDistanceSingular
984 (theShape1, theShape2, thePnt1, thePnt2);
990 BRepExtrema_DistShapeShape dst (theShape1, theShape2);
994 for (int i = 1; i <= dst.NbSolution(); i++) {
995 P1 = dst.PointOnShape1(i);
996 P2 = dst.PointOnShape2(i);
998 Standard_Real Dist = P1.Distance(P2);
999 if (aResult > Dist) {
1010 //=======================================================================
1011 // function : ConvertClickToPoint()
1012 // purpose : Returns the point clicked in 3D view
1013 //=======================================================================
1014 gp_Pnt GEOMUtils::ConvertClickToPoint( int x, int y, Handle(V3d_View) aView )
1016 V3d_Coordinate XEye, YEye, ZEye, XAt, YAt, ZAt;
1017 aView->Eye( XEye, YEye, ZEye );
1019 aView->At( XAt, YAt, ZAt );
1020 gp_Pnt EyePoint( XEye, YEye, ZEye );
1021 gp_Pnt AtPoint( XAt, YAt, ZAt );
1023 gp_Vec EyeVector( EyePoint, AtPoint );
1024 gp_Dir EyeDir( EyeVector );
1026 gp_Pln PlaneOfTheView = gp_Pln( AtPoint, EyeDir );
1027 Standard_Real X, Y, Z;
1028 aView->Convert( x, y, X, Y, Z );
1029 gp_Pnt ConvertedPoint( X, Y, Z );
1031 gp_Pnt2d ConvertedPointOnPlane = ProjLib::Project( PlaneOfTheView, ConvertedPoint );
1032 gp_Pnt ResultPoint = ElSLib::Value( ConvertedPointOnPlane.X(), ConvertedPointOnPlane.Y(), PlaneOfTheView );
1036 //=======================================================================
1037 // function : ConvertTreeToString()
1038 // purpose : Returns the string representation of dependency tree
1039 //=======================================================================
1040 void GEOMUtils::ConvertTreeToString( const TreeModel &tree,
1041 std::string &treeStr )
1043 TreeModel::const_iterator i;
1044 for ( i = tree.begin(); i != tree.end(); ++i ) {
1045 treeStr.append( i->first );
1046 treeStr.append( "-" );
1047 std::vector<LevelInfo> upLevelList = i->second.first;
1048 treeStr.append( "upward" );
1049 parseWard( upLevelList, treeStr );
1050 std::vector<LevelInfo> downLevelList = i->second.second;
1051 treeStr.append( "downward" );
1052 parseWard( downLevelList, treeStr );
1056 //=======================================================================
1057 // function : ConvertStringToTree()
1058 // purpose : Returns the dependency tree
1059 //=======================================================================
1060 void GEOMUtils::ConvertStringToTree( const std::string &theData,
1063 std::size_t cursor = 0;
1065 while( theData.find('-',cursor) != std::string::npos ) //find next selected object
1067 std::size_t objectIndex = theData.find( '-', cursor );
1068 std::string objectEntry = theData.substr( cursor, objectIndex - cursor );
1069 cursor = objectIndex;
1071 std::size_t upwardIndexBegin = theData.find("{",cursor) + 1;
1072 std::size_t upwardIndexFinish = theData.find("}",upwardIndexBegin);
1073 LevelsList upwardList = parseWard( theData, cursor );
1075 LevelsList downwardList = parseWard( theData, cursor );
1077 tree[objectEntry] = std::pair<LevelsList,LevelsList>( upwardList, downwardList );