Salome HOME
Merge branch 'BR_LAND_COVER_MAP' of ssh://git.salome-platform.org/modules/hydro into...
[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 #include <HYDROData_ShapeFile.h>
24
25 #include <BOPAlgo_BOP.hxx>
26 #include <BOPAlgo_Builder.hxx>
27 #include <BOPAlgo_PaveFiller.hxx>
28 #include <BOPCol_ListOfShape.hxx>
29 #include <BRep_Builder.hxx>
30 #include <BRepAdaptor_Curve.hxx>
31 #include <BRepAlgoAPI_Fuse.hxx>
32 #include <BRepBuilderAPI_MakeFace.hxx>
33 #include <GCPnts_QuasiUniformDeflection.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 <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
43 #include <BOPAlgo_PaveFiller.hxx>
44 #include <BRepTools.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <ShapeUpgrade_UnifySameDomain.hxx>
47 #include <TopExp.hxx>
48 #include <TopTools_IndexedMapOfShape.hxx>
49 #include <ShapeBuild_ReShape.hxx>
50 #include <ShapeFix_Shape.hxx>
51
52
53 #include <QFile>
54 #include <QString>
55 #include <QTextStream>
56
57 const char TELEMAC_FORMAT = 'f';
58 const int TELEMAC_PRECISION = 3;
59
60
61 IMPLEMENT_STANDARD_HANDLE(HYDROData_LandCoverMap, HYDROData_Entity)
62 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_LandCoverMap, HYDROData_Entity)
63
64 /**
65   Constructor
66   @param theMap the land cover map to iterate through
67 */
68 HYDROData_LandCoverMap::Iterator::Iterator( const HYDROData_LandCoverMap& theMap )
69 {
70   Init( theMap );
71 }
72
73 HYDROData_LandCoverMap::Iterator::Iterator( const Handle( HYDROData_LandCoverMap )& theMap )
74 {
75   if( theMap.IsNull() )
76   {
77     myIterator = 0;
78     myIndex = -1;
79   }
80   else
81     Init( *theMap );
82 }
83
84 /**
85   Initialize the iterator
86   @param theMap the land cover map to iterate through
87 */
88 void HYDROData_LandCoverMap::Iterator::Init( const HYDROData_LandCoverMap& theMap )
89 {
90   TopoDS_Shape aShape = theMap.GetShape();
91   if( aShape.IsNull() )
92     myIterator = 0;
93   else
94     myIterator = new TopoDS_Iterator( aShape );
95   
96   theMap.myLab.FindChild( DataTag_Types ).FindAttribute( TDataStd_ExtStringArray::GetID(), myArray );
97   if( myArray.IsNull() )
98     myIndex = -1;
99   else
100     myIndex = myArray->Lower();
101 }
102
103 /**
104   Destructor
105 */
106 HYDROData_LandCoverMap::Iterator::~Iterator()
107 {
108   delete myIterator;
109 }
110
111 /**
112   Return the current 0-based index of the iterator
113   @return the current index
114 */
115 int HYDROData_LandCoverMap::Iterator::Index() const
116 {
117   if( myArray.IsNull() )
118     return -1;
119   else
120     return myIndex - myArray->Lower();
121 }
122
123 /**
124   Return if the iterator has more elements
125   @return if the iterator has more elements
126 */
127 bool HYDROData_LandCoverMap::Iterator::More() const
128 {
129   return !myArray.IsNull() && myIterator && myIterator->More();
130 }
131
132 /**
133   Move iterator to the next element
134 */
135 void HYDROData_LandCoverMap::Iterator::Next()
136 {
137   if( myIterator )
138   {
139     myIterator->Next();
140     myIndex++;
141   }
142 }
143
144 /**
145   Get the current land cover (face)
146   @return the land cover's face
147 */
148 TopoDS_Face HYDROData_LandCoverMap::Iterator::Face() const
149 {
150   if( myIterator )
151     return TopoDS::Face( myIterator->Value() );
152   else
153     return TopoDS_Face();
154 }
155
156 /**
157   Get the current land cover's Strickler type 
158   @return the land cover's Strickler type 
159 */
160 QString HYDROData_LandCoverMap::Iterator::StricklerType() const
161 {
162   if( myArray.IsNull() || myIndex < myArray->Lower() || myIndex > myArray->Upper() )
163     return "";
164   else
165     return HYDROData_Tool::toQString( myArray->Value( myIndex ) );
166 }
167
168 /**
169   Set the Strickler type for the current land cover
170   @param theType the Strickler type
171 */
172 void HYDROData_LandCoverMap::Iterator::SetStricklerType( const QString& theType )
173 {
174   if( myArray.IsNull() || myIndex < myArray->Lower() || myIndex > myArray->Upper() )
175     return;
176   else
177     myArray->SetValue( myIndex, HYDROData_Tool::toExtString( theType ) );
178 }
179
180 /**
181   Constructor
182 */
183 HYDROData_LandCoverMap::HYDROData_LandCoverMap()
184   : HYDROData_Entity( Geom_No )
185 {
186 }
187
188 /**
189   Destructor
190 */
191 HYDROData_LandCoverMap::~HYDROData_LandCoverMap()
192 {
193 }
194
195 /**
196   Get object's kind
197   @return object's kind
198 */
199 const ObjectKind HYDROData_LandCoverMap::GetKind() const
200 {
201   return KIND_LAND_COVER_MAP;
202 }
203
204 int HYDROData_LandCoverMap::GetLCCount() const
205 {
206   Iterator anIt( *this );
207   int i = 0;
208   for( ; anIt.More(); anIt.Next() )
209     i++;
210   return i;
211 }
212
213 bool HYDROData_LandCoverMap::IsEmpty() const
214 {
215   Iterator anIt( *this );
216   if ( !anIt.More() )
217     return true;
218   else
219     return false;
220 }
221
222 /**
223   Load attributes from DBF File
224 ///
225 */
226 HYDROData_LandCoverMap::DBFStatus HYDROData_LandCoverMap::ImportDBF( const QString& theDBFFileName, 
227                                                                      const QString& theFieldName, 
228                                                                      const QStringList& theDBFValues,
229                                                                      const QStringList& theStricklerTypes,
230                                                                      const QList<int>& theIndices )
231 {
232   if (theDBFValues.size() != theStricklerTypes.size())
233     return DBFStatus_DIFF_SIZE_ERROR;
234   HYDROData_ShapeFile aDBFImporter;
235   if (!aDBFImporter.DBF_OpenDBF(theDBFFileName))
236     return DBFStatus_OPEN_FILE_ERROR; //cant open file
237
238   QStringList FieldList = aDBFImporter.DBF_GetFieldList();
239   int FieldNameIndex = FieldList.indexOf(theFieldName);
240   if (FieldNameIndex == -1)
241     return DBFStatus_NO_SUCH_FIELD_ERROR; //no such field
242
243   std::vector<HYDROData_ShapeFile::DBF_AttrValue> theAttrV;
244   aDBFImporter.DBF_GetAttributeList(FieldNameIndex, theAttrV ); 
245
246   bool allOK = true;
247   Iterator anIt( *this );
248   for( ; anIt.More(); anIt.Next() )
249   {
250     int CurIndex = anIt.Index();
251     HYDROData_ShapeFile::DBF_AttrValue AValue = theAttrV[theIndices[CurIndex]];
252     int StricklerTypesInd = theDBFValues.indexOf(QString(AValue.myStrVal));
253     if ( StricklerTypesInd != -1)
254       anIt.SetStricklerType(theStricklerTypes[StricklerTypesInd]);
255     else
256       allOK = false;
257   }
258   if (allOK)
259     return DBFStatus_OK;
260   else
261     return DBFStatus_NO_DBFVALUES_CORRESPONDENCE_WARNING;
262 }
263
264 /**
265   Export attributes to DBF File
266 ///
267 */
268 void HYDROData_LandCoverMap::ExportDBF( const QString& theDBFFileName, 
269                                         const QString& theFieldName, 
270                                         const QStringList& theDBFValues,
271                                         const QStringList& theStricklerTypes) const
272 {
273   if (theDBFValues.size() != theStricklerTypes.size())
274     return;
275   HYDROData_ShapeFile anExporter; 
276   std::vector<HYDROData_ShapeFile::DBF_AttrValue> theAttrV;
277   Iterator anIt( *this );
278   for( ; anIt.More(); anIt.Next() )
279   {
280     QString CurST = anIt.StricklerType();
281     HYDROData_ShapeFile::DBF_AttrValue aCurAttrV;
282     aCurAttrV.myIsNull = false;
283     int StricklerTypesInd = theStricklerTypes.indexOf(CurST);
284     if (StricklerTypesInd != -1)
285     {
286       aCurAttrV.myStrVal = theDBFValues[StricklerTypesInd];
287       aCurAttrV.myFieldType = HYDROData_ShapeFile::DBF_FieldType_String;
288       theAttrV.push_back(aCurAttrV);
289     }
290     else
291       aCurAttrV.myIsNull = true;
292   }
293   //use actual str value; not the raw value
294   anExporter.DBF_WriteFieldAndValues(theDBFFileName, theFieldName, HYDROData_ShapeFile::DBF_FieldType_String, theAttrV, false);
295
296 }
297
298 int HashCode( const gp_Pnt& thePoint, const Standard_Integer theUpper )
299 {
300   int aHashX = HashCode( thePoint.X(), theUpper );
301   int aHashY = HashCode( thePoint.Y(), theUpper );
302   return (aHashX^aHashY)%theUpper;
303 }
304
305 bool operator == ( const gp_Pnt& thePoint1, const gp_Pnt& thePoint2 )
306 {
307   return thePoint1.IsEqual( thePoint2, Precision::Confusion() );
308 }
309
310 bool EdgeDiscretization( const TopoDS_Edge& theEdge, 
311                          Standard_Real theDeflection,
312                          NCollection_IndexedMap<gp_Pnt>& theVerticesMap,
313                          QList<int>& theVerticesIds )
314 {
315   BRepAdaptor_Curve aCurve( theEdge );
316   GCPnts_QuasiUniformDeflection aDiscrete( aCurve, theDeflection );
317   if( !aDiscrete.IsDone() )
318     return false;
319
320   int n = aDiscrete.NbPoints();
321   for( int i=1; i<=n; i++ )
322   {
323     gp_Pnt aPnt = aDiscrete.Value( i );
324     int anId;
325     if( theVerticesMap.Contains( aPnt ) )
326       anId = theVerticesMap.FindIndex( aPnt );
327     else
328     {
329       anId = theVerticesMap.Size();
330       theVerticesMap.Add( aPnt );
331     }
332     theVerticesIds.append( anId );
333   }
334   return true;
335 }
336
337 /**
338   Export the land cover map for the solver (Telemac)
339   @param theFileName the name of file
340   @return if the export is successful
341 */
342 bool HYDROData_LandCoverMap::ExportTelemac( const QString& theFileName, Standard_Real theDeflection ) const
343 {
344   TopoDS_Shape aLandCoverMapShape = GetShape();
345   TopTools_ListOfShape aListOfFaces;
346   TopExp_Explorer anExp( aLandCoverMapShape, TopAbs_FACE );
347   for( ; anExp.More(); anExp.Next() )
348     aListOfFaces.Append( anExp.Current() );
349
350   TopoDS_Shape aShape = MergeFaces( aListOfFaces, false );
351
352   NCollection_IndexedMap<gp_Pnt> aVerticesMap;
353   NCollection_IndexedDataMap< TopoDS_Edge, QList<int> > anEdgesMap;
354   NCollection_IndexedDataMap< TopoDS_Face, QList<int> > aFacesMap;
355
356   // add into the map all edges existing in the shell
357   TopExp_Explorer anExp1( aShape, TopAbs_EDGE );
358   for( ; anExp1.More(); anExp1.Next() )
359   {
360     TopoDS_Edge anEdge = TopoDS::Edge( anExp1.Current() );
361     QList<int> aVerticesIdsList;
362     if( EdgeDiscretization( anEdge, theDeflection, aVerticesMap, aVerticesIdsList ) )
363       anEdgesMap.Add( anEdge, aVerticesIdsList );
364   }
365
366   // add into the map all faces existing in the shell and correspondence between face and edges ids
367   TopExp_Explorer anExp2( aShape, TopAbs_FACE );
368   for( ; anExp2.More(); anExp2.Next() )
369   {
370     TopoDS_Face aFace = TopoDS::Face( anExp2.Current() );
371     TopExp_Explorer anExp3( aFace, TopAbs_EDGE );
372     QList<int> anEdgesIdsList;
373     for( ; anExp3.More(); anExp3.Next() )
374     {
375       TopoDS_Edge anEdge = TopoDS::Edge( anExp3.Current() );
376       int anEdgeId = anEdgesMap.FindIndex( anEdge );
377       anEdgesIdsList.append( anEdgeId );
378     }
379     aFacesMap.Add( aFace, anEdgesIdsList );
380   }
381
382   QFile aFile( theFileName );
383   if( !aFile.open( QFile::WriteOnly | QFile::Text ) )
384     return false;
385
386   QTextStream aStream( &aFile );
387   aStream << "# nodes\n";
388   NCollection_IndexedMap<gp_Pnt>::Iterator anIt1( aVerticesMap );
389   for( ; anIt1.More(); anIt1.Next() )
390   {
391     gp_Pnt aPnt = anIt1.Value();
392     aStream << QString::number( aPnt.X(), TELEMAC_FORMAT, TELEMAC_PRECISION );
393     aStream << " ";
394     aStream << QString::number( aPnt.Y(), TELEMAC_FORMAT, TELEMAC_PRECISION );
395     aStream << " ";
396     aStream << QString::number( aPnt.Z(), TELEMAC_FORMAT, TELEMAC_PRECISION );
397     aStream << "\n";
398   }
399   aStream << "\n";
400
401   aStream << "# edges\n";
402   NCollection_IndexedDataMap< TopoDS_Edge, QList<int> >::Iterator anIt2( anEdgesMap );
403   for( ; anIt2.More(); anIt2.Next() )
404   {
405     QList<int> aVerticesIds = anIt2.Value();
406     foreach( int anId, aVerticesIds )
407       aStream << anId << " ";
408     aStream << "\n";
409   }
410   aStream << "\n";
411
412   aStream << "# faces\n";
413   NCollection_IndexedDataMap< TopoDS_Face, QList<int> >::Iterator anIt3( aFacesMap );
414   for( ; anIt3.More(); anIt3.Next() )
415   {
416     QList<int> anEdgesIds = anIt3.Value();
417     foreach( int anId, anEdgesIds )
418       aStream << anId << " ";
419     aStream << "\n";
420   }
421   aStream << "\n";
422
423   aFile.close();
424   return true;
425 }
426
427 /**
428   Add a new object as land cover
429   @param theObject the object to add as land cover
430   @param theType the Strickler type for the new land cover
431   @return if the addition is successful
432 */
433 bool HYDROData_LandCoverMap::Add( const Handle( HYDROData_Object )& theObject, const QString& theType )
434 {
435   if( theObject.IsNull() )
436     return false;
437
438   TopoDS_Shape aShape = theObject->GetTopShape();
439   if( aShape.ShapeType()!=TopAbs_FACE )
440     return false;
441
442   TopoDS_Face aFace = TopoDS::Face( aShape );
443   return LocalPartition( aFace, theType );
444 }
445
446 bool HYDROData_LandCoverMap::Add( const TopoDS_Wire& theWire, const QString& theType )
447 {
448   if( !theWire.Closed() )
449     return false;
450
451   TopoDS_Face aFace = BRepBuilderAPI_MakeFace( theWire, Standard_True ).Face();
452   return LocalPartition( aFace, theType );
453 }
454
455 /**
456   Add a new polyline as land cover
457   @param thePolyline the polyline to add as land cover
458   @param theType the Strickler type for the new land cover
459   @return if the addition is successful
460 */
461 bool HYDROData_LandCoverMap::Add( const Handle( HYDROData_PolylineXY )& thePolyline, const QString& theType )
462 {
463   if( thePolyline.IsNull() )
464     return false;
465
466   TopoDS_Shape aShape = thePolyline->GetShape();
467   if( aShape.ShapeType()==TopAbs_WIRE )
468     return Add( TopoDS::Wire( aShape ), theType );
469
470   if( aShape.ShapeType()==TopAbs_COMPOUND )
471   {
472     TopExp_Explorer anExp( aShape, TopAbs_WIRE );
473     for( ; anExp.More(); anExp.Next() )
474     {
475       TopoDS_Wire aPart = TopoDS::Wire( anExp.Current() );
476       if( !Add( aPart, theType ) )
477         return false;
478     }
479     return true;
480   }
481
482   return false;
483 }
484
485 /**
486   Remove the given face from land cover map
487   @param theFace the face to be removed
488   @return if the removing is successful
489 */
490 bool HYDROData_LandCoverMap::Remove( const TopoDS_Face& theFace )
491 {
492   TopTools_ListOfShape aList;
493   aList.Append( theFace );
494   return Remove( aList );
495 }
496
497 /**
498   Remove the given faces from land cover map
499   @param theFacesToRemove the face list to be removed
500   @return if the removing is successful
501 */
502 bool HYDROData_LandCoverMap::Remove( const TopTools_ListOfShape& theFacesToRemove )
503 {
504   HYDROData_MapOfFaceToStricklerType aFacesToRemove, aNewFaces;
505   TopTools_ListIteratorOfListOfShape aFIt( theFacesToRemove );
506   for( ; aFIt.More(); aFIt.Next() )
507   {
508     TopoDS_Shape aShape = aFIt.Value();
509     if( aShape.ShapeType()==TopAbs_FACE )
510       aFacesToRemove.Add( TopoDS::Face( aShape ), "" );
511   }
512
513   Iterator anIt( *this );
514   for( ; anIt.More(); anIt.Next() )
515     if( !aFacesToRemove.Contains( anIt.Face() ) )
516       aNewFaces.Add( anIt.Face(), anIt.StricklerType() );
517
518   if ( aNewFaces.IsEmpty() )
519     return false;
520
521   StoreLandCovers( aNewFaces );
522   return true;
523 }
524
525 /**
526   Split the land cover map by the given polyline
527   @param thePolyline the tool polyline to split the land cover map
528   @return if the removing is successful
529 */
530 bool HYDROData_LandCoverMap::Split( const Handle( HYDROData_PolylineXY )& thePolyline )
531 {
532   if( thePolyline.IsNull() )
533     return false;
534
535   TopoDS_Shape aShape = thePolyline->GetShape();
536   return Split( aShape );
537 }
538
539
540 /**
541   Split the land cover map by the given polyline
542   @param theShape the tool polyline to split the land cover map
543   @return if the removing is successful
544 */
545 bool HYDROData_LandCoverMap::Split( const TopoDS_Shape& theShape )
546 {
547   return LocalPartition( theShape, "" );
548 }
549
550
551 /**
552   Merge the given faces in the land cover
553   @param theFaces the faces to merge in the land cover map
554   @param theType the Strickler type for the merged land cover
555   @return if the merge is successful
556 */
557 bool HYDROData_LandCoverMap::Merge( const TopTools_ListOfShape& theFaces, const QString& theType )
558 {
559   // 1. to fuse the faces into the new face
560   TopoDS_Shape aMergedFace = MergeFaces( theFaces, true );
561   if( !aMergedFace.IsNull() && aMergedFace.ShapeType()==TopAbs_FACE )
562   {
563     // 2. to remove the merged faces from the current map
564     Remove( theFaces );
565
566     // 3. to add the face into the map
567     return LocalPartition( TopoDS::Face( aMergedFace ), theType );
568   }
569   return false;
570 }
571
572 /**
573   Merge the given faces into the shell/face
574   @param theFaces the faces to merge
575   @param IsToUnify if the common edges should be removed (fused)
576   @param theTolerance the operation's tolerance
577   @return result shape (face or shell)
578 */
579 TopoDS_Shape HYDROData_LandCoverMap::MergeFaces( const TopTools_ListOfShape& theFaces,
580                                                  bool IsToUnify, double theTolerance )
581 {
582   int anError;
583   TopTools_ListIteratorOfListOfShape anIt;
584   BOPCol_ListOfShape aLC;
585   anIt.Initialize(theFaces);
586   for( ; anIt.More(); anIt.Next() )
587   {
588     if (anIt.Value().ShapeType() != TopAbs_FACE)
589       return TopoDS_Shape();
590     aLC.Append( anIt.Value() );
591   }
592
593   BOPAlgo_PaveFiller aPF;
594   aPF.SetArguments( aLC );
595   aPF.SetRunParallel( Standard_False );
596   aPF.SetFuzzyValue( theTolerance );
597
598   aPF.Perform();
599   anError = aPF.ErrorStatus();
600   if( anError )
601     return TopoDS_Shape();
602
603   BOPAlgo_Builder anAlgo;
604   anIt.Initialize( theFaces );
605   for( ; anIt.More(); anIt.Next() )
606     anAlgo.AddArgument( anIt.Value() );
607
608   anAlgo.PerformWithFiller( aPF ); 
609   anError = anAlgo.ErrorStatus();
610   if( anError )
611     return TopoDS_Shape();
612
613   const TopoDS_Shape& aMergedShape = anAlgo.Shape();
614
615   BRep_Builder aBuilder;
616   TopoDS_Shell aShell; 
617   aBuilder.MakeShell( aShell ); 
618   aShell.Closed( Standard_False );
619   TopExp_Explorer anExplorer( aMergedShape, TopAbs_FACE );
620   for( ; anExplorer.More(); anExplorer.Next() ) 
621   {
622     const TopoDS_Face& aFace = TopoDS::Face(anExplorer.Current());
623     if( aFace.IsNull() ) 
624       continue;
625     if( aFace.ShapeType() == TopAbs_FACE )
626     {
627       aBuilder.Add( aShell, aFace );
628       aShell.Closed( Standard_False );
629     }
630   }
631
632   TopoDS_Shape aResult;
633   if( IsToUnify )
634   {
635     ShapeUpgrade_UnifySameDomain aUSD;
636     aUSD.Initialize( aShell );
637     aUSD.Build();
638     aResult = aUSD.Shape();
639   }
640   else
641     aResult = aShell;
642
643   anExplorer.Init( aResult, TopAbs_FACE );
644   int n = 0;
645   TopoDS_Face anOneFace;
646   for( ; anExplorer.More(); anExplorer.Next(), n++ ) 
647     anOneFace = TopoDS::Face( anExplorer.Current() );
648
649   if( n == 1 )
650     aResult = anOneFace;
651
652   return aResult;
653 }
654
655 /**
656   Change Strickler type for the list of faces to the given one
657   @param theFaces the faces to change type
658   @param theType the Strickler type for the given land cover(s)
659   @return if the change type operation is successful
660 */
661 bool HYDROData_LandCoverMap::ChangeType( const TopTools_ListOfShape& theFaces, const QString& theType )
662 {
663   HYDROData_MapOfFaceToStricklerType aFacesToChangeType;
664   TopTools_ListIteratorOfListOfShape aFIt( theFaces );
665   for( ; aFIt.More(); aFIt.Next() )
666   {
667     TopoDS_Shape aShape = aFIt.Value();
668     if( aShape.ShapeType()==TopAbs_FACE )
669       aFacesToChangeType.Add( TopoDS::Face( aShape ), "" );
670   }
671
672   int aNbChanges = 0;
673   Iterator anIt( *this );
674   for( ; anIt.More(); anIt.Next() )
675     if( aFacesToChangeType.Contains( anIt.Face() ) )
676     {
677       anIt.SetStricklerType( theType );
678       aNbChanges++;
679     }
680   if ( aNbChanges != theFaces.Extent() )
681     return false;
682
683   return true;
684 }
685
686 /**
687   Get the shape of the land cover map
688 */
689 TopoDS_Shape HYDROData_LandCoverMap::GetShape() const
690 {
691   return HYDROData_Entity::GetShape( DataTag_Shape );
692 }
693
694 /**
695   Get Strickler type of the given land cover
696   @param theLandCover the land cover to get Strickler type of
697   @return name of Strickler type
698 */
699 QString HYDROData_LandCoverMap::StricklerType( const TopoDS_Face& theLandCover ) const
700 {
701   QString aType = "";
702
703   Iterator anIt( *this );
704   for( ; anIt.More(); anIt.Next() )
705     if( anIt.Face().IsEqual( theLandCover) )
706     {
707       aType = anIt.StricklerType();
708       break;
709     }
710
711   return aType;
712 }
713
714 /**
715   Set the shape of the land cover map
716   @param theShape the new shape for the land cover map
717 */
718 void HYDROData_LandCoverMap::SetShape( const TopoDS_Shape& theShape )
719 {
720   HYDROData_Entity::SetShape( DataTag_Shape, theShape );
721 }
722
723 /**
724   Perform the local partition algorithm on the land cover
725   @param theNewShape the new shape to add into the land cover
726   @param theNewType the new Strickler type for the new land cover
727   @return if the local partition is successful
728 */
729 bool HYDROData_LandCoverMap::LocalPartition( const TopoDS_Shape& theNewShape, const QString& theNewType )
730 {
731   if( theNewShape.IsNull() )
732     return false;
733
734   BOPCol_ListOfShape aShapesList;
735   BOPAlgo_PaveFiller aPaveFiller;
736   HYDROData_MapOfFaceToStricklerType aNewFaces;
737
738   // add faces to shapes list
739   Iterator anIt( *this );
740   for( ; anIt.More(); anIt.Next() )
741     aShapesList.Append( anIt.Face() );
742   aShapesList.Append( theNewShape );
743
744   if( aShapesList.Size()==1 && theNewShape.ShapeType()==TopAbs_FACE )
745   {
746     aNewFaces.Add( TopoDS::Face( theNewShape ), theNewType );
747     StoreLandCovers( aNewFaces );
748     return true;
749   }
750
751   // prepare pave filler
752   aPaveFiller.SetArguments( aShapesList );
753   aPaveFiller.Perform();
754   Standard_Integer anError = aPaveFiller.ErrorStatus();
755   if( anError )
756     return false;
757
758   // add faces to builder
759   BOPAlgo_Builder aBuilder;
760   anIt.Init( *this );
761   for( ; anIt.More(); anIt.Next() )
762     aBuilder.AddArgument( anIt.Face() );
763   aBuilder.AddArgument( theNewShape );
764
765   // perform the partition with the pave filler
766   aBuilder.PerformWithFiller( aPaveFiller );
767   anError = aBuilder.ErrorStatus();
768   if( anError )
769     return false;
770
771   //std::cout << "History:" << std::endl;
772   // analysis of the history
773   //     a. to fill map of shapes which come from the new face
774   NCollection_IndexedMap<int> aShapesFromNewFace;
775   //std::cout << "from NEW " << theNewShape << ":" << theNewType << std::endl;
776   TopTools_ListOfShape aModified = aBuilder.Modified( theNewShape );
777   TopTools_ListIteratorOfListOfShape aMIt( aModified );
778   for( ; aMIt.More(); aMIt.Next() )
779   {
780     //std::cout << "   " << aMIt.Value() << std::endl;
781     int aKey = (int)(uintptr_t)aMIt.Value().TShape().operator->();
782     aShapesFromNewFace.Add( aKey );
783   }
784
785   //     b. to fill map of parts except parts from new face
786   anIt.Init( *this );
787   for( ; anIt.More(); anIt.Next() )
788   {
789     QString aSType = anIt.StricklerType();
790     //std::cout << "from " << anIt.Face() << ": " << anIt.StricklerType() << std::endl;
791     TopTools_ListOfShape aModified = aBuilder.Modified( anIt.Face() );
792     if( aModified.Extent() == 0 )
793       aModified.Append( anIt.Face() );
794
795     TopTools_ListIteratorOfListOfShape aMIt( aModified );
796     for( ; aMIt.More(); aMIt.Next() )
797     {
798       TopoDS_Shape aShape = aMIt.Value();
799       bool isFace = aShape.ShapeType()==TopAbs_FACE;
800       int aKey = (int)(uintptr_t)aShape.TShape().operator->();
801       bool isAlsoFromNew = aShapesFromNewFace.Contains( aKey );
802       //std::cout << "   " << aShape << " " << isAlsoFromNew << std::endl;
803       if( isFace && !isAlsoFromNew )
804         aNewFaces.Add( TopoDS::Face( aShape ), aSType );
805     }
806   }
807
808   //     c. add the new shape if it is face with its type
809   if( theNewShape.ShapeType()==TopAbs_FACE )
810     aNewFaces.Add( TopoDS::Face( theNewShape ), theNewType );
811   
812   // convert map of shape to type to compound and list of types
813   StoreLandCovers( aNewFaces );
814   return true;
815 }
816
817 /**
818   Replace the set of land covers in the land cover map
819   @param theMap the map of shape (face) to Strickler type (string)
820 */
821 void HYDROData_LandCoverMap::StoreLandCovers( const HYDROData_MapOfFaceToStricklerType& theMap )
822 {
823   TopTools_ListOfShape aListOfFaces;
824
825   int n = theMap.Size();
826
827   Handle( TDataStd_ExtStringArray ) aTypes = 
828     TDataStd_ExtStringArray::Set( myLab.FindChild( DataTag_Types ), 0, n-1, Standard_True );
829
830   HYDROData_MapOfFaceToStricklerType::Iterator aNFIt( theMap );
831   for( int i=0; aNFIt.More(); aNFIt.Next(), i++ )
832   {
833     TopoDS_Face aFace = aNFIt.Key();
834     if( aFace.IsNull() )
835       continue;
836     QString aType = aNFIt.Value();
837     aListOfFaces.Append(aFace);
838     aTypes->SetValue( i, HYDROData_Tool::toExtString( aType ) );
839   }
840
841   TopoDS_Shape aResult;
842   if( aListOfFaces.Extent() == 1 )
843   {
844     TopoDS_Shell aShell;
845     BRep_Builder aShellBuilder;
846     aShellBuilder.MakeShell( aShell );
847     aShell.Closed( Standard_False );
848     aShellBuilder.Add( aShell, aListOfFaces.First() );
849     aResult = aShell;
850   }
851   else if( aListOfFaces.Extent() > 1 )
852     aResult = MergeFaces( aListOfFaces, false );
853
854   //remove internal edges
855   aResult = RemoveInternal(aResult);
856   SetShape( aResult );
857 }
858
859 /**
860   Find the land cover for the given point
861   @param thePoint the point laying in some land cover
862   @param theType the returned type
863   @return the found land cover's face
864 */
865 TopoDS_Face HYDROData_LandCoverMap::FindByPoint( const gp_Pnt2d& thePoint, QString& theType ) const
866 {
867   //TODO: some more optimal algorithm
868   Iterator anIt( *this );
869   for( ; anIt.More(); anIt.Next() )
870     if( HYDROData_Tool::ComputePointState( thePoint.XY(), anIt.Face() ) == TopAbs_IN )
871     {
872       theType = anIt.StricklerType();
873       return anIt.Face();
874     }
875
876   theType = "";
877   return TopoDS_Face();
878 }
879
880 /**
881   Dump to Python
882   @param theTreatedObjects the map of treated objects
883 */
884 QStringList HYDROData_LandCoverMap::DumpToPython( MapOfTreatedObjects& theTreatedObjects ) const
885 {
886   QStringList aResList = dumpObjectCreation( theTreatedObjects );
887   QString aName = GetObjPyName();
888
889   //Handle(HYDROData_PolylineXY) aHydAxis = GetHydraulicAxis();
890   //setPythonReferenceObject( theTreatedObjects, aResList, aHydAxis, "SetHydraulicAxis" );
891
892   //HYDROData_SequenceOfObjects aSeqOfProfiles = GetProfiles();
893   //for ( int i = 1, aNb = aSeqOfProfiles.Size(); i <= aNb; ++i )
894   //{
895     //const Handle(HYDROData_Entity) aProfile = aSeqOfProfiles.Value( i );
896     //setPythonReferenceObject( theTreatedObjects, aResList, aProfile, "AddProfile" );
897   //}
898
899   //TODO
900
901   return aResList;
902 }
903
904 TopoDS_Shape HYDROData_LandCoverMap::RemoveInternal(const TopoDS_Shape& InSh)
905 {
906   //Shape must be topologically correct
907   TopExp_Explorer anExp(InSh, TopAbs_EDGE);
908   TopTools_ListOfShape anEdgesToRemove;
909
910   for(; anExp.More(); anExp.Next() )
911   {
912     TopoDS_Edge CurEdge = TopoDS::Edge(anExp.Current());
913     if (CurEdge.Orientation() == TopAbs_INTERNAL)
914       anEdgesToRemove.Append(CurEdge);
915   }
916  
917   Handle_ShapeBuild_ReShape aReshape = new ShapeBuild_ReShape();
918   TopoDS_Shape OutSh = aReshape->Apply(InSh);
919   TopTools_ListIteratorOfListOfShape aIt(anEdgesToRemove);
920   for (; aIt.More(); aIt.Next()) 
921     aReshape->Remove(aIt.Value());
922   OutSh = aReshape->Apply(InSh);
923
924   Handle(ShapeFix_Shape) sfs = new ShapeFix_Shape;
925   sfs->Init(OutSh);
926   sfs->Perform();
927   return sfs->Shape();
928
929 }