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