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