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