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