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