Salome HOME
2e7ffffa29416343c07d4f4cfec44b7a1e76567d
[modules/hydro.git] / src / HYDROData / HYDROData_LandCoverMap.cxx
1 // Copyright (C) 2014-2015  EDF-R&D
2 // This library is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU Lesser General Public
4 // License as published by the Free Software Foundation; either
5 // version 2.1 of the License, or (at your option) any later version.
6 //
7 // This library is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 // Lesser General Public License for more details.
11 //
12 // You should have received a copy of the GNU Lesser General Public
13 // License along with this library; if not, write to the Free Software
14 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
15 //
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
17 //
18
19 #include <HYDROData_LandCoverMap.h>
20 #include <HYDROData_Object.h>
21 #include <HYDROData_PolylineXY.h>
22 #include <HYDROData_Tool.h>
23
24 #include <BOPAlgo_BOP.hxx>
25 #include <BOPAlgo_Builder.hxx>
26 #include <BOPAlgo_PaveFiller.hxx>
27 #include <BOPCol_ListOfShape.hxx>
28 #include <BRep_Builder.hxx>
29 #include <BRepAdaptor_Curve.hxx>
30 #include <BRepAlgoAPI_Fuse.hxx>
31 #include <BRepBuilderAPI_MakeFace.hxx>
32 #include <GCPnts_QuasiUniformDeflection.hxx>
33 #include <NCollection_IndexedMap.hxx>
34 #include <TopoDS.hxx>
35 #include <TopoDS_Compound.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopoDS_Face.hxx>
38 #include <TopoDS_Iterator.hxx>
39 #include <TopoDS_Shell.hxx>
40 #include <TopExp_Explorer.hxx>
41 #include <TopTools_ListIteratorOfListOfShape.hxx>
42 #include <BOPAlgo_PaveFiller.hxx>
43 #include <BRepTools.hxx>
44 #include <TopExp_Explorer.hxx>
45 #include <ShapeUpgrade_UnifySameDomain.hxx>
46
47 #include <QFile>
48 #include <QString>
49 #include <QTextStream>
50
51 const char TELEMAC_FORMAT = 'f';
52 const int TELEMAC_PRECISION = 3;
53
54
55 IMPLEMENT_STANDARD_HANDLE(HYDROData_LandCoverMap, HYDROData_Entity)
56 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_LandCoverMap, HYDROData_Entity)
57
58 class HYDROData_MapOfFaceToStricklerType : public NCollection_IndexedDataMap<TopoDS_Face, QString>
59 {
60 };
61
62 /**
63   Constructor
64   @param theMap the land cover map to iterate through
65 */
66 HYDROData_LandCoverMap::Iterator::Iterator( const HYDROData_LandCoverMap& theMap )
67 {
68   Init( theMap );
69 }
70
71 HYDROData_LandCoverMap::Iterator::Iterator( const Handle( HYDROData_LandCoverMap )& theMap )
72 {
73   if( theMap.IsNull() )
74   {
75     myIterator = 0;
76     myIndex = -1;
77   }
78   else
79     Init( *theMap );
80 }
81
82 /**
83   Initialize the iterator
84   @param theMap the land cover map to iterate through
85 */
86 void HYDROData_LandCoverMap::Iterator::Init( const HYDROData_LandCoverMap& theMap )
87 {
88   TopoDS_Shape aShape = theMap.GetShape();
89   if( aShape.IsNull() )
90     myIterator = 0;
91   else
92     myIterator = new TopoDS_Iterator( aShape );
93   myIndex = 0;
94   theMap.myLab.FindChild( DataTag_Types ).FindAttribute( TDataStd_ExtStringArray::GetID(), myArray );
95 }
96
97 /**
98   Destructor
99 */
100 HYDROData_LandCoverMap::Iterator::~Iterator()
101 {
102   delete myIterator;
103 }
104
105 /**
106   Return if the iterator has more elements
107   @return if the iterator has more elements
108 */
109 bool HYDROData_LandCoverMap::Iterator::More() const
110 {
111   return !myArray.IsNull() && myIterator && myIterator->More();
112 }
113
114 /**
115   Move iterator to the next element
116 */
117 void HYDROData_LandCoverMap::Iterator::Next()
118 {
119   if( myIterator )
120   {
121     myIterator->Next();
122     myIndex++;
123   }
124 }
125
126 /**
127   Get the current land cover (face)
128   @return the land cover's face
129 */
130 TopoDS_Face HYDROData_LandCoverMap::Iterator::Face() const
131 {
132   if( myIterator )
133     return TopoDS::Face( myIterator->Value() );
134   else
135     return TopoDS_Face();
136 }
137
138 /**
139   Get the current land cover's Strickler type 
140   @return the land cover's Strickler type 
141 */
142 QString HYDROData_LandCoverMap::Iterator::StricklerType() const
143 {
144   if( myArray.IsNull() || myIndex < myArray->Lower() || myIndex > myArray->Upper() )
145     return "";
146   else
147     return HYDROData_Tool::toQString( myArray->Value( myIndex ) );
148 }
149
150 /**
151   Constructor
152 */
153 HYDROData_LandCoverMap::HYDROData_LandCoverMap()
154   : HYDROData_Entity( Geom_No )
155 {
156 }
157
158 /**
159   Destructor
160 */
161 HYDROData_LandCoverMap::~HYDROData_LandCoverMap()
162 {
163 }
164
165 /**
166   Get object's kind
167   @return object's kind
168 */
169 const ObjectKind HYDROData_LandCoverMap::GetKind() const
170 {
171   return KIND_LAND_COVER_MAP;
172 }
173
174 /**
175   Import the land cover map from QGIS
176   @param theFileName the name of file
177   @return if the import is successful
178 */
179 bool HYDROData_LandCoverMap::ImportQGIS( const QString& theFileName )
180 {
181   //TODO
182   return false;
183 }
184
185 /**
186   Export the land cover map to QGIS
187   @param theFileName the name of file
188   @return if the export is successful
189 */
190 bool HYDROData_LandCoverMap::ExportQGIS( const QString& theFileName ) const
191 {
192   //TODO
193   return false;
194 }
195
196 int HashCode( const gp_Pnt& thePoint, const Standard_Integer theUpper )
197 {
198   int aHashX = HashCode( thePoint.X(), theUpper );
199   int aHashY = HashCode( thePoint.Y(), theUpper );
200   return (aHashX^aHashY)%theUpper;
201 }
202
203 bool operator == ( const gp_Pnt& thePoint1, const gp_Pnt& thePoint2 )
204 {
205   return thePoint1.IsEqual( thePoint2, Precision::Confusion() );
206 }
207
208 bool EdgeDiscretization( const TopoDS_Edge& theEdge, 
209                          Standard_Real theDeflection,
210                          NCollection_IndexedMap<gp_Pnt>& theVerticesMap,
211                          QList<int>& theVerticesIds )
212 {
213   BRepAdaptor_Curve aCurve( theEdge );
214   GCPnts_QuasiUniformDeflection aDiscrete( aCurve, theDeflection );
215   if( !aDiscrete.IsDone() )
216     return false;
217
218   int n = aDiscrete.NbPoints();
219   for( int i=1; i<=n; i++ )
220   {
221     gp_Pnt aPnt = aDiscrete.Value( i );
222     int anId;
223     if( theVerticesMap.Contains( aPnt ) )
224       anId = theVerticesMap.FindIndex( aPnt );
225     else
226     {
227       anId = theVerticesMap.Size();
228       theVerticesMap.Add( aPnt );
229     }
230     theVerticesIds.append( anId );
231   }
232   return true;
233 }
234
235 /**
236   Export the land cover map for the solver (Telemac)
237   @param theFileName the name of file
238   @return if the export is successful
239 */
240 bool HYDROData_LandCoverMap::ExportTelemac( const QString& theFileName, Standard_Real theDeflection ) const
241 {
242   TopoDS_Shape aLandCoverMapShape = GetShape();
243   TopTools_ListOfShape aListOfFaces;
244   TopExp_Explorer anExp( aLandCoverMapShape, TopAbs_FACE );
245   for( ; anExp.More(); anExp.Next() )
246     aListOfFaces.Append( anExp.Current() );
247
248   TopoDS_Shape aShape = MergeFaces( aListOfFaces, false );
249
250   NCollection_IndexedMap<gp_Pnt> aVerticesMap;
251   NCollection_IndexedDataMap< TopoDS_Edge, QList<int> > anEdgesMap;
252   NCollection_IndexedDataMap< TopoDS_Face, QList<int> > aFacesMap;
253
254   // add into the map all edges existing in the shell
255   TopExp_Explorer anExp1( aShape, TopAbs_EDGE );
256   for( ; anExp1.More(); anExp1.Next() )
257   {
258     TopoDS_Edge anEdge = TopoDS::Edge( anExp1.Current() );
259     QList<int> aVerticesIdsList;
260     if( EdgeDiscretization( anEdge, theDeflection, aVerticesMap, aVerticesIdsList ) )
261       anEdgesMap.Add( anEdge, aVerticesIdsList );
262   }
263
264   // add into the map all faces existing in the shell and correspondence between face and edges ids
265   TopExp_Explorer anExp2( aShape, TopAbs_FACE );
266   for( ; anExp2.More(); anExp2.Next() )
267   {
268     TopoDS_Face aFace = TopoDS::Face( anExp2.Current() );
269     TopExp_Explorer anExp3( aFace, TopAbs_EDGE );
270     QList<int> anEdgesIdsList;
271     for( ; anExp3.More(); anExp3.Next() )
272     {
273       TopoDS_Edge anEdge = TopoDS::Edge( anExp3.Current() );
274       int anEdgeId = anEdgesMap.FindIndex( anEdge );
275       anEdgesIdsList.append( anEdgeId );
276     }
277     aFacesMap.Add( aFace, anEdgesIdsList );
278   }
279
280   QFile aFile( theFileName );
281   if( !aFile.open( QFile::WriteOnly | QFile::Text ) )
282     return false;
283
284   QTextStream aStream( &aFile );
285   aStream << "# nodes\n";
286   NCollection_IndexedMap<gp_Pnt>::Iterator anIt1( aVerticesMap );
287   for( ; anIt1.More(); anIt1.Next() )
288   {
289     gp_Pnt aPnt = anIt1.Value();
290     aStream << QString::number( aPnt.X(), TELEMAC_FORMAT, TELEMAC_PRECISION );
291     aStream << " ";
292     aStream << QString::number( aPnt.Y(), TELEMAC_FORMAT, TELEMAC_PRECISION );
293     aStream << " ";
294     aStream << QString::number( aPnt.Z(), TELEMAC_FORMAT, TELEMAC_PRECISION );
295     aStream << "\n";
296   }
297   aStream << "\n";
298
299   aStream << "# edges\n";
300   NCollection_IndexedDataMap< TopoDS_Edge, QList<int> >::Iterator anIt2( anEdgesMap );
301   for( ; anIt2.More(); anIt2.Next() )
302   {
303     QList<int> aVerticesIds = anIt2.Value();
304     foreach( int anId, aVerticesIds )
305       aStream << anId << " ";
306     aStream << "\n";
307   }
308   aStream << "\n";
309
310   aStream << "# faces\n";
311   NCollection_IndexedDataMap< TopoDS_Face, QList<int> >::Iterator anIt3( aFacesMap );
312   for( ; anIt3.More(); anIt3.Next() )
313   {
314     QList<int> anEdgesIds = anIt3.Value();
315     foreach( int anId, anEdgesIds )
316       aStream << anId << " ";
317     aStream << "\n";
318   }
319   aStream << "\n";
320
321   aFile.close();
322   return true;
323 }
324
325 /**
326   Add a new object as land cover
327   @param theObject the object to add as land cover
328   @param theType the Strickler type for the new land cover
329   @return if the addition is successful
330 */
331 bool HYDROData_LandCoverMap::Add( const Handle( HYDROData_Object )& theObject, const QString& theType )
332 {
333   if( theObject.IsNull() )
334     return false;
335
336   TopoDS_Shape aShape = theObject->GetTopShape();
337   if( aShape.ShapeType()!=TopAbs_FACE )
338     return false;
339
340   TopoDS_Face aFace = TopoDS::Face( aShape );
341   return LocalPartition( aFace, theType );
342 }
343
344 /**
345   Add a new polyline as land cover
346   @param thePolyline the polyline to add as land cover
347   @param theType the Strickler type for the new land cover
348   @return if the addition is successful
349 */
350 bool HYDROData_LandCoverMap::Add( const Handle( HYDROData_PolylineXY )& thePolyline, const QString& theType )
351 {
352   if( thePolyline.IsNull() )
353     return false;
354
355   TopoDS_Shape aShape = thePolyline->GetShape();
356   if( aShape.ShapeType()!=TopAbs_WIRE )
357     return false;
358
359   TopoDS_Wire aWire = TopoDS::Wire( aShape );
360   if( !aWire.Closed() )
361     return false;
362
363   TopoDS_Face aFace = BRepBuilderAPI_MakeFace( aWire, Standard_True ).Face();
364   return LocalPartition( aFace, theType );
365 }
366
367 /**
368   Remove the given face from land cover map
369   @param theFace the face to be removed
370   @return if the removing is successful
371 */
372 bool HYDROData_LandCoverMap::Remove( const TopoDS_Face& theFace )
373 {
374   TopTools_ListOfShape aList;
375   aList.Append( theFace );
376   return Remove( aList );
377 }
378
379 /**
380   Remove the given faces from land cover map
381   @param theFacesToRemove the face list to be removed
382   @return if the removing is successful
383 */
384 bool HYDROData_LandCoverMap::Remove( const TopTools_ListOfShape& theFacesToRemove )
385 {
386   HYDROData_MapOfFaceToStricklerType aFacesToRemove, aNewFaces;
387   TopTools_ListIteratorOfListOfShape aFIt( theFacesToRemove );
388   for( ; aFIt.More(); aFIt.Next() )
389   {
390     TopoDS_Shape aShape = aFIt.Value();
391     if( aShape.ShapeType()==TopAbs_FACE )
392       aFacesToRemove.Add( TopoDS::Face( aShape ), "" );
393   }
394
395   Iterator anIt( *this );
396   for( ; anIt.More(); anIt.Next() )
397     if( !aFacesToRemove.Contains( anIt.Face() ) )
398       aNewFaces.Add( anIt.Face(), anIt.StricklerType() );
399
400   StoreLandCovers( aNewFaces );
401   return true;
402 }
403
404 /**
405   Split the land cover map by the given polyline
406   @param thePolyline the tool polyline to split the land cover map
407   @return if the removing is successful
408 */
409 bool HYDROData_LandCoverMap::Split( const Handle( HYDROData_PolylineXY )& thePolyline )
410 {
411   if( thePolyline.IsNull() )
412     return false;
413
414   TopoDS_Shape aShape = thePolyline->GetShape();
415   return LocalPartition( aShape, "" );
416 }
417
418 /**
419   Merge the given faces in the land cover
420   @param theFaces the faces to merge in the land cover map
421   @param theType the Strickler type for the merged land cover
422   @return if the merge is successful
423 */
424 bool HYDROData_LandCoverMap::Merge( const TopTools_ListOfShape& theFaces, const QString& theType )
425 {
426   // 1. to fuse the faces into the new face
427   TopoDS_Shape aMergedFace = MergeFaces( theFaces, true );
428   if( aMergedFace.ShapeType()==TopAbs_FACE )
429   {
430     // 2. to remove the merged faces from the current map
431     Remove( theFaces );
432
433     // 3. to add the face into the map
434     return LocalPartition( TopoDS::Face( aMergedFace ), theType );
435   }
436   return false;
437 }
438
439 TopoDS_Shape HYDROData_LandCoverMap::MergeFaces( const TopTools_ListOfShape& theFaces,
440                                                  bool IsToUnify, double theTolerance )
441 {
442   int anError;
443   TopTools_ListIteratorOfListOfShape anIt;
444   BOPCol_ListOfShape aLC;
445   anIt.Initialize(theFaces);
446   for( ; anIt.More(); anIt.Next() )
447     aLC.Append( anIt.Value() );
448
449   BOPAlgo_PaveFiller aPF;
450   aPF.SetArguments( aLC );
451   aPF.SetRunParallel( Standard_False );
452   aPF.SetFuzzyValue( theTolerance );
453
454   aPF.Perform();
455   anError = aPF.ErrorStatus();
456   if( anError )
457     return TopoDS_Shape();
458
459   BOPAlgo_Builder anAlgo;
460   anIt.Initialize( theFaces );
461   for( ; anIt.More(); anIt.Next() )
462     anAlgo.AddArgument( anIt.Value() );
463
464   anAlgo.PerformWithFiller( aPF ); 
465   anError = anAlgo.ErrorStatus();
466   if( anError )
467     return TopoDS_Shape();
468
469   const TopoDS_Shape& aMergedShape = anAlgo.Shape();
470
471   BRep_Builder aBuilder;
472   TopoDS_Shell aShell; 
473   aBuilder.MakeShell( aShell ); 
474   aShell.Closed( Standard_False );
475   TopExp_Explorer anExplorer( aMergedShape, TopAbs_FACE );
476   for( ; anExplorer.More(); anExplorer.Next() ) 
477   {
478     const TopoDS_Face& aFace = TopoDS::Face(anExplorer.Current());
479     if( aFace.IsNull() ) 
480       continue;
481     if( aFace.ShapeType() == TopAbs_FACE )
482     {
483       aBuilder.Add( aShell, aFace );
484       aShell.Closed( Standard_False );
485     }
486   }
487
488   TopoDS_Shape aResult;
489   if( IsToUnify )
490   {
491     ShapeUpgrade_UnifySameDomain aUSD;
492     aUSD.Initialize( aShell );
493     aUSD.Build();
494     aResult = aUSD.Shape();
495   }
496   else
497     aResult = aShell;
498
499   anExplorer.Init( aResult, TopAbs_FACE );
500   int i = 0;
501   TopoDS_Face anOneFace;
502   for( ; anExplorer.More(); anExplorer.Next(), i++ ) 
503     anOneFace = TopoDS::Face( anExplorer.Current() );
504
505   if( i == 1 )
506     aResult = anOneFace;
507
508   return aResult;
509 }
510
511 /**
512   Get the shape of the land cover map
513 */
514 TopoDS_Shape HYDROData_LandCoverMap::GetShape() const
515 {
516   return HYDROData_Entity::GetShape( DataTag_Shape );
517 }
518
519 /**
520   Set the shape of the land cover map
521   @param theShape the new shape for the land cover map
522 */
523 void HYDROData_LandCoverMap::SetShape( const TopoDS_Shape& theShape )
524 {
525   HYDROData_Entity::SetShape( DataTag_Shape, theShape );
526 }
527
528 /**
529   Perform the local partition algorithm on the land cover
530   @param theNewShape the new shape to add into the land cover
531   @param theNewType the new Strickler type for the new land cover
532   @return if the local partition is successful
533 */
534 bool HYDROData_LandCoverMap::LocalPartition( const TopoDS_Shape& theNewShape, const QString& theNewType )
535 {
536   if( theNewShape.IsNull() )
537     return false;
538
539   BOPCol_ListOfShape aShapesList;
540   BOPAlgo_PaveFiller aPaveFiller;
541   HYDROData_MapOfFaceToStricklerType aNewFaces;
542
543   // add faces to shapes list
544   Iterator anIt( *this );
545   for( ; anIt.More(); anIt.Next() )
546     aShapesList.Append( anIt.Face() );
547   aShapesList.Append( theNewShape );
548
549   if( aShapesList.Size()==1 && theNewShape.ShapeType()==TopAbs_FACE )
550   {
551     aNewFaces.Add( TopoDS::Face( theNewShape ), theNewType );
552     StoreLandCovers( aNewFaces );
553     return true;
554   }
555
556   // prepare pave filler
557   aPaveFiller.SetArguments( aShapesList );
558   aPaveFiller.Perform();
559   Standard_Integer anError = aPaveFiller.ErrorStatus();
560   if( anError )
561     return false;
562
563   // add faces to builder
564   BOPAlgo_Builder aBuilder;
565   anIt.Init( *this );
566   for( ; anIt.More(); anIt.Next() )
567     aBuilder.AddArgument( anIt.Face() );
568   aBuilder.AddArgument( theNewShape );
569
570   // perform the partition with the pave filler
571   aBuilder.PerformWithFiller( aPaveFiller );
572   anError = aBuilder.ErrorStatus();
573   if( anError )
574     return false;
575
576   // analysis of the history
577   //     a. to fill map of shapes which come from the new face
578   NCollection_IndexedMap<TopoDS_Shape> aShapesFromNewFace;
579   //std::cout << "new: " << theNewShape << " " << theNewType << std::endl;
580   TopTools_ListOfShape aModified = aBuilder.Modified( theNewShape );
581   TopTools_ListIteratorOfListOfShape aMIt( aModified );
582   for( ; aMIt.More(); aMIt.Next() )
583   {
584     //std::cout << "   " << aMIt.Value() << std::endl;
585     aShapesFromNewFace.Add( aMIt.Value() );
586   }
587
588   //     b. to fill map of parts except parts from new face
589   anIt.Init( *this );
590   for( ; anIt.More(); anIt.Next() )
591   {
592     QString aSType = anIt.StricklerType();
593     //std::cout << anIt.Face() << " " << anIt.StricklerType() << std::endl;
594     TopTools_ListOfShape aModified = aBuilder.Modified( anIt.Face() );
595     TopTools_ListIteratorOfListOfShape aMIt( aModified );
596     for( ; aMIt.More(); aMIt.Next() )
597     {
598       TopoDS_Shape aShape = aMIt.Value();
599       bool isFace = aShape.ShapeType()==TopAbs_FACE;
600       bool isAlsoFromNew = aShapesFromNewFace.Contains( aShape );
601       //std::cout << "   " << aShape << " " << isAlsoFromNew << std::endl;
602       if( isFace && !isAlsoFromNew )
603         aNewFaces.Add( TopoDS::Face( aShape ), aSType );
604     }
605   }
606
607   //     c. add the new shape if it is face with its type
608   if( theNewShape.ShapeType()==TopAbs_FACE )
609     aNewFaces.Add( TopoDS::Face( theNewShape ), theNewType );
610   
611   // convert map of shape to type to compound and list of types
612   StoreLandCovers( aNewFaces );
613   return true;
614 }
615
616 /**
617   Replace the set of land covers in the land cover map
618   @param theMap the map of shape (face) to Strickler type (string)
619 */
620 void HYDROData_LandCoverMap::StoreLandCovers( const HYDROData_MapOfFaceToStricklerType& theMap )
621 {
622   TopoDS_Compound aCompound;
623   BRep_Builder aCompoundBuilder;
624   aCompoundBuilder.MakeCompound( aCompound );
625
626   int n = theMap.Size();
627   Handle( TDataStd_ExtStringArray ) aTypes = 
628     TDataStd_ExtStringArray::Set( myLab.FindChild( DataTag_Types ), 0, n-1, Standard_True );
629   HYDROData_MapOfFaceToStricklerType::Iterator aNFIt( theMap );
630   for( int i=0; aNFIt.More(); aNFIt.Next(), i++ )
631   {
632     TopoDS_Face aFace = aNFIt.Key();
633     QString aType = aNFIt.Value();
634     aCompoundBuilder.Add( aCompound, aFace );
635     aTypes->SetValue( i, HYDROData_Tool::toExtString( aType ) );
636   }
637
638   SetShape( aCompound );
639 }
640
641 /**
642   Find the land cover for the given point
643   @param thePoint the point laying in some land cover
644   @param theType the returned type
645   @return the found land cover's face
646 */
647 TopoDS_Face HYDROData_LandCoverMap::FindByPoint( const gp_Pnt2d& thePoint, QString& theType ) const
648 {
649   //TODO: some more optimal algorithm
650   Iterator anIt( *this );
651   for( ; anIt.More(); anIt.Next() )
652     if( HYDROData_Tool::ComputePointState( thePoint.XY(), anIt.Face() ) == TopAbs_IN )
653     {
654       theType = anIt.StricklerType();
655       return anIt.Face();
656     }
657
658   theType = "";
659   return TopoDS_Face();
660 }