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