Salome HOME
f44f98a22ec0f82a7cf755625a6d7459b3a82085
[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 <Geom_Plane.hxx>
40 #include <BRepTools_WireExplorer.hxx>
41 #include <TopTools_IndexedMapOfShape.hxx>
42 #include <BRepBuilderAPI_MakeFace.hxx>
43 #include <TopExp.hxx>
44 #include <TopTools_IndexedMapOfOrientedShape.hxx>
45
46 #include <BRepLib_MakeEdge.hxx>
47 #include <BRepLib_MakeWire.hxx>
48 #include <BRep_Builder.hxx>
49
50 IMPLEMENT_STANDARD_HANDLE( HYDROData_DTM, HYDROData_Bathymetry )
51 IMPLEMENT_STANDARD_RTTIEXT( HYDROData_DTM, HYDROData_Bathymetry )
52
53
54 HYDROData_DTM::CurveUZ::CurveUZ( double theXCurv, const gp_Vec2d& theProfileDir )
55   : myXcurv( theXCurv ), myProfileDir( theProfileDir )
56 {
57 }
58
59 HYDROData_DTM::CurveUZ::~CurveUZ()
60 {
61 }
62
63 double HYDROData_DTM::CurveUZ::Xcurv() const
64 {
65   return myXcurv;
66 }
67
68 gp_Vec2d HYDROData_DTM::CurveUZ::ProfileDir() const
69 {
70   return myProfileDir;
71 }
72
73 HYDROData_DTM::CurveUZ HYDROData_DTM::CurveUZ::operator + ( const CurveUZ& c ) const
74 {
75   HYDROData_DTM::CurveUZ res( Xcurv() + c.Xcurv(), ProfileDir() + c.ProfileDir() );
76   size_t n = size();
77   res.reserve( n );
78   for( int i=0; i<n; i++ )
79   {
80     PointUZ p;
81     p.U = operator[]( i ).U + c[i].U;
82     p.Z = operator[]( i ).Z;
83     res.push_back( p );
84   }
85   return res;
86 }
87
88 HYDROData_DTM::CurveUZ HYDROData_DTM::CurveUZ::operator * ( double d ) const
89 {
90   HYDROData_DTM::CurveUZ res( Xcurv()*d, ProfileDir()*d );
91   size_t n = size();
92   res.reserve( n );
93   for( int i=0; i<n; i++ )
94   {
95     PointUZ p;
96     p.U = operator[]( i ).U * d;
97     p.Z = operator[]( i ).Z;
98     res.push_back( p );
99   }
100   return res;
101 }
102
103
104
105
106 HYDROData_DTM::HYDROData_DTM()
107 {
108 }
109
110 HYDROData_DTM::~HYDROData_DTM()
111 {
112 }
113
114 HYDROData_SequenceOfObjects HYDROData_DTM::GetProfiles() const
115 {
116   return GetReferenceObjects( DataTag_Profiles );
117 }
118
119 void HYDROData_DTM::SetProfiles( const HYDROData_SequenceOfObjects& theProfiles )
120 {
121   SetReferenceObjects( theProfiles, DataTag_Profiles );
122 }
123
124 double HYDROData_DTM::GetDDZ() const
125 {
126   return GetDouble( DataTag_DDZ );
127 }
128
129 void HYDROData_DTM::SetDDZ( double theDDZ )
130 {
131   SetDouble( DataTag_DDZ, theDDZ );
132 }
133
134 double HYDROData_DTM::GetSpatialStep() const
135 {
136   return GetDouble( DataTag_SpatialStep );
137 }
138
139 void HYDROData_DTM::SetSpatialStep( double theSpatialStep )
140 {
141   SetDouble( DataTag_SpatialStep, theSpatialStep );
142 }
143
144 void HYDROData_DTM::PointToWire(const AltitudePoints& pnts, TopoDS_Wire& W )
145 {
146   BRepLib_MakeWire WM;
147   if (pnts.empty())
148     return;
149   for (int i = 0; i < pnts.size() - 1; i++)
150   {
151     gp_Pnt p1(pnts[i].X, pnts[i].Y, pnts[i].Z);
152     gp_Pnt p2(pnts[i+1].X, pnts[i+1].Y, pnts[i+1].Z);    
153     WM.Add(BRepLib_MakeEdge(p1, p2).Edge()); 
154   }
155   if (WM.IsDone())
156     W = WM.Wire();
157 }
158
159 TopTools_IndexedMapOfOrientedShape HYDROData_DTM::Create3DShape(const AltitudePoints& left,
160                                                                 const AltitudePoints& right,
161                                                                 const std::vector<AltitudePoints>& main_profiles)
162 {  
163   TopTools_IndexedMapOfOrientedShape ll;
164   TopoDS_Wire LWire, RWire;
165   PointToWire(left, LWire);
166   PointToWire(right, RWire);
167   if (!LWire.IsNull())
168     ll.Add(LWire.Oriented(TopAbs_FORWARD));
169
170   for (int k = 0; k < main_profiles.size(); k++)
171   {
172     TopoDS_Wire W;
173     PointToWire(main_profiles[k], W);
174     TopAbs_Orientation Ori = TopAbs_INTERNAL;
175     if (k == 0 || k == main_profiles.size() - 1)
176       Ori = TopAbs_FORWARD;
177     ll.Add(W.Oriented(Ori));
178   }
179
180   if (!RWire.IsNull())
181     ll.Add(RWire.Oriented(TopAbs_FORWARD)); 
182   //yes, add subshapes in this order (left + profiles + right)
183   //otherwise the projected wire will be non-manifold
184
185   return ll;
186 }
187
188
189 void HYDROData_DTM::Update()
190 {
191   AltitudePoints points;
192   TopoDS_Shape Out3dPres;
193   TopoDS_Shape Out2dPres;
194   TopoDS_Shape OutLeftB;
195   TopoDS_Shape OutRightB;
196   TopoDS_Shape OutInlet;
197   TopoDS_Shape OutOutlet;
198
199   HYDROData_SequenceOfObjects objs = GetProfiles();  
200   double ddz = GetDDZ();
201   double step = GetSpatialStep();
202   CreateProfilesFromDTM( objs, ddz, step, points, Out3dPres, Out2dPres, OutLeftB, OutRightB, OutInlet, OutOutlet, true, true  );
203   SetAltitudePoints( points );  
204
205   SetShape( DataTag_LeftBankShape, OutLeftB);
206   SetShape( DataTag_RightBankShape, OutRightB);
207   SetShape( DataTag_InletShape, OutInlet);
208   SetShape( DataTag_OutletShape, OutOutlet );
209   SetShape( DataTag_3DShape, Out3dPres );
210   SetShape( DataTag_2DShape, Out2dPres );
211   
212 }
213
214 void HYDROData_DTM::GetPresentationShapes( TopoDS_Shape& Out3dPres,
215                                            TopoDS_Shape& Out2dPres,
216                                            TopoDS_Shape& OutLeftB,
217                                            TopoDS_Shape& OutRightB,
218                                            TopoDS_Shape& OutInlet,
219                                            TopoDS_Shape& OutOutlet )
220 {
221   //without update!
222   OutLeftB = GetShape( DataTag_LeftBankShape);
223   OutRightB = GetShape( DataTag_RightBankShape);
224   OutInlet = GetShape( DataTag_InletShape);
225   OutOutlet = GetShape( DataTag_OutletShape );
226   Out3dPres = GetShape( DataTag_3DShape );
227   Out2dPres = GetShape( DataTag_2DShape );
228 }
229
230 void HYDROData_DTM::CreateProfilesFromDTM (const HYDROData_SequenceOfObjects& InpProfiles,
231                                            double ddz,
232                                            double step, 
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                                            bool Create3dPres,
241                                            bool Create2dPres)
242 {
243
244   int aLower = InpProfiles.Lower(), anUpper = InpProfiles.Upper();
245   size_t n = anUpper - aLower + 1;
246
247   std::vector<Handle_HYDROData_Profile> profiles;
248   profiles.reserve( n ); 
249   for( int i=aLower; i<=anUpper; i++ )
250   {
251     Handle(HYDROData_Profile) aProfile = Handle(HYDROData_Profile)::DownCast( InpProfiles.Value( i ) );
252     if( !aProfile.IsNull() )
253       profiles.push_back( aProfile );
254   }
255   const double EPS = 1E-3;
256   AltitudePoints left;
257   AltitudePoints right;
258   std::vector<AltitudePoints> main_profiles;
259
260   if( ddz>EPS && step>EPS )
261     CreateProfiles(profiles, ddz, step, left, right, points, main_profiles, 
262     Out3dPres, Out2dPres, OutLeftB, OutRightB, OutInlet, OutOutlet, Create3dPres, Create2dPres );
263 }
264
265 void HYDROData_DTM::ProjWireOnPlane(const TopoDS_Wire& inpWire, const Handle_Geom_Plane& RefPlane, TopoDS_Wire& outWire)
266 {
267   //its also possible to use BrepAlgo_NormalProjection here!
268   BRepTools_WireExplorer ex(TopoDS::Wire(inpWire.Oriented(TopAbs_FORWARD)));
269   BRepLib_MakeWire WM;
270   for (;ex.More();ex.Next())
271   {
272     const TopoDS_Edge& CE = ex.Current(); 
273     double f, l;
274     Handle(Geom_Curve) C3d = BRep_Tool::Curve(CE, f, l);
275     Handle(Geom_Curve) ProjectedCurve = GeomProjLib::ProjectOnPlane(new Geom_TrimmedCurve(C3d, f, l), RefPlane, RefPlane->Position().Direction(), Standard_True);
276     TopoDS_Edge ProjEdge = BRepLib_MakeEdge(ProjectedCurve);
277     WM.Add(ProjEdge); //auto sharing between edges if vertex is coincident
278   }
279   outWire = WM.Wire();
280   outWire.Orientation(inpWire.Orientation()); //take from the original wire
281 }
282
283
284 void HYDROData_DTM::Get2dFaceFrom3dPres(const TopoDS_Compound& cmp, TopoDS_Face& outF )
285 {
286   Handle_Geom_Plane refpl = new Geom_Plane(gp_Pnt(0,0,0), gp_Dir(0,0,1));
287   BRepLib_MakeWire WM;
288   TopoDS_Iterator it(cmp);
289   //TopTools_IndexedMapOfShape IntW;
290   for (;it.More(); it.Next())
291   {
292     const TopoDS_Wire& W = TopoDS::Wire(it.Value());
293     if (W.Orientation() != TopAbs_INTERNAL)
294     {
295       //use list of edges to protect againts non-manifold cases.
296       //auto sharing between edges will be added automatically
297       TopTools_IndexedMapOfShape ME;
298       TopTools_ListOfShape LE;
299       TopExp::MapShapes(W, TopAbs_EDGE, ME);
300       for (int i = 1; i <= ME.Extent(); i++)
301         LE.Append(ME(i));
302       WM.Add(LE);
303     }
304     //else
305     //  IntW.Add(W);
306   }
307
308   TopoDS_Wire outW;
309   ProjWireOnPlane(WM.Wire(), refpl, outW);
310   BRepBuilderAPI_MakeFace mf(refpl, outW); //check inside is true by def
311   outF = mf.Face();
312
313   ///!!! the internal wires cant be added with 'internal' ori.
314   // it's possible to do with brep builder yet the result will not be correct!
315   // more proper way is to use BOP operation here.
316   /*for (int i = 1; i <= IntW.Extent(); i++)
317   {
318   TopoDS_Wire outIW;
319   const TopoDS_Wire& W = TopoDS::Wire(IntW(i));
320   ProjWireOnPlane(W, refpl, outIW);
321   BB.Add(outF, outIW);
322   }*/
323 }
324
325 void HYDROData_DTM::CreateProfiles(const std::vector<Handle_HYDROData_Profile>& theProfiles,
326                                    double theDDZ,
327                                    double theSpatialStep,
328                                    AltitudePoints& theOutLeft,
329                                    AltitudePoints& theOutRight,
330                                    AltitudePoints& theOutPoints,
331                                    std::vector<AltitudePoints>& theOutMainProfiles,
332                                    TopoDS_Shape& Out3dPres,
333                                    TopoDS_Shape& Out2dPres,
334                                    TopoDS_Shape& OutLeftB,
335                                    TopoDS_Shape& OutRightB,
336                                    TopoDS_Shape& OutInlet,
337                                    TopoDS_Shape& OutOutlet,
338                                    bool Create3dPres,
339                                    bool Create2dPres)
340 {
341   if (theProfiles.empty())
342     return;
343   theOutPoints = Interpolate( theProfiles, theDDZ, theSpatialStep, theOutLeft, theOutRight, theOutMainProfiles );
344   //note that if Create3dPres is false => Create2dPres flag is meaningless!
345   if (Create3dPres)
346   {
347     TopTools_IndexedMapOfOrientedShape ll = Create3DShape( theOutLeft, theOutRight, theOutMainProfiles);
348     
349     if (ll.IsEmpty())
350       return;
351     BRep_Builder BB;
352     TopoDS_Compound cmp;
353     BB.MakeCompound(cmp);
354     for (int i = 1; i <= ll.Extent(); i++)
355       BB.Add(cmp, ll(i));
356
357     Out3dPres = cmp;
358
359     //same order as in HYDROData_DTM::Update()
360     OutLeftB = ll(1);
361     OutRightB = ll(ll.Extent());
362     OutInlet = ll(2);
363     OutOutlet = ll(ll.Extent() - 1);
364
365     if (Create2dPres)
366     {
367       TopoDS_Face outF;
368       Get2dFaceFrom3dPres(cmp, outF);
369       Out2dPres = outF;
370     };
371   }
372 }
373
374
375
376
377 void HYDROData_DTM::GetProperties( const Handle_HYDROData_Profile& theProfile,
378                     gp_Pnt& theLowestPoint, gp_Vec2d& theDir,
379                     bool isNormalDir,
380                     double& theZMin, double& theZMax )
381 {
382   theLowestPoint = theProfile->GetBottomPoint();
383   
384   gp_XY aLeft, aRight;
385   theProfile->GetLeftPoint( aLeft, true, true );
386   theProfile->GetRightPoint( aRight, true, true );
387   double x = aRight.X()-aLeft.X();
388   double y = aRight.Y()-aLeft.Y();
389   if( isNormalDir )
390     theDir = gp_Vec2d( -y, x );
391   else
392     theDir = gp_Vec2d( x, y );
393
394   HYDROData_Profile::ProfilePoints points = theProfile->GetProfilePoints();
395   int lo = points.Lower();
396   int up = points.Upper();
397   theZMin = std::numeric_limits<double>::max();
398   theZMax = -theZMin;
399   for( int i=lo; i<=up; i++ )
400   {
401     double z = points.Value( i ).Z();
402     if( z>theZMax )
403       theZMax = z;
404     if( z<theZMin )
405       theZMin = z;
406   }
407 }
408
409 inline gp_Pnt2d To2D( const gp_Pnt& thePnt, const gp_Trsf& theTr,
410                       double& theUMin, double& theUMax )
411 {
412   gp_Pnt p = thePnt.Transformed( theTr );
413   double u = p.X();
414   double z = p.Z();
415   if( u<theUMin )
416     theUMin = u;
417   if( u>theUMax )
418     theUMax = u;
419   return gp_Pnt2d( u, z );
420 }
421
422 Handle(TColgp_HArray1OfPnt2d) To2D( const TColgp_Array1OfPnt& thePoints,
423                                     const gp_Trsf& theTr,
424                                     double& theUMin, double& theUMax )
425 {
426   int low = thePoints.Lower(), up = thePoints.Upper();
427   Handle(TColgp_HArray1OfPnt2d) points = new TColgp_HArray1OfPnt2d( low, up );
428   for( int i=low; i<=up; i++ )
429     points->SetValue( i, To2D( thePoints.Value( i ), theTr, theUMin, theUMax ) );
430   return points;
431 }
432
433 Handle(Geom2d_Curve) CurveTo2D( const Handle(Geom_Curve)& theCurve, 
434                                 Standard_Real theFirst, Standard_Real theLast,
435                                 const gp_Trsf& theTr,
436                                 double& theUMin, double& theUMax )
437 {
438   if( theCurve->IsKind( STANDARD_TYPE( Geom_Line ) ) )
439   {
440     gp_Pnt aFirstPnt, aLastPnt;
441     theCurve->D0( theFirst, aFirstPnt );
442     theCurve->D0( theLast, aLastPnt );
443
444     gp_Pnt2d
445       aFirst2d = To2D( aFirstPnt, theTr, theUMin, theUMax ),
446       aLast2d = To2D( aLastPnt, theTr, theUMin, theUMax );
447
448     gp_Vec2d dir( aFirst2d, aLast2d );
449     Handle_Geom2d_Line aLine2d = new Geom2d_Line( aFirst2d, gp_Dir2d( dir.X(), dir.Y() ) );
450     return new Geom2d_TrimmedCurve( aLine2d, 0, aLast2d.Distance( aFirst2d ) );
451   }
452
453   if( theCurve->IsKind( STANDARD_TYPE( Geom_BSplineCurve ) ) )
454   {
455     Handle(Geom_BSplineCurve) aSpline = Handle(Geom_BSplineCurve)::DownCast( theCurve );
456
457     Handle(TColgp_HArray1OfPnt2d) poles = To2D( aSpline->Poles(), theTr, theUMin, theUMax );
458     const TColStd_Array1OfReal& knots = aSpline->Knots();
459     const TColStd_Array1OfInteger& multiplicities = aSpline->Multiplicities();
460     int aDegree = aSpline->Degree();
461
462     return new Geom2d_BSplineCurve( poles->Array1(), knots, multiplicities, aDegree );
463   }
464
465   return Handle(Geom2d_Curve)();
466 }
467
468 Handle_Geom2d_BSplineCurve HYDROData_DTM::CreateHydraulicAxis( 
469   const std::vector<Handle_HYDROData_Profile>& theProfiles,
470   std::vector<double>& theDistances )
471 {
472   size_t n = theProfiles.size();
473   Handle_Geom2d_BSplineCurve aResult;
474
475   Handle(TColgp_HArray1OfPnt2d) points = new TColgp_HArray1OfPnt2d( 1, (int)n );
476   TColgp_Array1OfVec2d tangents( 1, (int)n );
477   Handle(TColStd_HArray1OfBoolean) flags = new TColStd_HArray1OfBoolean( 1, (int)n );
478
479   for( size_t i = 1; i <= n; i++ )
480   {
481     Handle_HYDROData_Profile aProfile = theProfiles[i-1];
482     aProfile->Update();
483
484     gp_Pnt aLowest;
485     gp_Vec2d aTangent;
486     double zmin, zmax;
487     GetProperties( aProfile, aLowest, aTangent, true, zmin, zmax );
488     aTangent.Normalize();
489
490     points->SetValue( (int)i, gp_Pnt2d( aLowest.X(), aLowest.Y() ) );
491     tangents.SetValue( (int)i, aTangent );
492     flags->SetValue( (int)i, Standard_True );
493   }
494
495   Geom2dAPI_Interpolate anInterpolator( points, Standard_False, Standard_False );
496   anInterpolator.Load( tangents, flags );
497   anInterpolator.Perform();
498   if( anInterpolator.IsDone() )
499   {
500     aResult = anInterpolator.Curve();
501
502     //fill the distances vector
503     Geom2dAdaptor_Curve anAdaptor( aResult );
504
505     theDistances.clear();
506     theDistances.reserve( n );
507     Standard_Real aParamFirst = anAdaptor.FirstParameter(), aParamLast = anAdaptor.LastParameter();
508     for( size_t i = 1; i <= n; i++ )
509     {
510       gp_Pnt2d aPnt = points->Value( (Standard_Integer)i );
511       Geom2dAPI_ProjectPointOnCurve aProject( aPnt, aResult );
512       Standard_Real aParam = aProject.LowerDistanceParameter();
513       double aDistance = GCPnts_AbscissaPoint::Length( anAdaptor, aParamFirst, aParam );  
514       theDistances.push_back( aDistance );
515     }
516   }
517   return aResult;
518 }
519
520 std::vector<Handle_Geom2d_Curve> HYDROData_DTM::ProfileToParametric( 
521   const Handle_HYDROData_Profile& theProfile,
522   double& theUMin, double& theUMax, gp_Vec2d& theDir )
523 {
524   std::vector<Handle_Geom2d_Curve> curves;
525   
526   // Transformation of the coordinate systems
527   gp_Pnt aLowest;
528   double zmin, zmax;
529   GetProperties( theProfile, aLowest, theDir, false, zmin, zmax );
530
531   gp_Ax3 aStd3d( gp_Pnt( 0, 0, 0 ), gp_Dir( 0, 0, 1 ), gp_Dir( 1, 0, 0 ) );
532   gp_Ax3 aLocal( aLowest, gp_Dir( 0, 0, 1 ), gp_Dir( theDir.X(), theDir.Y(), 0 ) );
533
534   gp_Trsf aTransf;
535   aTransf.SetTransformation( aStd3d, aLocal );
536
537   // Iteration via edges
538   TopoDS_Wire aWire = TopoDS::Wire( theProfile->GetShape3D() );
539   TopExp_Explorer anExp( aWire, TopAbs_EDGE );
540   for( ; anExp.More(); anExp.Next() )
541   {
542     // Extract an edge from wire
543     TopoDS_Edge anEdge = TopoDS::Edge( anExp.Current() );
544
545     // Extract a curve corresponding to the edge
546     TopLoc_Location aLoc;
547     Standard_Real aFirst, aLast;
548     Handle(Geom_Curve) aCurve = BRep_Tool::Curve( anEdge, aLoc, aFirst, aLast );
549
550     // Convert the curve to 2d CS
551     Handle(Geom2d_Curve) aCurve2d = CurveTo2D( aCurve, aFirst, aLast, aTransf, theUMin, theUMax );
552     if( !aCurve2d.IsNull() )
553       curves.push_back( aCurve2d );
554   }
555   return curves;
556 }
557
558
559 bool CalcMidWidth( const std::vector<gp_Pnt2d>& intersections, double& theMid, double& theWid )
560 {
561   double umin = std::numeric_limits<double>::max(),
562          umax = -umin;
563
564   size_t n = intersections.size();
565   if( n <= 1 )
566     return false;
567
568   for( size_t i = 0; i < n; i++ )
569   {
570     double u = intersections[i].X();
571     if( u<umin )
572       umin = u;
573     if( u>umax )
574       umax = u;
575   }
576   theMid = ( umin+umax )/2;
577   theWid = umax-umin;
578   return true;
579 }
580
581 void HYDROData_DTM::ProfileDiscretization( const Handle_HYDROData_Profile& theProfile, 
582                                            double theXCurv, double theMinZ, double theMaxZ, double theDDZ,
583                                            CurveUZ& theMidPointCurve,
584                                            CurveUZ& theWidthCurve,
585                                            double theTolerance )
586 {
587   double aDblMax = std::numeric_limits<double>::max(),
588          aUMin = aDblMax,
589          aUMax = -aUMin,
590          aVMax = 1000000;
591   
592   gp_Vec2d aProfileDir;
593   std::vector<Handle_Geom2d_Curve> curves = ProfileToParametric( theProfile, aUMin, aUMax, aProfileDir );
594   size_t n = curves.size();
595
596   if( n==0 )
597     return;
598
599   // we add the "virtual" vertical lines to simulate the intersection with profile 
600   gp_Pnt2d aFirst, aLast;
601   curves[0]->D0( curves[0]->FirstParameter(), aFirst );
602   curves[n-1]->D0( curves[n-1]->LastParameter(), aLast );
603   Handle(Geom2d_Line) aV1 = new Geom2d_Line( aFirst, gp_Dir2d( 0, 1 ) );
604   Handle(Geom2d_TrimmedCurve) aT1 = new Geom2d_TrimmedCurve( aV1, 0.0, aVMax );
605   
606   Handle(Geom2d_Line) aV2 = new Geom2d_Line( aLast, gp_Dir2d( 0, 1 ) );
607   Handle(Geom2d_TrimmedCurve) aT2 = new Geom2d_TrimmedCurve( aV2, 0.0, aVMax );
608
609   curves.push_back( aT1 );
610   curves.push_back( aT2 );
611   
612   int psize = ( int )( ( theMaxZ-theMinZ ) / theDDZ + 1 );
613   theMidPointCurve = CurveUZ( theXCurv, aProfileDir );
614   theMidPointCurve.reserve( psize );
615   theWidthCurve = CurveUZ( theXCurv, aProfileDir );
616   theWidthCurve.reserve( psize );
617
618   n = curves.size();
619   // for each discrete value of z we search intersection with profile
620   for( double z = theMinZ; z <= theMaxZ; z += theDDZ )
621   {
622     Handle(Geom2d_Line) aLine = new Geom2d_Line( gp_Pnt2d( 0, z ), gp_Dir2d( 1, 0 ) );
623     std::vector<gp_Pnt2d> intersections;
624     for( size_t i = 0; i < n; i++ )
625     {
626       Handle_Geom2d_Curve aCurve = curves[i];
627       Geom2dAPI_InterCurveCurve anIntersect( aCurve, aLine, theTolerance );
628       for( int k=1, m=anIntersect.NbPoints(); k<=m; k++ )
629         intersections.push_back( anIntersect.Point( k ) );
630     }
631
632     if( intersections.size() >= 2 )
633     {
634       double u_mid, u_wid;
635       if( !CalcMidWidth( intersections, u_mid, u_wid ) )
636         continue;
637
638       PointUZ p_mid;
639       p_mid.U = u_mid;
640       p_mid.Z = z;
641       theMidPointCurve.push_back( p_mid );
642
643       PointUZ p_wid;
644       p_wid.U = u_wid;
645       p_wid.Z = z;
646       theWidthCurve.push_back( p_wid );
647     }
648   }
649 }
650
651 void HYDROData_DTM::Interpolate( const CurveUZ& theCurveA, const CurveUZ& theCurveB, 
652                                  int theNbSteps, std::vector<CurveUZ>& theInterpolation,
653                                  bool isAddSecond )
654 {
655   theInterpolation.clear();
656   int d = isAddSecond ? 2 : 1;
657   theInterpolation.reserve( theNbSteps+d );
658   double dt = 1.0 / double( theNbSteps + 1 );
659   double t = dt;
660   theInterpolation.push_back( theCurveA );
661   for( int i=0; i<theNbSteps; i++, t+=dt )
662   {
663     CurveUZ anInterp = theCurveA*(1-t) + theCurveB*t;
664     theInterpolation.push_back( anInterp );
665   }
666   if( isAddSecond )
667     theInterpolation.push_back( theCurveB );
668 }
669 #include <BRepLib_MakeEdge2d.hxx>
670 void HYDROData_DTM::CurveTo3D( const Handle_Geom2d_BSplineCurve& theHydraulicAxis,
671                                const CurveUZ& theMidCurve, const CurveUZ& theWidthCurve,
672                                AltitudePoints& thePoints, double dz )
673 {
674   Geom2dAdaptor_Curve anAdaptor( theHydraulicAxis );
675   TopoDS_Edge E2d = BRepLib_MakeEdge2d(theHydraulicAxis).Edge();
676   GCPnts_AbscissaPoint ap( anAdaptor, theMidCurve.Xcurv(), anAdaptor.FirstParameter() );  
677   double aParam = ap.Parameter();
678
679   gp_Pnt2d point;
680   anAdaptor.D0( aParam, point );
681   gp_Vec2d profile_dir = theMidCurve.ProfileDir();
682   gp_Dir tangent_n( -profile_dir.Y(), profile_dir.X(), dz );
683   profile_dir.Normalize();
684   
685   size_t n = theMidCurve.size();
686   std::map<double, AltitudePoint> sorted_points;
687   for( size_t i=0; i<n; i++ )
688   {
689     double param1 = theMidCurve[i].U - theWidthCurve[i].U / 2;
690     double param2 = theMidCurve[i].U + theWidthCurve[i].U / 2;
691
692     gp_Pnt2d p1 = point.Translated( param1 * profile_dir);
693     gp_Pnt2d p2 = point.Translated( param2 * profile_dir);
694
695     double z = theMidCurve[i].Z;
696
697     AltitudePoint p3d_1( p1.X(), p1.Y(), z ), p3d_2( p2.X(), p2.Y(), z );
698
699     sorted_points[param1] = p3d_1;
700     sorted_points[param2] = p3d_2;
701   }
702
703   thePoints.reserve( sorted_points.size() );
704   std::map<double, AltitudePoint>::const_iterator it = sorted_points.begin(), last = sorted_points.end();
705   for( ; it!=last; it++ )
706     thePoints.push_back( it->second );
707 }
708
709 inline double max( double a, double b )
710 {
711   if( a>b )
712     return a;
713   else
714     return b;
715 }
716
717 #include <BRepLib_MakeWire.hxx>
718
719 std::vector<HYDROData_Bathymetry::AltitudePoints> HYDROData_DTM::Interpolate
720   ( const Handle_Geom2d_BSplineCurve& theHydraulicAxis,
721     const Handle_HYDROData_Profile& theProfileA,
722     double theXCurvA,
723     const Handle_HYDROData_Profile& theProfileB,
724     double theXCurvB,
725     double theDDZ, int theNbSteps, bool isAddSecond )
726 {
727   double zminA, zmaxA, zminB, zmaxB;
728   gp_Pnt lowestA, lowestB;
729   gp_Vec2d dirA, dirB;
730
731   GetProperties( theProfileA, lowestA, dirA, false, zminA, zmaxA ); 
732   GetProperties( theProfileB, lowestB, dirB, false, zminB, zmaxB ); 
733
734   double dz = zminB - zminA;
735
736   double zmin = max( zminA, zminB );
737   double zmax = max( zmaxA, zmaxB );
738
739   CurveUZ midA(0, gp_Vec2d()), midB(0, gp_Vec2d());
740   CurveUZ widA(0, gp_Vec2d()), widB(0, gp_Vec2d());
741
742   ProfileDiscretization( theProfileA, theXCurvA, zmin, zmax, theDDZ, midA, widA ); 
743   ProfileDiscretization( theProfileB, theXCurvB, zmin, zmax, theDDZ, midB, widB );
744
745   std::vector<CurveUZ> mid, wid;
746   Interpolate( midA, midB, theNbSteps, mid, isAddSecond );
747   Interpolate( widA, widB, theNbSteps, wid, isAddSecond );
748
749   size_t p = mid.size();
750   size_t q = p>0 ? 2*mid[0].size() : 1;
751   std::vector<AltitudePoints> points;
752   points.resize( p );
753
754   for( size_t i=0; i<p; i++ )
755   {
756     points[i].reserve( q );
757     CurveTo3D( theHydraulicAxis, mid[i], wid[i], points[i], dz );
758   }
759
760   return points;
761 }
762
763 HYDROData_Bathymetry::AltitudePoints HYDROData_DTM::Interpolate
764   ( const std::vector<Handle_HYDROData_Profile>& theProfiles,
765     double theDDZ, double theSpatialStep,
766     AltitudePoints& theLeft,
767     AltitudePoints& theRight,
768     std::vector<AltitudePoints>& theMainProfiles )
769 {
770   AltitudePoints points;
771   size_t n = theProfiles.size();
772   if( n<=1 )
773     return points;
774
775   std::vector<double> distances;
776   Handle_Geom2d_BSplineCurve aHydraulicAxis = CreateHydraulicAxis( theProfiles, distances );
777   if( aHydraulicAxis.IsNull() )
778     return points;
779
780   theMainProfiles.reserve( n );
781
782   for( size_t i=0, n1=n-1; i<n1; i++ )
783   {
784     double aDistance = distances[i+1]-distances[i];
785     int aNbSteps = int(aDistance/theSpatialStep);
786     bool isAddSecond = i==n1-1;
787
788     // 1. Calculate interpolated profiles
789     std::vector<AltitudePoints> local_points = Interpolate( aHydraulicAxis, theProfiles[i], distances[i], 
790       theProfiles[i+1], distances[i+1], theDDZ, aNbSteps, isAddSecond );
791     int lps = local_points.size();
792
793     // 2. Put all points into the global container
794     for( size_t j=0; j<lps; j++ )
795     {
796       const AltitudePoints& lp = local_points[j];
797       if( i==0 && j==0 )
798         points.reserve( lp.size() * n );
799       for( size_t k=0, ks=lp.size(); k<ks; k++ )
800         points.push_back( lp[k] );
801     }
802
803     // 3. Get left/right banks' points
804     if( i==0 )
805     {
806       theLeft.reserve( lps * n );
807       theRight.reserve( lps * n );
808     }
809     for( size_t j=0; j<lps; j++ )
810     {
811       const AltitudePoints& lp = local_points[j];
812       theLeft.push_back( lp[0] );
813       theRight.push_back( lp[lp.size()-1] );
814     }
815
816     // 4. Get main profiles points
817     theMainProfiles.push_back( local_points[0] );
818     if( isAddSecond )
819       theMainProfiles.push_back( local_points[lps-1] );
820   }
821   return points;
822 }