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