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