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