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