Salome HOME
refs #1456: correct Python name on dump ECW images
[modules/hydro.git] / src / HYDROData / HYDROData_DTM.cxx
1
2 #include <HYDROData_DTM.h>
3 #include <HYDROData_Profile.h>
4
5 #include <Geom2d_BSplineCurve.hxx>
6 #include <Geom2dAPI_Interpolate.hxx>
7 #include <TColgp_HArray1OfPnt2d.hxx>
8 #include <TColgp_Array1OfVec2d.hxx>
9 #include <TColStd_HArray1OfBoolean.hxx>
10 #include <TopoDS.hxx>
11 #include <TopoDS_Edge.hxx>
12 #include <TopoDS_Wire.hxx>
13 #include <TopExp_Explorer.hxx>
14 #include <BRep_Tool.hxx>
15 #include <gp_Ax3.hxx>
16 #include <Geom_Line.hxx>
17 #include <Geom2d_Line.hxx>
18 #include <Geom2d_TrimmedCurve.hxx>
19 #include <Geom_BSplineCurve.hxx>
20 #include <Geom2d_BSplineCurve.hxx>
21 #include <GeomAPI_Interpolate.hxx>
22 #include <TColStd_Array1OfReal.hxx>
23 #include <TColStd_Array1OfInteger.hxx>
24 #include <TColgp_Array1OfPnt.hxx>
25 #include <TColgp_Array1OfVec.hxx>
26 #include <TColgp_HArray1OfPnt.hxx>
27 #include <Geom2dAPI_InterCurveCurve.hxx>
28 #include <Geom2dAPI_ProjectPointOnCurve.hxx>
29 #include <Geom2dAdaptor_Curve.hxx>
30 #include <GCPnts_AbscissaPoint.hxx>
31 #include <BRepBuilderAPI_MakeEdge.hxx>
32 #include <limits>
33
34 #include <BRepLib_MakeEdge.hxx>
35 #include <BRepLib_MakeWire.hxx>
36 #include <BRep_Builder.hxx>
37 #include <GeomProjLib.hxx>
38 #include <Geom_TrimmedCurve.hxx>
39 #include <BRepTools_WireExplorer.hxx>
40 #include <TopTools_IndexedMapOfShape.hxx>
41 #include <BRepBuilderAPI_MakeFace.hxx>
42 #include <TopExp.hxx>
43 #include <TopTools_IndexedMapOfOrientedShape.hxx>
44 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
45
46 #include <BRepLib_MakeEdge.hxx>
47 #include <BRepLib_MakeWire.hxx>
48 #include <BRep_Builder.hxx>
49 #include <ShapeAnalysis_Wire.hxx>
50 #include <BRepAlgo_NormalProjection.hxx>
51 #include <ShapeUpgrade_UnifySameDomain.hxx>
52 #include <BRepBuilderAPI_MakePolygon.hxx>
53 #include <BOPAlgo_Builder.hxx>
54 #include <BRepAdaptor_Curve.hxx>
55 #include <GeomProjLib.hxx>
56 #include <gp_Pln.hxx>
57 #include <TopTools_IndexedDataMapOfShapeShape.hxx>
58 #include <TopTools_ListIteratorOfListOfShape.hxx>
59 #include <TopTools_SequenceOfShape.hxx>
60 #include <assert.h>
61
62 IMPLEMENT_STANDARD_RTTIEXT( HYDROData_DTM, HYDROData_Bathymetry )
63
64 HYDROData_DTM::CurveUZ::CurveUZ( double theXCurv, const gp_Vec2d& theProfileDir, double theDeltaZ, double theMaxZ )
65   : myXcurv( theXCurv ), myProfileDir( theProfileDir ), myDeltaZ( theDeltaZ ), myMaxZ (theMaxZ)
66 {
67 }
68
69 HYDROData_DTM::CurveUZ::~CurveUZ()
70 {
71 }
72
73 double HYDROData_DTM::CurveUZ::Xcurv() const
74 {
75   return myXcurv;
76 }
77
78 gp_Vec2d HYDROData_DTM::CurveUZ::ProfileDir() const
79 {
80   return myProfileDir;
81 }
82
83 double HYDROData_DTM::CurveUZ::DeltaZ() const
84 {
85   return myDeltaZ;
86 }
87
88 double HYDROData_DTM::CurveUZ::MaxZ() const
89 {
90   return myMaxZ;
91 }
92
93 HYDROData_DTM::CurveUZ HYDROData_DTM::CurveUZ::operator + ( const CurveUZ& c ) const
94 {
95   HYDROData_DTM::CurveUZ res( Xcurv() + c.Xcurv(), ProfileDir() + c.ProfileDir(), DeltaZ() + c.DeltaZ(), MaxZ() + c.MaxZ() );
96   size_t n = size(), n1 = c.size();
97   if( n!=n1 )
98   {
99     std::cout << "Warning: different number of points in curves: " << n << ", " << n1 << std::endl;
100   }
101   int q = std::min(n, n1);
102   res.reserve( q );
103   for( int i=0; i<q; i++ )
104   {
105     PointUZ p;
106     p.U = operator[]( i ).U + c[i].U;
107     p.Z = operator[]( i ).Z;
108     res.push_back( p );
109   }
110   return res;
111 }
112
113 HYDROData_DTM::CurveUZ HYDROData_DTM::CurveUZ::operator * ( double d ) const
114 {
115   HYDROData_DTM::CurveUZ res( Xcurv()*d, ProfileDir()*d, DeltaZ()*d, MaxZ()*d );
116   size_t n = size();
117   res.reserve( n );
118   for( int i=0; i<n; i++ )
119   {
120     PointUZ p;
121     p.U = operator[]( i ).U * d;
122     p.Z = operator[]( i ).Z;
123     res.push_back( p );
124   }
125   return res;
126 }
127
128
129
130
131 HYDROData_DTM::HYDROData_DTM()
132 {
133 }
134
135 HYDROData_DTM::~HYDROData_DTM()
136 {
137 }
138
139 HYDROData_SequenceOfObjects HYDROData_DTM::GetProfiles() const
140 {
141   return GetReferenceObjects( DataTag_Profiles );
142 }
143
144 void HYDROData_DTM::SetProfiles( const HYDROData_SequenceOfObjects& theProfiles )
145 {
146   SetReferenceObjects( theProfiles, DataTag_Profiles );
147   Changed( Geom_3d );
148 }
149
150 double HYDROData_DTM::GetDDZ() const
151 {
152   return GetDouble( DataTag_DDZ );
153 }
154
155 void HYDROData_DTM::SetDDZ( double theDDZ )
156 {
157   SetDouble( DataTag_DDZ, theDDZ );
158   Changed( Geom_3d );
159 }
160
161 double HYDROData_DTM::GetSpatialStep() const
162 {
163   return GetDouble( DataTag_SpatialStep );
164 }
165
166 void HYDROData_DTM::SetSpatialStep( double theSpatialStep )
167 {
168   SetDouble( DataTag_SpatialStep, theSpatialStep );
169   Changed( Geom_3d );
170 }
171
172 void HYDROData_DTM::PointsToWire(const AltitudePoints& pnts, TopoDS_Wire& W )
173 {
174  
175   BRepBuilderAPI_MakePolygon PM;
176   for (int i = 0; i < pnts.size(); i++)
177     PM.Add(gp_Pnt(pnts[i].X, pnts[i].Y, pnts[i].Z));
178   
179   W = PM.Wire();
180 }
181
182 void HYDROData_DTM::PointsToEdge(const AltitudePoints& pnts, TopoDS_Edge& E )
183
184   Handle(TColgp_HArray1OfPnt) gpPoints = new TColgp_HArray1OfPnt(1, (int)pnts.size());
185
186   for (int i = 0; i < pnts.size(); i++)
187     gpPoints->SetValue(i+1, gp_Pnt(pnts[i].X, pnts[i].Y, pnts[i].Z));
188
189   GeomAPI_Interpolate anInterpolator(gpPoints, Standard_False,1.0e-6);
190   anInterpolator.Perform() ;
191   if (anInterpolator.IsDone()) 
192   {
193     Handle(Geom_BSplineCurve) C = anInterpolator.Curve();
194     E = BRepBuilderAPI_MakeEdge(C).Edge();
195   }
196 }
197
198 TopTools_IndexedMapOfOrientedShape HYDROData_DTM::Create3DShape(const AltitudePoints& left,
199                                                                 const AltitudePoints& right,
200                                                                 const std::vector<AltitudePoints>& main_profiles)
201 {  
202   TopTools_IndexedMapOfOrientedShape ll;
203   //TopoDS_Wire LWire, RWire;
204   //PointsToWire(left, LWire);
205   //PointsToWire(right, RWire);
206   TopoDS_Edge LEdge, REdge;
207   PointsToEdge(left, LEdge);
208   PointsToEdge(right, REdge);
209   if (!LEdge.IsNull())
210     ll.Add(LEdge.Oriented(TopAbs_FORWARD));
211
212   for (int k = 0; k < main_profiles.size(); k++)
213   {
214     TopoDS_Wire W;
215     PointsToWire(main_profiles[k], W);
216     TopAbs_Orientation Ori = TopAbs_INTERNAL;
217     if (k == 0 || k == main_profiles.size() - 1)
218       Ori = TopAbs_FORWARD;
219     ll.Add(W.Oriented(Ori));
220   }
221
222   if (!REdge.IsNull())
223     ll.Add(REdge.Oriented(TopAbs_FORWARD)); 
224   //yes, add subshapes in this order (left + profiles + right)
225   //otherwise the projected wire will be non-manifold
226
227   return ll;
228 }
229
230
231 void HYDROData_DTM::Update()
232 {
233   AltitudePoints points;
234   TopoDS_Shape Out3dPres;
235   TopoDS_Shape Out2dPres;
236   TopoDS_Shape OutLeftB;
237   TopoDS_Shape OutRightB;
238   TopoDS_Shape OutInlet;
239   TopoDS_Shape OutOutlet;
240
241   HYDROData_SequenceOfObjects objs = GetProfiles();  
242   double ddz = GetDDZ();
243   double step = GetSpatialStep();
244   std::set<int> InvInd;
245   bool WireIntersections; //__TODO
246   CreateProfilesFromDTM( objs, ddz, step, points, Out3dPres, Out2dPres, OutLeftB, OutRightB, OutInlet, OutOutlet, true, true, InvInd, -1, WireIntersections );
247   SetAltitudePoints( points );  
248   
249   SetShape( DataTag_LeftBankShape, OutLeftB);
250   SetShape( DataTag_RightBankShape, OutRightB);
251   SetShape( DataTag_InletShape, OutInlet);
252   SetShape( DataTag_OutletShape, OutOutlet );
253   SetShape( DataTag_3DShape, Out3dPres );
254   SetShape( DataTag_2DShape, Out2dPres );
255
256   HYDROData_Bathymetry::Update();
257 }
258
259 void HYDROData_DTM::GetPresentationShapes( TopoDS_Shape& Out3dPres,
260                                            TopoDS_Shape& Out2dPres,
261                                            TopoDS_Shape& OutLeftB,
262                                            TopoDS_Shape& OutRightB,
263                                            TopoDS_Shape& OutInlet,
264                                            TopoDS_Shape& OutOutlet )
265 {
266   //without update!
267   OutLeftB = GetShape( DataTag_LeftBankShape);
268   OutRightB = GetShape( DataTag_RightBankShape);
269   OutInlet = GetShape( DataTag_InletShape);
270   OutOutlet = GetShape( DataTag_OutletShape );
271   Out3dPres = GetShape( DataTag_3DShape );
272   Out2dPres = GetShape( DataTag_2DShape );
273 }
274 void HYDROData_DTM::CreateProfilesFromDTM (const HYDROData_SequenceOfObjects& InpProfiles,
275                                            double ddz,
276                                            double step, 
277                                            AltitudePoints& points,
278                                            TopoDS_Shape& Out3dPres,
279                                            TopoDS_Shape& Out2dPres,
280                                            TopoDS_Shape& OutLeftB,
281                                            TopoDS_Shape& OutRightB,
282                                            TopoDS_Shape& OutInlet,
283                                            TopoDS_Shape& OutOutlet,
284                                            bool Create3dPres,
285                                            bool Create2dPres,
286                                            std::set<int>& InvInd,
287                                            int thePntsLimit,
288                                            bool& WireIntersections)
289 {
290   int aLower = InpProfiles.Lower(), anUpper = InpProfiles.Upper();
291   size_t n = anUpper - aLower + 1;
292
293   std::vector<Handle(HYDROData_Profile)> profiles;
294   profiles.reserve( n ); 
295   for( int i=aLower; i<=anUpper; i++ )
296   {
297     Handle(HYDROData_Profile) aProfile = Handle(HYDROData_Profile)::DownCast( InpProfiles.Value( i ) );
298     if( !aProfile.IsNull() )
299       profiles.push_back( aProfile );
300   }
301   const double EPS = 1E-3;
302   AltitudePoints left;
303   AltitudePoints right;
304   std::vector<AltitudePoints> main_profiles;
305
306   if( thePntsLimit > 0 )
307   {
308     int aNbPoints = EstimateNbPoints( profiles, ddz, step );
309     if( aNbPoints < 0 || aNbPoints > thePntsLimit )
310       return;
311   }
312
313   if( ddz>EPS && step>EPS )
314     CreateProfiles(profiles, ddz, step, left, right, points, main_profiles, 
315     Out3dPres, Out2dPres, OutLeftB, OutRightB, OutInlet, OutOutlet, Create3dPres, Create2dPres, InvInd, WireIntersections );
316 }
317
318 bool HYDROData_DTM::GetPlanarFaceFromBanks( const TopoDS_Edge& LB, const TopoDS_Edge& RB, TopoDS_Face& outF,
319   TopTools_SequenceOfShape* Boundr)
320 {
321   BRep_Builder BB;
322   TopoDS_Face F;
323   Handle_Geom_Plane refpl = new Geom_Plane(gp_Pnt(0,0,0), gp_Dir(0,0,1));
324
325   TopoDS_Vertex VFI, VLI, VFO, VLO;
326   TopoDS_Edge prLB;
327   TopoDS_Edge prRB;
328
329
330   BRepAdaptor_Curve LBAD(LB);
331   Handle_Geom_Curve LBPC = GeomProjLib::ProjectOnPlane(LBAD.Curve().Curve(), refpl, gp_Dir(0, 0, -1), 1 );
332   prLB = BRepLib_MakeEdge(LBPC).Edge();
333
334   BRepAdaptor_Curve RBAD(RB);
335   Handle_Geom_Curve RBPC = GeomProjLib::ProjectOnPlane(RBAD.Curve().Curve(), refpl, gp_Dir(0, 0, -1), 1 );
336   prRB = BRepLib_MakeEdge(RBPC).Edge();
337
338   TopExp::Vertices(prLB, VFI, VFO, 1);
339   TopExp::Vertices(prRB, VLI, VLO, 1);
340   TopoDS_Edge prIL = BRepLib_MakeEdge(VFI, VLI).Edge();
341   TopoDS_Edge prOL = BRepLib_MakeEdge(VFO, VLO).Edge();
342   TopoDS_Wire prW = BRepLib_MakeWire(prLB, prIL, prOL, prRB).Wire();
343   outF = BRepBuilderAPI_MakeFace(refpl->Pln(), prW, 1).Face();
344
345   if (Boundr)
346   {
347     Boundr->Append(prLB);
348     Boundr->Append(prIL);
349     Boundr->Append(prOL);
350     Boundr->Append(prRB);
351   }
352
353   ShapeAnalysis_Wire WA(prW, outF, Precision::Confusion());
354   bool res = WA.CheckSelfIntersection();
355   return !res;
356 }
357
358 void HYDROData_DTM::CreateProfiles(const std::vector<Handle(HYDROData_Profile)>& theProfiles,
359                                    double theDDZ,
360                                    double theSpatialStep,
361                                    AltitudePoints& theOutLeft,
362                                    AltitudePoints& theOutRight,
363                                    AltitudePoints& theOutPoints,
364                                    std::vector<AltitudePoints>& theOutMainProfiles,
365                                    TopoDS_Shape& Out3dPres,
366                                    TopoDS_Shape& Out2dPres,
367                                    TopoDS_Shape& OutLeftB,
368                                    TopoDS_Shape& OutRightB,
369                                    TopoDS_Shape& OutInlet,
370                                    TopoDS_Shape& OutOutlet,
371                                    bool Create3dPres,
372                                    bool Create2dPres,
373                                    std::set<int>& InvInd,
374                                    bool& ProjStat)
375 {
376   if (theProfiles.empty())
377     return;
378   theOutPoints = Interpolate( theProfiles, theDDZ, theSpatialStep, theOutLeft, theOutRight, theOutMainProfiles, InvInd );
379   //note that if Create3dPres is false => Create2dPres flag is meaningless!
380   if( theOutPoints.empty() )
381     return;
382
383   if (Create3dPres)
384   {
385     TopTools_IndexedMapOfOrientedShape ll = Create3DShape( theOutLeft, theOutRight, theOutMainProfiles);
386     
387     if (ll.IsEmpty())
388       return;
389     BRep_Builder BB;
390     TopoDS_Compound cmp;
391     BB.MakeCompound(cmp);
392     for (int i = 1; i <= ll.Extent(); i++)
393       BB.Add(cmp, ll(i));
394
395     Out3dPres = cmp;
396
397     //same order as in HYDROData_DTM::Update()
398     OutLeftB = ll(1);
399     OutRightB = ll(ll.Extent());
400     OutInlet = ll(2);
401     OutOutlet = ll(ll.Extent() - 1);
402
403     if (Create2dPres)
404     {
405       TopoDS_Face outF;
406       ProjStat = GetPlanarFaceFromBanks(TopoDS::Edge(OutLeftB), TopoDS::Edge(OutRightB), outF, NULL);
407       Out2dPres = outF;
408     };
409   }
410 }
411
412
413
414
415 void HYDROData_DTM::GetProperties( const Handle(HYDROData_Profile)& theProfile,
416                     gp_Pnt& theLowestPoint, gp_Vec2d& theDir,
417                     double& theZMin, double& theZMax )
418 {
419   theLowestPoint = theProfile->GetBottomPoint();
420   
421   gp_XY aLeft, aRight;
422   theProfile->GetLeftPoint( aLeft, true, true );
423   theProfile->GetRightPoint( aRight, true, true );
424   double x = aRight.X()-aLeft.X();
425   double y = aRight.Y()-aLeft.Y();
426   theDir = gp_Vec2d( x, y );
427
428   HYDROData_Profile::ProfilePoints points = theProfile->GetProfilePoints();
429   int lo = points.Lower();
430   int up = points.Upper();
431   theZMin = std::numeric_limits<double>::max();
432   theZMax = -theZMin;
433   for( int i=lo; i<=up; i++ )
434   {
435     double z = points.Value( i ).Z();
436     if( z>theZMax )
437       theZMax = z;
438     if( z<theZMin )
439       theZMin = z;
440   }
441 }
442
443 inline gp_Pnt2d To2D( const gp_Pnt& thePnt, const gp_Trsf& theTr,
444                       double& theUMin, double& theUMax )
445 {
446   gp_Pnt p = thePnt.Transformed( theTr );
447   double u = p.X();
448   double z = p.Z();
449   if( u<theUMin )
450     theUMin = u;
451   if( u>theUMax )
452     theUMax = u;
453   return gp_Pnt2d( u, z );
454 }
455
456 Handle(TColgp_HArray1OfPnt2d) To2D( const TColgp_Array1OfPnt& thePoints,
457                                     const gp_Trsf& theTr,
458                                     double& theUMin, double& theUMax )
459 {
460   int low = thePoints.Lower(), up = thePoints.Upper();
461   Handle(TColgp_HArray1OfPnt2d) points = new TColgp_HArray1OfPnt2d( low, up );
462   for( int i=low; i<=up; i++ )
463     points->SetValue( i, To2D( thePoints.Value( i ), theTr, theUMin, theUMax ) );
464   return points;
465 }
466
467 Handle(Geom2d_Curve) CurveTo2D( const Handle(Geom_Curve)& theCurve, 
468                                 Standard_Real theFirst, Standard_Real theLast,
469                                 const gp_Trsf& theTr,
470                                 double& theUMin, double& theUMax )
471 {
472   if( theCurve->IsKind( STANDARD_TYPE( Geom_Line ) ) )
473   {
474     gp_Pnt aFirstPnt, aLastPnt;
475     theCurve->D0( theFirst, aFirstPnt );
476     theCurve->D0( theLast, aLastPnt );
477
478     gp_Pnt2d
479       aFirst2d = To2D( aFirstPnt, theTr, theUMin, theUMax ),
480       aLast2d = To2D( aLastPnt, theTr, theUMin, theUMax );
481
482     gp_Vec2d dir( aFirst2d, aLast2d );
483     Handle(Geom2d_Line) aLine2d = new Geom2d_Line( aFirst2d, gp_Dir2d( dir.X(), dir.Y() ) );
484     return new Geom2d_TrimmedCurve( aLine2d, 0, aLast2d.Distance( aFirst2d ) );
485   }
486
487   if( theCurve->IsKind( STANDARD_TYPE( Geom_BSplineCurve ) ) )
488   {
489     Handle(Geom_BSplineCurve) aSpline = Handle(Geom_BSplineCurve)::DownCast( theCurve );
490
491     Handle(TColgp_HArray1OfPnt2d) poles = To2D( aSpline->Poles(), theTr, theUMin, theUMax );
492     const TColStd_Array1OfReal& knots = aSpline->Knots();
493     const TColStd_Array1OfInteger& multiplicities = aSpline->Multiplicities();
494     int aDegree = aSpline->Degree();
495
496     return new Geom2d_BSplineCurve( poles->Array1(), knots, multiplicities, aDegree );
497   }
498
499   return Handle(Geom2d_Curve)();
500 }
501
502 #include <GCE2d_MakeSegment.hxx>
503 #include <Geom2dAPI_InterCurveCurve.hxx>
504 bool IsCooriented( const Handle(HYDROData_Profile)& theProfile1,
505                    const Handle(HYDROData_Profile)& theProfile2 ) 
506 {
507   if( theProfile1==theProfile2 )
508     return true;
509   
510   gp_XY lp1, rp1, lp2, rp2;
511   theProfile1->GetLeftPoint(lp1);
512   theProfile1->GetRightPoint(rp1);
513   theProfile2->GetLeftPoint(lp2);
514   theProfile2->GetRightPoint(rp2);
515
516   GCE2d_MakeSegment s1(lp1, lp2);
517   GCE2d_MakeSegment s2(rp1, rp2);
518
519   Geom2dAPI_InterCurveCurve inter;
520   inter.Init(s1.Value(), s2.Value());
521   if (inter.NbPoints() == 0)
522     return true;
523   else
524     return false;
525 }
526
527 Handle(Geom2d_BSplineCurve) HYDROData_DTM::CreateHydraulicAxis( 
528   const std::vector<Handle(HYDROData_Profile)>& theProfiles,
529   std::vector<double>& theDistances )
530 {
531   size_t n = theProfiles.size();
532   if( n==1 )
533     return Handle_Geom2d_BSplineCurve();
534
535   Handle_Geom2d_BSplineCurve aResult;
536
537   Handle(TColgp_HArray1OfPnt2d) points = new TColgp_HArray1OfPnt2d( 1, (int)n );
538   TColgp_Array1OfVec2d tangents( 1, (int)n );
539   Handle(TColStd_HArray1OfBoolean) flags = new TColStd_HArray1OfBoolean( 1, (int)n );
540
541   // Stage 1. Orient all profiles to be co-oriented with the first profile
542   theProfiles[0]->Update();
543   for( size_t i = 1; i < n; i++ )
544   {
545     Handle(HYDROData_Profile) aProfile = theProfiles[i];
546     Handle(HYDROData_Profile) aPrevProfile = theProfiles[i-1];
547
548     if( !IsCooriented( aProfile, aPrevProfile ) )
549     {
550       gp_XY lp, rp;
551       aProfile->GetLeftPoint( lp, true );
552       aProfile->GetRightPoint( rp, true );
553       aProfile->SetLeftPoint( rp, true );
554       aProfile->SetRightPoint( lp, true );
555     }
556     aProfile->Update();
557   }
558
559   // Stage 2. Calculate normals so that each normal "points" to the next profile
560   for( size_t i = 0; i < n; i++ )
561   {
562     Handle(HYDROData_Profile) aProfile = theProfiles[i];
563     Handle(HYDROData_Profile) aNextProfile = i==n-1 ? theProfiles[i-1] : theProfiles[i+1];
564
565     gp_Pnt aLowest;
566     gp_Vec2d aNormal;
567     double zmin, zmax;
568
569     gp_XYZ curP = aProfile->GetBottomPoint(true);
570     gp_XY curP2d = gp_XY(curP.X(), curP.Y());
571
572     gp_XYZ nextP = aNextProfile->GetBottomPoint(true);
573     gp_XY nextP2d = gp_XY(nextP.X(), nextP.Y());
574
575     gp_Vec2d aPrTangent;
576     GetProperties( aProfile, aLowest, aPrTangent, zmin, zmax );
577     aNormal.SetCoord( -aPrTangent.Y(), aPrTangent.X() );
578
579     gp_Vec2d aDirToNextProfile(nextP2d.X() - curP2d.X(), nextP2d.Y() - curP2d.Y() );
580     if( i==n-1 )
581       aDirToNextProfile.Reverse();
582
583     if (aNormal.Dot(aDirToNextProfile) < 0)
584       aNormal.Reverse();
585
586     aNormal.Normalize();
587
588     points->SetValue( (int)(i+1), gp_Pnt2d( aLowest.X(), aLowest.Y() ) );
589     tangents.SetValue( (int)(i+1), aNormal );
590     flags->SetValue( (int)(i+1), Standard_True );
591   }
592
593   Geom2dAPI_Interpolate anInterpolator( points, Standard_False, Standard_False );
594   anInterpolator.Load( tangents, flags );
595   anInterpolator.Perform();
596   if( anInterpolator.IsDone() )
597   {
598     aResult = anInterpolator.Curve();
599
600     //fill the distances vector
601     Geom2dAdaptor_Curve anAdaptor( aResult );
602
603     theDistances.clear();
604     theDistances.reserve( n );
605     Standard_Real aParamFirst = anAdaptor.FirstParameter(), aParamLast = anAdaptor.LastParameter();
606     for( size_t i = 1; i <= n; i++ )
607     {
608       gp_Pnt2d aPnt = points->Value( (Standard_Integer)i );
609       Geom2dAPI_ProjectPointOnCurve aProject( aPnt, aResult );
610       Standard_Real aParam = aProject.LowerDistanceParameter();
611       double aDistance = GCPnts_AbscissaPoint::Length( anAdaptor, aParamFirst, aParam );  
612       theDistances.push_back( aDistance );
613     }
614   }
615   return aResult;
616 }
617
618 std::vector<Handle(Geom2d_Curve)> HYDROData_DTM::ProfileToParametric( 
619   const Handle(HYDROData_Profile)& theProfile,
620   double& theUMin, double& theUMax, gp_Vec2d& theDir )
621 {
622   std::vector<Handle(Geom2d_Curve)> curves;
623   
624   // Transformation of the coordinate systems
625   gp_Pnt aLowest;
626   double zmin, zmax;
627   GetProperties( theProfile, aLowest, theDir, zmin, zmax );
628
629   gp_Ax3 aStd3d( gp_Pnt( 0, 0, 0 ), gp_Dir( 0, 0, 1 ), gp_Dir( 1, 0, 0 ) );
630   gp_Ax3 aLocal( gp_Pnt( aLowest.X(), aLowest.Y(), 0 ), gp_Dir( 0, 0, 1 ), gp_Dir( theDir.X(), theDir.Y(), 0 ) );
631
632   gp_Trsf aTransf;
633   aTransf.SetTransformation( aStd3d, aLocal );
634
635   // Iteration via edges
636   TopoDS_Wire aWire = TopoDS::Wire( theProfile->GetShape3D() );
637   TopExp_Explorer anExp( aWire, TopAbs_EDGE );
638   for( ; anExp.More(); anExp.Next() )
639   {
640     // Extract an edge from wire
641     TopoDS_Edge anEdge = TopoDS::Edge( anExp.Current() );
642
643     // Extract a curve corresponding to the edge
644     TopLoc_Location aLoc;
645     Standard_Real aFirst, aLast;
646     Handle(Geom_Curve) aCurve = BRep_Tool::Curve( anEdge, aLoc, aFirst, aLast );
647
648     // Convert the curve to 2d CS
649     Handle(Geom2d_Curve) aCurve2d = CurveTo2D( aCurve, aFirst, aLast, aTransf, theUMin, theUMax );
650     if( !aCurve2d.IsNull() )
651       curves.push_back( aCurve2d );
652   }
653   return curves;
654 }
655
656
657 bool CalcMidWidth( const std::set<double>& intersections, double& theMid, double& theWid )
658 {
659   double umin = std::numeric_limits<double>::max(),
660          umax = -umin;
661
662   size_t n = intersections.size();
663   if( n <= 0 )
664     return false;
665
666   std::set<double>::const_iterator it = intersections.begin(), last = intersections.end();
667   for( ; it!=last; it++ )
668   {
669     double u = *it;
670     if( u<umin )
671       umin = u;
672     if( u>umax )
673       umax = u;
674   }
675   theMid = ( umin+umax )/2;
676   theWid = umax-umin;
677   return true;
678 }
679
680 void HYDROData_DTM::ProfileDiscretization( const Handle(HYDROData_Profile)& theProfile, 
681                                            double theXCurv, double theMinZ, double theMaxZ, double theTopZ, double theDDZ,
682                                            CurveUZ& theMidPointCurve,
683                                            CurveUZ& theWidthCurve,                                           
684                                            int& intersection_nb,
685                                            double theTolerance)
686 {
687   double aDblMax = std::numeric_limits<double>::max(),
688          aUMin = aDblMax,
689          aUMax = -aUMin,
690          aVMax = 1000000;
691   
692   gp_Vec2d aProfileDir;
693   std::vector<Handle(Geom2d_Curve)> curves = ProfileToParametric( theProfile, aUMin, aUMax, aProfileDir );
694   size_t n = curves.size();
695
696   if( n==0 )
697     return;
698
699   // we add the "virtual" vertical lines to simulate the intersection with profile 
700   gp_Pnt2d aFirst, aLast;
701   curves[0]->D0( curves[0]->FirstParameter(), aFirst );
702   curves[n-1]->D0( curves[n-1]->LastParameter(), aLast );
703   Handle(Geom2d_Line) aV1 = new Geom2d_Line( aFirst, gp_Dir2d( 0, 1 ) );
704   Handle(Geom2d_TrimmedCurve) aT1 = new Geom2d_TrimmedCurve( aV1, 0.0, aVMax );
705   
706   Handle(Geom2d_Line) aV2 = new Geom2d_Line( aLast, gp_Dir2d( 0, 1 ) );
707   Handle(Geom2d_TrimmedCurve) aT2 = new Geom2d_TrimmedCurve( aV2, 0.0, aVMax );
708
709   curves.push_back( aT1 );
710   curves.push_back( aT2 );
711   
712   int psize = ( int )( ( theMaxZ-theMinZ ) / theDDZ + 1 );
713   theMidPointCurve = CurveUZ( theXCurv, aProfileDir, theMinZ, theTopZ);
714   theMidPointCurve.reserve( psize );
715   theWidthCurve = CurveUZ( theXCurv, aProfileDir, theMinZ, theTopZ );
716   theWidthCurve.reserve( psize );
717
718   n = curves.size();
719   // for each discrete value of z we search intersection with profile
720   for( double z1 = theMinZ; z1 <= theMaxZ; z1 += theDDZ )
721   {
722     Handle(Geom2d_Line) aLine = new Geom2d_Line( gp_Pnt2d( 0, z1 ), gp_Dir2d( 1, 0 ) );
723     std::set<double> intersections;
724     for( size_t i = 0; i < n; i++ )
725     {
726       Handle(Geom2d_Curve) aCurve = curves[i];
727       Geom2dAPI_InterCurveCurve anIntersect( aCurve, aLine, theTolerance );
728       for( int k=1, m=anIntersect.NbPoints(); k<=m; k++ )
729         intersections.insert( anIntersect.Point( k ).X() );
730     }
731
732     intersection_nb = intersections.size();
733     if( intersection_nb >= 1 )
734     {
735       double u_mid, u_wid;
736       if( !CalcMidWidth( intersections, u_mid, u_wid ) )
737         continue;
738
739       double z = z1 - theMinZ;
740       PointUZ p_mid;
741       p_mid.U = u_mid;
742       p_mid.Z = z;
743       theMidPointCurve.push_back( p_mid );
744
745       PointUZ p_wid;
746       p_wid.U = u_wid;
747       p_wid.Z = z;
748       theWidthCurve.push_back( p_wid );
749     }
750   }
751 }
752
753 void HYDROData_DTM::Interpolate( const CurveUZ& theCurveA, const CurveUZ& theCurveB, 
754                                  int theNbSteps, std::vector<CurveUZ>& theInterpolation,
755                                  bool isAddSecond )
756 {
757   theInterpolation.clear();
758   int d = isAddSecond ? 2 : 1;
759   theInterpolation.reserve( theNbSteps+d );
760   double dt = 1.0 / double( theNbSteps + 1 );
761   double t = dt;
762   theInterpolation.push_back( theCurveA );
763   for( int i=0; i<theNbSteps; i++, t+=dt )
764   {
765     CurveUZ anInterp = theCurveA*(1-t) + theCurveB*t;
766     theInterpolation.push_back( anInterp );
767   }
768   if( isAddSecond )
769     theInterpolation.push_back( theCurveB );
770 }
771 #include <BRepLib_MakeEdge2d.hxx>
772 void HYDROData_DTM::CurveTo3D( const Handle(Geom2d_BSplineCurve)& theHydraulicAxis,
773                                const CurveUZ& theMidCurve, const CurveUZ& theWidthCurve,
774                                AltitudePoints& thePoints )
775 {
776   Geom2dAdaptor_Curve anAdaptor( theHydraulicAxis );
777   TopoDS_Edge E2d = BRepLib_MakeEdge2d(theHydraulicAxis).Edge();
778   GCPnts_AbscissaPoint ap( anAdaptor, theMidCurve.Xcurv(), anAdaptor.FirstParameter() );  
779   double aParam = ap.Parameter();
780
781   gp_Pnt2d point;
782   anAdaptor.D0( aParam, point );
783   gp_Vec2d profile_dir = theMidCurve.ProfileDir();
784   //gp_Dir tangent_n( -profile_dir.Y(), profile_dir.X(), dz );
785   profile_dir.Normalize();
786   
787   size_t n = theMidCurve.size();
788   std::map<double, AltitudePoint> sorted_points;
789   bool isOnTop = false;
790   for( size_t i=0; i<n; i++ ) // build the two banks of the interpolated profile, from bottom to top
791   {
792     double param1 = theMidCurve[i].U - theWidthCurve[i].U / 2;
793     double param2 = theMidCurve[i].U + theWidthCurve[i].U / 2;
794
795     gp_Pnt2d p1 = point.Translated( param1 * profile_dir);
796     gp_Pnt2d p2 = point.Translated( param2 * profile_dir);
797
798     bool arrivedOnTop = false;
799     double z = 0;
800     if (theMidCurve[i].Z <= theMidCurve.MaxZ())
801       z = theMidCurve[i].Z + theMidCurve.DeltaZ();
802     else
803       {
804         z = theMidCurve.MaxZ() + theMidCurve.DeltaZ(); // limit z to linear interpolation between maxima on extremity profiles
805         arrivedOnTop = true; // do not keep points after this one
806       }
807     if (!isOnTop)
808       {
809         AltitudePoint p3d_1( p1.X(), p1.Y(), z ), p3d_2( p2.X(), p2.Y(), z );
810
811         sorted_points[param1] = p3d_1;
812         sorted_points[param2] = p3d_2;
813       }
814     //if (arrivedOnTop)
815     //  isOnTop =true; // do not keep points after this one (commented: leads to strange limits of 2D shape)
816   }
817
818   thePoints.reserve( sorted_points.size() );
819   const double EPS = 1E-12;
820   std::map<double, AltitudePoint>::const_iterator it = sorted_points.begin(), last = sorted_points.end();
821   for( ; it!=last; it++ )
822     if( thePoints.empty() || thePoints.back().SquareDistance( it->second ) > EPS )
823       thePoints.push_back( it->second );
824 }
825
826 inline double max( double a, double b )
827 {
828   if( a>b )
829     return a;
830   else
831     return b;
832 }
833
834 inline double min( double a, double b )
835 {
836   if( a<b )
837     return a;
838   else
839     return b;
840 }
841
842 #include <BRepLib_MakeWire.hxx>
843
844 std::vector<HYDROData_Bathymetry::AltitudePoints> HYDROData_DTM::Interpolate
845   ( const Handle(Geom2d_BSplineCurve)& theHydraulicAxis,
846     const Handle(HYDROData_Profile)& theProfileA,
847     double theXCurvA,
848     const Handle(HYDROData_Profile)& theProfileB,
849     double theXCurvB,
850     double theDDZ, int theNbSteps, bool isAddSecond,
851     int& inter_nb_1, int& inter_nb_2)
852 {
853   double zminA, zmaxA, zminB, zmaxB;
854   gp_Pnt lowestA, lowestB;
855   gp_Vec2d dirA, dirB;
856
857   GetProperties( theProfileA, lowestA, dirA, zminA, zmaxA ); 
858   GetProperties( theProfileB, lowestB, dirB, zminB, zmaxB ); 
859
860   
861   double hmax = max( zmaxA-zminA, zmaxB-zminB );
862
863   //double dz = zminB - zminA;
864   //double zmin = min( zminA, zminB );
865   //double zmax = max( zmaxA, zmaxB );
866
867   CurveUZ midA(0, gp_Vec2d(), 0, 0), midB(0, gp_Vec2d(), 0, 0);
868   CurveUZ widA(0, gp_Vec2d(), 0, 0), widB(0, gp_Vec2d(), 0, 0);
869
870   ProfileDiscretization( theProfileA, theXCurvA, zminA, zminA+hmax, zmaxA-zminA, theDDZ, midA, widA, inter_nb_1 );
871   ProfileDiscretization( theProfileB, theXCurvB, zminB, zminB+hmax, zmaxB-zminB, theDDZ, midB, widB, inter_nb_2 );
872
873   std::vector<CurveUZ> mid, wid;
874   Interpolate( midA, midB, theNbSteps, mid, isAddSecond );
875   Interpolate( widA, widB, theNbSteps, wid, isAddSecond );
876
877   size_t p = mid.size();
878   size_t q = p>0 ? 2*mid[0].size() : 1;
879   std::vector<AltitudePoints> points;
880   points.resize( p );
881
882   for( size_t i=0; i<p; i++ )
883   {
884     points[i].reserve( q );
885     CurveTo3D( theHydraulicAxis, mid[i], wid[i], points[i] );
886   }
887
888   return points;
889 }
890
891 HYDROData_Bathymetry::AltitudePoints HYDROData_DTM::Interpolate
892   ( const std::vector<Handle(HYDROData_Profile)>& theProfiles,
893     double theDDZ, double theSpatialStep,
894     AltitudePoints& theLeft,
895     AltitudePoints& theRight,
896     std::vector<AltitudePoints>& theMainProfiles,
897     std::set<int>& invalInd)
898 {
899   AltitudePoints points;
900   size_t n = theProfiles.size();
901   if( n<=1 )
902     return points;
903
904   std::vector<double> distances;
905   Handle(Geom2d_BSplineCurve) aHydraulicAxis = CreateHydraulicAxis( theProfiles, distances );
906   if( aHydraulicAxis.IsNull() )
907     return points;
908
909   theMainProfiles.reserve( n );
910
911   for( size_t i=0, n1=n-1; i<n1; i++ )
912   {
913     double aDistance = distances[i+1]-distances[i];
914     int aNbSteps = int(aDistance/theSpatialStep);
915     bool isAddSecond = i==n1-1;
916
917     // 1. Calculate interpolated profiles
918     int inter_nb_1, inter_nb_2;
919     std::vector<AltitudePoints> local_points = Interpolate( aHydraulicAxis, theProfiles[i], distances[i], 
920       theProfiles[i+1], distances[i+1], theDDZ, aNbSteps, isAddSecond, inter_nb_1, inter_nb_2 );
921     int lps = local_points.size();
922
923     if (inter_nb_1 > 2)
924       invalInd.insert(i);
925
926     if (inter_nb_2 > 2)
927       invalInd.insert(i+1);
928
929     // 2. Put all points into the global container
930     for( size_t j=0; j<lps; j++ )
931     {
932       const AltitudePoints& lp = local_points[j];
933       if( i==0 && j==0 )
934         points.reserve( lp.size() * n );
935       for( size_t k=0, ks=lp.size(); k<ks; k++ )
936         points.push_back( lp[k] );
937     }
938
939     // 3. Get left/right banks' points
940     if( i==0 )
941     {
942       theLeft.reserve( lps * n );
943       theRight.reserve( lps * n );
944     }
945     for( size_t j=0; j<lps; j++ )
946     {
947       const AltitudePoints& lp = local_points[j];
948       theLeft.push_back( lp[0] );
949       theRight.push_back( lp[lp.size()-1] );
950     }
951
952     // 4. Get main profiles points
953     theMainProfiles.push_back( local_points[0] );
954     if( isAddSecond )
955       theMainProfiles.push_back( local_points[lps-1] );
956   }
957   return points;
958 }
959
960 int HYDROData_DTM::EstimateNbPoints( const std::vector<Handle(HYDROData_Profile)>& theProfiles,
961                                      double theDDZ, double theSpatialStep )
962 {
963   size_t n = theProfiles.size();
964   if( n<=1 )
965     return 0;
966   if( theDDZ<1E-6 || theSpatialStep<1E-6 )
967     return 1 << 20;
968
969   std::vector<double> distances;
970   Handle(Geom2d_BSplineCurve) aHydraulicAxis = CreateHydraulicAxis( theProfiles, distances );
971   if( aHydraulicAxis.IsNull() )
972     return 0;
973
974   double aCompleteDistance = distances[n-1];
975   int aNbSteps = int( aCompleteDistance / theSpatialStep ) + 1;
976   gp_Pnt aLowest;
977   gp_Vec2d aDir;
978   double aZMin, aZMax;
979   GetProperties( theProfiles[0], aLowest, aDir, aZMin, aZMax );
980   int aNbZSteps = (aZMax-aZMin)/theDDZ;
981
982   if( aNbSteps > ( 1<<16 ) || aNbZSteps > ( 1<<16 ) )
983     return 1 << 20;
984
985   return aNbSteps * aNbZSteps;
986 }