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