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