1 // Copyright (C) 2014-2015 EDF-R&D
2 // This library is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU Lesser General Public
4 // License as published by the Free Software Foundation; either
5 // version 2.1 of the License, or (at your option) any later version.
7 // This library is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 // Lesser General Public License for more details.
12 // You should have received a copy of the GNU Lesser General Public
13 // License along with this library; if not, write to the Free Software
14 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #include <HYDROData_Tool.h>
20 #include <HYDROData_ArtificialObject.h>
21 #include <HYDROData_Document.h>
22 #include <HYDROData_Entity.h>
23 #include <HYDROData_Iterator.h>
24 #include <HYDROData_NaturalObject.h>
25 #include <HYDROData_ShapesGroup.h>
26 #include <HYDROData_PolylineXY.h>
29 #include <QStringList>
30 #include <QTextStream>
32 #include <BRep_Tool.hxx>
33 #include <BRepAdaptor_Surface.hxx>
34 #include <BRepTopAdaptor_FClass2d.hxx>
36 #include <Geom_Curve.hxx>
38 #include <Quantity_Color.hxx>
39 #include <TopExp_Explorer.hxx>
41 #include <TopoDS_Face.hxx>
42 #include <TopoDS_Shape.hxx>
43 #include <TopoDS_Wire.hxx>
48 #include <BRepTools.hxx>
49 #include <NCollection_Map.hxx>
50 #include <TopTools_ShapeMapHasher.hxx>
51 #include <BRep_Builder.hxx>
52 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
54 #include <NCollection_List.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
57 #include <BRepBuilderAPI_MakeFace.hxx>
59 #include <TopExp_Explorer.hxx>
60 #include <TopTools_ListIteratorOfListOfShape.hxx>
61 #include <TopTools_HSequenceOfShape.hxx>
63 #include <BRep_Builder.hxx>
64 #include <BRepAlgo_FaceRestrictor.hxx>
65 #include <BRepCheck_Analyzer.hxx>
67 #include <ShapeAnalysis.hxx>
68 #include <ShapeAnalysis_FreeBounds.hxx>
71 static int aMaxNameId = INT_MAX;
72 static int aMaxColorNb = 92000;
73 void HYDROData_Tool::WriteStringsToFile( QFile& theFile,
74 const QStringList& theStrings,
75 const QString& theSep )
77 if ( !theFile.isOpen() || theStrings.isEmpty() )
80 QString aWriteStr = theStrings.join( theSep );
81 if ( aWriteStr.isEmpty() )
84 QTextStream anOutStream( &theFile );
85 anOutStream << aWriteStr.toUtf8() << theSep << theSep;
88 bool HYDROData_Tool::ExtractGeneratedObjectName(const QString& theName, int& outValue, QString& thePrefName)
90 QStringList aLs = theName.split('_');
92 QString last = aLs.last();
93 outValue = last.toInt(&ok);
96 int last_len = last.length();
97 int total_len = theName.length();
98 thePrefName = theName.left(total_len-last_len-1);
102 QString HYDROData_Tool::GenerateObjectName( const Handle(HYDROData_Document)& theDoc,
103 const QString& thePrefix,
104 const QStringList& theUsedNames,
105 const bool theIsTryToUsePurePrefix )
107 QStringList aNamesList( theUsedNames );
109 // Collect all used names in the document
110 HYDROData_Iterator anIter( theDoc );
111 for( ; anIter.More(); anIter.Next() )
113 Handle(HYDROData_Entity) anObject = anIter.Current();
114 if( anObject.IsNull() )
117 QString anObjName = anObject->GetName();
118 if ( anObjName.isEmpty() )
121 aNamesList.append( anObjName );
126 if ( theIsTryToUsePurePrefix && !aNamesList.contains( thePrefix ) ) {
130 while( anId < aMaxNameId )
132 aName = QString( "%1_%2" ).arg( thePrefix ).arg( QString::number( anId++ ) );
134 // check that there are no other objects with the same name in the document
135 if ( !aNamesList.contains( aName ) )
143 bool HYDROData_Tool::IsGeometryObject( const Handle(HYDROData_Entity)& theObject )
145 if ( theObject.IsNull() )
148 return theObject->IsKind( STANDARD_TYPE(HYDROData_ArtificialObject) ) ||
149 theObject->IsKind( STANDARD_TYPE(HYDROData_NaturalObject) );
152 void HYDROData_Tool::UpdateChildObjectName( const QString& theOldStr,
153 const QString& theNewStr,
154 const Handle(HYDROData_Entity)& theObject )
156 if ( theObject.IsNull() )
159 QString anObjName = theObject->GetName();
160 if ( theOldStr.isEmpty() )
162 while ( anObjName.startsWith( '_' ) )
163 anObjName.remove( 0, 1 );
165 anObjName.prepend( theNewStr + "_" );
167 else if ( anObjName.startsWith( theOldStr ) )
169 anObjName.replace( 0, theOldStr.length(), theNewStr );
174 theObject->SetName( anObjName );
177 QString HYDROData_Tool::GenerateNameForPython( const MapOfTreatedObjects& theTreatedObjects,
178 const QString& thePrefix )
180 QString aName = thePrefix;
181 if ( !theTreatedObjects.contains( aName ) )
185 while( anId < aMaxNameId )
187 aName = QString( "%1_%2" ).arg( thePrefix ).arg( QString::number( anId++ ) );
189 // check that there are no other objects with the same name
190 if ( !theTreatedObjects.contains( aName ) )
196 //======================================================================================================
197 TopAbs_State HYDROData_Tool::ComputePointState( const gp_XY& theXY, const TopoDS_Face& theFace )
199 TopAbs_State aState(TopAbs_UNKNOWN);
200 if(theFace.IsNull()) return aState;
201 Standard_Real aTol = BRep_Tool::Tolerance(theFace);
202 BRepAdaptor_Surface Ads ( theFace, Standard_False );
203 Standard_Real toluv = Min ( Ads.UResolution(aTol), Ads.VResolution(aTol) );
205 toluv = 0.01; // there is no need to be more precise than 1cm a any case !
206 // another solution could be to compute a tolerance related to the distance between the border nodes
207 const gp_Pln& aPlane = Ads.Surface().Plane();
208 gp_Pnt aPnt(theXY.X(), theXY.Y(), 0.);
209 Standard_Real aU1, aV1;
210 ElSLib::Parameters(aPlane,aPnt, aU1, aV1);
211 BRepTopAdaptor_FClass2d aClassifier( theFace, toluv );
212 aState = aClassifier.Perform( gp_Pnt2d(aU1, aV1), Standard_False );
216 double HYDROData_Tool::GetAltitudeForEdge( const TopoDS_Edge& theEdge,
217 const gp_XY& thePoint,
218 double theParameterTolerance,
219 double theSquareDistanceTolerance,
220 double theInvalidAltitude )
222 double aFirst, aLast;
223 Handle(Geom_Curve) aCurve = BRep_Tool::Curve( theEdge, aFirst, aLast );
224 if( aCurve.IsNull() )
225 return theInvalidAltitude;
227 gp_Pnt aFirstPnt, aLastPnt;
229 aCurve->D0( aFirst, aFirstPnt );
230 aCurve->D0( aLast, aLastPnt );
232 gp_Pnt2d aFirstPnt2d( aFirstPnt.X(), aFirstPnt.Y() );
233 gp_Pnt2d aLastPnt2d( aLastPnt.X(), aLastPnt.Y() );
235 double aFirstDist = 0;
236 double aLastDist = aFirstPnt2d.SquareDistance( aLastPnt2d );
237 double aNecDist = aFirstPnt2d.SquareDistance( thePoint );
239 while( fabs( aLast - aFirst ) > theParameterTolerance )
241 double aMid = ( aFirst + aLast ) / 2;
243 aCurve->D0( aMid, aMidPnt );
244 double aDist = aFirstPnt2d.SquareDistance( gp_Pnt2d( aMidPnt.X(), aMidPnt.Y() ) );
246 if( aDist < aNecDist )
252 double aMid = ( aFirst + aLast ) / 2;
254 aCurve->D0( aMid, aMidPnt );
256 gp_Pnt2d aMidPnt2d( aMidPnt.X(), aMidPnt.Y() );
257 if( aMidPnt2d.SquareDistance( thePoint ) < theSquareDistanceTolerance )
260 return theInvalidAltitude;
263 double HYDROData_Tool::GetAltitudeForWire( const TopoDS_Wire& theWire,
264 const gp_XY& thePoint,
265 double theParameterTolerance,
266 double theSquareDistanceTolerance,
267 double theInvalidAltitude )
269 TopExp_Explorer anExp( theWire, TopAbs_EDGE );
270 for( ; anExp.More(); anExp.Next() )
272 double anAltitude = GetAltitudeForEdge( TopoDS::Edge( anExp.Current() ), thePoint,
273 theParameterTolerance, theSquareDistanceTolerance, theInvalidAltitude );
274 if( anAltitude != theInvalidAltitude )
277 return theInvalidAltitude;
280 TopoDS_Shape HYDROData_Tool::getFirstShapeFromGroup( const HYDROData_SequenceOfObjects& theGroups,
281 const int theGroupId )
283 TopoDS_Shape aResShape;
284 if ( theGroupId < 1 || theGroupId > theGroups.Length() )
287 Handle(HYDROData_ShapesGroup) aGroup =
288 Handle(HYDROData_ShapesGroup)::DownCast( theGroups.Value( theGroupId ) );
289 if ( aGroup.IsNull() )
292 TopTools_SequenceOfShape aGroupShapes;
293 aGroup->GetShapes( aGroupShapes );
295 if ( !aGroupShapes.IsEmpty() )
296 aResShape = aGroupShapes.First();
301 TCollection_ExtendedString HYDROData_Tool::toExtString( const QString& theStr )
303 TCollection_ExtendedString aRes;
304 if( !theStr.isEmpty() )
306 Standard_ExtString extStr = new Standard_ExtCharacter[ ( theStr.length() + 1 ) * 2 ];
307 memcpy( (void*)extStr, theStr.unicode(), theStr.length() * 2 );
308 ((short*)extStr)[theStr.length()] = '\0';
309 aRes = TCollection_ExtendedString( extStr );
315 QString HYDROData_Tool::toQString( const TCollection_ExtendedString& theStr )
317 return QString( (QChar*)theStr.ToExtString(), theStr.Length() );
320 Quantity_Color HYDROData_Tool::toOccColor( const QColor& theColor )
322 double r = theColor.red() / 255.0;
323 double g = theColor.green() / 255.0;
324 double b = theColor.blue() / 255.0;
326 return Quantity_Color( r, g, b, Quantity_TOC_RGB );
329 QColor HYDROData_Tool::toQtColor( const Quantity_Color& theColor )
331 int r = 255 * theColor.Red();
332 int g = 255 * theColor.Green();
333 int b = 255 * theColor.Blue();
334 return QColor( r, g, b );
337 QColor HYDROData_Tool::GenerateRandColor()
339 float aHue = ( rand()%1000 ) * 0.001f;
342 aColor.setHsl( (int)(aHue*255.), 200, 128 );
343 int r = aColor.red();
344 int g = aColor.green();
345 int b = aColor.blue();
346 return ( aColor.isValid() ? aColor : Qt::darkBlue );
349 void HYDROData_Tool::GenerateRepeatableRandColors(int nbColorsToGen, QVector<QColor>& theColors)
351 for (int i = 1; i <= nbColorsToGen; i++)
352 theColors.append(HYDROData_Tool::GenerateRandColor());
355 bool HYDROData_Tool::GenerateNonRepeatableRandColors(int nbColorsToGen, QVector<QColor>& theColors)
357 if (nbColorsToGen > aMaxColorNb)
368 if (Codes.contains(Code))
370 aColor.setHsl( H, S, 128 );
371 if (aColor.isValid())
373 theColors.append(aColor);
376 } while (theColors.size() <= nbColorsToGen);
381 bool HYDROData_Tool::IsNan( double theValue )
384 return _isnan( theValue );
386 return isnan( theValue );
390 bool HYDROData_Tool::IsInf( double theValue )
393 return (!_finite( theValue ) );
395 return isinf( theValue );
399 static void MakeShellG(const NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>& FG,
403 NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>::Iterator itFG(FG);
406 //face nb > 1 => make shell
407 TopoDS_Shell outShell;
408 bb.MakeShell(outShell);
409 for (;itFG.More();itFG.Next())
410 bb.Add(outShell, itFG.Value());
413 else if (FG.Extent() == 1)
415 outSh = itFG.Value(); //one face
419 TopoDS_Shape HYDROData_Tool::RebuildCmp(const TopoDS_Shape& in)
421 TopTools_IndexedDataMapOfShapeListOfShape mE2LF;
422 TopExp::MapShapesAndAncestors(in, TopAbs_EDGE, TopAbs_FACE, mE2LF);
424 return TopoDS_Shape();
425 NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> dfm;
426 //TopExp::MapShapes(aFuseShape, TopAbs_FACE, dfm);
427 TopExp_Explorer expf(in, TopAbs_FACE);
428 for (;expf.More(); expf.Next())
429 dfm.Add(TopoDS::Face(expf.Current()));
431 int nbF = dfm.Extent();
432 TopExp_Explorer exp_f(in, TopAbs_FACE);
433 const TopoDS_Face& FF = TopoDS::Face(exp_f.Current());
434 NCollection_List<TopoDS_Face> CurrFS;
435 NCollection_List<TopoDS_Face> NeighFS;
436 NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> PrF;
438 NCollection_List<NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>> GL_F;
439 NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher> OneGr;
443 NCollection_List<TopoDS_Face>::Iterator it_currfs(CurrFS);
445 for (;it_currfs.More();it_currfs.Next())
447 const TopoDS_Face& CF = it_currfs.Value();
448 TopExp_Explorer exp_edge(CF, TopAbs_EDGE);
449 for (;exp_edge.More();exp_edge.Next())
451 const TopoDS_Shape& CE = exp_edge.Current();
452 const TopTools_ListOfShape& lsf = mE2LF.FindFromKey(CE);
453 TopTools_ListIteratorOfListOfShape ls_it(lsf); //always one face (since all faces are planar)
454 for (;ls_it.More();ls_it.Next())
456 const TopoDS_Face& F = TopoDS::Face(ls_it.Value());
459 if (!PrF.Contains(F))
470 if (NeighFS.IsEmpty())
479 NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>::Iterator itDm(dfm);
480 const TopoDS_Face& nsh = itDm.Key();
489 if (GL_F.Extent() > 1)
492 NCollection_List<NCollection_Map<TopoDS_Face, TopTools_ShapeMapHasher>>::Iterator itGL_F(GL_F);
494 bb.MakeCompound(cmp);
495 for (;itGL_F.More();itGL_F.Next())
497 MakeShellG(itGL_F.Value(), sh);
503 else if (GL_F.Extent() == 1)
505 MakeShellG(GL_F.First(), sh);
511 TopoDS_Shape HYDROData_Tool::PolyXY2Face( const Handle(HYDROData_PolylineXY)& aPolyline )
513 //DEBTRACE("generateTopShape");
514 TopoDS_Face aResultFace = TopoDS_Face(); // --- result: default = null face
516 if (!aPolyline.IsNull())
518 TopoDS_Shape aPolylineShape = aPolyline->GetShape();
520 std::string brepName = "imz.brep";
521 BRepTools::Write(aPolylineShape, brepName.c_str());
523 TopTools_ListOfShape aWiresList;
525 if (!aPolylineShape.IsNull() && aPolylineShape.ShapeType() == TopAbs_WIRE)
527 // --- only one wire: try to make a face
528 //DEBTRACE("one wire: try to build a face");
529 const TopoDS_Wire& aPolylineWire = TopoDS::Wire(aPolylineShape);
530 if (!aPolylineWire.IsNull())
532 BRepBuilderAPI_MakeFace aMakeFace(aPolylineWire, Standard_True);
534 if (aMakeFace.IsDone())
536 //DEBTRACE(" a face with the only wire given");
537 aResultFace = aMakeFace.Face();
543 // --- a list of wires ? inventory of wires and edges
544 Handle(TopTools_HSequenceOfShape) aSeqWires = new TopTools_HSequenceOfShape;
545 Handle(TopTools_HSequenceOfShape) aSeqEdges = new TopTools_HSequenceOfShape;
546 TopExp_Explorer anExp(aPolylineShape, TopAbs_WIRE);
547 //DEBTRACE("list of wires ?");
548 for (; anExp.More(); anExp.Next())
550 if (!anExp.Current().IsNull())
552 const TopoDS_Wire& aWire = TopoDS::Wire(anExp.Current());
553 aWiresList.Append(aWire);
554 //DEBTRACE(" append wire");
555 TopExp_Explorer it2(aWire, TopAbs_EDGE);
556 for (; it2.More(); it2.Next())
557 aSeqEdges->Append(it2.Current());
560 if (aWiresList.IsEmpty())
561 return aResultFace; // --- no wires: null result
563 if (aSeqEdges->Length() > 1)
565 //DEBTRACE("try to connect all the edges together, build a unique wire and a face");
566 // --- try to create one wire by connecting edges with a distance tolerance (no necessity of sharing points)
567 ShapeAnalysis_FreeBounds::ConnectEdgesToWires(aSeqEdges, 1E-5, Standard_False, aSeqWires);
569 if (aSeqWires->Length() == 1)
571 // --- one wire: try to make a face
572 const TopoDS_Wire& aPolylineWire = TopoDS::Wire(aSeqWires->Value(1));
573 if (!aPolylineWire.IsNull())
575 BRepBuilderAPI_MakeFace aMakeFace(aPolylineWire, Standard_True);
577 if (aMakeFace.IsDone())
579 //DEBTRACE(" a face from all the wires connected");
580 aResultFace = aMakeFace.Face();
586 if (aResultFace.IsNull())
588 //DEBTRACE("try to make a face with the first wire of the list and other wires as restrictions");
589 // --- try to make a face with the first wire of the list and other wires as restrictions
590 BRepAlgo_FaceRestrictor aFR;
591 TopoDS_Face aRefFace;
592 TopoDS_Shape aS = aWiresList.First();
593 BRepBuilderAPI_MakeFace aMakeFace(TopoDS::Wire(aWiresList.First()), Standard_True);
595 if (aMakeFace.IsDone())
597 //DEBTRACE(" a face with first wire");
598 aRefFace = aMakeFace.Face();
600 if (!aRefFace.IsNull())
602 aFR.Init(aRefFace, Standard_False, Standard_True);
603 TopTools_ListIteratorOfListOfShape anIt(aWiresList);
604 for (; anIt.More(); anIt.Next())
606 TopoDS_Wire& aWire = TopoDS::Wire(anIt.Value());
614 for (; aFR.More(); aFR.Next())
616 //DEBTRACE(" a restricted face");
617 aResultFace = aFR.Current();
626 if (aResultFace.IsNull())
629 //DEBTRACE("check the face");
630 BRepCheck_Analyzer anAnalyzer(aResultFace);
631 if (anAnalyzer.IsValid() && aResultFace.ShapeType() == TopAbs_FACE)
633 //DEBTRACE("face OK");
638 //DEBTRACE("bad face");
640 return TopoDS_Face();
643 std::ostream& operator<<( std::ostream& theStream, const QString& theText )
645 theStream << theText.toStdString();
649 std::ostream& operator<<( std::ostream& theStream, const QColor& theColor )
651 theStream << "[" << theColor.red() << ", " << theColor.green() << ", " << theColor.blue() << "]";
655 std::ostream& operator<<( std::ostream& theStream, const TopoDS_Shape& theShape )
657 theStream << "[" << theShape.TShape().operator->() << "]";
661 std::ostream& operator<<( std::ostream& theStream, const TopoDS_Face& theFace )
663 theStream << "[" << theFace.TShape().operator->() << "]";
667 std::ostream& operator<<( std::ostream& theStream, const gp_XY& theXY )
669 theStream << "(" << theXY.X() << "; " << theXY.Y() << ")";
673 bool operator == ( const gp_XY& thePoint1, const gp_XY& thePoint2 )
675 const double EPS = 1E-3;
677 fabs( thePoint1.X() - thePoint2.X() ) < EPS &&
678 fabs( thePoint1.Y() - thePoint2.Y() ) < EPS;