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