Salome HOME
07397d1a64ee1dbee12cd9ff728e10e38106dc1c
[modules/hydro.git] / src / HYDROData / HYDROData_CalculationCase.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 #ifdef WIN32
20   #pragma warning ( disable: 4251 )
21 #endif
22
23 #include "HYDROData_CalculationCase.h"
24 #include "HYDROData_ArtificialObject.h"
25 #include "HYDROData_IAltitudeObject.h"
26 #include "HYDROData_Document.h"
27 #include "HYDROData_ShapesGroup.h"
28 #include "HYDROData_Iterator.h"
29 #include "HYDROData_NaturalObject.h"
30 #include "HYDROData_PolylineXY.h"
31 #include "HYDROData_StricklerTable.h"
32 #include "HYDROData_LandCover.h"
33 #include "HYDROData_SplittedShapesGroup.h"
34 #include "HYDROData_Region.h"
35 #include "HYDROData_Tool.h"
36 #include "HYDROData_GeomTool.h"
37
38 #include <GEOMBase.h>
39
40 #include <QSet>
41
42 #include <TopoDS.hxx>
43 #include <TopoDS_Shell.hxx>
44 #include <TopoDS_Edge.hxx>
45
46 #include <BRep_Builder.hxx>
47 #include <BRepBuilderAPI_Sewing.hxx>
48 #include <BRepTopAdaptor_FClass2d.hxx>
49
50 #include <BRepTools.hxx>
51
52 #include <TopAbs.hxx>
53 #include <TopExp_Explorer.hxx>
54 #include <TopExp.hxx>
55 #include <TopTools_ListOfShape.hxx>
56 #include <TopTools_ListIteratorOfListOfShape.hxx>
57 #include <TDataStd_Integer.hxx>
58
59 //#define  DEB_CALCULATION 1
60 #ifdef DEB_CALCULATION
61 #include <BRepTools.hxx>
62 #include <TopLoc_Location.hxx>
63 #endif 
64 #define CALCULATION_REGIONS_PREF GetName() + "_Reg"
65 #define CALCULATION_ZONES_PREF GetName() + "_Zone"
66 #define CALCULATION_LANDCOVER_ZONES_PREF GetName() + "_LandCoverZone"
67 #define CALCULATION_GROUPS_PREF GetName() + "_"
68 //#define DEB_CLASS2D 1
69 #ifdef DEB_CLASS2D
70 #include <BRepBuilderAPI_MakeVertex.hxx>
71 #endif
72
73 #ifdef WIN32
74   #pragma warning ( default: 4251 )
75 #endif
76
77 #define EXPORT_NAME "HYDRO_" + GetName()
78
79 #include <SALOME_NamingService.hxx>
80 #include <SALOME_LifeCycleCORBA.hxx>
81
82 #define _DEVDEBUG_
83 #include "HYDRO_trace.hxx"
84
85 IMPLEMENT_STANDARD_HANDLE(HYDROData_CalculationCase, HYDROData_Entity)
86 IMPLEMENT_STANDARD_RTTIEXT(HYDROData_CalculationCase, HYDROData_Entity)
87
88 HYDROData_CalculationCase::HYDROData_CalculationCase()
89 : HYDROData_Entity( Geom_2d_and_groups )
90 {
91 }
92
93 HYDROData_CalculationCase::~HYDROData_CalculationCase()
94 {
95 }
96
97 void HYDROData_CalculationCase::SetName( const QString& theName )
98 {
99   QString anOldCaseName = GetName();
100   if ( anOldCaseName != theName )
101   {
102     // Update names of regions and its zones
103     UpdateRegionsNames( GetRegions( false ), anOldCaseName, theName );
104     // Update names of land cover regions and its zones
105     UpdateRegionsNames( GetRegions( true ), anOldCaseName, theName );
106
107     HYDROData_SequenceOfObjects aGroups = GetSplittedGroups();
108
109     HYDROData_SequenceOfObjects::Iterator anIter;
110     anIter.Init( aGroups );
111     for ( ; anIter.More(); anIter.Next() )
112     {
113       Handle(HYDROData_SplittedShapesGroup) aGroup =
114         Handle(HYDROData_SplittedShapesGroup)::DownCast( anIter.Value() );
115       if ( aGroup.IsNull() )
116         continue;
117
118       HYDROData_Tool::UpdateChildObjectName( anOldCaseName, theName, aGroup );
119     }
120   }
121
122   HYDROData_Entity::SetName( theName );
123 }
124
125 QStringList HYDROData_CalculationCase::DumpToPython( MapOfTreatedObjects& theTreatedObjects ) const
126 {
127   QStringList aResList = dumpObjectCreation( theTreatedObjects );
128   aResList.prepend( "# Calculation case" );
129
130   QString aCalculName = GetObjPyName();
131
132   AssignmentMode aMode = GetAssignmentMode();  
133   QString aModeStr = aMode==MANUAL ? "HYDROData_CalculationCase.MANUAL" : "HYDROData_CalculationCase.AUTOMATIC";
134   aResList << QString( "%0.SetAssignmentMode( %1 )" ).arg( aCalculName ).arg( aModeStr );
135
136   AssignmentMode aModeLC = GetAssignmentLandCoverMode();
137   QString aModeLCStr = aModeLC==MANUAL ? "HYDROData_CalculationCase.MANUAL" : "HYDROData_CalculationCase.AUTOMATIC";
138   aResList << QString( "%0.SetAssignmentLandCoverMode( %1 )" ).arg( aCalculName ).arg( aModeLCStr );
139
140   HYDROData_SequenceOfObjects aGeomObjects = GetGeometryObjects();
141   HYDROData_SequenceOfObjects::Iterator anIter( aGeomObjects );
142   for ( ; anIter.More(); anIter.Next() )
143   {
144     Handle(HYDROData_Object) aRefGeomObj =
145       Handle(HYDROData_Object)::DownCast( anIter.Value() );
146     setPythonReferenceObject( theTreatedObjects, aResList, aRefGeomObj, "AddGeometryObject" );
147   }
148   aResList << QString( "" );
149
150   QString aGroupName = HYDROData_Tool::GenerateNameForPython( theTreatedObjects, "case_geom_group" );
151
152   HYDROData_SequenceOfObjects aGeomGroups = GetGeometryGroups();
153   anIter.Init( aGeomGroups );
154   for ( ; anIter.More(); anIter.Next() )
155   {
156     Handle(HYDROData_ShapesGroup) aGeomGroup =
157       Handle(HYDROData_ShapesGroup)::DownCast( anIter.Value() );
158     if ( aGeomGroup.IsNull() )
159       continue;
160
161     Handle(HYDROData_Object) aFatherGeom =
162       Handle(HYDROData_Object)::DownCast( aGeomGroup->GetFatherObject() );
163     if ( aFatherGeom.IsNull() )
164       continue;
165
166     int aGroupId = aFatherGeom->GetGroupId( aGeomGroup );
167     aResList << QString( "%1 = %2.GetGroup( %3 );" )
168               .arg( aGroupName ).arg( aFatherGeom->GetObjPyName() ).arg( aGroupId );
169
170     aResList << QString( "%1.AddGeometryGroup( %2 );" ).arg( aCalculName ).arg( aGroupName );
171   }
172
173   Handle(HYDROData_PolylineXY) aBoundaryPolyline = GetBoundaryPolyline();
174   setPythonReferenceObject( theTreatedObjects, aResList, aBoundaryPolyline, "SetBoundaryPolyline" );
175
176   if( aMode==AUTOMATIC )
177     DumpRulesToPython( aCalculName, aResList );
178   if( aModeLC==AUTOMATIC )
179     DumpLandCoverRulesToPython( aCalculName, aResList );
180
181   aResList << QString( "" );
182   aResList << "# Start the algorithm of the partition and assignment";
183   aResList << QString( "%1.Update();" ).arg( aCalculName );
184
185   if( aMode==MANUAL )
186   {
187     // Now we restore the
188     // - regions and zones order
189     DumpRegionsToPython( aResList, theTreatedObjects, GetRegions( false ) );   
190   }
191
192   if( aModeLC==MANUAL )
193   {
194     // Now we restore the
195     // - land cover regions and zones order
196     DumpRegionsToPython( aResList, theTreatedObjects, GetRegions( true ) );
197   }
198
199   // Export calculation case
200   aResList << QString( "" );
201   aResList << "# Export of the calculation case";
202   QString aStudyName = "theStudy";
203   QString anEntryVar = aCalculName + "_entry";
204   aResList << QString( "%1 = %2.Export( %3._get_StudyId() )" ).arg( anEntryVar ).arg( aCalculName ).arg( aStudyName );
205
206   // Get geometry object and print debug information
207   aResList << "";
208   aResList << "# Get geometry shape and print debug information";
209   aResList << "import GEOM";
210   aResList << QString( "print \"Entry:\", %1" ).arg( anEntryVar );
211   QString aGeomShapeName = aCalculName + "_geom";
212   aResList << QString( "%1 = salome.IDToObject( str( %2 ) )" ).arg( aGeomShapeName ).arg( anEntryVar );
213   aResList << QString( "print \"Geom shape:\", %1" ).arg( aGeomShapeName );
214   aResList << QString( "print \"Geom shape name:\", %1.GetName()" ).arg( aGeomShapeName );
215
216   DumpSampleMeshing( aResList, aStudyName, aGeomShapeName, aCalculName+"_mesh" );
217
218   aResList << QString( "" );
219   return aResList;
220 }
221
222 void HYDROData_CalculationCase::DumpSampleMeshing( QStringList& theResList,
223                                                    const QString& theStudyName,
224                                                    const QString& theGeomShapeName,
225                                                    const QString& theMeshName ) const
226 {
227   theResList << "";
228   theResList << "# Meshing";
229   theResList << "import SMESH, SALOMEDS";
230   theResList << "from salome.smesh import smeshBuilder";
231   theResList << "from salome.geom import geomBuilder";
232
233   theResList << QString( "smesh = smeshBuilder.New( %1 )" ).arg( theStudyName );
234   theResList << QString( "%1 = smesh.Mesh( %2 )" ).arg( theMeshName ).arg( theGeomShapeName );
235   theResList << QString( "MEFISTO_2D = %1.Triangle( algo=smeshBuilder.MEFISTO )" ).arg( theMeshName );
236   theResList << "Max_Element_Area_1 = MEFISTO_2D.MaxElementArea( 10 )";
237   theResList << QString( "Regular_1D = %1.Segment()" ).arg( theMeshName );
238   theResList << "Max_Size_1 = Regular_1D.MaxSize(10)";
239   theResList << QString( "isDone = %1.Compute()" ).arg( theMeshName );
240
241   theResList << "";
242   theResList << "# Set names of Mesh objects";
243   theResList << "smesh.SetName( MEFISTO_2D.GetAlgorithm(), 'MEFISTO_2D' )";
244   theResList << "smesh.SetName( Regular_1D.GetAlgorithm(), 'Regular_1D' )";
245   theResList << "smesh.SetName( Max_Size_1, 'Max Size_1' )";
246   theResList << "smesh.SetName( Max_Element_Area_1, 'Max. Element Area_1' )";
247   theResList << QString( "smesh.SetName( %1.GetMesh(), '%1' )" ).arg( theMeshName );
248
249   theResList << "";
250   theResList << "# Greate SMESH groups";
251   theResList << QString( "geompy = geomBuilder.New( %1 )" ).arg( theStudyName );
252   theResList << QString( "geom_groups = geompy.GetGroups( %1 )" ).arg( theGeomShapeName );
253   theResList << QString( "for group in geom_groups:" );
254   theResList << QString( "    smesh_group = %1.GroupOnGeom(group, group.GetName(), SMESH.EDGE)" )
255                 .arg( theMeshName );
256   theResList << QString( "    smesh.SetName(smesh_group, group.GetName())" );
257   theResList << QString( "    print \"SMESH group '%s': %s\" % (smesh_group.GetName(), smesh_group)" );
258 }
259
260 HYDROData_SequenceOfObjects HYDROData_CalculationCase::GetAllReferenceObjects() const
261 {
262   HYDROData_SequenceOfObjects aResSeq = HYDROData_Entity::GetAllReferenceObjects();
263
264   Handle(HYDROData_PolylineXY) aBoundaryPolyline = GetBoundaryPolyline();
265   if ( !aBoundaryPolyline.IsNull() )
266     aResSeq.Append( aBoundaryPolyline );
267
268   // Regions
269   HYDROData_SequenceOfObjects aSeqOfRegions = GetRegions( false );
270   aResSeq.Append( aSeqOfRegions );
271
272   // Land cover regions
273   HYDROData_SequenceOfObjects aSeqOfLandCoverRegions = GetRegions( true );
274   aResSeq.Append( aSeqOfLandCoverRegions );
275
276   return aResSeq;
277 }
278
279 void HYDROData_CalculationCase::Update()
280 {
281   HYDROData_Entity::Update();
282   SetWarning();
283
284   // At first we remove previously created objects
285   RemoveRegions( false );
286   RemoveRegions( true );
287   RemoveSplittedGroups();
288
289   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
290   if ( aDocument.IsNull() )
291     return;
292
293   // Split to zones
294   HYDROData_SplitToZonesTool::SplitDataList aZonesList, anEdgesList;
295
296   Handle(HYDROData_PolylineXY) aBoundaryPolyline = GetBoundaryPolyline();
297   HYDROData_SequenceOfObjects aGeomObjects = GetGeometryObjects();
298   if ( !aGeomObjects.IsEmpty() ) {
299     HYDROData_SequenceOfObjects aGeomGroups = GetGeometryGroups();
300
301     HYDROData_SplitToZonesTool::SplitDataList aSplitObjects =
302       HYDROData_SplitToZonesTool::Split( aGeomObjects, aGeomGroups, aBoundaryPolyline );
303     if ( !aSplitObjects.isEmpty() ) {
304       HYDROData_SplitToZonesTool::SplitDataListIterator anIter( aSplitObjects );
305       while( anIter.hasNext() ) {
306         const HYDROData_SplitToZonesTool::SplitData& aSplitData = anIter.next();
307         if ( aSplitData.Type == HYDROData_SplitToZonesTool::SplitData::Data_Zone )
308           aZonesList.append( aSplitData );
309         else if ( aSplitData.Type == HYDROData_SplitToZonesTool::SplitData::Data_Edge )
310           anEdgesList.append( aSplitData );
311       }
312     }
313   }
314
315   // Split to land cover zones
316   HYDROData_SplitToZonesTool::SplitDataList aLandCoverZonesList;
317
318   HYDROData_SequenceOfObjects aLandCovers = GetLandCovers();
319   if ( !aLandCovers.IsEmpty() ) {
320     HYDROData_SplitToZonesTool::SplitDataList aSplitLandCoverObjects =
321       HYDROData_SplitToZonesTool::Split( aLandCovers );
322     if ( !aSplitLandCoverObjects.isEmpty() ) {
323       HYDROData_SplitToZonesTool::SplitDataListIterator anIter( aSplitLandCoverObjects );
324       while( anIter.hasNext() ) {
325         const HYDROData_SplitToZonesTool::SplitData& aSplitData = anIter.next();
326         if ( aSplitData.Type == HYDROData_SplitToZonesTool::SplitData::Data_Zone )
327           aLandCoverZonesList.append( aSplitData );
328       }
329     }
330   }
331
332   switch( GetAssignmentMode() )
333   {
334   case MANUAL:
335     CreateRegionsDef( aDocument, aZonesList, false );    
336     break;
337   case AUTOMATIC:
338     CreateRegionsAuto( aDocument, aZonesList, false );    
339     break;
340   }
341
342   switch( GetAssignmentLandCoverMode() )
343   {
344   case MANUAL:
345     CreateRegionsDef( aDocument, aLandCoverZonesList, true );
346     break;
347   case AUTOMATIC:
348     CreateRegionsAuto( aDocument, aLandCoverZonesList, true );
349     break;
350   }
351
352   CreateEdgeGroupsDef( aDocument, anEdgesList );
353 }
354
355 void HYDROData_CalculationCase::CreateRegionsDef( const Handle(HYDROData_Document)& theDoc,
356                                                   const HYDROData_SplitToZonesTool::SplitDataList& theZones,
357                                                   const bool theLandCover )
358 {
359   // Create result regions for case, by default one zone for one region
360   QString aRegsPref = CALCULATION_REGIONS_PREF;
361   QString aZonesPref = theLandCover ? CALCULATION_LANDCOVER_ZONES_PREF : CALCULATION_ZONES_PREF;
362
363   HYDROData_SplitToZonesTool::SplitDataListIterator anIter( theZones );
364   while( anIter.hasNext() )
365   {
366     const HYDROData_SplitToZonesTool::SplitData& aSplitData = anIter.next();
367     // Create new region
368     Handle(HYDROData_Region) aRegion = addNewRegion( theDoc, aRegsPref, theLandCover );
369
370     // Add the zone for region
371     Handle(HYDROData_Zone) aRegionZone = aRegion->addNewZone( theDoc, aZonesPref, aSplitData.Face(), aSplitData.ObjectNames );
372   }
373 }
374
375 void HYDROData_CalculationCase::CreateRegionsAuto( const Handle(HYDROData_Document)& theDoc,
376                                                    const HYDROData_SplitToZonesTool::SplitDataList& theZones,
377                                                    const bool theLandCover )
378 {
379   DEBTRACE("HYDROData_CalculationCase::CreateRegionsAuto");
380   QMap<QString, Handle(HYDROData_Region)> aRegionsMap; //object name to region
381   QMap<QString, QString> aRegionNameToObjNameMap;
382   QString aZonesPref = theLandCover ? CALCULATION_LANDCOVER_ZONES_PREF : CALCULATION_ZONES_PREF;
383   HYDROData_PriorityQueue aPr( this, theLandCover ? DataTag_CustomLandCoverRules : DataTag_CustomRules );
384
385   // 1. First we create a default region for each object included into the calculation case
386   HYDROData_SequenceOfObjects anObjects = theLandCover ? GetLandCovers() : GetGeometryObjects();
387   for( int i = anObjects.Lower(), n = anObjects.Upper(); i<=n; i++ )
388   {
389     Handle(HYDROData_Entity) anObj = anObjects.Value( i );
390     if( anObj.IsNull() )
391       continue;
392     QString anObjName = anObj->GetName();
393     QString aRegName = anObjName + "_reg";
394     Handle(HYDROData_Region) aRegion = addNewRegion( theDoc, aRegName, theLandCover, false );
395     aRegionsMap.insert( anObjName, aRegion );
396     aRegionNameToObjNameMap.insert( aRegName, anObjName );
397   }
398
399   // 2. Now for each zone it is necessary to determine the most priority object
400   //    and assign to zone to corresponding region
401   HYDROData_SplitToZonesTool::SplitDataListIterator anIter( theZones );
402   while( anIter.hasNext() )
403   {
404     const HYDROData_SplitToZonesTool::SplitData& aSplitData = anIter.next();
405     HYDROData_Zone::MergeType aMergeType;
406     Handle(HYDROData_Entity) aRegObj = aPr.GetMostPriorityObject( aSplitData.ObjectNames, aMergeType );
407     if( aRegObj.IsNull() )
408       continue;
409     Handle(HYDROData_Region) aRegion = aRegionsMap[aRegObj->GetName()];
410     if( aRegion.IsNull() )
411       continue;
412     Handle(HYDROData_Zone) aRegionZone = aRegion->addNewZone( theDoc, aZonesPref, aSplitData.Face(), aSplitData.ObjectNames );
413
414     if( aSplitData.ObjectNames.count() > 1 && aMergeType==HYDROData_Zone::Merge_UNKNOWN )
415     {
416       qDebug( "Error in algorithm: unresolved conflicts" );
417     }
418
419     Handle(HYDROData_Entity) aMergeEntity = aRegObj;
420     if ( !theLandCover ) {
421       Handle(HYDROData_Object) aMergeObject = Handle(HYDROData_Object)::DownCast( aMergeEntity );
422       if ( !aMergeObject.IsNull() ) {
423         DEBTRACE("aMergeEntity " << aMergeEntity->GetName().toStdString());
424         aMergeEntity = aMergeObject->GetAltitudeObject();
425       }
426     }
427
428     switch( aMergeType )
429     {
430     case HYDROData_Zone::Merge_ZMIN:
431     case HYDROData_Zone::Merge_ZMAX:
432       aRegionZone->SetMergeType( aMergeType );
433       break;
434     case HYDROData_Zone::Merge_Object:
435       aRegionZone->SetMergeType( aMergeType );
436       aRegionZone->RemoveMergeObject();
437       aRegionZone->SetMergeObject( aMergeEntity );
438       break;
439     }
440   }
441
442   QStringList anObjectsWithEmptyRegions;
443   QMap<QString, Handle(HYDROData_Region)>::const_iterator
444     anIt = aRegionsMap.begin(), aLast = aRegionsMap.end();
445   for( ; anIt!=aLast; anIt++ )
446   {
447     Handle(HYDROData_Region) aRegion = anIt.value();
448     if( aRegion->GetZones().IsEmpty() )
449     {
450       QString aRegName = aRegion->GetName();
451       QString anObjName = aRegionNameToObjNameMap[aRegName];
452       anObjectsWithEmptyRegions.append( anObjName );
453     }
454   }
455   
456   if( !anObjectsWithEmptyRegions.empty() )
457   {
458     QString aData = anObjectsWithEmptyRegions.join( ", " );
459     SetWarning( WARN_EMPTY_REGIONS, aData );
460   }
461 }
462
463 void HYDROData_CalculationCase::CreateEdgeGroupsDef( const Handle(HYDROData_Document)& theDoc,
464                                                      const HYDROData_SplitToZonesTool::SplitDataList& theEdges )
465 {
466   QMap<QString,Handle(HYDROData_SplittedShapesGroup)> aSplittedEdgesGroupsMap;
467
468   HYDROData_SplitToZonesTool::SplitDataListIterator anIter( theEdges );
469   while( anIter.hasNext() )
470   {
471     const HYDROData_SplitToZonesTool::SplitData& aSplitData = anIter.next();
472     // Create new edges group
473     if ( aSplitData.ObjectNames.isEmpty() || aSplitData.Shape.IsNull() )
474       continue;
475
476     QString anObjName = aSplitData.ObjectNames.first();
477     if ( anObjName.isEmpty() )
478       continue;
479 #ifdef DEB_CALCULATION
480     QString aStr = aSplitData.ObjectNames.join(" "); 
481           cout << " CCase: Names = "<<aStr.toStdString() << " size = " <<aSplitData.ObjectNames.size() <<endl; 
482 #endif
483     Handle(HYDROData_SplittedShapesGroup) aSplittedGroup;
484     if ( !aSplittedEdgesGroupsMap.contains( anObjName ) )
485     {
486       aSplittedGroup = addNewSplittedGroup( CALCULATION_GROUPS_PREF + anObjName );
487       aSplittedEdgesGroupsMap.insert( anObjName, aSplittedGroup );
488     }
489     else
490     {
491       aSplittedGroup = aSplittedEdgesGroupsMap[ anObjName ];
492     }
493     if ( aSplittedGroup.IsNull() )
494       continue;
495
496     aSplittedGroup->AddShape( aSplitData.Shape );
497   }
498 }
499
500 bool HYDROData_CalculationCase::AddGeometryObject( const Handle(HYDROData_Object)& theObject )
501 {
502   if ( !HYDROData_Tool::IsGeometryObject( theObject ) )
503     return false; // Wrong type of object
504
505   if ( HasReference( theObject, DataTag_GeometryObject ) )
506     return false; // Object is already in reference list
507
508   AddReferenceObject( theObject, DataTag_GeometryObject );
509   
510   // Indicate model of the need to update splitting
511   Changed( Geom_2d );
512
513   return true;
514 }
515
516 HYDROData_SequenceOfObjects HYDROData_CalculationCase::GetGeometryObjects() const
517 {
518   return GetReferenceObjects( DataTag_GeometryObject );
519 }
520
521 void HYDROData_CalculationCase::RemoveGeometryObject( const Handle(HYDROData_Object)& theObject )
522 {
523   if ( theObject.IsNull() )
524     return;
525
526   RemoveReferenceObject( theObject->Label(), DataTag_GeometryObject );
527
528   // Indicate model of the need to update splitting
529   Changed( Geom_2d );
530 }
531
532 void HYDROData_CalculationCase::RemoveGeometryObjects()
533 {
534   ClearReferenceObjects( DataTag_GeometryObject );
535
536   // Indicate model of the need to update splitting
537   Changed( Geom_2d );
538 }
539
540 bool HYDROData_CalculationCase::AddGeometryGroup( const Handle(HYDROData_ShapesGroup)& theGroup )
541 {
542   if ( theGroup.IsNull() )
543     return false;
544
545   if ( HasReference( theGroup, DataTag_GeometryGroup ) )
546     return false; // Object is already in reference list
547
548   AddReferenceObject( theGroup, DataTag_GeometryGroup );
549   
550   // Indicate model of the need to update splitting
551   Changed( Geom_Groups );
552
553   return true;
554 }
555
556 HYDROData_SequenceOfObjects HYDROData_CalculationCase::GetGeometryGroups() const
557 {
558   return GetReferenceObjects( DataTag_GeometryGroup );
559 }
560
561 void HYDROData_CalculationCase::RemoveGeometryGroup( const Handle(HYDROData_ShapesGroup)& theGroup )
562 {
563   if ( theGroup.IsNull() )
564     return;
565
566   RemoveReferenceObject( theGroup->Label(), DataTag_GeometryGroup );
567
568   // Indicate model of the need to update splitting
569   Changed( Geom_Groups );
570 }
571
572 void HYDROData_CalculationCase::RemoveGeometryGroups()
573 {
574   ClearReferenceObjects( DataTag_GeometryGroup );
575
576   // Indicate model of the need to update splitting
577   Changed( Geom_Groups );
578 }
579
580 void HYDROData_CalculationCase::SetBoundaryPolyline( const Handle(HYDROData_PolylineXY)& thePolyline )
581 {
582   Handle(HYDROData_PolylineXY) aPrevPolyline = GetBoundaryPolyline();
583
584   SetReferenceObject( thePolyline, DataTag_Polyline );
585
586   // Indicate model of the need to update zones splitting
587   if( !IsEqual( aPrevPolyline, thePolyline ) )
588     Changed( Geom_2d );
589 }
590
591 Handle(HYDROData_PolylineXY) HYDROData_CalculationCase::GetBoundaryPolyline() const
592 {
593   return Handle(HYDROData_PolylineXY)::DownCast( 
594            GetReferenceObject( DataTag_Polyline ) );
595 }
596
597 void HYDROData_CalculationCase::RemoveBoundaryPolyline()
598 {
599   Handle(HYDROData_PolylineXY) aPrevPolyline = GetBoundaryPolyline();
600
601   ClearReferenceObjects( DataTag_Polyline );
602
603   // Indicate model of the need to update zones splitting
604   Changed( Geom_2d );
605 }
606
607 void HYDROData_CalculationCase::SetStricklerTable( const Handle(HYDROData_StricklerTable)& theStricklerTable )
608 {
609   Handle(HYDROData_StricklerTable) aPrevStricklerTable = GetStricklerTable();
610
611   SetReferenceObject( theStricklerTable, DataTag_StricklerTable );
612
613   // Indicate model of the need to update land covers partition
614   if( !IsEqual( aPrevStricklerTable, theStricklerTable ) )
615     Changed( Geom_No );
616 }
617
618 Handle(HYDROData_StricklerTable) HYDROData_CalculationCase::GetStricklerTable() const
619 {
620   return Handle(HYDROData_StricklerTable)::DownCast( 
621            GetReferenceObject( DataTag_StricklerTable ) );
622 }
623
624 void HYDROData_CalculationCase::RemoveStricklerTable()
625 {
626   Handle(HYDROData_StricklerTable) aPrevStricklerTable = GetStricklerTable();
627
628   ClearReferenceObjects( DataTag_StricklerTable );
629
630   // Indicate model of the need to update land covers partition
631   Changed( Geom_No );
632 }
633
634 bool HYDROData_CalculationCase::AddLandCover( const Handle(HYDROData_LandCover)& theLandCover )
635 {
636   if ( HasReference( theLandCover, DataTag_LandCover ) )
637     return false; // Land cover is already in reference list
638
639   AddReferenceObject( theLandCover, DataTag_LandCover );
640   
641   // Indicate model of the need to update land covers partition
642   Changed( Geom_No );
643
644   return true;
645 }
646
647 HYDROData_SequenceOfObjects HYDROData_CalculationCase::GetLandCovers() const
648 {
649   return GetReferenceObjects( DataTag_LandCover );
650 }
651
652 void HYDROData_CalculationCase::RemoveLandCover( const Handle(HYDROData_LandCover)& theLandCover )
653 {
654   if ( theLandCover.IsNull() )
655     return;
656
657   RemoveReferenceObject( theLandCover->Label(), DataTag_LandCover );
658
659   // Indicate model of the need to update land cover partition
660   Changed( Geom_No );
661 }
662
663 void HYDROData_CalculationCase::RemoveLandCovers()
664 {
665   ClearReferenceObjects( DataTag_LandCover );
666
667   // Indicate model of the need to update land cover partition
668   Changed( Geom_No );
669 }
670
671 Handle(HYDROData_Region) HYDROData_CalculationCase::AddNewRegion( const Handle(HYDROData_Zone)& theZone,
672                                                                   const bool theLandCover )
673 {
674   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
675   Handle(HYDROData_Region) aNewRegion = addNewRegion( aDocument, CALCULATION_REGIONS_PREF, theLandCover );
676   if ( aNewRegion.IsNull() )
677     return aNewRegion;
678
679   aNewRegion->AddZone( theZone );
680
681   return aNewRegion;
682 }
683
684 bool HYDROData_CalculationCase::AddRegion( const Handle(HYDROData_Region)& theRegion,
685                                            const bool theLandCover )
686 {
687   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
688
689   if ( theRegion.IsNull() )
690     return false;
691   
692   HYDROData_CalculationCase::DataTag aDataTag = 
693     theLandCover ? DataTag_LandCoverRegion : DataTag_Region;
694
695   if ( HasReference( theRegion, aDataTag ) )
696     return false; // Object is already in reference list
697
698   // Move the region from other calculation
699   Handle(HYDROData_CalculationCase) aFatherCalc = 
700     Handle(HYDROData_CalculationCase)::DownCast( theRegion->GetFatherObject() );
701   if ( !aFatherCalc.IsNull() && aFatherCalc->Label() != myLab )
702   {
703     Handle(HYDROData_Region) aNewRegion = addNewRegion( aDocument, CALCULATION_REGIONS_PREF, theLandCover );
704     theRegion->CopyTo( aNewRegion, true );
705
706     aFatherCalc->RemoveRegion( theRegion, theLandCover );
707
708     theRegion->SetLabel( aNewRegion->Label() );
709   }
710   else
711   {
712     AddReferenceObject( theRegion, aDataTag );
713   }
714
715   return true;
716 }
717
718 HYDROData_SequenceOfObjects HYDROData_CalculationCase::GetRegions( const bool theLandCover ) const
719 {
720   return GetReferenceObjects( theLandCover ? DataTag_LandCoverRegion : DataTag_Region );
721 }
722
723 void HYDROData_CalculationCase::UpdateRegionsOrder()
724 {
725   Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
726   if ( aDocument.IsNull() )
727     return;
728
729   HYDROData_SequenceOfObjects aRegions = GetRegions( false );
730   HYDROData_SequenceOfObjects aRegionsLC = GetRegions( true );
731   aRegions.Append( aRegionsLC );
732
733   HYDROData_SequenceOfObjects::Iterator anIter( aRegions );
734   for ( ; anIter.More(); anIter.Next() )
735   {
736     Handle(HYDROData_Region) aRegion =
737       Handle(HYDROData_Region)::DownCast( anIter.Value() );
738     if ( aRegion.IsNull() )
739       continue;
740
741     aRegion->SetName( "" );
742   }
743
744   QString aRegsPref = CALCULATION_REGIONS_PREF;
745
746   anIter.Init( aRegions );
747   for ( ; anIter.More(); anIter.Next() )
748   {
749     Handle(HYDROData_Region) aRegion =
750       Handle(HYDROData_Region)::DownCast( anIter.Value() );
751     if ( aRegion.IsNull() )
752       continue;
753
754     QString aRegionName = HYDROData_Tool::GenerateObjectName( aDocument, aRegsPref );
755     aRegion->SetName( aRegionName );
756   }
757 }
758
759 void HYDROData_CalculationCase::RemoveRegion( const Handle(HYDROData_Region)& theRegion,
760                                               const bool theLandCover )
761 {
762   if ( theRegion.IsNull() )
763     return;
764
765   HYDROData_CalculationCase::DataTag aDataTag = 
766     theLandCover ? DataTag_LandCoverRegion : DataTag_Region;
767   RemoveReferenceObject( theRegion->Label(), aDataTag );
768
769   // Remove region from data model
770   Handle(HYDROData_CalculationCase) aFatherCalc = 
771     Handle(HYDROData_CalculationCase)::DownCast( theRegion->GetFatherObject() );
772   if ( !aFatherCalc.IsNull() && aFatherCalc->Label() == myLab )
773     theRegion->Remove();
774 }
775
776 void HYDROData_CalculationCase::RemoveRegions( const bool theLandCover )
777 {
778   myLab.FindChild( theLandCover ? DataTag_ChildLandCoverRegion : DataTag_ChildRegion ).ForgetAllAttributes();
779 }
780
781 HYDROData_SequenceOfObjects HYDROData_CalculationCase::GetSplittedGroups() const
782 {
783   return GetReferenceObjects( DataTag_SplittedGroups );
784 }
785
786 void HYDROData_CalculationCase::RemoveSplittedGroups()
787 {
788   myLab.FindChild( DataTag_SplittedGroups ).ForgetAllAttributes();
789 }
790
791 double HYDROData_CalculationCase::GetAltitudeForPoint( const gp_XY& thePoint ) const
792 {
793   Handle(HYDROData_Zone) aZone = GetZoneFromPoint( thePoint, false );
794   return GetAltitudeForPoint( thePoint, aZone );
795 }
796
797 double HYDROData_CalculationCase::GetAltitudeForPoint( const gp_XY&                    thePoint,
798                                                        const Handle(HYDROData_Region)& theRegion ) const
799 {
800   double aResAltitude = HYDROData_IAltitudeObject::GetInvalidAltitude();
801
802   Handle(HYDROData_Zone) aZone = GetZoneFromPoint( thePoint, false );
803   if ( !aZone.IsNull() )
804   {
805     //DEBTRACE("GetAltitudeForPoint Region " << theRegion->GetName().toStdString() << " Zone " << aZone->GetName().toStdString());
806     Handle(HYDROData_Region) aRefRegion = Handle(HYDROData_Region)::DownCast( aZone->GetFatherObject() );
807     if ( IsEqual( aRefRegion, theRegion ) )
808       aResAltitude = GetAltitudeForPoint( thePoint, aZone );
809     else
810       {
811         DEBTRACE("GetAltitudeForPoint Region " << aRefRegion->GetName().toStdString() << " Zone " << aZone->GetName().toStdString() << " ---------------------------");
812         aResAltitude = GetAltitudeForPoint( thePoint, aZone );
813       }
814   }
815   else
816     {
817       DEBTRACE(" --- GetAltitudeForPoint No Zone ---");
818     }
819
820   return aResAltitude;
821 }
822
823 double HYDROData_CalculationCase::GetAltitudeForPoint( const gp_XY&                  thePoint,
824                                                        const Handle(HYDROData_Zone)& theZone ) const
825 {
826   //DEBTRACE("GetAltitudeForPoint Zone " << theZone->GetName().toStdString());
827   double aResAltitude = HYDROData_IAltitudeObject::GetInvalidAltitude();
828   if ( theZone.IsNull() )
829   {
830         DEBTRACE("Zone nulle");
831     return aResAltitude;
832   }
833
834   HYDROData_Zone::MergeType aZoneMergeType = theZone->GetMergeType();
835   //DEBTRACE("aZoneMergeType " << aZoneMergeType);
836   if ( !theZone->IsMergingNeed() )
837   {
838     aZoneMergeType = HYDROData_Zone::Merge_UNKNOWN;
839     //DEBTRACE("---");
840   }
841   else if ( aZoneMergeType == HYDROData_Zone::Merge_UNKNOWN )
842   {
843         DEBTRACE("GetAltitudeForPoint Zone " << theZone->GetName().toStdString() << " Merge_UNKNOWN");
844     return aResAltitude;
845   }
846
847   HYDROData_IInterpolator* aZoneInterpolator = theZone->GetInterpolator();
848   if ( aZoneMergeType == HYDROData_Zone::Merge_Object )
849   {
850     Handle(HYDROData_IAltitudeObject) aMergeAltitude = 
851       Handle(HYDROData_IAltitudeObject)::DownCast( theZone->GetMergeObject() );
852     if ( !aMergeAltitude.IsNull() )
853     {
854       if ( aZoneInterpolator != NULL )
855       {
856         DEBTRACE("aZoneInterpolator != NULL");
857         aZoneInterpolator->SetAltitudeObject( aMergeAltitude );
858         aResAltitude = aZoneInterpolator->GetAltitudeForPoint( thePoint );
859       }
860       else
861       {
862         DEBTRACE("aZoneInterpolator == NULL");
863         aResAltitude = aMergeAltitude->GetAltitudeForPoint( thePoint );
864       }
865     }
866   }
867   else
868   {
869         //DEBTRACE("aZoneMergeType != HYDROData_Zone::Merge_Object");
870     HYDROData_SequenceOfObjects aZoneObjects = theZone->GetObjects();
871     HYDROData_SequenceOfObjects::Iterator anIter( aZoneObjects );
872     for ( ; anIter.More(); anIter.Next() )
873     {
874       Handle(HYDROData_Object) aZoneObj =
875         Handle(HYDROData_Object)::DownCast( anIter.Value() );
876       if ( aZoneObj.IsNull() )
877         continue;
878
879       Handle(HYDROData_IAltitudeObject) anObjAltitude = aZoneObj->GetAltitudeObject();
880       if ( anObjAltitude.IsNull() )
881         continue;
882
883       double aPointAltitude = 0.0;
884       if ( aZoneInterpolator != NULL )
885       {
886         DEBTRACE("aZoneInterpolator != NULL");
887         aZoneInterpolator->SetAltitudeObject( anObjAltitude );
888         aPointAltitude = aZoneInterpolator->GetAltitudeForPoint( thePoint );
889       }
890       else
891       {
892         //DEBTRACE("aZoneInterpolator == NULL");
893         aPointAltitude = anObjAltitude->GetAltitudeForPoint( thePoint );
894       }
895
896       if ( ValuesEquals( aPointAltitude, HYDROData_IAltitudeObject::GetInvalidAltitude() ) )
897         continue;
898
899       if ( aZoneMergeType == HYDROData_Zone::Merge_UNKNOWN )
900       {
901         aResAltitude = aPointAltitude;
902         break;
903       }
904       else if ( aZoneMergeType == HYDROData_Zone::Merge_ZMIN )
905       {
906         if ( ValuesEquals( aResAltitude, HYDROData_IAltitudeObject::GetInvalidAltitude() ) ||
907              aResAltitude > aPointAltitude )
908         {
909           aResAltitude = aPointAltitude;
910         }
911       }
912       else if ( aZoneMergeType == HYDROData_Zone::Merge_ZMAX )
913       {
914         if ( ValuesEquals( aResAltitude, HYDROData_IAltitudeObject::GetInvalidAltitude() ) ||
915              aResAltitude < aPointAltitude )
916         {
917           aResAltitude = aPointAltitude;
918         }
919       }
920     }
921   }
922
923   return aResAltitude;
924 }
925
926 NCollection_Sequence<double> HYDROData_CalculationCase::GetAltitudesForPoints( 
927   const NCollection_Sequence<gp_XY>& thePoints,
928   const Handle(HYDROData_Region)&    theRegion ) const
929 {
930   //DEBTRACE("HYDROData_CalculationCase::GetAltitudesForPoints " << theRegion->GetName().toStdString());
931   NCollection_Sequence<double> aResSeq;
932
933   for ( int i = 1, n = thePoints.Length(); i <= n; ++i )
934   {
935     const gp_XY& thePnt = thePoints.Value( i );
936     
937     double anAltitude = GetAltitudeForPoint( thePnt, theRegion );
938     aResSeq.Append( anAltitude );
939   }
940
941   return aResSeq;
942 }
943
944 NCollection_Sequence<double> HYDROData_CalculationCase::GetAltitudesForPoints( 
945   const NCollection_Sequence<gp_XY>& thePoints,
946   const Handle(HYDROData_Zone)&      theZone ) const
947 {
948   NCollection_Sequence<double> aResSeq;
949
950   for ( int i = 1, n = thePoints.Length(); i <= n; ++i )
951   {
952     const gp_XY& thePnt = thePoints.Value( i );
953     
954     double anAltitude = GetAltitudeForPoint( thePnt, theZone );
955     aResSeq.Append( anAltitude );
956   }
957
958   return aResSeq;
959 }
960
961 double HYDROData_CalculationCase::GetStricklerCoefficientForPoint( const gp_XY& thePoint ) const
962 {
963     double aCoeff = 0;
964     Handle(HYDROData_Document) aDocument = HYDROData_Document::Document( myLab );
965     if ( !aDocument.IsNull() )
966         aCoeff = aDocument->GetDefaultStricklerCoefficient();
967
968     Handle(HYDROData_LandCover) aLandCover;
969     Handle(HYDROData_Zone) aZone = GetZoneFromPoint( thePoint, Standard_True );
970     if ( !aZone.IsNull() )
971     {
972         HYDROData_SequenceOfObjects anObjList = aZone->GetObjects();
973         if ( anObjList.Length() == 1 )
974             aLandCover = Handle(HYDROData_LandCover)::DownCast( anObjList.First() );
975         else
976             aLandCover = Handle(HYDROData_LandCover)::DownCast( aZone->GetMergeObject() );
977     }
978
979     if ( !aLandCover.IsNull() )
980     {
981         QString aType = aLandCover->GetStricklerType();
982         Handle(HYDROData_StricklerTable) aTable = GetStricklerTable();
983         if ( !aTable.IsNull() )
984         {
985             if ( aTable->GetTypes().contains( aType ) )
986                 aCoeff = aTable->Get( aType, aCoeff );
987         }
988     }
989
990     return aCoeff;
991 }
992
993 Handle(HYDROData_Region) HYDROData_CalculationCase::GetRegionFromPoint( const gp_XY& thePoint,
994                                                                         const bool theLandCover ) const
995 {
996   Handle(HYDROData_Region) aResRegion;
997
998   Handle(HYDROData_Zone) aZone = GetZoneFromPoint( thePoint, theLandCover );
999   if ( !aZone.IsNull() )
1000     aResRegion = Handle(HYDROData_Region)::DownCast( aZone->GetFatherObject() );
1001
1002   return aResRegion;
1003 }
1004
1005 Handle(HYDROData_Zone) HYDROData_CalculationCase::GetZoneFromPoint( const gp_XY& thePoint,
1006                                                                     const bool theLandCover ) const
1007 {
1008   Handle(HYDROData_Zone) aResZone;
1009
1010   HYDROData_SequenceOfObjects aRegions = GetRegions( theLandCover );
1011
1012   HYDROData_SequenceOfObjects::Iterator anIter( aRegions );
1013   for ( ; anIter.More() && aResZone.IsNull(); anIter.Next() )
1014   {
1015     Handle(HYDROData_Region) aRegion =
1016       Handle(HYDROData_Region)::DownCast( anIter.Value() );
1017     if ( aRegion.IsNull() )
1018       continue;
1019
1020     HYDROData_SequenceOfObjects aZones = aRegion->GetZones();
1021     HYDROData_SequenceOfObjects::Iterator aZonesIter( aZones );
1022     for ( ; aZonesIter.More() && aResZone.IsNull(); aZonesIter.Next() )
1023     {
1024       Handle(HYDROData_Zone) aRegZone =
1025         Handle(HYDROData_Zone)::DownCast( aZonesIter.Value() );
1026       if ( aRegZone.IsNull() )
1027         continue;
1028
1029       PointClassification aPointRelation = GetPointClassification( thePoint, aRegZone );
1030       if ( aPointRelation != POINT_OUT )
1031         aResZone = aRegZone; // We found the desired zone
1032     }
1033   }
1034
1035   return aResZone;
1036 }
1037
1038 HYDROData_CalculationCase::PointClassification HYDROData_CalculationCase::GetPointClassification(
1039   const gp_XY&                  thePoint,
1040   const Handle(HYDROData_Zone)& theZone ) const
1041 {
1042   PointClassification aRes = POINT_OUT;
1043   if ( theZone.IsNull() )
1044     return aRes;
1045
1046   TopoDS_Face aZoneFace = TopoDS::Face( theZone->GetShape() );
1047   if ( aZoneFace.IsNull() )
1048     return aRes;
1049 #ifdef DEB_CLASS2D      
1050           TopoDS_Compound aCmp;
1051       BRep_Builder aBB;
1052       aBB.MakeCompound(aCmp);
1053           aBB.Add(aCmp, aZoneFace);
1054           gp_Pnt aPnt (thePoint.X(), thePoint.Y(), 0.);
1055           BRepBuilderAPI_MakeVertex aMk(aPnt);
1056           aBB.Add(aCmp, aMk.Vertex());
1057           BRepTools::Write(aCmp, "FCL2d.brep");
1058 #endif  
1059   TopAbs_State State = HYDROData_Tool::ComputePointState(thePoint, aZoneFace);
1060   if (State == TopAbs_OUT)
1061     aRes =  POINT_OUT;
1062   else if(State == TopAbs_IN)
1063     aRes =  POINT_IN;
1064   else if(State == TopAbs_ON)
1065     aRes =  POINT_ON;
1066   return aRes;
1067 }
1068
1069 Handle(HYDROData_Region) HYDROData_CalculationCase::addNewRegion( const Handle(HYDROData_Document)& theDoc,
1070                                                                   const QString& thePrefixOrName,
1071                                                                   const bool theLandCover,
1072                                                                   bool isPrefix )
1073 {
1074   TDF_Label aNewLab = myLab.FindChild( theLandCover ? DataTag_ChildLandCoverRegion : DataTag_ChildRegion ).NewChild();
1075   int aTag = aNewLab.Tag();
1076
1077   Handle(HYDROData_Region) aNewRegion =
1078     Handle(HYDROData_Region)::DownCast( HYDROData_Iterator::CreateObject( aNewLab, KIND_REGION ) );
1079   AddRegion( aNewRegion, theLandCover );
1080
1081   QString aRegionName = isPrefix ? HYDROData_Tool::GenerateObjectName( theDoc, thePrefixOrName ) : thePrefixOrName;
1082   aNewRegion->SetName( aRegionName );
1083
1084   return aNewRegion;
1085 }
1086
1087 Handle(HYDROData_SplittedShapesGroup) HYDROData_CalculationCase::addNewSplittedGroup( const QString& theName )
1088 {
1089   TDF_Label aNewLab = myLab.FindChild( DataTag_SplittedGroups ).NewChild();
1090
1091   Handle(HYDROData_SplittedShapesGroup) aNewGroup =
1092     Handle(HYDROData_SplittedShapesGroup)::DownCast( 
1093       HYDROData_Iterator::CreateObject( aNewLab, KIND_SPLITTED_GROUP ) );
1094   AddReferenceObject( aNewGroup, DataTag_SplittedGroups );
1095
1096   aNewGroup->SetName( theName );
1097
1098   return aNewGroup;
1099 }
1100
1101 QString HYDROData_CalculationCase::Export( int theStudyId ) const
1102 {
1103   GEOM::GEOM_Gen_var aGEOMEngine = HYDROData_GeomTool::GetGeomGen();
1104   SALOMEDS::Study_var aDSStudy = HYDROData_GeomTool::GetStudyByID( theStudyId );
1105   
1106   QString aGeomObjEntry, anErrorMsg;
1107   bool isOK = Export( aGEOMEngine, aDSStudy, aGeomObjEntry, anErrorMsg );
1108   return isOK ? aGeomObjEntry : QString();
1109 }
1110
1111 bool HYDROData_CalculationCase::Export( GEOM::GEOM_Gen_var  theGeomEngine,
1112                                         SALOMEDS::Study_ptr theStudy,
1113                                         QString& theGeomObjEntry,
1114                                         QString& theErrorMsg ) const
1115 {
1116   HYDROData_ShapesGroup::SeqOfGroupsDefs aSeqOfGroupsDefs;
1117
1118   // Get groups definitions
1119   HYDROData_SequenceOfObjects aSplittedGroups = GetSplittedGroups();
1120
1121   HYDROData_SequenceOfObjects::Iterator anIter( aSplittedGroups );
1122   for ( ; anIter.More(); anIter.Next() )
1123   {
1124     // Get shapes group
1125     Handle(HYDROData_ShapesGroup) aGroup =
1126       Handle(HYDROData_ShapesGroup)::DownCast( anIter.Value() );
1127     if ( aGroup.IsNull() )
1128       continue;
1129
1130     HYDROData_ShapesGroup::GroupDefinition aGroupDef;
1131
1132     aGroupDef.Name = aGroup->GetName().toLatin1().constData();
1133     aGroup->GetShapes( aGroupDef.Shapes );
1134
1135     aSeqOfGroupsDefs.Append( aGroupDef );
1136   }
1137   
1138   // Get faces
1139   bool isAllNotSubmersible = true;
1140   TopTools_ListOfShape aFaces;
1141   HYDROData_SequenceOfObjects aCaseRegions = GetRegions( false );
1142   HYDROData_SequenceOfObjects::Iterator aRegionIter( aCaseRegions );
1143   for ( ; aRegionIter.More(); aRegionIter.Next() )
1144   {
1145     Handle(HYDROData_Region) aRegion =
1146       Handle(HYDROData_Region)::DownCast( aRegionIter.Value() );
1147     if( aRegion.IsNull() || !aRegion->IsSubmersible() )
1148       continue;
1149     
1150     if ( isAllNotSubmersible )
1151       isAllNotSubmersible = false;
1152
1153     TopoDS_Shape aRegionShape = aRegion->GetShape( &aSeqOfGroupsDefs );
1154     aFaces.Append( aRegionShape );
1155   }
1156
1157   bool aRes = false;
1158
1159   if ( aCaseRegions.IsEmpty() ) {
1160     theErrorMsg = QString("the list of regions is empty.");
1161   } else if ( isAllNotSubmersible ) {
1162     theErrorMsg = QString("there are no submersible regions.");
1163   } else {
1164     aRes = Export( theGeomEngine, theStudy, aFaces, aSeqOfGroupsDefs, theGeomObjEntry );;
1165   }
1166
1167   return aRes;
1168 }
1169
1170 bool HYDROData_CalculationCase::Export( GEOM::GEOM_Gen_var                            theGeomEngine,
1171                                         SALOMEDS::Study_ptr                           theStudy,
1172                                         const TopTools_ListOfShape&                   theFaces,
1173                                         const HYDROData_ShapesGroup::SeqOfGroupsDefs& theGroupsDefs,
1174                                         QString& theGeomObjEntry ) const
1175 {
1176   // Sew faces
1177   BRepBuilderAPI_Sewing aSewing( Precision::Confusion() * 10.0 );
1178   aSewing.SetNonManifoldMode( Standard_False );
1179 #ifdef DEB_CALCULATION
1180   TCollection_AsciiString aNam("Sh_");
1181   int i=1;
1182 #endif
1183   TopTools_ListIteratorOfListOfShape aFaceIter( theFaces );
1184   for ( ; aFaceIter.More(); aFaceIter.Next() )
1185   {
1186     TopoDS_Shape aShape = aFaceIter.Value();
1187     if ( aShape.IsNull() )
1188       continue;
1189
1190     if ( aShape.ShapeType() == TopAbs_FACE )
1191     {
1192       aSewing.Add( aShape );
1193 #ifdef DEB_CALCULATION
1194       TCollection_AsciiString aName = aNam + ++i + ".brep";
1195       BRepTools::Write(aShape ,aName.ToCString());
1196 #endif
1197     }
1198     else
1199     {
1200 #ifdef DEB_CALCULATION
1201       int j = 1;
1202 #endif
1203       TopExp_Explorer anExp( aShape, TopAbs_FACE );
1204       for (; anExp.More(); anExp.Next() ) {
1205         aSewing.Add( anExp.Current() );
1206 #ifdef DEB_CALCULATION
1207
1208         TCollection_AsciiString aName = aNam + i + "_" + ++j + ".brep";
1209         BRepTools::Write(anExp.Current() ,aName.ToCString());
1210 #endif
1211       }
1212     }
1213   } // faces iterator
1214   
1215   aSewing.Perform();
1216   TopoDS_Shape aSewedShape = aSewing.SewedShape();
1217
1218   // If the sewed shape is empty - return false
1219   if ( aSewedShape.IsNull() || !TopoDS_Iterator( aSewedShape ).More() )
1220     return false;
1221
1222 #ifdef DEB_CALCULATION
1223   BRepTools::Write(aSewedShape ,"Sew.brep");
1224 #endif
1225   // Publish the sewed shape
1226   QString aName = EXPORT_NAME;
1227   GEOM::GEOM_Object_ptr aMainShape = 
1228     HYDROData_GeomTool::publishShapeInGEOM( theGeomEngine, theStudy, aSewedShape, aName, theGeomObjEntry );
1229
1230   if ( aMainShape->_is_nil() )  
1231     return false;
1232
1233   if ( theGroupsDefs.IsEmpty() )
1234     return true;
1235
1236   // Create groups
1237   TopTools_IndexedMapOfShape aMapOfSubShapes;
1238   TopExp::MapShapes( aSewedShape, aMapOfSubShapes );
1239
1240   NCollection_DataMap< TCollection_AsciiString, NCollection_Sequence<int> > aGroupsData;
1241
1242   for ( int aGrId = 1, nbGroups = theGroupsDefs.Length(); aGrId <= nbGroups; ++aGrId )
1243   {
1244     const HYDROData_ShapesGroup::GroupDefinition& aGroupDef = theGroupsDefs.Value( aGrId );
1245
1246     NCollection_Sequence<int> aGroupIndexes;
1247     for( int i = 1, n = aGroupDef.Shapes.Length(); i <= n; i++ )
1248     {
1249       const TopoDS_Shape& aShape = aGroupDef.Shapes.Value( i );
1250 #ifdef DEB_CALCULATION
1251       cout << "\nOld shape(" << i << ") = " << aShape.TShape() <<endl;
1252 #endif
1253       
1254       TopoDS_Shape aModifiedShape = aShape;
1255       if ( aSewing.IsModified( aShape ) )
1256         aModifiedShape = aSewing.Modified( aShape );
1257       else if ( aSewing.IsModifiedSubShape( aShape ) )
1258         aModifiedShape = aSewing.ModifiedSubShape( aShape );
1259
1260 #ifdef DEB_CALCULATION
1261       const TopLoc_Location& aL1 = aShape.Location();
1262       const TopLoc_Location& aL2 = aModifiedShape.Location();
1263       cout << "\nNew shape(" << i << ") = " << aModifiedShape.TShape() << " Location is Equal = " << aL1.IsEqual(aL2)<<endl;
1264 #endif
1265
1266       int anIndex = aMapOfSubShapes.FindIndex(aModifiedShape);
1267       if ( anIndex > 0 ) {
1268         aGroupIndexes.Append( anIndex );
1269       } else {
1270 #ifdef DEB_CALCULATION    
1271         TCollection_AsciiString aNam("Lost_");
1272         if(!aMapOfSubShapes.Contains(aModifiedShape)) {
1273         for ( int anIndex = 1; anIndex <= aMapOfSubShapes.Extent(); anIndex++ )
1274         {
1275            const TopoDS_Shape& aS = aMapOfSubShapes.FindKey( anIndex );
1276            if ( aModifiedShape.IsPartner( aS ) )
1277            {
1278              cout <<"\nIndex in Map = " << anIndex << "TShape = " << aS.TShape() <<endl;
1279              TCollection_AsciiString aName = aNam + i + "_" + anIndex + ".brep";
1280              BRepTools::Write(aS ,aName.ToCString());
1281             break;
1282            }
1283          }
1284         }
1285 #endif
1286       }
1287     }
1288     if ( !aGroupIndexes.IsEmpty() )
1289       aGroupsData.Bind( aGroupDef.Name, aGroupIndexes );
1290   }
1291  
1292   if ( !aGroupsData.IsEmpty() )
1293   {
1294     GEOM::GEOM_IGroupOperations_var aGroupOp = 
1295       theGeomEngine->GetIGroupOperations( theStudy->StudyId() );  
1296
1297     NCollection_DataMap< TCollection_AsciiString, NCollection_Sequence<int> >::Iterator aMapIt( aGroupsData );
1298     for ( ; aMapIt.More(); aMapIt.Next() )
1299     {
1300       const TCollection_AsciiString& aGroupName = aMapIt.Key(); 
1301       const NCollection_Sequence<int>& aGroupIndexes = aMapIt.Value();
1302
1303       GEOM::GEOM_Object_var aGeomGroup = aGroupOp->CreateGroup( aMainShape, TopAbs_EDGE );
1304       if ( CORBA::is_nil( aGeomGroup ) || !aGroupOp->IsDone() )
1305         continue;
1306
1307       GEOM::ListOfLong_var aGeomIndexes = new GEOM::ListOfLong;
1308       aGeomIndexes->length( aGroupIndexes.Length() );
1309
1310       for( int i = 1, n = aGroupIndexes.Length(); i <= n; i++ )
1311         aGeomIndexes[ i - 1 ] = aGroupIndexes.Value( i );
1312
1313       aGroupOp->UnionIDs( aGeomGroup, aGeomIndexes );
1314       if ( aGroupOp->IsDone() )
1315       {
1316         SALOMEDS::SObject_var aGroupSO = 
1317           theGeomEngine->AddInStudy( theStudy, aGeomGroup, aGroupName.ToCString(), aMainShape );
1318       }
1319     }
1320   }
1321
1322   return true;
1323 }
1324
1325 void HYDROData_CalculationCase::ClearRules( HYDROData_CalculationCase::DataTag theDataTag,
1326                                             const bool theIsSetToUpdate )
1327 {
1328   TDF_Label aRulesLab = myLab.FindChild( theDataTag );
1329   HYDROData_PriorityQueue::ClearRules( aRulesLab );
1330
1331   // Indicate model of the need to update splitting
1332   if ( theIsSetToUpdate ) {
1333     Changed( Geom_2d );
1334   }
1335 }
1336
1337 void HYDROData_CalculationCase::AddRule( const Handle(HYDROData_Entity)&    theObject1,
1338                                          HYDROData_PriorityType             thePriority,
1339                                          const Handle(HYDROData_Entity)&    theObject2,
1340                                          HYDROData_Zone::MergeType          theMergeType,
1341                                          HYDROData_CalculationCase::DataTag theDataTag )
1342 {
1343   TDF_Label aRulesLab = myLab.FindChild( theDataTag );
1344   HYDROData_PriorityQueue::AddRule( aRulesLab, theObject1, thePriority, theObject2, theMergeType );
1345
1346   // Indicate model of the need to update splitting
1347   Changed( Geom_2d );
1348 }
1349
1350 QString HYDROData_CalculationCase::DumpRules() const
1351 {
1352   TDF_Label aRulesLab = myLab.FindChild( DataTag_CustomRules );
1353   return HYDROData_PriorityQueue::DumpRules( aRulesLab );
1354 }
1355
1356 QString HYDROData_CalculationCase::DumpLandCoverRules() const
1357 {
1358   TDF_Label aRulesLab = myLab.FindChild( DataTag_CustomLandCoverRules );
1359   return HYDROData_PriorityQueue::DumpRules( aRulesLab );
1360 }
1361
1362 void HYDROData_CalculationCase::SetAssignmentMode( AssignmentMode theMode )
1363 {
1364   TDF_Label aModeLab = myLab.FindChild( DataTag_AssignmentMode );
1365   TDataStd_Integer::Set( aModeLab, ( int ) theMode );
1366
1367   // Indicate model of the need to update splitting
1368   Changed( Geom_2d );
1369 }
1370
1371 HYDROData_CalculationCase::AssignmentMode HYDROData_CalculationCase::GetAssignmentMode() const
1372 {
1373   Handle(TDataStd_Integer) aModeAttr;
1374   bool isOK = myLab.FindChild( DataTag_AssignmentMode ).FindAttribute( TDataStd_Integer::GetID(), aModeAttr );
1375   if( isOK )
1376     return ( AssignmentMode ) aModeAttr->Get();
1377   else
1378     return MANUAL;
1379 }
1380
1381 void HYDROData_CalculationCase::DumpRulesToPython( const QString& theCalcCaseName,
1382                                                    QStringList& theScript ) const
1383 {
1384   TDF_Label aRulesLab = myLab.FindChild( DataTag_CustomRules );
1385   HYDROData_PriorityQueue::DumpRulesToPython( aRulesLab, theCalcCaseName, theScript );
1386 }
1387
1388 void HYDROData_CalculationCase::DumpLandCoverRulesToPython( const QString& theCalcCaseName,
1389                                                             QStringList& theScript ) const
1390 {
1391   TDF_Label aRulesLab = myLab.FindChild( DataTag_CustomLandCoverRules );
1392   HYDROData_PriorityQueue::DumpRulesToPython( aRulesLab, theCalcCaseName, theScript );
1393 }
1394
1395 HYDROData_Warning HYDROData_CalculationCase::GetLastWarning() const
1396 {
1397   return myLastWarning;
1398 }
1399
1400 void HYDROData_CalculationCase::SetWarning( HYDROData_WarningType theType, const QString& theData )
1401 {
1402   myLastWarning.Type = theType;
1403   myLastWarning.Data = theData;
1404 }
1405
1406 void HYDROData_CalculationCase::UpdateRegionsNames( const HYDROData_SequenceOfObjects& theRegions,
1407                                                     const QString& theOldCaseName,
1408                                                     const QString& theName )
1409 {
1410   HYDROData_SequenceOfObjects::Iterator anIter( theRegions );
1411   for ( ; anIter.More(); anIter.Next() )
1412   {
1413     Handle(HYDROData_Region) aRegion =
1414       Handle(HYDROData_Region)::DownCast( anIter.Value() );
1415     if ( aRegion.IsNull() )
1416       continue;
1417
1418     HYDROData_Tool::UpdateChildObjectName( theOldCaseName, theName, aRegion );
1419
1420     HYDROData_SequenceOfObjects aZones = aRegion->GetZones();
1421     HYDROData_SequenceOfObjects::Iterator anIter( aZones );
1422     for ( ; anIter.More(); anIter.Next() )
1423     {
1424       Handle(HYDROData_Zone) aRegZone =
1425         Handle(HYDROData_Zone)::DownCast( anIter.Value() );
1426       if ( aRegZone.IsNull() )
1427         continue;
1428
1429       HYDROData_Tool::UpdateChildObjectName( theOldCaseName, theName, aRegZone );
1430     }
1431   }
1432 }
1433
1434 void HYDROData_CalculationCase::DumpRegionsToPython( QStringList& theResList,
1435                                                      MapOfTreatedObjects& theTreatedObjects,
1436                                                      const HYDROData_SequenceOfObjects& theRegions ) const
1437 {
1438   HYDROData_SequenceOfObjects::Iterator anIter;
1439   anIter.Init( theRegions );
1440   for ( ; anIter.More(); anIter.Next() )
1441   {
1442     Handle(HYDROData_Region) aRegion =
1443       Handle(HYDROData_Region)::DownCast( anIter.Value() );
1444     if ( aRegion.IsNull() )
1445       continue;
1446
1447     theTreatedObjects.insert( aRegion->GetName(), aRegion );
1448     QStringList aRegDump = aRegion->DumpToPython( theTreatedObjects );
1449     theResList << aRegDump;
1450   }
1451 }
1452
1453 bool HYDROData_CalculationCase::GetRule( int theIndex, 
1454                                          Handle(HYDROData_Entity)&           theObject1,
1455                                          HYDROData_PriorityType&             thePriority,
1456                                          Handle(HYDROData_Entity)&           theObject2,
1457                                          HYDROData_Zone::MergeType&          theMergeType,
1458                                          HYDROData_CalculationCase::DataTag& theDataTag) const
1459 {
1460   TDF_Label aRulesLab = myLab.FindChild( theDataTag );
1461   return HYDROData_PriorityQueue::GetRule( aRulesLab, theIndex,
1462     theObject1, thePriority, theObject2, theMergeType );
1463 }
1464
1465 void HYDROData_CalculationCase::SetAssignmentLandCoverMode( AssignmentMode theMode )
1466 {
1467   TDF_Label aModeLab = myLab.FindChild( DataTag_AssignmentLandCoverMode );
1468   TDataStd_Integer::Set( aModeLab, ( int ) theMode );
1469
1470   // Indicate model of the need to update land covers partition
1471   Changed( Geom_No );
1472 }
1473
1474 HYDROData_CalculationCase::AssignmentMode HYDROData_CalculationCase::GetAssignmentLandCoverMode() const
1475 {
1476   Handle(TDataStd_Integer) aModeAttr;
1477   bool isOK = myLab.FindChild( DataTag_AssignmentLandCoverMode ).FindAttribute( TDataStd_Integer::GetID(), aModeAttr );
1478   if( isOK )
1479     return ( AssignmentMode ) aModeAttr->Get();
1480   else
1481     return MANUAL;
1482 }