Salome HOME
2836229ae258c99d95418898cae18777c6edae4e
[modules/hydro.git] / src / HYDROData / HYDROData_SplitToZonesTool.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_SplitToZonesTool.h"
20
21 #include "HYDROData_PolylineXY.h"
22 #include "HYDROData_ShapesGroup.h"
23 #include <HYDROData_Transform.h>
24 #include <BRepAlgoAPI_Cut.hxx>
25 #include <BRepAlgoAPI_Common.hxx>
26 #include <BRepBuilderAPI_MakeFace.hxx>
27 #include <BRep_Builder.hxx>
28 #include <TopExp_Explorer.hxx>
29 #include <TopoDS.hxx>
30 #include <TopoDS_Shape.hxx>
31 #include <TopoDS_Compound.hxx>
32 #include <TopoDS_Wire.hxx>
33 #include <TopoDS_Edge.hxx>
34 #include <BRepCheck_Analyzer.hxx>
35 #include <TopTools_ListOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_IndexedMapOfShape.hxx>
38 #include <gp_Pln.hxx>
39 #include <BRepGProp.hxx>
40 #include <GProp_GProps.hxx>
41 #include <Geom_Plane.hxx>
42 #include <BRepBuilderAPI_FindPlane.hxx>
43
44 #include <BOPAlgo_BOP.hxx>
45 #include <BOPAlgo_Builder.hxx>
46 #include <TopExp.hxx>
47
48 //#define DEB_SPLIT_TO_ZONES 1
49 //#define DEB_SPLIT_TO_ZONES_CHECK_PARTITION 1
50 #if (defined (DEB_SPLIT_TO_ZONES) || defined(DEB_SPLIT_TO_ZONES_CHECK_PARTITION))
51 #include <BRepTools.hxx>
52 static TCollection_AsciiString fileNameBefore("BeforeTranslation");
53 #endif
54
55 #define _DEVDEBUG_
56 #include "HYDRO_trace.hxx"
57
58 TopoDS_Face HYDROData_SplitToZonesTool::SplitData::Face() const
59 {
60   TopoDS_Face aResFace;
61
62   if( !Shape.IsNull() )
63   {
64     if ( Shape.ShapeType() == TopAbs_FACE )
65     {
66       aResFace = TopoDS::Face( Shape );
67     }
68     else if ( Shape.ShapeType() == TopAbs_WIRE )
69     {
70       BRepBuilderAPI_MakeFace aMakeFace( TopoDS::Wire( Shape ), Standard_True );
71       aMakeFace.Build();
72       if( aMakeFace.IsDone() )
73         aResFace = aMakeFace.Face();
74     }
75   }
76
77   return aResFace;
78 }
79
80 Standard_Boolean buildLimFace(const TopoDS_Wire& theBndWire, TopoDS_Face& outFace) 
81 {
82   GProp_GProps G;
83   BRepGProp::LinearProperties(theBndWire,G);
84   const gp_Pnt& aCPnt = G.CentreOfMass();
85   gp_Pln aPln;
86   BRepBuilderAPI_FindPlane fndPlane (theBndWire, Precision::Confusion());  
87   if(fndPlane.Found())
88     aPln = fndPlane.Plane()->Pln();
89   else
90     aPln = gp_Pln(aCPnt, gp::OZ().Direction());
91   BRepBuilderAPI_MakeFace  aMkFace(aPln, theBndWire);
92   if(aMkFace.IsDone()) {
93     outFace = aMkFace.Face();      
94     if(!outFace.IsNull()) {
95 #ifdef DEB_SPLIT_TO_ZONES
96 //      BRepTools::Write(limFace,"FL.brep");
97 #endif
98       return Standard_True;
99     }
100   }
101   return Standard_False;
102 }
103 //======================================================================================
104
105 void HYDROData_SplitToZonesTool::SetFileNames(const QString& theNameBefore, const QString& theNameAfter)
106 {
107 #ifdef DEB_SPLIT_TO_ZONES_CHECK_PARTITION
108   if(!theNameBefore.isNull() && !theNameBefore.isEmpty())
109   {
110     TCollection_AsciiString aName (theNameBefore.toStdString().data());
111     fileNameBefore = aName;
112   }
113   if(!theNameAfter.isNull() && !theNameAfter.isEmpty())
114   {
115     TCollection_AsciiString aName (theNameAfter.toStdString().data());
116     HYDROData_Transform::SetFileName (aName);
117   }
118 #endif
119 }
120 //======================================================================================
121 Standard_Integer HYDROData_SplitToZonesTool::SplitFaces(const TopoDS_Compound& theComp, 
122                                                         HYDROData_Transform& theTool)
123 {
124   theTool.Clear();
125   theTool.SetArgument(theComp);
126   theTool.Detect();
127   const Standard_Boolean bToTransform = theTool.ToTransform();  
128   theTool.SetToTransform(bToTransform);  
129   theTool.Perform();
130   Standard_Integer anErr = theTool.ErrorStatus();
131   return anErr;
132 }
133
134 //======================================================================================
135 HYDROData_SplitToZonesTool::SplitDataList
136   HYDROData_SplitToZonesTool::Split( const HYDROData_SequenceOfObjects&  theObjectList,
137                                      const HYDROData_SequenceOfObjects&  theGroupsList,
138                                      const Handle(HYDROData_PolylineXY)& thePolyline,
139                                      const HYDROData_SequenceOfObjects& InterPolys)
140 {
141 #ifndef NDEBUG
142   DEBTRACE("Split");
143 #endif
144   SplitDataList anOutputSplitDataList;
145   NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher> OutNE;
146   if(theObjectList.IsEmpty())
147     return anOutputSplitDataList;
148   // Preparation. 
149   // Collect the object shapes to split. InputDataList will contain elements which will hold shape & name_of_shape.
150   SplitDataList anInputSplitDataList;
151 #ifdef DEB_SPLIT_TO_ZONES
152   TCollection_AsciiString aNam("Faces_");
153 #endif
154   for( int anIndex = 1, aLength = theObjectList.Length(); anIndex <= aLength; anIndex++ )
155   {
156     Handle(HYDROData_Entity) anObj = theObjectList.Value( anIndex );
157     TopoDS_Shape aShape;
158
159     Handle(HYDROData_Object) aGeomObj = Handle(HYDROData_Object)::DownCast( anObj );
160     if( !aGeomObj.IsNull() ) {
161       aShape = aGeomObj->GetTopShape();
162     }
163
164     if ( aShape.IsNull() )
165       continue;  
166 #ifdef DEB_SPLIT_TO_ZONES
167    TCollection_AsciiString aName = aNam + anIndex + "_a.brep";
168    BRepTools::Write(aShape, aName.ToCString());
169 #endif
170     if ( aShape.ShapeType() == TopAbs_COMPOUND ) {
171       // Create split data for each face contained in the compound
172       TopExp_Explorer anExp( aShape, TopAbs_FACE );
173       for ( ; anExp.More(); anExp.Next() ) {
174         const TopoDS_Face& aFace = TopoDS::Face( anExp.Current() );
175         if ( !aFace.IsNull() ) {
176           SplitData aSplitData( SplitData::Data_Zone, aFace, anObj->GetName() );
177           anInputSplitDataList.append( aSplitData );
178         }
179       }
180     } else {
181       SplitData aSplitData( SplitData::Data_Zone, aShape, anObj->GetName() );
182       anInputSplitDataList.append( aSplitData );
183     }
184   }
185   //
186   SplitDataList anInputGroupList;
187   for( int anIndex = 1, aLength = theGroupsList.Length(); anIndex <=aLength; anIndex++ )
188   {
189     Handle(HYDROData_ShapesGroup) aGeomGroup = 
190       Handle(HYDROData_ShapesGroup)::DownCast( theGroupsList.Value( anIndex ) );
191     if( aGeomGroup.IsNull() )
192       continue;
193       
194     TopTools_SequenceOfShape aGroupShapes;
195     aGeomGroup->GetShapes( aGroupShapes );
196     for( int i = 1, aNbShapes = aGroupShapes.Length(); i <= aNbShapes; i++ ) {
197       const TopoDS_Shape& aGroupShape = aGroupShapes.Value( i );
198       if ( aGroupShape.IsNull() )
199         continue;  
200
201       if ( aGroupShape.ShapeType() == TopAbs_COMPOUND ) {    
202         TopExp_Explorer anExp( aGroupShape, TopAbs_EDGE );
203         for ( ; anExp.More(); anExp.Next() ) {
204           const TopoDS_Edge& anEdge = TopoDS::Edge( anExp.Current() );
205           if ( !anEdge.IsNull() ) {
206             SplitData aSplitData( SplitData::Data_Edge, anEdge, aGeomGroup->GetName() );
207             anInputGroupList.append( aSplitData );
208           }
209         }
210       } else {
211         SplitData aSplitData( SplitData::Data_Edge, aGroupShape, aGeomGroup->GetName() );
212         anInputGroupList.append( aSplitData );
213 #ifdef DEB_SPLIT_TO_ZONES
214         QString aStr = aSplitData.ObjectNames.join(" "); 
215         DEBTRACE("Group# = " <<anIndex <<" Nmb in grp = " << i<< " Names = "<<aStr.toStdString() << " size = " <<aSplitData.ObjectNames.size());
216 #endif
217       }
218     }
219   }
220   // If only one shape is given we don't split it 
221   // algorithm just returns the unpacked input data
222   bool limplus1Object(false);
223   if(theObjectList.Size() == 1 ) 
224   {
225     if(thePolyline.IsNull()) 
226     {
227       //anOutputSplitDataList.append(anInputSplitDataList); 
228       SplitData SD = anInputSplitDataList.at(0);
229       TopTools_ListOfShape newshs;
230       CutFaceByEdges(SD.Face(), newshs, InterPolys, &OutNE);
231       for (TopTools_ListIteratorOfListOfShape it(newshs); it.More(); it.Next())
232       {
233         SplitData NSD = SD;
234         NSD.Shape = it.Value();
235         anOutputSplitDataList.append(NSD);
236       }
237
238       NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher>::Iterator spit(OutNE);
239       for (;spit.More();spit.Next())
240       {
241         const TopoDS_Edge& E = TopoDS::Edge(spit.Key());
242         if (E.IsNull())
243           continue;
244         SplitData SDI(SplitData::Data_IntEdge, E, spit.Value()->GetName());   
245         anOutputSplitDataList.append(SDI);
246       }
247
248       if(!theGroupsList.IsEmpty() ) 
249         anOutputSplitDataList.append(anInputGroupList);
250       return anOutputSplitDataList;
251     }
252     else
253       limplus1Object = true;// size =1 && hasLimits
254   }
255   HYDROData_DataMapOfShapeListOfString aDM3;
256   if(!anInputGroupList.isEmpty()) {// Old edge ==> List_Of_Names
257     QStringList aListOfNames;
258     for (int i=0;i < anInputGroupList.size() ;i++) {
259       const TopoDS_Shape& aSh = anInputGroupList.at(i).Shape;
260       aDM3.Add(aSh, anInputGroupList.at(i).ObjectNames);
261     }
262   }
263
264   // Step 1. Prepare Partition structures. 
265   TopoDS_Shape aResult;
266   BOPCol_ListOfShape aLS;  
267   QStringList aListOfNames;
268   TopoDS_Compound aCmp;
269   BRep_Builder aBB;
270   aBB.MakeCompound(aCmp);
271   for (int i=0;i < anInputSplitDataList.size() ;i++) {
272     const TopoDS_Shape& aSh = anInputSplitDataList.at(i).Shape;
273     aDM3.Add(aSh, anInputSplitDataList.at(i).ObjectNames);
274     aLS.Append(aSh);
275     aBB.Add(aCmp,aSh);
276 #ifdef DEB_SPLIT_TO_ZONES
277     TCollection_AsciiString aName = aNam + i + "_b.brep";
278     BRepTools::Write(aSh, aName.ToCString());
279 #endif
280   }
281 #ifdef DEB_SPLIT_TO_ZONES_CHECK_PARTITION
282   TCollection_AsciiString aNameBefore = fileNameBefore + "_c.brep";
283   BRepTools::Write(aCmp, aNameBefore.ToCString());
284 #endif
285
286   HYDROData_DataMapOfShapeListOfShape aDM1;
287   if(anInputSplitDataList.size() > 1) {
288     HYDROData_Transform splitTool; 
289     const Standard_Integer anErr = SplitFaces(aCmp, splitTool);    
290     if(anErr)
291       return anOutputSplitDataList;
292     aResult = splitTool.Shape();
293     if (aResult.IsNull()) 
294       return anOutputSplitDataList;
295     BRepCheck_Analyzer aCheck (aResult);
296     if(!aCheck.IsValid()) {
297   #ifdef DEB_SPLIT_TO_ZONES
298       DEBTRACE("result is not valid");
299       BRepTools::Write(aResult, "SplitFacesNV.brep");  
300   #endif
301       return anOutputSplitDataList;
302     }
303   #ifdef DEB_SPLIT_TO_ZONES
304     BRepTools::Write(aResult, "SplitFacesV.brep");
305   #endif
306     
307     // Step 3. Collect history  
308     //HYDROData_DataMapOfShapeListOfShape aDM1;
309     BOPCol_ListIteratorOfListOfShape anIt(aLS); 
310   #ifdef DEB_SPLIT_TO_ZONES
311     TCollection_AsciiString aNamM ("EdgM_");
312     TCollection_AsciiString aNamG ("EdgG_");
313   #endif
314     for (int i =1;anIt.More();anIt.Next(),i++) {
315       Standard_Boolean foundF(Standard_False);
316       const TopTools_ListOfShape& aListOfNew = splitTool.Modified(anIt.Value());
317       if(!aListOfNew.IsEmpty())
318         foundF = Standard_True;
319
320       TopTools_ListOfShape aList;
321
322       TopTools_ListIteratorOfListOfShape it(aListOfNew);
323       for(;it.More();it.Next())       
324         aList.Append(it.Value());
325           /* *********************************************************************
326       // Bug in History: partition should give only modified entities! => temporary solution is used
327       //const TopTools_ListOfShape& aListOfGen = splitTool.Generated(anIt.Value());
328       //if(!aListOfGen.IsEmpty())
329         //foundF = Standard_True;
330       //it.Initialize(aListOfGen);    
331       //for(;it.More();it.Next())     
332        // aList.Append(it.Value());  
333            ********************************************************************* */
334       if(!foundF) // face is not modified
335         aList.Append (anIt.Value());
336       aDM1.Add(anIt.Value(), aList);
337   #ifdef DEB_SPLIT_TO_ZONES
338       TCollection_AsciiString aName;
339   #endif
340       if(!anInputGroupList.isEmpty() ) { // 1
341         TopExp_Explorer exp (anIt.Value(), TopAbs_EDGE);
342         for (int j =1;exp.More();exp.Next(),j++) {
343           aList.Clear();
344           Standard_Boolean foundE(Standard_False);
345           const TopTools_ListOfShape& aListM = splitTool.Modified(exp.Current()); 
346 #ifdef NDEBUG
347           DEBTRACE("NB_EDGE_M = " << aListM.Extent());
348 #endif
349           if(aListM.Extent()) foundE = Standard_True;
350           it.Initialize(aListM);    
351           for(int k=1;it.More();it.Next(),k++) {    
352             aList.Append(it.Value());
353   #ifdef DEB_SPLIT_TO_ZONES
354             aName = aNamM + i + j +k +"_d.brep";
355             BRepTools::Write(it.Value(),aName.ToCString());
356   #endif
357           }
358           /* *********************************************************************
359                   //const TopTools_ListOfShape& aListG = splitTool.Generated(exp.Current());
360           //if(aListG.Extent()) foundE = Standard_True;
361           //it.Initialize(aListG);    
362           //for(int k=1;it.More();it.Next(),k++)
363             //aList.Append(it.Value());
364           //cout << "NB_EDGE = " << aList.Extent() <<endl;
365                   ************************************************************************** */
366           if(!foundE) {
367             aList.Append (exp.Current());
368   #ifdef DEB_SPLIT_TO_ZONES
369             aName = aNamG + i + j +"_e.brep";
370             BRepTools::Write(exp.Current(),aName.ToCString());
371             DEBTRACE(aName.ToCString()<< " = " << exp.Current().TShape());
372   #endif
373           }
374           aDM1.Add(exp.Current(), aList);
375         }
376       }
377     }
378   } else {
379       aResult = anInputSplitDataList.at(0).Shape; // get single input shape
380   }
381
382   // aDM2: NewShape ==> ListOfOldShapes
383   HYDROData_DataMapOfShapeListOfShape aDM2;
384   // make limiting face
385   HYDROData_DataMapOfShapeListOfShape aDM4;
386   Standard_Boolean hasLimits(Standard_False);
387   QString aBndName;
388   HYDROData_MapOfShape aBndView;
389   if (! thePolyline.IsNull()) {
390     Handle(TopTools_HSequenceOfShape) aConnectedWires = new TopTools_HSequenceOfShape;
391     int nbWires = thePolyline->GetNbConnectedWires(aConnectedWires);
392     const TopoDS_Wire aBndWire = TopoDS::Wire(aConnectedWires->Value(1));
393     if(!aBndWire.IsNull()) {
394       TopoDS_Face limFace;       
395       if(buildLimFace(aBndWire, limFace)) {
396         TopoDS_Shape aComResult;
397         BRepAlgoAPI_Common mkCom(aResult, limFace);
398         if(mkCom.IsDone()) {
399           aComResult = mkCom.Shape();
400           BRepCheck_Analyzer aCheck (aComResult);
401           if(aCheck.IsValid()) {
402 #ifdef DEB_SPLIT_TO_ZONES
403             BRepTools::Write(aComResult,"CommonV.brep");
404             BRepTools::Write(limFace,"limFace.brep");
405 #endif    
406             aBndName = thePolyline->GetName();
407             hasLimits = Standard_True; // DM2 should be filled here
408             TopExp_Explorer exp (limFace, TopAbs_EDGE);
409             for (int i =1;exp.More();exp.Next(),i++) {
410               const TopoDS_Shape& anEdge = exp.Current();
411               if(anEdge.IsNull()) continue;
412               aBndView.Add(anEdge);
413               QStringList aListOfNames;
414               aListOfNames.append(aBndName);
415               aDM3.Add(anEdge, aListOfNames);
416               TopTools_ListOfShape aList;
417               aList.Append(anEdge);
418               aDM1.Add(anEdge,aList);
419             }
420             HYDROData_MapOfShape aView;
421             exp.Init (aResult, TopAbs_FACE);
422             for (int i =1;exp.More();exp.Next(),i++) {
423               const TopoDS_Shape& aFace = exp.Current();
424               if(!aFace.IsNull()) {
425                 const TopTools_ListOfShape& aListOfNew = mkCom.Modified(aFace);
426 #ifdef NDEBUG
427                 DEBTRACE("Modified: " << aListOfNew.Extent());
428 #endif
429                 if(!aListOfNew.IsEmpty()) {
430                   aDM4.Add(aFace, aListOfNew);
431 #ifdef DEB_SPLIT_TO_ZONES
432                   TCollection_AsciiString aName = aNam + i + "_f.brep";
433                   BRepTools::Write(aListOfNew.Last(), aName.ToCString());
434 #endif
435                 }
436                 else {
437                     if(!mkCom.IsDeleted(aFace)) {
438                       const TopTools_ListOfShape& aListOfGen = mkCom.Generated(aFace);    
439                       if(!aListOfGen.IsEmpty()) {
440                         /* aDM4.Bind(aFace, aListOfGen); ???   */
441 #ifdef DEB_SPLIT_TO_ZONES
442                         TCollection_AsciiString aName = aNam + i + "_g.brep";
443                         BRepTools::Write(aListOfGen.Last(), aName.ToCString());
444 #endif
445                       }
446                        else {
447                         TopTools_ListOfShape aList; 
448                         aList.Append(aFace);
449                         aDM4.Add(aFace, aList); //the same face - not modified
450                        }
451                     }
452              }
453              TopExp_Explorer exp2 (aFace, TopAbs_EDGE);
454              for (int j =1;exp2.More();exp2.Next(),j++) {
455                const TopoDS_Shape& anEdge = exp2.Current();
456                if(!anEdge.IsNull()) {
457                  if(aView.Contains(anEdge)) continue;
458                  aView.Add(anEdge);
459                  const TopTools_ListOfShape& aListOfNewEd = mkCom.Modified(anEdge);                 
460                  if(!aListOfNewEd.IsEmpty())
461                    aDM4.Add(anEdge, aListOfNewEd);
462                  else {
463                    if(!mkCom.IsDeleted(anEdge)) {
464                      const TopTools_ListOfShape& aListOfGenEd = mkCom.Generated(anEdge);
465                      if(!aListOfGenEd.IsEmpty()) {
466                        /* aDM4.Bind(anEdge, aListOfGenEd); ???*/
467                      } else {
468                        TopTools_ListOfShape aList; 
469                        aList.Append(anEdge);
470                        aDM4.Add(anEdge, aList);//the same edge - not modified
471                      }
472                    }
473                  }
474                }
475              }
476             }
477             } //end DM4 filling (phase 1)
478             //cout << "DM4 Ext = " <<aDM4.Extent() <<endl;
479          // phase 2 (from tool)
480 #ifdef DEB_SPLIT_TO_ZONES
481          TCollection_AsciiString aNam("BndEd_");
482 #endif
483          TopExp_Explorer expt (limFace, TopAbs_EDGE);
484          for(int i =1;expt.More();expt.Next(),i++) {
485            const TopoDS_Shape& anEdge = expt.Current();
486            if(!anEdge.IsNull()) {
487              const TopTools_ListOfShape& aListOfNewEd = mkCom.Modified(anEdge);    
488 #ifdef DEB_SPLIT_TO_ZONES
489              TopTools_ListIteratorOfListOfShape itl(aListOfNewEd);
490              for(int j=1;itl.More();itl.Next(),j++) {
491                TCollection_AsciiString aName = aNam + i + "_" + j + "_j.brep";
492                BRepTools::Write(itl.Value(), aName.ToCString());
493                DEBTRACE(aName.ToCString()<<" = "<< itl.Value().TShape());
494              }
495 #endif
496              if(!aListOfNewEd.IsEmpty())
497                aDM4.Add(anEdge, aListOfNewEd);
498              else {
499                if(!mkCom.IsDeleted(anEdge)) {
500                  const TopTools_ListOfShape& aListOfGenEd = mkCom.Generated(anEdge);
501                  if(!aListOfGenEd.IsEmpty()) {
502                    /* aDM4.Bind(anEdge, aListOfGenEd); ??? */
503                  } else {
504                    TopTools_ListOfShape aList; 
505                    aList.Append(anEdge);
506                    aDM4.Add(anEdge, aList);//the same edge - not modified
507                  }
508                }
509              }
510            }
511          }
512          //cout << "DM4 Ext = " <<aDM4.Extent() <<endl;
513          if(limplus1Object) {
514            // fill DM1 (old - new) and DM2 (new - old)
515            HYDROData_DataMapIteratorOfDataMapOfShapeListOfShape mIt(aDM4);
516            for(;mIt.More();mIt.Next()) {
517              const TopoDS_Shape& aKey = mIt.Key();//old
518              TopTools_ListOfShape aList;
519              aList.Append(aKey);
520              const TopTools_ListOfShape& aListOfNew = mIt.Value();
521              aDM1.Add(aKey, aListOfNew);
522              TopTools_ListIteratorOfListOfShape it(aListOfNew);
523              for(;it.More();it.Next()) {
524                if(!aDM2.Contains(it.Value()))
525                  aDM2.Add(it.Value(), aList);
526                else {
527                  TopTools_ListOfShape& aList = aDM2.ChangeFromKey(it.Value());
528                  aList.Prepend(aKey);
529                }
530              }
531            }
532          } else {
533            HYDROData_DataMapIteratorOfDataMapOfShapeListOfShape aMIt(aDM1); 
534            //DM4 contains Old - New after common op. DM1: old - new after Split op.
535            for(;aMIt.More();aMIt.Next()) {
536              const TopoDS_Shape& aKey = aMIt.Key();
537              TopTools_ListOfShape aList;
538              aList.Append(aKey);
539              const TopTools_ListOfShape& aListOfNew = aMIt.Value();
540              TopTools_ListIteratorOfListOfShape it(aListOfNew);
541              for(;it.More();it.Next()) {// iterate new: b1, b2, b3...
542                if(!aDM4.Contains(it.Value())) // bi - is deleted
543                  continue; // go to the next bi
544                else {
545                  const TopTools_ListOfShape& aListOfNew4 = aDM4.FindFromKey(it.Value());
546                   TopTools_ListIteratorOfListOfShape it4(aListOfNew4); // {c1, c2, c3,...}
547                   for(;it4.More();it4.Next()) {
548                     if(!aDM2.Contains(it4.Value()))
549                       aDM2.Add(it4.Value(), aList);
550                     else {
551                       TopTools_ListOfShape& aList = aDM2.ChangeFromKey(it4.Value());
552                       aList.Prepend(aKey);
553                     }
554                   }
555                }
556              }
557            }
558          }
559          } else {
560              hasLimits = Standard_False;
561 #ifdef DEB_SPLIT_TO_ZONES
562              BRepTools::Write(aComResult,"CommonNV.brep");
563 #endif    
564           }
565        }
566       }
567     }
568   }// end limits processing
569   if(!hasLimits) {
570     HYDROData_DataMapIteratorOfDataMapOfShapeListOfShape aMIt(aDM1);
571     for(;aMIt.More();aMIt.Next()) {
572       const TopoDS_Shape& aKey = aMIt.Key();
573       TopTools_ListOfShape aList;
574       aList.Append(aKey);
575       const TopTools_ListOfShape& aListOfNew = aMIt.Value();
576       TopTools_ListIteratorOfListOfShape it(aListOfNew);
577       for(;it.More();it.Next()) {
578         if(!aDM2.Contains(it.Value()))
579           aDM2.Add(it.Value(), aList);
580         else {
581           TopTools_ListOfShape& aList = aDM2.ChangeFromKey(it.Value());
582           aList.Prepend(aKey);
583         }
584       }
585     }
586   }
587
588   AddInternalEdges(aDM2, InterPolys, &OutNE);
589   NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher>::Iterator spit(OutNE);
590   for (;spit.More();spit.Next())
591   {
592     const TopoDS_Edge& E = TopoDS::Edge(spit.Key());
593     if (E.IsNull())
594       continue;
595     SplitData SDI(SplitData::Data_IntEdge, E, spit.Value()->GetName());   
596     anOutputSplitDataList.append(SDI);
597   }
598
599   // Step 4. Fill output structure.
600 #ifdef DEB_SPLIT_TO_ZONES
601   TCollection_AsciiString aNam4 ("SC_");
602 #endif  
603   HYDROData_DataMapIteratorOfDataMapOfShapeListOfShape aMIt(aDM2);
604   for(int i =1;aMIt.More();aMIt.Next(),i++) {
605     SplitData aDestSplitData;
606     const TopoDS_Shape& aKey = aMIt.Key(); //new
607     aDestSplitData.Shape = aKey;
608     if(aKey.ShapeType() == TopAbs_FACE)
609       aDestSplitData.Type = SplitData::Data_Zone;
610     else {
611       aDestSplitData.Type = SplitData::Data_Edge;
612 #ifdef DEB_SPLIT_TO_ZONES
613       TCollection_AsciiString aName = aNam4 + i + "_k.brep";
614       BRepTools::Write(aKey,aName.ToCString());
615 #endif    
616     }
617
618     QStringList aListOfNames; // names processing
619     const TopTools_ListOfShape& aListOfOld = aMIt.Value();
620     TopTools_ListIteratorOfListOfShape it(aListOfOld);
621     for(int j =1;it.More();it.Next(),j++) {    
622       const TopoDS_Shape& aSh = it.Value(); //old
623       if(aDM3.Contains(aSh)) {
624         const QStringList& ObjectNames = aDM3.FindFromKey(aSh);    
625         aListOfNames.append(ObjectNames);
626 #ifdef DEB_SPLIT_TO_ZONES
627         TCollection_AsciiString aName = aNam4 + i +"_" + j + "_l.brep";
628         BRepTools::Write(aSh ,aName.ToCString());        
629 #endif    
630       }    else {
631 #ifdef DEB_SPLIT_TO_ZONES
632         TCollection_AsciiString aName = aNam4 +"__" + i +"_" + j + "_m.brep";
633         BRepTools::Write(aSh ,aName.ToCString());        
634         DEBTRACE(aName.ToCString()<<" = "<< aSh.TShape());
635 #endif
636           if(aBndView.Contains(aSh) && hasLimits) {            
637             aListOfNames.append(aBndName);
638 #ifdef DEB_SPLIT_TO_ZONES
639             DEBTRACE(" BndName = "<<aBndName.toStdString());
640 #endif
641           }
642       }
643     }
644
645     aDestSplitData.ObjectNames = aListOfNames;  
646     anOutputSplitDataList.append(aDestSplitData);    
647 #ifdef DEB_SPLIT_TO_ZONES
648     QString aStr = aDestSplitData.ObjectNames.join(" "); 
649     DEBTRACE("New# = " << i<< " Names = "<<aStr.toStdString() << " size = " <<aDestSplitData.ObjectNames.size());
650 #endif
651   }
652
653   return anOutputSplitDataList;
654 }
655
656 HYDROData_SplitToZonesTool::SplitDataList
657   HYDROData_SplitToZonesTool::Split( const HYDROData_SequenceOfObjects& theObjectList )
658 {
659   HYDROData_SequenceOfObjects aGeomGroups;
660   Handle(HYDROData_PolylineXY) aPolyline;
661   HYDROData_SequenceOfObjects InterPolys;
662
663   return Split( theObjectList, aGeomGroups, aPolyline, InterPolys );
664 }
665
666 void HYDROData_SplitToZonesTool::AddInternalEdges(HYDROData_DataMapOfShapeListOfShape& DM,
667    const HYDROData_SequenceOfObjects& thePolylines,
668    NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher>* OutNE)
669 {
670
671   HYDROData_SequenceOfObjects::Iterator it(thePolylines);
672   TopTools_ListOfShape Wires;
673   NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher> W2P;
674   for (;it.More();it.Next())
675   {
676     Handle(HYDROData_PolylineXY) P = Handle(HYDROData_PolylineXY)::DownCast(it.Value());
677     const TopoDS_Shape& CW = P->GetShape();
678     Wires.Append(CW);
679     W2P.Bind(CW, P);
680   }
681
682   HYDROData_DataMapOfShapeListOfShape newDM;
683   TopTools_IndexedDataMapOfShapeShape OutNE1;
684   for (int i = 1; i <= DM.Extent();i++)
685   {
686     const TopoDS_Shape& K = DM.FindKey(i);
687     const TopTools_ListOfShape& V = DM.FindFromIndex(i);
688     TopTools_ListOfShape out;
689     if (K.ShapeType() == TopAbs_FACE)
690     {
691       CutByEdges(K, Wires, out, &OutNE1);
692       TopTools_ListIteratorOfListOfShape it(out);
693       for (;it.More(); it.Next())
694       {
695         const TopoDS_Shape& NF = it.Value();
696         if (!NF.IsNull())
697           newDM.Add(NF, V);
698       }
699     }
700     else
701       newDM.Add(K, V); // ignore edges, wires...
702   }
703
704   for (int i = 1; i <= OutNE1.Extent(); i++)
705     OutNE->Bind(OutNE1.FindKey(i), W2P(OutNE1.FindFromIndex(i)));
706
707   DM = newDM;
708 }
709
710 void HYDROData_SplitToZonesTool::CutFaceByEdges(const TopoDS_Face& in, 
711                                                 TopTools_ListOfShape& out, 
712                                                 const HYDROData_SequenceOfObjects& thePolylines,
713                                                 NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher>* OutNE)
714 {
715
716   HYDROData_SequenceOfObjects::Iterator it(thePolylines);
717   TopTools_ListOfShape Wires;
718   NCollection_DataMap<TopoDS_Shape, Handle(HYDROData_PolylineXY), TopTools_ShapeMapHasher> W2P;
719   for (;it.More();it.Next())
720   {
721     Handle(HYDROData_PolylineXY) P = Handle(HYDROData_PolylineXY)::DownCast(it.Value());
722     const TopoDS_Shape& CW = P->GetShape();
723     Wires.Append(CW);
724     W2P.Bind(CW, P);
725   }
726
727   TopTools_IndexedDataMapOfShapeShape OutNE1;
728   CutByEdges(in, Wires, out, &OutNE1);
729
730   for (int i = 1; i <= OutNE1.Extent(); i++)
731     OutNE->Bind(OutNE1.FindKey(i), W2P(OutNE1.FindFromIndex(i)));
732
733 }
734
735 int HYDROData_SplitToZonesTool::CutByEdges(const TopoDS_Shape& InSh, const TopTools_ListOfShape& InW,
736   TopTools_ListOfShape& outShs, TopTools_IndexedDataMapOfShapeShape* OutNE)
737 {
738   int anError;
739   if (InSh.IsNull())
740     return -1;
741   if (InW.IsEmpty())
742   {
743     outShs.Clear();
744     outShs.Append(InSh);
745     return 0;
746   }
747   TopTools_ListIteratorOfListOfShape anIt;
748   BOPAlgo_Builder anAlgo;
749   anAlgo.AddArgument(InSh);
750
751   anIt.Initialize( InW );
752   for( ; anIt.More(); anIt.Next() )
753     anAlgo.AddArgument( anIt.Value() );
754
755   anAlgo.Perform(); 
756   anError = anAlgo.ErrorStatus();
757   if (anError)
758     return anError;
759
760   outShs = anAlgo.Modified( InSh );
761   if (outShs.IsEmpty())
762     outShs.Append(InSh);
763
764   if (OutNE)
765   {
766     TopTools_IndexedDataMapOfShapeShape NonFOutNE;
767     anIt.Initialize( InW );
768     for( ; anIt.More(); anIt.Next() )
769     {
770       const TopoDS_Shape& OSH = anIt.Value(); 
771       TopExp_Explorer exp(OSH, TopAbs_EDGE);
772       for (;exp.More();exp.Next())
773       {
774         const TopoDS_Edge& OE = TopoDS::Edge(exp.Current());
775         const TopTools_ListOfShape& ls = anAlgo.Modified(OE);
776         TopTools_ListIteratorOfListOfShape itls(ls);
777         for (;itls.More();itls.Next())
778           NonFOutNE.Add(itls.Value(), OSH);
779       }
780     }
781
782     //filter edges; if face contain an edge => keep it
783     TopTools_IndexedMapOfShape AllEdges; //edges from output shape
784     for (anIt.Initialize(outShs); anIt.More();anIt.Next())
785       TopExp::MapShapes(anIt.Value(), TopAbs_EDGE, AllEdges);
786
787     for (int i = 1; i <= NonFOutNE.Extent(); i++)
788     {
789       const TopoDS_Shape& CE = NonFOutNE.FindKey(i);
790       const TopoDS_Shape& V = NonFOutNE.FindFromIndex(i);
791       if (AllEdges.Contains(CE))
792         OutNE->Add(CE, V);
793     }
794
795   }
796
797   return 0;
798 }