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