Salome HOME
242310905264fab10a71851065867906ac382c1d
[modules/hydro.git] / src / HYDROData / HYDROData_Stream.cxx
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.
6 //
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.
11 //
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
15 //
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
17 //
18
19 #include "HYDROData_Stream.h"
20
21 #include "HYDROData_Document.h"
22 #include "HYDROData_PolylineXY.h"
23 #include "HYDROData_Polyline3D.h"
24 #include "HYDROData_Profile.h"
25 #include "HYDROData_ShapesGroup.h"
26 #include "HYDROData_ShapesTool.h"
27 #include "HYDROData_IAltitudeObject.h"
28 #include "HYDROData_IProfilesInterpolator.h"
29 #include "HYDROData_Tool.h"
30
31 #include <TDataStd_RealArray.hxx>
32
33 #include <Precision.hxx>
34
35 #include <NCollection_DataMap.hxx>
36
37 #include <TColStd_Array1OfReal.hxx>
38 #include <TColStd_ListOfReal.hxx>
39 #include <TColStd_ListIteratorOfListOfReal.hxx>
40 #include <TCollection_CompareOfReal.hxx>
41 #include <TColgp_Array1OfPnt.hxx>
42 #include <TColgp_HArray1OfPnt.hxx>
43
44 #include <TopoDS.hxx>
45 #include <TopoDS_Wire.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Face.hxx>
48 #include <TopoDS_Edge.hxx>
49 #include <TopoDS_Vertex.hxx>
50 #include <TopExp.hxx>
51 #include <TopExp_Explorer.hxx>
52
53 #include <Bnd_Box.hxx>
54
55 #include <BRep_Builder.hxx>
56 #include <BRepBuilderAPI_MakeEdge.hxx>
57 #include <BRepBuilderAPI_MakeWire.hxx>
58 #include <BRepBuilderAPI_MakeFace.hxx>
59
60 #include <BRepBndLib.hxx>
61 #include <BRepProj_Projection.hxx>
62 #include <BRepExtrema_ExtCC.hxx>
63 #include <BRepCheck_Analyzer.hxx>
64
65 #include <gp.hxx>
66 #include <gp_Ax1.hxx>
67 #include <gp_Ax2.hxx>
68 #include <gp_Ax3.hxx>
69 #include <gp_Vec.hxx>
70 #include <gp_Pnt.hxx>
71 #include <gp_Pln.hxx>
72
73 #include <GeomAPI_Interpolate.hxx>
74 #include <Geom_BSplineCurve.hxx>
75
76 #include <TopTools_HArray1OfShape.hxx>
77
78 #include <SortTools_QuickSortOfReal.hxx>
79
80 #include <QColor>
81 #include <QStringList>
82
83 //#define DEB_STREAM 1
84 #ifdef DEB_STREAM
85 //#define DEB_HASINT 1
86 //#define DEB_UPDATE 1
87 #include <BRepTools.hxx>
88 #include <TCollection_AsciiString.hxx>
89 #endif
90
91 typedef NCollection_DataMap<Standard_Real, Handle(HYDROData_Profile)> HYDROData_DataMapOfRealOfHDProfile;
92
93 IMPLEMENT_STANDARD_HANDLE(HYDROData_Stream,HYDROData_NaturalObject)
94 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_Stream,HYDROData_NaturalObject)
95
96
97 HYDROData_Stream::HYDROData_Stream()
98 : HYDROData_NaturalObject()
99 {
100 }
101
102 HYDROData_Stream::~HYDROData_Stream()
103 {
104 }
105
106 QStringList HYDROData_Stream::DumpToPython( MapOfTreatedObjects& theTreatedObjects ) const
107 {
108   QStringList aResList = dumpObjectCreation( theTreatedObjects );
109   QString aName = GetObjPyName();
110
111   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
112   setPythonReferenceObject( theTreatedObjects, aResList, aHydAxis, "SetHydraulicAxis" );
113
114   HYDROData_SequenceOfObjects aSeqOfProfiles = GetProfiles();
115   for ( int i = 1, aNb = aSeqOfProfiles.Size(); i <= aNb; ++i )
116   {
117     const Handle(HYDROData_Entity) aProfile = aSeqOfProfiles.Value( i );
118     setPythonReferenceObject( theTreatedObjects, aResList, aProfile, "AddProfile" );
119   }
120
121   // Set bottom polyline if exists
122   const Handle(HYDROData_Polyline3D) aBottomPolyline = GetBottomPolyline();
123   if ( !aBottomPolyline.IsNull() ) {
124     setPythonReferenceObject( theTreatedObjects, aResList, aBottomPolyline, "SetBottomPolyline" );
125   }
126
127   aResList << QString( "" );
128   aResList << QString( "%1.Update();" ).arg( aName );
129   aResList << QString( "" );
130
131   return aResList;
132 }
133
134 HYDROData_SequenceOfObjects HYDROData_Stream::GetAllReferenceObjects() const
135 {
136   HYDROData_SequenceOfObjects aResSeq = HYDROData_Object::GetAllReferenceObjects();
137
138   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
139   if ( !aHydAxis.IsNull() )
140     aResSeq.Append( aHydAxis );
141
142   HYDROData_SequenceOfObjects aSeqOfProfiles = GetProfiles();
143   aResSeq.Append( aSeqOfProfiles );
144
145   return aResSeq;
146 }
147
148 TopoDS_Shape HYDROData_Stream::GetTopShape() const
149 {
150   return getTopShape();
151 }
152
153 TopoDS_Shape HYDROData_Stream::GetShape3D() const
154 {
155   return getShape3D();
156 }
157
158 Handle(Geom_BSplineCurve) HYDROData_Stream::buildInterpolationCurve( 
159   const Handle(TColgp_HArray1OfPnt)& theArrayOfPnt )
160 {
161   Handle(Geom_BSplineCurve) aBSpline;
162   GeomAPI_Interpolate anInterpolator (theArrayOfPnt, Standard_False, 1.0e-5); 
163   anInterpolator.Perform() ;
164   if (anInterpolator.IsDone()) 
165     aBSpline = anInterpolator.Curve();
166   return aBSpline; 
167 }
168
169 void HYDROData_Stream::Update()
170 {
171   updateProfilesOrder();
172
173   // Update bottom polyline if exists
174   const Handle(HYDROData_Polyline3D) aBottomPolyline = GetBottomPolyline();
175   if ( !aBottomPolyline.IsNull() ) {
176     if ( GenerateBottomPolyline() ) {
177       Handle(HYDROData_PolylineXY) aPolylineXY = aBottomPolyline->GetPolylineXY();
178       if ( !aPolylineXY.IsNull() ) {
179         aPolylineXY->Update();
180       }
181       aBottomPolyline->Update();
182     }
183   }
184
185   UpdatePrs();
186 }
187
188 bool HYDROData_Stream::IsHas2dPrs() const
189 {
190   return true;
191 }
192
193 bool HYDROData_Stream::CreatePresentations( const Handle(HYDROData_PolylineXY)& theHydAxis,
194                                             const HYDROData_SequenceOfObjects&  theProfiles,
195                                             PrsDefinition&                      thePrs )
196 {
197   if ( theHydAxis.IsNull() || theProfiles.Length() < 2 )
198     return false;
199
200   Handle(TColgp_HArray1OfPnt) anArrayOfFPnt    = new TColgp_HArray1OfPnt(1, theProfiles.Length());
201   Handle(TColgp_HArray1OfPnt) anArrayOfLPnt    = new TColgp_HArray1OfPnt(1, theProfiles.Length());  
202   Handle(TopTools_HArray1OfShape) anArrOfProfiles = new TopTools_HArray1OfShape(1, theProfiles.Length());
203   Handle(TopTools_HArray1OfShape) anArrOf2DProfiles = new TopTools_HArray1OfShape(1, theProfiles.Length());
204
205   // Pre-processing
206   HYDROData_SequenceOfObjects::Iterator anIter( theProfiles );
207   for (int i=1 ; anIter.More(); anIter.Next(),i++ )
208   {
209     Handle(HYDROData_Profile) aProfile =
210       Handle(HYDROData_Profile)::DownCast( anIter.Value() );
211     if ( aProfile.IsNull() )
212       continue;
213
214     const TopoDS_Shape& aProf3d = aProfile->GetShape3D();
215     gp_XY aPnt1, aPnt2;
216     if ( !aProfile->GetLeftPoint( aPnt1, false ) || !aProfile->GetRightPoint( aPnt2, false ) )
217       continue;
218
219     anArrOfProfiles->SetValue(i,aProfile->GetShape3D());//aProfile->GetTopShape();
220     anArrOf2DProfiles->SetValue(i,aProfile->GetTopShape());
221
222     gp_Pnt aCurFP, aCurLP;
223     TopoDS_Vertex aV1, aV2;
224     TopExp::Vertices(TopoDS::Wire(aProf3d), aV1, aV2);
225        gp_Pnt aP1 = BRep_Tool::Pnt(aV1);
226     if(aP1.X() == aPnt1.X() && aP1.Y() == aPnt1.Y())
227       aCurFP = aP1;
228     else
229       aCurLP = aP1;
230     aP1 = BRep_Tool::Pnt(aV2);
231     if(aP1.X() == aPnt2.X() && aP1.Y() == aPnt2.Y())
232       aCurLP = aP1;
233     else
234       aCurFP = aP1;
235     anArrayOfFPnt->SetValue(i,aCurFP);
236     anArrayOfLPnt->SetValue(i,aCurLP);
237   }
238
239   return CreatePresentations( anArrayOfFPnt, anArrayOfLPnt, anArrOfProfiles, anArrOf2DProfiles, thePrs );
240 }
241
242 void HYDROData_Stream::UpdatePrs()
243 {
244   HYDROData_NaturalObject::Update();
245
246   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
247   HYDROData_SequenceOfObjects aRefProfiles = GetProfiles();
248
249   PrsDefinition aResultPrs;
250   if ( !CreatePresentations( aHydAxis, aRefProfiles, aResultPrs ) )
251     return;
252
253   SetShape3D( aResultPrs.myPrs3D );
254   SetTopShape( aResultPrs.myPrs2D );
255
256   // Create the stream groups
257   QString aLeftGroupName = GetName() + "_Left_Bank";
258
259   Handle(HYDROData_ShapesGroup) aLeftGroup = createGroupObject();
260   aLeftGroup->SetName( aLeftGroupName );
261   aLeftGroup->AddShape( aResultPrs.myLeftBank );
262
263   QString aRightGroupName = GetName() + "_Right_Bank";
264
265   Handle(HYDROData_ShapesGroup) aRightGroup = createGroupObject();
266   aRightGroup->SetName( aRightGroupName );
267   aRightGroup->AddShape( aResultPrs.myRightBank );
268
269   QString anInGroupName = GetName() + "_Inlet";
270
271   Handle(HYDROData_ShapesGroup) anInGroup = createGroupObject();
272   anInGroup->SetName( anInGroupName );
273   anInGroup->AddShape( aResultPrs.myInlet );
274
275   QString anOutGroupName = GetName() + "_Outlet";
276   
277   Handle(HYDROData_ShapesGroup) anOutGroup = createGroupObject();
278   anOutGroup->SetName( anOutGroupName );
279   anOutGroup->AddShape( aResultPrs.myOutlet );
280 }
281
282 QColor HYDROData_Stream::DefaultFillingColor()
283 {
284   return QColor( Qt::green );
285 }
286
287 QColor HYDROData_Stream::DefaultBorderColor()
288 {
289   return QColor( Qt::transparent );
290 }
291
292 bool HYDROData_Stream::IsValidAsAxis( const Handle(HYDROData_PolylineXY)& theHydAxis )
293 {
294   if ( theHydAxis.IsNull() )
295     return false;
296
297   TopoDS_Shape aHydraulicShape = theHydAxis->GetShape();
298   if ( aHydraulicShape.IsNull() || 
299        aHydraulicShape.ShapeType() != TopAbs_WIRE ||
300        BRep_Tool::IsClosed( aHydraulicShape ) )
301     return false; // The polyline must be a single not closed wire
302
303   return true;
304 }
305
306 TopoDS_Shape HYDROData_Stream::GetLeftShape() const
307 {
308   HYDROData_SequenceOfObjects aGroups = GetGroups();
309   return HYDROData_Tool::getFirstShapeFromGroup( aGroups, 1);
310 }
311
312 TopoDS_Shape HYDROData_Stream::GetRightShape() const
313 {
314   HYDROData_SequenceOfObjects aGroups = GetGroups();
315   return HYDROData_Tool::getFirstShapeFromGroup( aGroups, 2);
316 }
317
318 TopoDS_Shape HYDROData_Stream::GetInletShape() const
319 {
320   HYDROData_SequenceOfObjects aGroups = GetGroups();
321   return HYDROData_Tool::getFirstShapeFromGroup( aGroups, 3);
322 }
323
324 TopoDS_Shape HYDROData_Stream::GetOutletShape() const
325 {
326   HYDROData_SequenceOfObjects aGroups = GetGroups();
327   return HYDROData_Tool::getFirstShapeFromGroup( aGroups, 4);
328 }
329
330 QColor HYDROData_Stream::getDefaultFillingColor() const
331 {
332   return DefaultFillingColor();
333 }
334
335 QColor HYDROData_Stream::getDefaultBorderColor() const
336 {
337   return DefaultBorderColor();
338 }
339
340 bool HYDROData_Stream::SetHydraulicAxis( const Handle(HYDROData_PolylineXY)& theAxis )
341 {
342   if ( !IsValidAsAxis( theAxis ) )
343     return false;
344
345   Handle(HYDROData_PolylineXY) aPrevAxis = GetHydraulicAxis();
346   if ( IsEqual( aPrevAxis, theAxis ) )
347     return true;
348
349   SetReferenceObject( theAxis, DataTag_HydraulicAxis );
350
351   // Update the order of profiles
352   updateProfilesOrder();
353
354   // Indicate model of the need to update the stream presentation
355   SetToUpdate( true );
356
357   return true;
358 }
359
360 Handle(HYDROData_PolylineXY) HYDROData_Stream::GetHydraulicAxis() const
361 {
362   return Handle(HYDROData_PolylineXY)::DownCast( 
363            GetReferenceObject( DataTag_HydraulicAxis ) );
364 }
365
366 void HYDROData_Stream::RemoveHydraulicAxis()
367 {
368   Handle(HYDROData_PolylineXY) aPrevAxis = GetHydraulicAxis();
369   if ( aPrevAxis.IsNull() )
370     return;
371
372   ClearReferenceObjects( DataTag_HydraulicAxis );
373
374   // We remove the reference profiles
375   RemoveProfiles();
376
377   // Indicate model of the need to update the stream presentation
378   SetToUpdate( true );
379 }
380
381 bool HYDROData_Stream::HasIntersection( const Handle(HYDROData_Profile)& theProfile,
382                                         const TopoDS_Face&               thePlane,
383                                         Standard_Real&                   theOutPar ) const
384 {
385   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
386   return HasIntersection( aHydAxis, theProfile, thePlane, theOutPar );
387 }
388
389 bool HYDROData_Stream::HasIntersection( const Handle(HYDROData_PolylineXY)& theHydAxis, 
390                                         const Handle(HYDROData_Profile)&    theProfile, 
391                                         const TopoDS_Face&                  thePlane,
392                                         Standard_Real&                      theOutPar )
393 {
394   if ( theProfile.IsNull() || !IsValidAsAxis( theHydAxis ) )
395     return false; 
396
397   TopoDS_Wire aHydraulicWire = TopoDS::Wire( theHydAxis->GetShape() ); //guide line
398   TopoDS_Wire aProfileWire = TopoDS::Wire( theProfile->GetTopShape() );
399   if ( aHydraulicWire.IsNull() || aProfileWire.IsNull() )
400     return false;
401
402   BRepProj_Projection aProjector (aProfileWire, thePlane, gp::OZ().Direction());
403   if(!aProjector.IsDone())
404     return false;
405   TopoDS_Shape aPrjProfile = aProjector.Shape();
406   if(aPrjProfile.IsNull())
407     return false;
408   TopoDS_Vertex aV1, aV2;
409   if(aPrjProfile.ShapeType() == TopAbs_EDGE)
410     TopExp::Vertices(TopoDS::Edge(aPrjProfile), aV1, aV2);
411   else if(aPrjProfile.ShapeType() == TopAbs_WIRE)  
412     TopExp::Vertices(TopoDS::Wire(aPrjProfile), aV1, aV2);
413   else if(aPrjProfile.ShapeType() == TopAbs_COMPOUND){
414     TopExp_Explorer anExp(aPrjProfile, TopAbs_WIRE);
415     if(anExp.More()) {
416       TopExp::Vertices(TopoDS::Wire(anExp.Current()), aV1, aV2);
417     } else {
418       anExp.Init(aPrjProfile, TopAbs_EDGE);
419       if(anExp.More()) {
420         TopExp::Vertices(TopoDS::Edge(anExp.Current()), aV1, aV2);
421       }
422     }
423   }
424   if(aV1.IsNull() || aV2.IsNull())
425     return false;
426   gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
427   gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
428   aPnt1.SetZ(0.0);
429   aPnt2.SetZ(0.0);
430   BRepBuilderAPI_MakeEdge aMk(aPnt1, aPnt2); 
431   if(!aMk.IsDone())
432     return false;
433   const TopoDS_Edge& anEdg2 = aMk.Edge();//Section edge
434   Standard_Integer aNum(0);
435   
436   TopExp_Explorer anExplo(aHydraulicWire, TopAbs_EDGE);
437   for(;anExplo.More();anExplo.Next()) aNum++;
438   // check for self-intersection
439   const Standard_Real SquareTolerance = Precision::Confusion()*Precision::Confusion();
440   Standard_Boolean hasInt(false);
441   Standard_Real aSqDist(DBL_MAX);
442   Standard_Integer anIndx(0);
443   BRepExtrema_ExtCC aCC;
444   aCC.Initialize(anEdg2);
445   theOutPar = 0.0;
446   anExplo.Init(aHydraulicWire, TopAbs_EDGE);
447   for(Standard_Integer j=1;anExplo.More();anExplo.Next(),j++) {
448     const TopoDS_Edge& anEdg1 = TopoDS::Edge(anExplo.Current());
449     if(anEdg1.IsNull())
450       continue;
451     Standard_Boolean hasSol(false);
452     aCC.Perform(anEdg1);
453     if(aCC.IsDone()) {
454     // find minimal dist
455     for(Standard_Integer i=1; i<= aCC.NbExt();i++)
456       if(aCC.SquareDistance(i) < aSqDist) {
457         aSqDist = aCC.SquareDistance(i);
458         anIndx = i;
459         hasSol = true;
460       }  
461     }
462     if(hasSol) {
463       if(aSqDist <= SquareTolerance) { // hasInt
464         const gp_Pnt& aPnt = aCC.PointOnE1(anIndx);
465         if(aNum > 1) {
466           TopExp::Vertices(anEdg1, aV1, aV2, Standard_True);
467           theOutPar += BRep_Tool::Pnt(aV1).Distance(aPnt);
468         } else {
469           Standard_Real aPar = aCC.ParameterOnE1(anIndx);
470           theOutPar = aPar;
471         }
472         hasInt = true;
473         break;
474       } else {
475           // no ints-n
476         if(aNum > 1) {
477           TopExp::Vertices(anEdg1, aV1, aV2);
478           theOutPar += BRep_Tool::Pnt(aV1).Distance(BRep_Tool::Pnt(aV2));
479         }
480       }
481     } else if(aNum > 1) {
482       TopExp::Vertices(anEdg1, aV1, aV2);
483       theOutPar += BRep_Tool::Pnt(aV1).Distance(BRep_Tool::Pnt(aV2));
484     }
485   }
486   if(hasInt)
487     return true;
488   return false;
489 }
490
491 bool HYDROData_Stream::AddProfile( const Handle(HYDROData_Profile)& theProfile )
492 {
493   if ( theProfile.IsNull() )
494     return false;
495
496   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
497   if ( aHydAxis.IsNull() )
498     return false;
499
500   TopoDS_Face aPlane;
501   if(!BuildFace(aHydAxis, aPlane))
502     return false;
503
504   Standard_Real aPar(.0);
505   if ( HasReference( theProfile, DataTag_Profile ) || !HasIntersection( theProfile, aPlane, aPar ) )
506     return false; // Object is already in reference list or it has no intersection
507   
508   int aProfileIndex = insertParameter( aPar );
509   insertProfileInToOrder( theProfile, aProfileIndex );
510   
511   // Indicate model of the need to update the stream presentation
512   SetToUpdate( true );
513
514   return true;
515 }
516
517 bool HYDROData_Stream::SetProfiles( const HYDROData_SequenceOfObjects& theProfiles,
518                                     const bool&                        theIsToOrder )
519 {
520   if ( theIsToOrder )
521   {
522     for ( int i = 1; i <= theProfiles.Length(); ++i )
523     {
524       Handle(HYDROData_Profile) aProfile = 
525         Handle(HYDROData_Profile)::DownCast( theProfiles.Value( i ) );
526       if ( aProfile.IsNull() )
527         continue;
528
529       if ( !AddProfile( aProfile ) )
530         return false;
531     }
532   }
533   else // Just store the sequence of objects as is
534   {
535     bool anIsToUpdate = true;
536
537     HYDROData_SequenceOfObjects anOldProfiles = GetProfiles();
538     if ( anOldProfiles.Length() == theProfiles.Length() )
539     {
540       anIsToUpdate = false;
541
542       for ( int i = 1; i <= theProfiles.Length(); ++i )
543       {
544         Handle(HYDROData_Entity) anOldProfile = anOldProfiles.Value( i );
545         Handle(HYDROData_Entity) aNewProfile = theProfiles.Value( i );
546         if ( !IsEqual( anOldProfile, aNewProfile ) )
547         {
548           anIsToUpdate = true;
549           break;
550         }
551       }
552     }
553     
554     SetReferenceObjects( theProfiles, DataTag_Profile );
555
556     if ( anIsToUpdate )
557       SetToUpdate( true );
558   }
559
560   return true;
561 }
562
563 HYDROData_SequenceOfObjects HYDROData_Stream::GetProfiles() const
564 {
565   return GetReferenceObjects( DataTag_Profile );
566 }
567
568 bool HYDROData_Stream::RemoveProfile( const Handle(HYDROData_Profile)& theProfile )
569 {
570   if ( theProfile.IsNull() )
571     return false;
572
573   int aProfileIndex = -1;
574
575   HYDROData_SequenceOfObjects aRefProfiles = GetProfiles();
576   HYDROData_SequenceOfObjects::Iterator anIter( aRefProfiles );
577   for ( int i = 0 ; anIter.More(); anIter.Next(), ++i )
578   {
579     Handle(HYDROData_Profile) aProfile =
580       Handle(HYDROData_Profile)::DownCast( anIter.Value() );
581     if ( aProfile.IsNull() )
582       continue;
583
584     if ( IsEqual( theProfile, aProfile ) )
585     {
586       aProfileIndex = i;
587       break;
588     }
589   }
590
591   if ( aProfileIndex == -1 )
592     return false;
593
594   RemoveReferenceObject( theProfile->Label(), DataTag_Profile );
595
596   // Remove parameter for removed profile
597   removeParameter( aProfileIndex );
598
599   // Indicate model of the need to update the stream presentation
600   SetToUpdate( true );
601
602   return true;
603 }
604
605 void HYDROData_Stream::RemoveProfiles()
606 {
607   bool anIsToUpdate = IsMustBeUpdated() || NbReferenceObjects( DataTag_Profile ) > 0;
608
609   ClearReferenceObjects( DataTag_Profile );
610
611   // Remove the parameters array
612   removeParametersArray();
613
614   // Indicate model of the need to update the stream presentation
615   SetToUpdate( anIsToUpdate );
616 }
617
618 void HYDROData_Stream::insertProfileInToOrder( const Handle(HYDROData_Profile)& theProfile,
619                                                const int                        theBeforeIndex )
620 {
621   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
622   if ( theProfile.IsNull() || aHydAxis.IsNull() )
623     return; 
624
625   TopoDS_Wire aHydraulicWire = TopoDS::Wire( aHydAxis->GetShape() );
626   TopoDS_Wire aProfileWire = TopoDS::Wire( theProfile->GetTopShape() );
627   if ( aHydraulicWire.IsNull() || aProfileWire.IsNull() )
628     return;
629
630   if ( theBeforeIndex == -1 )
631     AddReferenceObject( theProfile, DataTag_Profile );
632   else
633     InsertReferenceObject( theProfile, DataTag_Profile, theBeforeIndex );
634 }
635
636 bool HYDROData_Stream::BuildFace( const Handle(HYDROData_PolylineXY)& theHydAxis,
637                                   TopoDS_Face&                        thePlane )
638 {
639   if ( !IsValidAsAxis( theHydAxis ) )
640     return false;
641
642   TopoDS_Wire aHydraulicWire = TopoDS::Wire( theHydAxis->GetShape() );
643
644   gp_Ax2 aX2(gp::XOY());
645   gp_Ax3 aX3(aX2);
646   gp_Pln aPln(aX3);   
647   Bnd_Box B;
648   BRepBndLib::Add(aHydraulicWire,B);
649   Standard_Real axmin,aymin,azmin,axmax,aymax,azmax;
650   B.Get(axmin,aymin,azmin,axmax,aymax,azmax);
651   BRepBuilderAPI_MakeFace aMkr(aPln, axmin-500., axmax+500., aymin-500., aymax+500.); // to be tuned later according max/ Profile deviation
652   if(!aMkr.IsDone() || aMkr.Shape().IsNull()) return false;
653   thePlane = TopoDS::Face(aMkr.Shape());
654   return true;
655 }
656
657 void HYDROData_Stream::updateProfilesOrder()
658 {
659   HYDROData_SequenceOfObjects aRefProfiles = GetProfiles();
660   if ( aRefProfiles.IsEmpty() )
661     return;
662
663   // At first we remove all profiles from order
664   RemoveProfiles();
665
666   Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
667   if ( aHydAxis.IsNull() )
668     return; 
669
670   TopoDS_Face aPlane;
671   if ( !BuildFace( aHydAxis, aPlane ) )
672     return;
673
674   Standard_Real aPar( .0 );
675
676 #ifdef DEB_HASINT
677   BRep_Builder aBB;
678   TopoDS_Compound aCmp;
679   aBB.MakeCompound(aCmp);
680 #endif
681
682   HYDROData_DataMapOfRealOfHDProfile aDM;  
683   TColStd_ListOfReal aList;
684   HYDROData_SequenceOfObjects::Iterator anIter( aRefProfiles );
685   for (int i = 1 ; anIter.More(); anIter.Next(), i++ )
686   {
687     Handle(HYDROData_Profile) aProfile =
688       Handle(HYDROData_Profile)::DownCast( anIter.Value() );
689 #ifdef DEB_HASINT
690   TopoDS_Wire aProfileWire = TopoDS::Wire( aProfile->GetTopShape() );
691   aBB.Add( aCmp, aProfileWire ); 
692 #endif
693     if ( aProfile.IsNull() || !HasIntersection( aProfile, aPlane, aPar ) )
694       continue;
695     
696     aDM.Bind( aPar, aProfile );
697     aList.Append( aPar );
698   }
699   
700   if ( aList.IsEmpty() )
701     return;
702
703   TColStd_Array1OfReal anArr( 1, aList.Extent() );
704
705   TColStd_ListIteratorOfListOfReal it( aList );
706   for ( int j = 1; it.More(); it.Next(), j++ )
707     anArr( j ) = it.Value();
708
709   // sorting
710   if ( aList.Extent() > 1 )
711   {
712     TCollection_CompareOfReal Compar;
713     SortTools_QuickSortOfReal::Sort( anArr, Compar );
714
715     for (int j = 1; j <= anArr.Length(); j++) {
716       const Standard_Real aKey =  anArr(j);
717       const Handle(HYDROData_Profile)& aProfile = aDM.Find(aKey);
718       insertProfileInToOrder( aProfile );
719     }
720   } else if ( aList.Extent() == 1 ) {
721      const Standard_Real aKey = aList.Last();
722      const Handle(HYDROData_Profile)& aProfile = aDM.Find(aKey);
723      insertProfileInToOrder( aProfile );
724   } 
725
726   setParametersArray( anArr );
727
728 #ifdef DEB_HASINT
729   TopoDS_Wire aHydraulicWire = TopoDS::Wire( aHydAxis->GetShape() );
730   BRepTools::Write(aHydraulicWire, "Path.brep");
731   BRepTools::Write(aCmp, "Prof.brep");
732 #endif
733 }
734
735 ObjectKind HYDROData_Stream::getAltitudeObjectType() const
736 {
737   return KIND_STREAM_ALTITUDE;
738 }
739
740 void HYDROData_Stream::setParametersArray( const TColStd_Array1OfReal& theArray )
741 {
742   if ( theArray.Length() == 0 )
743   {
744     removeParametersArray();
745     return;
746   }
747
748   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray );
749   
750   Handle(TDataStd_RealArray) aParamsArray = 
751     TDataStd_RealArray::Set( aLabel, theArray.Lower(), theArray.Upper() );
752
753   for ( int i = theArray.Lower(), n = theArray.Upper(); i <= n; ++i )
754   {
755     const Standard_Real& aParam = theArray( i );
756     aParamsArray->SetValue( i, aParam );
757   }
758 }
759
760 TColStd_Array1OfReal* HYDROData_Stream::getParametersArray() const
761 {
762   TColStd_Array1OfReal* anArray = NULL;
763
764   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray, false );
765   if ( !aLabel.IsNull() )
766   {
767     Handle(TDataStd_RealArray) aParamsArray;
768     if ( aLabel.FindAttribute( TDataStd_RealArray::GetID(), aParamsArray ) )
769     {
770       anArray = new TColStd_Array1OfReal( aParamsArray->Lower(), aParamsArray->Upper() );
771       for ( int i = aParamsArray->Lower(), n = aParamsArray->Upper(); i <= n; ++i )
772       {
773         const Standard_Real& aParam = aParamsArray->Value( i );
774         anArray->SetValue( i, aParam );
775       }
776     }
777   }
778
779   return anArray;
780 }
781
782 void HYDROData_Stream::removeParametersArray()
783 {
784   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray, false );
785   if ( !aLabel.IsNull() )
786     aLabel.ForgetAllAttributes();
787 }
788
789 int HYDROData_Stream::insertParameter( const Standard_Real& theParam )
790 {
791   int aResIndex = -1;
792
793   TColStd_Array1OfReal* anArr = getParametersArray();
794   if ( anArr )
795   {
796     aResIndex = 0;
797
798     TColStd_Array1OfReal aNewArr( anArr->Lower(), anArr->Upper() + 1 );
799
800     bool isInserted = false;
801     for ( int i = anArr->Lower(), j = i, n = anArr->Upper(); i <= n; ++i, ++j )
802     {
803       const Standard_Real& aStoredParam = anArr->Value( i );
804       if ( !isInserted )
805       {
806         if ( theParam > aStoredParam )
807         {
808           aResIndex++;
809         }
810         else
811         {
812           aNewArr( j ) = theParam;
813           isInserted = true;
814           ++j;
815         }
816       }
817
818       aNewArr( j ) = aStoredParam;
819     }
820
821     if ( !isInserted )
822     {
823       aResIndex = -1;
824       aNewArr( aNewArr.Upper() ) = theParam;
825     }
826     
827     setParametersArray( aNewArr );
828     delete anArr;
829   }
830   else
831   {
832     TColStd_Array1OfReal aNewArr( 1, 1 );
833     aNewArr.SetValue( 1, theParam );
834     setParametersArray( aNewArr );
835   }
836
837   return aResIndex;
838 }
839
840 void HYDROData_Stream::removeParameter( const int& theIndex )
841 {
842   TDF_Label aLabel = myLab.FindChild( DataTag_ParamsArray, false );
843   if ( aLabel.IsNull() )
844     return;
845
846   Handle(TDataStd_RealArray) aParamsArray;
847   if ( !aLabel.FindAttribute( TDataStd_RealArray::GetID(), aParamsArray ) )
848     return;
849
850   if ( aParamsArray->Length() == 1 )
851   {
852     removeParametersArray();
853     return;
854   }
855
856   TColStd_Array1OfReal aNewArr( aParamsArray->Lower(), aParamsArray->Upper() - 1 );
857
858   for ( int i = aParamsArray->Lower(), j = i, k = 0, n = aParamsArray->Upper(); i <= n; ++i, ++k )
859   {
860     const Standard_Real& aStoredParam = aParamsArray->Value( i );
861     if ( k == theIndex )
862       continue;
863
864     aNewArr.SetValue( j, aStoredParam );
865     ++j;
866   }
867
868   setParametersArray( aNewArr );
869 }
870
871 bool HYDROData_Stream::GenerateBottomPolyline()
872 {
873   // Get the document
874   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
875   if ( aDocument.IsNull() ) {
876     return false;
877   }
878
879   // Collect bottom points ( one bottom point from each profile of the stream )
880   HYDROData_Profile::ProfilePoints aBottomPoints;
881   
882   HYDROData_SequenceOfObjects aSeqOfProfiles = GetProfiles();
883   for ( int i = 1, aNb = aSeqOfProfiles.Size(); i <= aNb; i++ ) {
884     const Handle(HYDROData_Profile) aProfile = 
885       Handle(HYDROData_Profile)::DownCast( aSeqOfProfiles.Value( i ) );
886     if ( aProfile.IsNull() ) {
887       continue;
888     }
889     
890     aBottomPoints.Append( aProfile->GetBottomPoint() );
891   }
892
893   int aNbBottomPoints = aBottomPoints.Size();
894
895   if ( aNbBottomPoints < 2 ) {
896     return false;
897   }
898
899   // Create bottom polyline object if the stream doesn't contain it yet
900   Handle(HYDROData_Polyline3D) aBottom = GetBottomPolyline();
901   if ( aBottom.IsNull() ) {
902     aBottom = Handle(HYDROData_Polyline3D)::DownCast( aDocument->CreateObject( KIND_POLYLINE ) );  
903     QString aBaseName = GetName() + "_bottom";
904     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName, QStringList(), true );
905     aBottom->SetName( aName );
906
907     SetReferenceObject( aBottom, DataTag_BottomPolyline );
908   }
909   
910   // Create 2D polyline if the bottom polyline doesn't contain it yet
911   Handle(HYDROData_PolylineXY) aPolylineXY = aBottom->GetPolylineXY();
912   if ( aPolylineXY.IsNull() ) {
913     aPolylineXY = Handle(HYDROData_PolylineXY)::DownCast( aDocument->CreateObject( KIND_POLYLINEXY ) );
914     QString aBaseName = GetName() + "_bottom_2d";
915     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName, QStringList(), true );
916     aPolylineXY->SetName( aName );
917     aBottom->SetPolylineXY( aPolylineXY, false );
918   }
919
920   aPolylineXY->RemoveSections();
921   aPolylineXY->AddSection( "", HYDROData_PolylineXY::SECTION_SPLINE, false );
922   
923   // Create profile if the bottom polyline doesn't contain it yet
924   Handle(HYDROData_ProfileUZ) aProfileUZ = aBottom->GetProfileUZ();
925   if ( aProfileUZ.IsNull() ) {
926     Handle(HYDROData_Profile) aProfile = 
927       Handle(HYDROData_Profile)::DownCast( aDocument->CreateObject( KIND_PROFILE ) );
928     QString aBaseName = GetName() + "_bottom_profile";
929     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName, QStringList(), true );
930     aProfile->SetName( aName );
931     aProfileUZ = aProfile->GetProfileUZ( true );
932     aBottom->SetProfileUZ( aProfileUZ );
933   }
934   
935   aProfileUZ->RemoveSection( 0 );
936
937   aProfileUZ->CalculateAndAddPoints(aBottomPoints, aPolylineXY);
938   
939   return true;
940 }
941
942 Handle(HYDROData_Polyline3D) HYDROData_Stream::GetBottomPolyline() const
943 {
944   return Handle(HYDROData_Polyline3D)::DownCast( 
945            GetReferenceObject( DataTag_BottomPolyline ) );
946 }
947
948 bool HYDROData_Stream::SetBottomPolyline( const Handle(HYDROData_Polyline3D)& theBottom )
949 {
950   if ( theBottom.IsNull() ) {
951     return false;
952   }
953
954   SetReferenceObject( theBottom, DataTag_BottomPolyline );
955
956   return true;
957 }
958
959 bool HYDROData_Stream::Interpolate( HYDROData_IProfilesInterpolator* theInterpolator )
960 {
961   // Get the document
962   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
963   if ( aDocument.IsNull() ) {
964     return false;
965   }
966   
967   if ( theInterpolator->GetCalculatedProfilesNumber() < 1 ) {
968     theInterpolator->Calculate();
969   }
970
971   if ( theInterpolator->GetErrorCode() != OK ) {
972     return false;
973   }
974
975   bool isOK = true;
976
977   for ( int aProfileInd = 0; aProfileInd < theInterpolator->GetCalculatedProfilesNumber(); aProfileInd++ ) {
978     // Get calculated point coordinates
979     HYDROData_Profile::ProfilePoints aResultPoints = theInterpolator->GetResultProfilePoints( aProfileInd );
980     if ( aResultPoints.IsEmpty() ) {
981       isOK = false;
982       continue;
983     }
984         
985     // Create profile object
986     Handle(HYDROData_Profile) aProfile = 
987       Handle(HYDROData_Profile)::DownCast( aDocument->CreateObject( KIND_PROFILE ) );
988     QString aBaseName = GetName() + "_interp_profile";
989     QString aName = HYDROData_Tool::GenerateObjectName( aDocument, aBaseName );
990     aProfile->SetName( aName );
991
992     // Fill the profile with points
993     aProfile->SetProfilePoints( aResultPoints );
994
995     // Add profile to the stream
996     bool isAdded = AddProfile( aProfile );
997     if ( !isAdded ) {
998       aProfile->Remove();
999     }
1000     else
1001       aProfile->Update();
1002   }
1003
1004   if ( isOK )
1005     Update();
1006
1007   return isOK;
1008 }
1009
1010 void HYDROData_Stream::CopyTo( const Handle(HYDROData_Entity)& theDestination,
1011                                bool isGenerateNewName ) const
1012 {
1013   // Get the document
1014   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
1015   if ( aDocument.IsNull() ) {
1016     return;
1017   }
1018
1019   // Call base method
1020   HYDROData_Entity::CopyTo( theDestination, isGenerateNewName );
1021
1022   Handle(HYDROData_Stream) aStreamCopy = 
1023     Handle(HYDROData_Stream)::DownCast( theDestination );
1024
1025   // Copy bottom polyline if exists
1026   if ( !aStreamCopy.IsNull() ) {
1027     const Handle(HYDROData_Polyline3D) aBottom = GetBottomPolyline();
1028     if ( !aBottom.IsNull() ) {
1029       aStreamCopy->ClearReferenceObjects( DataTag_BottomPolyline );
1030       aStreamCopy->GenerateBottomPolyline();
1031       const Handle(HYDROData_Polyline3D) aBottomCopy = aStreamCopy->GetBottomPolyline();
1032       if ( !aBottomCopy.IsNull() && !aBottomCopy->GetPolylineXY().IsNull() ) {
1033         aBottomCopy->GetPolylineXY()->Update();
1034         aBottomCopy->Update();
1035       }
1036     }
1037   }
1038 }
1039
1040 bool HYDROData_Stream::CreatePresentations( const Handle(TColgp_HArray1OfPnt)     theArrayOfFPnt,
1041                                             const Handle(TColgp_HArray1OfPnt)     theArrayOfLPnt,
1042                                             const Handle(TopTools_HArray1OfShape) theArrOfProfiles,
1043                                             const Handle(TopTools_HArray1OfShape) theArrOf2DProfiles,
1044                                             PrsDefinition&                        thePrs )
1045 {
1046   if ( theArrayOfFPnt.IsNull() || theArrayOfLPnt.IsNull() || theArrOfProfiles.IsNull() ) {
1047     return false;
1048   }
1049
1050   if ( theArrayOfFPnt->Length() != theArrayOfLPnt->Length() ) {
1051     return false;
1052   }
1053   
1054   // Construct of the 3D presentation
1055   Handle(Geom_BSplineCurve) aBSpline = buildInterpolationCurve (theArrayOfFPnt);
1056   if(aBSpline.IsNull())
1057     return false;
1058
1059   TopoDS_Edge anEdgLeft, anEdgRight;
1060   
1061   BRepBuilderAPI_MakeEdge aMakeEdge(aBSpline);
1062   if(aMakeEdge.IsDone()) 
1063     anEdgLeft = aMakeEdge.Edge();
1064
1065   if(anEdgLeft.IsNull())
1066     return false;
1067
1068   aBSpline.Nullify();
1069   aBSpline = buildInterpolationCurve (theArrayOfLPnt);  
1070   if(aBSpline.IsNull())
1071     return false;
1072
1073   aMakeEdge.Init(aBSpline);
1074   if(aMakeEdge.IsDone()) 
1075     anEdgRight = aMakeEdge.Edge();
1076
1077   if(anEdgRight.IsNull())
1078     return false;
1079
1080   BRep_Builder aBB;
1081   TopoDS_Compound aCmp;
1082   aBB.MakeCompound(aCmp);
1083   for (int i=1 ; i < theArrOfProfiles->Length() +1; i++ )  
1084     aBB.Add(aCmp, theArrOfProfiles->Value(i));
1085
1086   aBB.Add(aCmp,anEdgLeft);
1087   aBB.Add(aCmp,anEdgRight);
1088   BRepCheck_Analyzer aCh(aCmp);
1089   if(aCh.IsValid())
1090     thePrs.myPrs3D = aCmp;
1091 #ifdef DEB_UPDATE
1092   else {
1093     BRepTools::Write(aCmp, "str3d.brep");
1094     thePrs.myPrs3D = aCmp;
1095   }
1096 #endif
1097
1098   // Construct the top presentation
1099   int aNbPoints = theArrayOfFPnt->Length();
1100   Handle(TColgp_HArray1OfPnt) anArrayOfFPnt = new TColgp_HArray1OfPnt(1, aNbPoints);
1101   Handle(TColgp_HArray1OfPnt) anArrayOfLPnt = new TColgp_HArray1OfPnt(1, aNbPoints);  
1102   for( int i=1; i <= aNbPoints; i++ ) {
1103       gp_Pnt aPnt = theArrayOfFPnt->Value(i);
1104       aPnt.SetZ(.0); // make 2d
1105       anArrayOfFPnt->SetValue(i, aPnt);
1106       aPnt = theArrayOfLPnt->Value(i);
1107       aPnt.SetZ(.0);
1108       anArrayOfLPnt->SetValue(i, aPnt);
1109   }
1110
1111   aBSpline.Nullify();
1112   aBSpline = buildInterpolationCurve (anArrayOfFPnt);  
1113   if(aBSpline.IsNull())
1114     return false; 
1115
1116   aMakeEdge.Init(aBSpline);
1117   if(aMakeEdge.IsDone()) 
1118       anEdgLeft = aMakeEdge.Edge();
1119
1120   aBSpline.Nullify();
1121   aBSpline = buildInterpolationCurve (anArrayOfLPnt);  
1122   if(aBSpline.IsNull())
1123     return false; 
1124
1125   aMakeEdge.Init(aBSpline);
1126   if(aMakeEdge.IsDone()) 
1127     anEdgRight = aMakeEdge.Edge();
1128   if(anEdgRight.IsNull())
1129     return false;
1130
1131   BRepBuilderAPI_MakeEdge aMakeEdge2(anArrayOfFPnt->Value(1),anArrayOfLPnt->Value(1));
1132   TopoDS_Edge aBotEdge, aTopEdge;
1133   if(aMakeEdge2.IsDone()) 
1134     aBotEdge = aMakeEdge2.Edge();
1135
1136   BRepBuilderAPI_MakeEdge aMakeEdge3(anArrayOfFPnt->Value(anArrayOfFPnt->Length()),anArrayOfLPnt->Value(anArrayOfLPnt->Length()));
1137   if(aMakeEdge3.IsDone()) 
1138     aTopEdge = aMakeEdge3.Edge();
1139
1140   // Make wire for 2D presentation with updating of corresponding edges
1141   BRepBuilderAPI_MakeWire aMakeWire;
1142   
1143   aMakeWire.Add( aBotEdge );
1144   thePrs.myInlet = aMakeWire.Edge();
1145
1146   aMakeWire.Add( anEdgLeft );
1147   thePrs.myLeftBank = aMakeWire.Edge();
1148
1149   aMakeWire.Add( aTopEdge );
1150   thePrs.myOutlet = aMakeWire.Edge();
1151
1152   aMakeWire.Add( anEdgRight );
1153   thePrs.myRightBank = aMakeWire.Edge();
1154
1155   TopoDS_Wire aSectProfileWire;
1156   if(aMakeWire.IsDone())
1157     aSectProfileWire = aMakeWire.Wire();
1158
1159   BRepBuilderAPI_MakeFace aMakeFace( aSectProfileWire, Standard_True );
1160   TopoDS_Face aFace;
1161   aMakeFace.Build();
1162   if( aMakeFace.IsDone() )
1163     aFace = aMakeFace.Face();
1164
1165   TopoDS_Shape aPrs2D;
1166
1167   if ( !theArrOf2DProfiles.IsNull() ) {
1168     aCmp.Nullify();
1169     aBB.MakeCompound(aCmp);
1170     aBB.Add(aCmp,aFace);
1171     for(int i=1;i <= theArrOf2DProfiles->Length(); i++)
1172       aBB.Add(aCmp, theArrOf2DProfiles->Value(i));
1173
1174     aPrs2D = aCmp;
1175   } else {
1176     aPrs2D = aFace;
1177   }
1178
1179   aCh.Init(aPrs2D);
1180   if(aCh.IsValid())
1181    thePrs.myPrs2D = aPrs2D;
1182 #ifdef DEB_UPDATE
1183   else {
1184     BRepTools::Write(aPrs2D, "str2d.brep");
1185     thePrs.myPrs2D = aPrs2D;
1186   }
1187 #endif
1188
1189   return true;
1190 }