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