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