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