Salome HOME
Bug 0020233: Infinite loop in boolean operation with a sphere with r=0
[modules/geom.git] / src / GEOMImpl / GEOMImpl_PipeDriver.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21
22 #include <Standard_Stream.hxx>
23
24 #include <GEOMImpl_PipeDriver.hxx>
25
26 #include <GEOMImpl_IShapesOperations.hxx>
27 #include <GEOMImpl_IPipeDiffSect.hxx>
28 #include <GEOMImpl_IPipeShellSect.hxx>
29 #include <GEOMImpl_IPipeBiNormal.hxx>
30 #include <GEOMImpl_IPipe.hxx>
31 #include <GEOMImpl_GlueDriver.hxx>
32 #include <GEOMImpl_Types.hxx>
33 #include <GEOM_Function.hxx>
34
35 //#include <GEOMAlgo_GlueAnalyser.hxx>
36
37 #include <ShapeAnalysis_FreeBounds.hxx>
38 #include <ShapeAnalysis_Edge.hxx>
39 #include <ShapeFix_Face.hxx>
40 #include <ShapeFix_Shell.hxx>
41 #include <ShapeFix_Shape.hxx>
42 #include <ShapeFix_ShapeTolerance.hxx>
43
44 #include <BRep_Tool.hxx>
45 #include <BRep_Builder.hxx>
46 #include <BRepBuilderAPI_MakeWire.hxx>
47 #include <BRepBuilderAPI_Sewing.hxx>
48 #include <BRepCheck_Analyzer.hxx>
49 #include <BRepOffsetAPI_MakePipe.hxx>
50 #include <BRepOffsetAPI_MakePipeShell.hxx>
51 #include <GProp_GProps.hxx>
52 #include <BRepGProp.hxx>
53 #include <BRepBuilderAPI_MakeFace.hxx>
54
55 #include <TopAbs.hxx>
56 #include <TopExp.hxx>
57 #include <TopExp_Explorer.hxx>
58 #include <TopoDS.hxx>
59 #include <TopoDS_Wire.hxx>
60 #include <TopoDS_Edge.hxx>
61 #include <TopoDS_Shape.hxx>
62 #include <TopoDS_Solid.hxx>
63 #include <TopoDS_Shell.hxx>
64 #include <TopoDS_Face.hxx>
65 #include <TopoDS_Compound.hxx>
66 #include <TopTools_SequenceOfShape.hxx>
67 #include <TopTools_IndexedDataMapOfShapeShape.hxx>
68 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
69 #include <TopTools_ListIteratorOfListOfShape.hxx>
70
71 #include <GeomAPI_ProjectPointOnCurve.hxx>
72 #include <GeomAPI_Interpolate.hxx>
73 #include <Geom_TrimmedCurve.hxx>
74 #include <Geom_Plane.hxx>
75 #include <Geom_RectangularTrimmedSurface.hxx>
76 #include <Geom_BezierSurface.hxx>
77 #include <Geom_Line.hxx>
78 #include <Geom_Conic.hxx>
79 #include <Geom_BSplineCurve.hxx>
80 #include <Geom_BSplineSurface.hxx>
81 #include <GeomFill_BSplineCurves.hxx>
82 #include <GeomConvert_ApproxCurve.hxx>
83 #include <GeomConvert.hxx>
84
85 #include <TColgp_SequenceOfPnt.hxx>
86 #include <TColgp_HArray1OfPnt.hxx>
87 #include <TColgp_Array2OfPnt.hxx>
88 #include <TColStd_HSequenceOfTransient.hxx>
89
90 #include <Precision.hxx>
91 #include <Standard_NullObject.hxx>
92 #include <Standard_TypeMismatch.hxx>
93 #include <Standard_ConstructionError.hxx>
94
95 #include "utilities.h"
96
97
98 //=======================================================================
99 //function : GetID
100 //purpose  :
101 //=======================================================================
102 const Standard_GUID& GEOMImpl_PipeDriver::GetID()
103 {
104   static Standard_GUID aPipeDriver("FF1BBB19-5D14-4df2-980B-3A668264EA16");
105   return aPipeDriver;
106 }
107
108
109 //=======================================================================
110 //function : GEOMImpl_PipeDriver
111 //purpose  :
112 //=======================================================================
113 GEOMImpl_PipeDriver::GEOMImpl_PipeDriver()
114 {
115 }
116
117
118 //=======================================================================
119 //function : FillForOtherEdges
120 //purpose  : auxilary for CreatePipeForShellSections()
121 //=======================================================================
122 static bool FillForOtherEdges(const TopoDS_Shape& F1,
123                               const TopoDS_Shape& E1,
124                               const TopoDS_Shape& V1,
125                               TopTools_IndexedDataMapOfShapeShape& FF)
126 {
127   //cout<<"FillForOtherEdges"<<endl;
128   // find other pairs for vertexes and edges
129   // creating map of vertex edges for both faces
130   TopTools_IndexedDataMapOfShapeListOfShape aMapVertEdge1;
131   TopExp::MapShapesAndAncestors(F1, TopAbs_VERTEX, TopAbs_EDGE, aMapVertEdge1);
132   if (!FF.Contains(F1))
133     MESSAGE("    FillForOtherEdges: map FF not contains key F1");
134   if (!FF.Contains(E1))
135     MESSAGE("    FillForOtherEdges: map FF not contains key E1");
136   if (!FF.Contains(V1))
137     MESSAGE("    FillForOtherEdges: map FF not contains key V1");
138   const TopoDS_Shape& F2 = FF.FindFromKey(F1);
139   const TopoDS_Shape& E2 = FF.FindFromKey(E1);
140   const TopoDS_Shape& V2 = FF.FindFromKey(V1);
141   TopTools_IndexedDataMapOfShapeListOfShape aMapVertEdge2;
142   TopExp::MapShapesAndAncestors(F2, TopAbs_VERTEX, TopAbs_EDGE, aMapVertEdge2);
143
144   TopoDS_Edge ES1 = TopoDS::Edge(E1);
145   TopoDS_Edge ES2 = TopoDS::Edge(E2);
146   TopoDS_Shape VS1 = V1;
147   TopoDS_Shape VS2 = V2;
148
149   ShapeAnalysis_Edge sae;
150   while(1) {
151     if(!aMapVertEdge1.Contains(VS1))
152       MESSAGE ("    FillForOtherEdges: map aMapVertEdge1 not contains key VS1");
153     const TopTools_ListOfShape& aList1 = aMapVertEdge1.FindFromKey(VS1);
154     //TopoDS_Shape E1next;
155     TopTools_ListIteratorOfListOfShape anIter1(aList1);
156     if(anIter1.Value().IsSame(ES1)) {
157       anIter1.Next();
158     }
159     //E1next = anIter1.Value();
160     if(!aMapVertEdge2.Contains(VS2))
161       MESSAGE ("    FillForOtherEdges: map aMapVertEdge2 not contains key VS2");
162     const TopTools_ListOfShape& aList2 = aMapVertEdge2.FindFromKey(VS2);
163     //TopoDS_Shape E2next;
164     TopTools_ListIteratorOfListOfShape anIter2(aList2);
165     if(anIter2.Value().IsSame(ES2)) {
166       anIter2.Next();
167     }
168     //E2next = anIter2.Value();
169     //ES1 = TopoDS::Edge(E1next);
170     //ES2 = TopoDS::Edge(E2next);
171     ES1 = TopoDS::Edge(anIter1.Value());
172     ES2 = TopoDS::Edge(anIter2.Value());
173     if(!FF.Contains(ES1)) {
174       FF.Add(ES1,ES2);
175     }
176     if(VS1.IsSame(sae.FirstVertex(ES1)))
177       VS1 = sae.LastVertex(ES1);
178     else
179       VS1 = sae.FirstVertex(ES1);
180     if(VS2.IsSame(sae.FirstVertex(ES2)))
181       VS2 = sae.LastVertex(ES2);
182     else
183       VS2 = sae.FirstVertex(ES2);
184     if(VS1.IsSame(V1))
185       break;
186     if(!FF.Contains(VS1)) {
187       FF.Add(VS1,VS2);
188     }
189   }
190
191   return true;
192 }
193
194
195 //=======================================================================
196 //function : FillCorrespondingEdges
197 //purpose  : auxilary for CreatePipeForShellSections()
198 //=======================================================================
199 static bool FillCorrespondingEdges(const TopoDS_Shape& FS1,
200                                    const TopoDS_Shape& FS2,
201                                    const TopoDS_Vertex& aLoc1,
202                                    const TopoDS_Vertex& aLoc2,
203                                    const TopoDS_Wire& aWirePath,
204                                    TopTools_IndexedDataMapOfShapeShape& FF)
205 {
206   //cout<<"FillCorrespondingEdges"<<endl;
207   // find corresponding edges
208   TopExp_Explorer expw1(FS1,TopAbs_WIRE);
209   TopoDS_Wire aWire1 = TopoDS::Wire(expw1.Current());
210   //exp = TopExp_Explorer(FS2,TopAbs_WIRE);
211   TopExp_Explorer expw2(FS2,TopAbs_WIRE);
212   TopoDS_Wire aWire2 = TopoDS::Wire(expw2.Current());
213   BRepOffsetAPI_MakePipeShell aBuilder(aWirePath);
214   aBuilder.Add(aWire1, aLoc1);
215   aBuilder.Add(aWire2, aLoc2);
216   if(!aBuilder.IsReady()) {
217     return false;
218   }
219   aBuilder.Build();
220   TopoDS_Shape aShape = aBuilder.Shape();
221   /*
222   TopoDS_Compound C;
223   BRep_Builder B;
224   B.MakeCompound(C);
225   B.Add(C,aShape);
226   B.Add(C,FS1);
227   B.Add(C,FS2);
228   BRepTools::Write(C,"/dn02/users_Linux/skl/work/Bugs/14857/comp.brep");
229   */
230   ShapeAnalysis_Edge sae;
231   double tol = Max( BRep_Tool::Tolerance(TopoDS::Face(FS1)),
232                     BRep_Tool::Tolerance(TopoDS::Face(FS2)) );
233   TopTools_MapOfShape Vs1,Vs2;
234   TopExp_Explorer exp;
235   exp.Init( FS1, TopAbs_EDGE );
236   TopoDS_Edge E1 = TopoDS::Edge(exp.Current());
237   TopoDS_Vertex V11 = sae.FirstVertex(E1);
238   TopoDS_Vertex V21 = sae.LastVertex(E1);
239   gp_Pnt P11 = BRep_Tool::Pnt(V11);
240   gp_Pnt P21 = BRep_Tool::Pnt(V21);
241   //cout<<"P11("<<P11.X()<<","<<P11.Y()<<","<<P11.Z()<<")"<<endl;
242   //cout<<"P21("<<P21.X()<<","<<P21.Y()<<","<<P21.Z()<<")"<<endl;
243   // find corresponding vertexes from created shape
244   TopoDS_Vertex VN11,VN21;
245   for( exp.Init( aShape, TopAbs_VERTEX ); exp.More(); exp.Next() ) {
246     TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
247     gp_Pnt P = BRep_Tool::Pnt(V);
248     if(P.Distance(P11)<tol) {
249       VN11 = V;
250     }
251     if(P.Distance(P21)<tol) {
252       VN21 = V;
253     }
254   }
255   // find edge contains VN11 and VN21 and corresponding vertexes
256   TopoDS_Vertex VN12,VN22;
257   for( exp.Init( aShape, TopAbs_FACE ); exp.More(); exp.Next() ) {
258     TopoDS_Shape F = exp.Current();
259     TopExp_Explorer expe;
260     bool IsFind = false;
261     for( expe.Init( F, TopAbs_EDGE ); expe.More(); expe.Next() ) {
262       TopoDS_Edge E = TopoDS::Edge(expe.Current());
263       TopoDS_Vertex VF = sae.FirstVertex(E);
264       TopoDS_Vertex VL = sae.LastVertex(E);
265       if( (VF.IsSame(VN11) && VL.IsSame(VN21)) || (VF.IsSame(VN21) && VL.IsSame(VN11)) ) {
266         IsFind = true;
267         break;
268       }
269     }
270     if(IsFind) {
271       for( expe.Init( F, TopAbs_EDGE ); expe.More(); expe.Next() ) {
272         TopoDS_Edge E = TopoDS::Edge(expe.Current());
273         TopoDS_Vertex VF = sae.FirstVertex(E);
274         TopoDS_Vertex VL = sae.LastVertex(E);
275         if( VF.IsSame(VN11) && !VL.IsSame(VN21) )
276           VN12 = VL;
277         if( VL.IsSame(VN11) && !VF.IsSame(VN21) )
278           VN12 = VF;
279         if( VF.IsSame(VN21) && !VL.IsSame(VN11) )
280           VN22 = VL;
281         if( VL.IsSame(VN21) && !VF.IsSame(VN11) )
282           VN22 = VF;
283       }
284       break;
285     }
286   }
287   // find vertexes from FS2 corresponded to VN12 and VN22
288   // and find edge from FS2 contains V12 and V22,
289   // this edge will be corresponded to edge E1
290   TopoDS_Vertex V12,V22;
291   gp_Pnt PN12 = BRep_Tool::Pnt(VN12);
292   gp_Pnt PN22 = BRep_Tool::Pnt(VN22);
293   //cout<<"PN12("<<PN12.X()<<","<<PN12.Y()<<","<<PN12.Z()<<")"<<endl;
294   //cout<<"PN22("<<PN22.X()<<","<<PN22.Y()<<","<<PN22.Z()<<")"<<endl;
295   TopoDS_Edge E2;
296   TopExp_Explorer expe;
297   for( expe.Init( FS2, TopAbs_EDGE ); expe.More(); expe.Next() ) {
298     TopoDS_Edge E = TopoDS::Edge(expe.Current());
299     TopoDS_Vertex VF = sae.FirstVertex(E);
300     TopoDS_Vertex VL = sae.LastVertex(E);
301     gp_Pnt PF = BRep_Tool::Pnt(VF);
302     gp_Pnt PL = BRep_Tool::Pnt(VL);
303     if( PF.Distance(PN12)<tol && PL.Distance(PN22)<tol ) {
304       V12 = VF;
305       V22 = VL;
306       E2 = E;
307       break;
308     }
309     if( PF.Distance(PN22)<tol && PL.Distance(PN12)<tol ) {
310       V12 = VL;
311       V22 = VF;
312       E2 = E;
313       break;
314     }
315   }
316   FF.Add(V11,V12);
317   FF.Add(V21,V22);
318   FF.Add(E1,E2);
319
320   // find other pairs for vertexes and edges
321   // creating map of vertex edges for both faces
322   return FillForOtherEdges(FS1,E1,V21,FF);
323
324   //return true;
325 }
326
327
328 //=======================================================================
329 //function : FillCorrespondingEdges
330 //purpose  : auxilary for CreatePipeShellsWithoutPath()
331 //=======================================================================
332 static bool FillCorrespondingEdges(const TopoDS_Shape& FS1,
333                                    const TopoDS_Shape& FS2,
334                                    const TopoDS_Vertex& aLoc1,
335                                    const TopoDS_Vertex& aLoc2,
336                                    TopTools_IndexedDataMapOfShapeShape& FF)
337 {
338   //cout<<"FillCorrespondingEdges"<<endl;
339
340   gp_Pnt P1 = BRep_Tool::Pnt(aLoc1);
341   gp_Pnt P2 = BRep_Tool::Pnt(aLoc2);
342   gp_Vec aDir(P1,P2);
343
344   ShapeAnalysis_Edge sae;
345   double tol = Max( BRep_Tool::Tolerance(TopoDS::Face(FS1)),
346                     BRep_Tool::Tolerance(TopoDS::Face(FS2)) );
347   TopTools_MapOfShape Vs1,Vs2;
348
349   TopoDS_Vertex V11=aLoc1, V12=aLoc2, V21, V22;
350   TopoDS_Edge E1,E2;
351
352   TopExp_Explorer exp1;
353   for( exp1.Init(FS1,TopAbs_EDGE); exp1.More(); exp1.Next() ) {
354     E1 = TopoDS::Edge(exp1.Current());
355     TopoDS_Vertex V1 = sae.FirstVertex(E1);
356     TopoDS_Vertex V2 = sae.LastVertex(E1);
357     gp_Pnt Ptmp1 = BRep_Tool::Pnt(V1);
358     gp_Pnt Ptmp2 = BRep_Tool::Pnt(V2);
359     //cout<<"P11("<<P11.X()<<","<<P11.Y()<<","<<P11.Z()<<")"<<endl;
360     //cout<<"P21("<<P21.X()<<","<<P21.Y()<<","<<P21.Z()<<")"<<endl;
361     if(P1.Distance(Ptmp1)<tol) {
362       V21 = V2;
363       break;
364     }
365     if(P1.Distance(Ptmp2)<tol) {
366       V21 = V1;
367       break;
368     }
369   }
370
371   TopoDS_Edge E21,E22;
372   TopoDS_Vertex VE21,VE22;
373   int nbe=0;
374   for( exp1.Init(FS2,TopAbs_EDGE); exp1.More() && nbe<2; exp1.Next() ) {
375     TopoDS_Edge E = TopoDS::Edge(exp1.Current());
376     TopoDS_Vertex V1 = sae.FirstVertex(E);
377     TopoDS_Vertex V2 = sae.LastVertex(E);
378     gp_Pnt Ptmp1 = BRep_Tool::Pnt(V1);
379     gp_Pnt Ptmp2 = BRep_Tool::Pnt(V2);
380     if(P2.Distance(Ptmp1)<tol) {
381       if(nbe==0) {
382         E21 = E;
383         VE21 = V2;
384         nbe++;
385       }
386       else if(nbe==1) {
387         E22 = E;
388         VE22 = V2;
389         nbe++;
390       }
391     }
392     if(P2.Distance(Ptmp2)<tol) {
393       if(nbe==0) {
394         E21 = E;
395         VE21 = V1;
396         nbe++;
397       }
398       else if(nbe==1) {
399         E22 = E;
400         VE22 = V1;
401         nbe++;
402       }
403     }
404   }
405
406   gp_Pnt PV21 = BRep_Tool::Pnt(V21);
407   gp_Pnt PE21 = BRep_Tool::Pnt(VE21);
408   gp_Pnt PE22 = BRep_Tool::Pnt(VE22);
409   gp_Vec aDir1(PV21,PE21);
410   gp_Vec aDir2(PV21,PE22);
411   double ang1 = aDir.Angle(aDir1);
412   double ang2 = aDir.Angle(aDir2);
413   if(fabs(ang1)<fabs(ang2)) {
414     E2 = E21;
415     V22 = VE21;
416   }
417   else {
418     E2 = E22;
419     V22 = VE22;
420   }
421
422   FF.Add(V11,V12);
423   FF.Add(V21,V22);
424   FF.Add(E1,E2);
425
426   // find other pairs for vertexes and edges
427   return FillForOtherEdges(FS1,E1,V21,FF);
428 }
429
430
431 //=======================================================================
432 //function : FindNextPairOfFaces
433 //purpose  : auxilary for CreatePipeForShellSections()
434 //=======================================================================
435 static void FindNextPairOfFaces(const TopoDS_Shape& aCurFace,
436                                 TopTools_IndexedDataMapOfShapeListOfShape& aMapEdgeFaces1,
437                                 TopTools_IndexedDataMapOfShapeListOfShape& aMapEdgeFaces2,
438                                 TopTools_IndexedDataMapOfShapeShape& FF,
439                                 GEOMImpl_IPipe* aCI)
440 {
441   //cout<<"FindNextPairOfFaces"<<endl;
442   TopExp_Explorer anExp;
443   for ( anExp.Init( aCurFace, TopAbs_EDGE ); anExp.More(); anExp.Next() ) {
444     TopoDS_Shape E1 = anExp.Current();
445     if(!FF.Contains(E1)) {
446       if(aCI) delete aCI;
447       Standard_ConstructionError::Raise("FindNextPairOfFaces: Can not find edge in map");
448     }
449     if(!FF.Contains(E1))
450       MESSAGE ("    FindNextPairOfFaces: map FF not contains key E1");
451     const TopoDS_Shape& E2 = FF.FindFromKey(E1);
452     TopExp_Explorer anExpV;
453     anExpV.Init( E1, TopAbs_VERTEX );
454     TopoDS_Shape V1 = anExpV.Current();
455     if(!FF.Contains(V1)) {
456       if(aCI) delete aCI;
457       Standard_ConstructionError::Raise("FindNextPairOfFaces: Can not find vertex in map");
458     }
459
460     if(!aMapEdgeFaces1.Contains(E1))
461       MESSAGE ("    FindNextPairOfFaces: map aMapEdgeFaces1 not contains key E1");
462     const TopTools_ListOfShape& aList1 = aMapEdgeFaces1.FindFromKey(E1);
463     if(aList1.Extent()<2)
464       continue;
465     TopTools_ListIteratorOfListOfShape anIter(aList1);
466     if(anIter.Value().IsEqual(aCurFace)) {
467       anIter.Next();
468     }
469     TopoDS_Shape F1other = anIter.Value();
470     if(FF.Contains(F1other))
471       continue;
472
473     if(!FF.Contains(aCurFace))
474       MESSAGE ("    FindNextPairOfFaces: map FF not contains key aCurFace");
475     const TopoDS_Shape& F2 = FF.FindFromKey(aCurFace);
476     if(!aMapEdgeFaces2.Contains(E2))
477       MESSAGE ("    FindNextPairOfFaces: map aMapEdgeFaces2 not contains key E2");
478     const TopTools_ListOfShape& aList2 = aMapEdgeFaces2.FindFromKey(E2);
479     if(aList2.Extent()<2) {
480       if(aCI) delete aCI;
481       Standard_ConstructionError::Raise("FindNextPairOfFaces: Can not find corresponding face");
482     }
483     TopTools_ListIteratorOfListOfShape anIter2(aList2);
484     if(anIter2.Value().IsEqual(F2)) {
485       anIter2.Next();
486     }
487     TopoDS_Shape F2other = anIter2.Value();
488     FF.Add(F1other,F2other);
489
490     // add pairs of edges to FF
491     bool stat =  FillForOtherEdges(F1other,E1,V1,FF);
492     if( !stat ) {
493       if(aCI) delete aCI;
494       Standard_ConstructionError::Raise("FindNextPairOfFaces: Can not mapping other egdes");
495     }
496
497     FindNextPairOfFaces(F1other, aMapEdgeFaces1, aMapEdgeFaces2, FF, aCI);
498   }
499 }
500
501
502 //=======================================================================
503 //function : FindFirstPairFaces
504 //purpose  : auxilary for Execute()
505 //=======================================================================
506 static void FindFirstPairFaces(const TopoDS_Shape& S1, const TopoDS_Shape& S2,
507                                TopoDS_Vertex& V1, TopoDS_Vertex& V2,
508                                TopoDS_Shape& FS1, TopoDS_Shape& FS2)
509 {
510   //cout<<"FindFirstPairFaces"<<endl;
511
512   // check if vertexes are subshapes of sections
513   gp_Pnt P1 = BRep_Tool::Pnt(V1);
514   gp_Pnt P2 = BRep_Tool::Pnt(V2);
515   TopoDS_Vertex V1new,V2new;
516   TopExp_Explorer exp;
517   double mindist = 1.e10;
518   for( exp.Init( S1, TopAbs_VERTEX ); exp.More(); exp.Next() ) {
519     TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
520     gp_Pnt P = BRep_Tool::Pnt(V);
521     double dist = P1.Distance(P);
522     if(dist<mindist) {
523       mindist = dist;
524       V1new = V;
525     }
526   }
527   mindist = 1.e10;
528   for( exp.Init( S2, TopAbs_VERTEX ); exp.More(); exp.Next() ) {
529     TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
530     gp_Pnt P = BRep_Tool::Pnt(V);
531     double dist = P2.Distance(P);
532     if(dist<mindist) {
533       mindist = dist;
534       V2new = V;
535     }
536   }
537
538   //gp_Pnt P1new = BRep_Tool::Pnt(V1new);
539   //gp_Pnt P2new = BRep_Tool::Pnt(V2new);
540   //cout<<"  P1("<<P1.X()<<","<<P1.Y()<<","<<P1.Z()<<")"<<endl;
541   //cout<<"  P2("<<P2.X()<<","<<P2.Y()<<","<<P2.Z()<<")"<<endl;
542   //cout<<"  P1new("<<P1new.X()<<","<<P1new.Y()<<","<<P1new.Z()<<")"<<endl;
543   //cout<<"  P2new("<<P2new.X()<<","<<P2new.Y()<<","<<P2new.Z()<<")"<<endl;
544
545   // replace vertexes if it is needed
546   if(!V1.IsSame(V1new)) {
547     V1 = V1new;
548     P1 = BRep_Tool::Pnt(V1);
549     MESSAGE ("  replace V1");
550   }
551   else
552     MESSAGE ("  not replace V1");
553   if(!V2.IsSame(V2new)) {
554     V2 = V2new;
555     P2 = BRep_Tool::Pnt(V2);
556     MESSAGE ("  replace V2");
557   }
558   else
559     MESSAGE ("  not replace V2");
560
561   TopTools_IndexedDataMapOfShapeListOfShape aMapVertFaces1;
562   TopExp::MapShapesAndAncestors(S1, TopAbs_VERTEX, TopAbs_FACE, aMapVertFaces1);
563   TopTools_IndexedDataMapOfShapeListOfShape aMapVertFaces2;
564   TopExp::MapShapesAndAncestors(S2, TopAbs_VERTEX, TopAbs_FACE, aMapVertFaces2);
565
566   if(!aMapVertFaces1.Contains(V1))
567     MESSAGE ("    FindFirstPairFaces: map aMapVertFaces1 not contains key V1");
568   const TopTools_ListOfShape& aList1 = aMapVertFaces1.FindFromKey(V1);
569   TopTools_ListIteratorOfListOfShape anIter1(aList1);
570   FS1 = anIter1.Value();
571   // find middle point
572   double x1=0., y1=0., z1=0.;
573   int nbv1=0;
574   for( exp.Init( FS1, TopAbs_VERTEX ); exp.More(); exp.Next() ) {
575     TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
576     gp_Pnt P = BRep_Tool::Pnt(V);
577     x1 += P.X();
578     y1 += P.Y();
579     z1 += P.Z();
580     nbv1++;
581   }
582   gp_Pnt PM1(x1/nbv1, y1/nbv1, z1/nbv1);
583
584   TColgp_SequenceOfPnt Ps;
585   TopTools_SequenceOfShape Fs;
586   if(!aMapVertFaces2.Contains(V2))
587     MESSAGE ("    FindFirstPairFaces: map aMapVertFaces2 not contains key V2");
588   const TopTools_ListOfShape& aList2 = aMapVertFaces2.FindFromKey(V2);
589   TopTools_ListIteratorOfListOfShape anIter2(aList2);
590   for(; anIter2.More(); anIter2.Next()) {
591     TopoDS_Shape F = anIter2.Value();
592     double x2=0., y2=0., z2=0.;
593     int nbv2=0;
594     for( exp.Init( F, TopAbs_VERTEX ); exp.More(); exp.Next() ) {
595       TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
596       gp_Pnt P = BRep_Tool::Pnt(V);
597       x2 += P.X();
598       y2 += P.Y();
599       z2 += P.Z();
600       nbv2++;
601     }
602     gp_Pnt PM(x2/nbv1, y2/nbv1, z2/nbv1);
603     Fs.Append(F);
604     Ps.Append(PM);
605   }
606
607   gp_Vec aDir(P1,P2);
608   int i=1;
609   double MinAng = PI;
610   int numface = 0;
611   for(; i<=Fs.Length(); i++) {
612     gp_Vec tmpDir(PM1,Ps(i));
613     double ang = fabs(aDir.Angle(tmpDir));
614     if(ang<MinAng) {
615       MinAng = ang;
616       numface = i;
617     }
618   }
619   FS2 = Fs(numface);
620 }
621
622
623 //=======================================================================
624 //function : CreatePipeForShellSections
625 //purpose  : auxilary for Execute()
626 //=======================================================================
627 static TopoDS_Shape CreatePipeForShellSections(const TopoDS_Wire& aWirePath,
628                                                GEOMImpl_IPipe* aCI)
629 {
630   //cout<<"CreatePipeForShellSections"<<endl;
631   //TopoDS_Shape res;
632   int i,j;
633   BRep_Builder B;
634
635   GEOMImpl_IPipeShellSect* aCIDS = (GEOMImpl_IPipeShellSect*)aCI;
636   Handle(TColStd_HSequenceOfTransient) aBasesObjs = aCIDS->GetBases();
637   Handle(TColStd_HSequenceOfTransient) aSubBasesObjs = aCIDS->GetSubBases();
638   Handle(TColStd_HSequenceOfTransient) aLocObjs = aCIDS->GetLocations();
639   Standard_Boolean aWithContact = (aCIDS->GetWithContactMode());
640   Standard_Boolean aWithCorrect = (aCIDS->GetWithCorrectionMode());
641
642   Standard_Integer nbBases = aBasesObjs->Length(),
643     nbSubBases = (aSubBasesObjs.IsNull() ? 0 :aSubBasesObjs->Length()),
644     nbLocs = (aLocObjs.IsNull() ? 0 :aLocObjs->Length());
645
646   if( nbLocs != nbBases) {
647     if(aCI) delete aCI;
648     Standard_ConstructionError::Raise("Number of sections is not equal to number of locations ");
649   }
650   if( nbSubBases && nbSubBases != nbBases) {
651     if(aCI) delete aCI;
652     Standard_ConstructionError::Raise("Number of sections is not equal to number of subsections ");
653   }
654
655   //BRepOffsetAPI_MakePipeShell aBuilder(aWirePath);
656
657   TopTools_SequenceOfShape VLocs;
658   for(i=1; i<=nbBases; i++) {
659     Handle(Standard_Transient) anItemLoc = aLocObjs->Value(i);
660     if(anItemLoc.IsNull())
661       continue;
662     Handle(GEOM_Function) aRefLoc = Handle(GEOM_Function)::DownCast(anItemLoc);
663     TopoDS_Shape aShapeLoc = aRefLoc->GetValue();
664     if(aShapeLoc.IsNull() || aShapeLoc.ShapeType() != TopAbs_VERTEX)
665       continue;
666     VLocs.Append(aShapeLoc);
667   }
668   nbLocs = VLocs.Length();
669   if( nbLocs != nbBases) {
670     if(aCI) delete aCI;
671     Standard_ConstructionError::Raise("One of location shapes is not a vertex");
672   }
673   // split wire path by location points
674   TColgp_SequenceOfPnt PLocs;
675   for(i=1; i<=nbLocs; i++) {
676     TopoDS_Vertex V = TopoDS::Vertex(VLocs.Value(i));
677     PLocs.Append(BRep_Tool::Pnt(V));
678   }
679
680   TopTools_SequenceOfShape Edges;
681   TopTools_SequenceOfShape Wires;
682   ShapeAnalysis_Edge sae;
683
684   if(nbLocs==2) {
685     TopExp_Explorer anExp;
686     for ( anExp.Init( aWirePath, TopAbs_EDGE ); anExp.More(); anExp.Next() ) {
687       Edges.Append(anExp.Current());
688     }
689     Standard_Integer Num1 = 0;
690     Standard_Integer Num2 = 0;
691     for(i=1; i<=Edges.Length(); i++) {
692       TopoDS_Edge E = TopoDS::Edge(Edges.Value(i));
693       double tol = BRep_Tool::Tolerance(E);
694       TopoDS_Vertex V1 = sae.FirstVertex(E);
695       TopoDS_Vertex V2 = sae.LastVertex(E);
696       gp_Pnt P1 = BRep_Tool::Pnt(V1);
697       gp_Pnt P2 = BRep_Tool::Pnt(V2);
698       if( P1.Distance(PLocs.First()) < tol ) {
699         Num1 = i;
700       }
701       if( P2.Distance(PLocs.Last()) < tol ) {
702         Num2 = i;
703       }
704     }
705     if( Num1>0 && Num2>0 ) {
706       TopoDS_Wire W;
707       B.MakeWire(W);
708       for(i=Num1; i<=Num2; i++) {
709         B.Add(W,Edges.Value(i));
710       }
711       Wires.Append(W);
712     }
713     else {
714       Wires.Append(aWirePath);
715     }
716   }
717   else {
718     TopExp_Explorer anExp;
719     for ( anExp.Init( aWirePath, TopAbs_EDGE ); anExp.More(); anExp.Next() ) {
720       Edges.Append(anExp.Current());
721     }
722     TopoDS_Edge edge = TopoDS::Edge(Edges.First());
723     double tol = BRep_Tool::Tolerance(edge);
724     TopoDS_Vertex VF = sae.FirstVertex(edge);
725     gp_Pnt PF = BRep_Tool::Pnt(VF);
726     //cout<<"PF("<<PF.X()<<","<<PF.Y()<<","<<PF.Z()<<")"<<endl;
727     if( PF.Distance(PLocs.First()) > tol ) {
728       if(aCI) delete aCI;
729       Standard_ConstructionError::Raise
730         ("First location shapes is not coincided with first vertex of aWirePath");
731     }
732     VLocs.ChangeValue(1) = VF;
733     edge = TopoDS::Edge(Edges.Last());
734     tol = BRep_Tool::Tolerance(edge);
735     TopoDS_Vertex VL = sae.LastVertex(edge);
736     gp_Pnt PL = BRep_Tool::Pnt(VL);
737     if( PL.Distance(PLocs.Last()) > tol ) {
738       if(aCI) delete aCI;
739       Standard_ConstructionError::Raise
740         ("Last location shapes is not coincided with last vertex of aWirePath");
741     }
742     VLocs.ChangeValue(nbLocs) = VL;
743     int jcurr = 2;
744     TopTools_SequenceOfShape tmpEdges;
745     for(i=1; i<=Edges.Length() && jcurr<nbLocs; i++) {
746       TopoDS_Edge E = TopoDS::Edge(Edges.Value(i));
747       tol = BRep_Tool::Tolerance(E);
748       TopoDS_Vertex V1 = sae.FirstVertex(E);
749       TopoDS_Vertex V2 = sae.LastVertex(E);
750       gp_Pnt P1 = BRep_Tool::Pnt(V1);
751       gp_Pnt P2 = BRep_Tool::Pnt(V2);
752       if( P2.Distance(PLocs.Value(jcurr)) < tol ) {
753         // make wire from current edge and add created
754         // wire to Wires
755         TopoDS_Wire W;
756         B.MakeWire(W);
757         for(j=1; j<=tmpEdges.Length(); j++)
758           B.Add(W,tmpEdges.Value(j));
759         B.Add(W,E);
760         Wires.Append(W);
761         VLocs.ChangeValue(jcurr) = V2;
762         jcurr++;
763         tmpEdges.Clear();
764       }
765       else {
766         // find distance between E and aLocs(jcurr)
767         double fp,lp;
768         Handle(Geom_Curve) C = BRep_Tool::Curve(E,fp,lp);
769         GeomAPI_ProjectPointOnCurve PPC (PLocs.Value(jcurr),C);
770         if( PPC.NbPoints()>0 &&
771             PLocs.Value(jcurr).Distance(PPC.Point(1)) < tol ) {
772           double param = PPC.Parameter(1);
773           gp_Pnt PC1;
774           C->D0(param,PC1);
775           // split current edge
776           Handle(Geom_TrimmedCurve) tc1 = new Geom_TrimmedCurve(C,fp,param);
777           Handle(Geom_TrimmedCurve) tc2 = new Geom_TrimmedCurve(C,param,lp);
778           TopoDS_Edge E1,E2;
779           gp_Pnt Pfp;
780           C->D0(fp,Pfp);
781           if(Pfp.Distance(P1)<tol) {
782             B.MakeEdge(E1,tc1,tol);
783             B.Add(E1,V1);
784             TopoDS_Shape tmpV = VLocs.Value(jcurr).Oriented(TopAbs_REVERSED);
785             B.Add(E1,TopoDS::Vertex(tmpV));
786             tmpEdges.Append(E1);
787             B.MakeEdge(E2,tc2,tol);
788             tmpV = VLocs.Value(jcurr).Oriented(TopAbs_FORWARD);
789             B.Add(E2,TopoDS::Vertex(tmpV));
790             B.Add(E2,V2);
791           }
792           else {
793             B.MakeEdge(E1,tc2,tol);
794             TopoDS_Shape tmpV = VLocs.Value(jcurr).Oriented(TopAbs_FORWARD);
795             B.Add(E1,TopoDS::Vertex(tmpV));
796             B.Add(E1,V1);
797             E1.Reverse();
798             tmpEdges.Append(E1);
799             B.MakeEdge(E2,tc1,tol);
800             B.Add(E2,V2);
801             tmpV = VLocs.Value(jcurr).Oriented(TopAbs_REVERSED);
802             B.Add(E2,TopoDS::Vertex(tmpV));
803             E2.Reverse();
804           }
805           // create wire from tmpEdges
806           TopoDS_Wire W;
807           B.MakeWire(W);
808           for(j=1; j<=tmpEdges.Length(); j++)
809             B.Add(W,tmpEdges.Value(j));
810           Wires.Append(W);
811           jcurr++;
812           tmpEdges.Clear();
813           Edges.Remove(i);
814           Edges.InsertAfter(i-1,E1);
815           Edges.InsertAfter(i,E2);
816         }
817         else {
818           tmpEdges.Append(E);
819         }
820       }
821     }
822     // create wire from other edges
823     TopoDS_Wire W;
824     B.MakeWire(W);
825     for(; i<=Edges.Length(); i++)
826       B.Add(W,Edges.Value(i));
827     Wires.Append(W);
828     //cout<<"Wires.Length()="<<Wires.Length()<<endl;
829   }
830
831   if( Wires.Length() != nbLocs-1 ) {
832     if(aCI) delete aCI;
833     Standard_ConstructionError::Raise
834       ("One of location shapes is not lied on the path");
835   }
836
837   //TopTools_SequenceOfShape aSeqBases;
838   //TopTools_SequenceOfShape aSeqSubBases;
839   //TopTools_SequenceOfShape aSeqFaces;
840   TopoDS_Compound aComp;
841   B.MakeCompound(aComp);
842   for(i=1 ; i<nbBases; i++) {
843     TopoDS_Wire WPath = TopoDS::Wire(Wires.Value(i));
844     // 1 section
845     Handle(Standard_Transient) anItem1 = aBasesObjs->Value(i);
846     if(anItem1.IsNull())
847       continue;
848     Handle(GEOM_Function) aRefBase1 = Handle(GEOM_Function)::DownCast(anItem1);
849     if(aRefBase1.IsNull())
850       continue;
851     TopoDS_Shape aShBase1 = aRefBase1->GetValue();
852     if(aShBase1.IsNull())
853       continue;
854     TopAbs_ShapeEnum aType1 = aShBase1.ShapeType();
855     // 2 section
856     Handle(Standard_Transient) anItem2 = aBasesObjs->Value(i+1);
857     if(anItem2.IsNull())
858       continue;
859     Handle(GEOM_Function) aRefBase2 = Handle(GEOM_Function)::DownCast(anItem2);
860     if(aRefBase2.IsNull())
861       continue;
862     TopoDS_Shape aShBase2 = aRefBase2->GetValue();
863     if(aShBase2.IsNull())
864       continue;
865     TopAbs_ShapeEnum aType2 = aShBase2.ShapeType();
866
867     //BRepTools::Write(aShBase1,"/dn02/users_Linux/skl/work/Bugs/14857/base1.brep");
868
869     bool OkSec = ( aType1==TopAbs_SHELL || aType1==TopAbs_FACE ) &&
870                  ( aType2==TopAbs_SHELL || aType2==TopAbs_FACE );
871     if( !OkSec ) {
872       if(aCI) delete aCI;
873       Standard_ConstructionError::Raise("One of section shapes has invalid type");
874     }
875
876     bool CreateFewSolids = false;
877     // compare sections
878     TopExp_Explorer anExp;
879     Standard_Integer nbf1 = 0;
880     for ( anExp.Init( aShBase1, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
881       nbf1++;
882     }
883     Standard_Integer nbf2 = 0;
884     for ( anExp.Init( aShBase2, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
885       nbf2++;
886     }
887     if(nbf1==nbf2) {
888       CreateFewSolids = true;
889     }
890
891     /*
892     // check orientation of sections
893     bool NeedReverse = false;
894     {
895       // first section
896       anExp.Init( aShBase1, TopAbs_FACE );
897       TopoDS_Shape aFace = anExp.Current();
898       TColgp_SequenceOfPnt aPnts;
899       double xc=0, yc=0, zc=0;
900       for ( anExp.Init( aFace, TopAbs_VERTEX ); anExp.More(); anExp.Next() ) {
901         TopoDS_Vertex V = TopoDS::Vertex(anExp.Current());
902         aPnts.Append(BRep_Tool::Pnt(V));
903         xc += aPnts.Last().X();
904         yc += aPnts.Last().Y();
905         zc += aPnts.Last().Z();
906       }
907       gp_Pnt PC( xc/aPnts.Length(), yc/aPnts.Length(), zc/aPnts.Length() );
908       gp_Vec V1(PC,aPnts.Value(1));
909       gp_Vec V2(PC,aPnts.Value(2));
910       gp_Vec VN = V1.Crossed(V2);
911       for(int ip=2; ip<aPnts.Length(); ip++) {
912         V1 = gp_Vec(PC,aPnts.Value(ip));
913         V2 = gp_Vec(PC,aPnts.Value(ip+1));
914         VN.Add(V1.Crossed(V2));
915       }
916       gp_Vec PathNorm;
917       gp_Pnt PLoc = BRep_Tool::Pnt(TopoDS::Vertex(VLocs(i)));
918       TopExp_Explorer WE;
919       for ( WE.Init( WPath, TopAbs_EDGE ); WE.More(); WE.Next() ) {
920         TopoDS_Edge edge = TopoDS::Edge(WE.Current());
921         double tol = BRep_Tool::Tolerance(edge);
922         TopoDS_Vertex VF = sae.FirstVertex(edge);
923         gp_Pnt PF = BRep_Tool::Pnt(VF);
924         if( PF.Distance(PLoc) < tol ) {
925           double fp,lp;
926           Handle(Geom_Curve) C = BRep_Tool::Curve(edge,fp,lp);
927           gp_Pnt P1,P2;
928           C->D0(fp,P1);
929           if( P1.Distance(PLoc) < tol ) {
930             C->D0(fp+(lp-fp)/100,P2);
931           }
932           else {
933             C->D0(lp,P1);
934             C->D0(lp+(fp-lp)/100,P2);
935           }
936           PathNorm = gp_Vec(P1,P2);
937           break;
938         }
939         else {
940           TopoDS_Vertex VL = sae.LastVertex(edge);
941           gp_Pnt PL = BRep_Tool::Pnt(VL);
942           if( PL.Distance(PLoc) < tol ) {
943             double fp,lp;
944             Handle(Geom_Curve) C = BRep_Tool::Curve(edge,fp,lp);
945             gp_Pnt P1,P2;
946             C->D0(fp,P1);
947             if( P1.Distance(PLoc) < tol ) {
948               C->D0(fp+(lp-fp)/100,P2);
949             }
950             else {
951               C->D0(lp,P1);
952               C->D0(lp+(fp-lp)/100,P2);
953             }
954             PathNorm = gp_Vec(P2,P1);
955             break;
956           }
957         }
958       }
959       cout<<"VN("<<VN.X()<<","<<VN.Y()<<","<<VN.Z()<<")"<<endl;
960       cout<<"PathNorm("<<PathNorm.X()<<","<<PathNorm.Y()<<","<<PathNorm.Z()<<")"<<endl;
961       if(fabs(VN.Angle(PathNorm))>PI/2.) {
962         NeedReverse = true;
963         aShBase1.Reverse();
964       }
965     }
966     {
967       // second section
968       anExp.Init( aShBase2, TopAbs_FACE );
969       TopoDS_Shape aFace = anExp.Current();
970       TColgp_SequenceOfPnt aPnts;
971       double xc=0, yc=0, zc=0;
972       for ( anExp.Init( aFace, TopAbs_VERTEX ); anExp.More(); anExp.Next() ) {
973         TopoDS_Vertex V = TopoDS::Vertex(anExp.Current());
974         aPnts.Append(BRep_Tool::Pnt(V));
975         xc += aPnts.Last().X();
976         yc += aPnts.Last().Y();
977         zc += aPnts.Last().Z();
978       }
979       gp_Pnt PC( xc/aPnts.Length(), yc/aPnts.Length(), zc/aPnts.Length() );
980       gp_Vec V1(PC,aPnts.Value(1));
981       gp_Vec V2(PC,aPnts.Value(2));
982       gp_Vec VN = V1.Crossed(V2);
983       for(int ip=2; ip<aPnts.Length(); ip++) {
984         V1 = gp_Vec(PC,aPnts.Value(ip));
985         V2 = gp_Vec(PC,aPnts.Value(ip+1));
986         VN.Add(V1.Crossed(V2));
987       }
988       gp_Vec PathNorm;
989       gp_Pnt PLoc = BRep_Tool::Pnt(TopoDS::Vertex(VLocs(i+1)));
990       TopExp_Explorer WE;
991       for ( WE.Init( WPath, TopAbs_EDGE ); WE.More(); WE.Next() ) {
992         TopoDS_Edge edge = TopoDS::Edge(WE.Current());
993         double tol = BRep_Tool::Tolerance(edge);
994         TopoDS_Vertex VF = sae.FirstVertex(edge);
995         gp_Pnt PF = BRep_Tool::Pnt(VF);
996         if( PF.Distance(PLoc) < tol ) {
997           double fp,lp;
998           Handle(Geom_Curve) C = BRep_Tool::Curve(edge,fp,lp);
999           gp_Pnt P1,P2;
1000           C->D0(fp,P1);
1001           if( P1.Distance(PLoc) < tol ) {
1002             C->D0(fp+(lp-fp)/100,P2);
1003           }
1004           else {
1005             C->D0(lp,P1);
1006             C->D0(lp+(fp-lp)/100,P2);
1007           }
1008           PathNorm = gp_Vec(P2,P1);
1009           break;
1010         }
1011         else {
1012           TopoDS_Vertex VL = sae.LastVertex(edge);
1013           gp_Pnt PL = BRep_Tool::Pnt(VL);
1014           if( PL.Distance(PLoc) < tol ) {
1015             double fp,lp;
1016             Handle(Geom_Curve) C = BRep_Tool::Curve(edge,fp,lp);
1017             gp_Pnt P1,P2;
1018             C->D0(fp,P1);
1019             if( P1.Distance(PLoc) < tol ) {
1020               C->D0(fp+(lp-fp)/100,P2);
1021             }
1022             else {
1023               C->D0(lp,P1);
1024               C->D0(lp+(fp-lp)/100,P2);
1025             }
1026             PathNorm = gp_Vec(P2,P1);
1027             break;
1028           }
1029         }
1030       }
1031       //cout<<"VN("<<VN.X()<<","<<VN.Y()<<","<<VN.Z()<<")"<<endl;
1032       //cout<<"PathNorm("<<PathNorm.X()<<","<<PathNorm.Y()<<","<<PathNorm.Z()<<")"<<endl;
1033       if(fabs(VN.Angle(PathNorm))>PI/2.)
1034         aShBase2.Reverse();
1035     }
1036     */
1037
1038     if(!CreateFewSolids) {
1039       // we can create only one solid
1040       TopoDS_Shape aWire1, aWire2;
1041       // prepare aWire1
1042       if(aType1==TopAbs_SHELL) {
1043         // create wire as boundary contour if shell is no closed
1044         // get free boundary shapes
1045         ShapeAnalysis_FreeBounds anAnalizer( aShBase1 );
1046         TopoDS_Compound aClosed = anAnalizer.GetClosedWires();
1047         //TopExp_Explorer anExp;
1048         Standard_Integer NbWires = 0;
1049         for ( anExp.Init( aClosed, TopAbs_WIRE ); anExp.More(); anExp.Next() ) {
1050           NbWires++;
1051           aWire1 = anExp.Current();
1052         }
1053         if(NbWires!=1) {
1054           // bad case
1055           if(aCI) delete aCI;
1056           Standard_ConstructionError::Raise("Bad shell is used as section ");
1057         }
1058       }
1059       else { // aType1==TopAbs_FACE
1060         TopExp_Explorer aExpW(aShBase1,TopAbs_WIRE);
1061         aWire1 = aExpW.Current();
1062       }
1063       // prepare aWire2
1064       if(aType2==TopAbs_SHELL) {
1065         // create wire as boundary contour if shell is no closed
1066         // get free boundary shapes
1067         ShapeAnalysis_FreeBounds anAnalizer( aShBase2 );
1068         TopoDS_Compound aClosed = anAnalizer.GetClosedWires();
1069         //TopExp_Explorer anExp;
1070         Standard_Integer NbWires = 0;
1071         for ( anExp.Init( aClosed, TopAbs_WIRE ); anExp.More(); anExp.Next() ) {
1072           NbWires++;
1073           aWire2 = anExp.Current();
1074         }
1075         if(NbWires!=1) {
1076           // bad case
1077           if(aCI) delete aCI;
1078           Standard_ConstructionError::Raise("Bad shell is used as section ");
1079         }
1080       }
1081       else { // aType2==TopAbs_FACE
1082         TopExp_Explorer aExpW(aShBase2,TopAbs_WIRE);
1083         aWire2 = aExpW.Current();
1084       }
1085       // make pipe using aWire1 and aWire2
1086       if( !aWire1.IsNull() && !aWire2.IsNull() ) {
1087         //BRepOffsetAPI_MakePipeShell aBuilder(aWirePath);
1088         BRepOffsetAPI_MakePipeShell aBuilder(WPath);
1089         aBuilder.Add(aWire1, TopoDS::Vertex(VLocs(i)),
1090                      aWithContact, aWithCorrect);
1091         aBuilder.Add(aWire2, TopoDS::Vertex(VLocs(i+1)),
1092                      aWithContact, aWithCorrect);
1093         if(!aBuilder.IsReady()) {
1094           if(aCI) delete aCI;
1095           Standard_ConstructionError::Raise("Invalid input data for building PIPE: bases are invalid");
1096         }
1097         aBuilder.Build();
1098         TopoDS_Shape aShape = aBuilder.Shape();
1099         TopoDS_Shell aShell;
1100         B.MakeShell(aShell);
1101         for ( anExp.Init( aShape, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1102           B.Add(aShell,anExp.Current());
1103         }
1104         for ( anExp.Init( aShBase1, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1105           B.Add(aShell,anExp.Current());
1106         }
1107         for ( anExp.Init( aShBase2, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1108           B.Add(aShell,anExp.Current());
1109         }
1110         // make sewing for this shell
1111         Handle(BRepBuilderAPI_Sewing) aSewing = new BRepBuilderAPI_Sewing;
1112         aSewing->SetTolerance(Precision::Confusion());
1113         aSewing->SetFaceMode(Standard_True);
1114         aSewing->SetFloatingEdgesMode(Standard_False);
1115         aSewing->SetNonManifoldMode(Standard_False);
1116         for ( anExp.Init( aShell, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1117           aSewing->Add(anExp.Current());
1118         }
1119         aSewing->Perform();
1120         const TopoDS_Shape aSewShape = aSewing->SewedShape();
1121         if( aSewShape.ShapeType() == TopAbs_SHELL ) {
1122           aShell = TopoDS::Shell(aSewShape);
1123           GProp_GProps aSystem;
1124           BRepGProp::VolumeProperties(aShell, aSystem);
1125           if(aSystem.Mass()<0) {
1126             aShell.Reverse();
1127           }
1128           if(BRep_Tool::IsClosed(aShell)) {
1129             TopoDS_Solid aSolid;
1130             B.MakeSolid(aSolid);
1131             B.Add(aSolid,aShell);
1132             B.Add(aComp,aSolid);
1133           }
1134           else {
1135             B.Add(aComp,aShell);
1136           }
1137         }
1138         else {
1139           B.Add(aComp,aShell);
1140         }
1141       }
1142     }
1143     else {
1144       // main block - creation few solids (for each pair of faces)
1145       TopTools_MapOfShape aFaces1,aFaces2;
1146       for ( anExp.Init( aShBase1, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1147         aFaces1.Add(anExp.Current());
1148       }
1149       for ( anExp.Init( aShBase2, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1150         aFaces2.Add(anExp.Current());
1151       }
1152       // creating map of edge faces
1153       TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces1;
1154       TopExp::MapShapesAndAncestors(aShBase1, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces1);
1155       TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces2;
1156       TopExp::MapShapesAndAncestors(aShBase2, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces2);
1157
1158       // constuct map face->face
1159       TopTools_IndexedDataMapOfShapeShape FF;
1160       TopoDS_Shape FS1,FS2;
1161       if(nbSubBases==0) {
1162         // find edge the most distant from location point
1163         // (this edge is not shared by two faces)
1164         double maxdist = 0.;
1165         TopoDS_Shape E1;
1166         TopoDS_Vertex V11,V21;
1167         for(j=1; j<=aMapEdgeFaces1.Extent(); j++) {
1168           TopoDS_Shape tmp = aMapEdgeFaces1.FindKey(j);
1169           const TopTools_ListOfShape& aList = aMapEdgeFaces1.FindFromKey(tmp);
1170           if(aList.Extent()>1)
1171             continue;
1172           TopExp_Explorer expv;
1173           expv.Init( tmp, TopAbs_VERTEX );
1174           TopoDS_Vertex V1 = TopoDS::Vertex(expv.Current());
1175           expv.Next();
1176           TopoDS_Vertex V2 = TopoDS::Vertex(expv.Current());
1177           gp_Pnt P1 = BRep_Tool::Pnt(V1);
1178           gp_Pnt P2 = BRep_Tool::Pnt(V2);
1179           double dist = PLocs.Value(i).Distance(P1) + PLocs.Value(i).Distance(P2);
1180           if(dist>maxdist) {
1181             E1 = tmp;
1182             V11 = V1;
1183             V21 = V2;
1184             TopTools_ListIteratorOfListOfShape anIter(aList);
1185             FS1 = anIter.Value();
1186             maxdist = dist;
1187           }
1188         }
1189         // main direction for comparing
1190         gp_Vec VM(PLocs.Value(i),PLocs.Value(i+1));
1191         // find corresponding edge from next section
1192         double minang = PI;
1193         gp_Pnt P11 = BRep_Tool::Pnt(V11);
1194         gp_Pnt P21 = BRep_Tool::Pnt(V21);
1195         TopoDS_Shape E2;
1196         TopoDS_Vertex V12,V22;
1197         for(j=1; j<=aMapEdgeFaces2.Extent(); j++) {
1198           TopoDS_Shape tmp = aMapEdgeFaces2.FindKey(j);
1199           const TopTools_ListOfShape& aList = aMapEdgeFaces2.FindFromKey(tmp);
1200           if(aList.Extent()>1)
1201             continue;
1202           TopExp_Explorer expv;
1203           expv.Init( tmp, TopAbs_VERTEX );
1204           TopoDS_Vertex V1tmp = TopoDS::Vertex(expv.Current());
1205           expv.Next();
1206           TopoDS_Vertex V2tmp = TopoDS::Vertex(expv.Current());
1207           gp_Pnt P1tmp = BRep_Tool::Pnt(V1tmp);
1208           gp_Pnt P2tmp = BRep_Tool::Pnt(V2tmp);
1209           double d1 = P1tmp.Distance(P11) + P2tmp.Distance(P21);
1210           double d2 = P1tmp.Distance(P21) + P2tmp.Distance(P11);
1211           TopoDS_Vertex V1,V2;
1212           gp_Pnt P1,P2;
1213           if(d1>d2) {
1214             V1 = V2tmp; P1 = P2tmp;
1215             V2 = V1tmp; P2 = P1tmp;
1216           }
1217           else {
1218             V1 = V1tmp; P1 = P1tmp;
1219             V2 = V2tmp; P2 = P2tmp;
1220           }
1221           gp_Vec Vec1(P11,P1);
1222           gp_Vec Vec2(P21,P2);
1223           double ang = fabs(Vec1.Angle(VM)) + fabs(Vec2.Angle(VM));
1224           if(ang<minang) {
1225             E2 = tmp;
1226             V12 = V1;
1227             V22 = V2;
1228             TopTools_ListIteratorOfListOfShape anIter(aList);
1229             FS2 = anIter.Value();
1230             minang = ang;
1231           }
1232         }
1233         // put all pairs to map FF
1234         FF.Add(FS1,FS2);
1235         FF.Add(E1,E2);
1236         FF.Add(V11,V12);
1237         FF.Add(V21,V22);
1238
1239         // add pairs of edges to FF
1240         bool stat =  FillForOtherEdges(FS1,E1,V11,FF);
1241         if( !stat ) {
1242           if(aCI) delete aCI;
1243           Standard_ConstructionError::Raise("FindForOtherEdges: Can not mapping other egdes");
1244         }
1245
1246       }
1247       else {
1248         { // 1 section
1249           Handle(Standard_Transient) anItem = aSubBasesObjs->Value(i);
1250           if(anItem.IsNull()) {
1251             if(aCI) delete aCI;
1252             Standard_ConstructionError::Raise("Invalid subbase shape");
1253           }
1254           Handle(GEOM_Function) aRefBase = Handle(GEOM_Function)::DownCast(anItem);
1255           if(aRefBase.IsNull()) {
1256             if(aCI) delete aCI;
1257             Standard_ConstructionError::Raise("Invalid subbase shape");
1258           }
1259           TopoDS_Shape aSh = aRefBase->GetValue();
1260           if(aSh.IsNull()) {
1261             if(aCI) delete aCI;
1262             Standard_ConstructionError::Raise("Invalid subbase shape");
1263           }
1264           if(aSh.ShapeType()!=TopAbs_FACE) {
1265             if(aCI) delete aCI;
1266             Standard_ConstructionError::Raise("Invalid subbase shape");
1267           }
1268           FS1 = aSh;
1269         }
1270         { // 2 section
1271           Handle(Standard_Transient) anItem = aSubBasesObjs->Value(i+1);
1272           if(anItem.IsNull()) {
1273             if(aCI) delete aCI;
1274             Standard_ConstructionError::Raise("Invalid subbase shape");
1275           }
1276           Handle(GEOM_Function) aRefBase = Handle(GEOM_Function)::DownCast(anItem);
1277           if(aRefBase.IsNull()) {
1278             if(aCI) delete aCI;
1279             Standard_ConstructionError::Raise("Invalid subbase shape");
1280           }
1281           TopoDS_Shape aSh = aRefBase->GetValue();
1282           if(aSh.IsNull()) {
1283             if(aCI) delete aCI;
1284             Standard_ConstructionError::Raise("Invalid subbase shape");
1285           }
1286           if(aSh.ShapeType()!=TopAbs_FACE) {
1287             if(aCI) delete aCI;
1288             Standard_ConstructionError::Raise("Invalid subbase shape");
1289           }
1290           FS2 = aSh;
1291         }
1292
1293         if( !aFaces1.Contains(FS1) || !aFaces2.Contains(FS2) ) {
1294           if(aCI) delete aCI;
1295           Standard_ConstructionError::Raise("Invalid subbase shape");
1296         }
1297
1298         FF.Add(FS1,FS2);
1299
1300         // add pairs of edges to FF
1301         bool stat =  FillCorrespondingEdges(FS1, FS2, TopoDS::Vertex(VLocs(i)),
1302                                             TopoDS::Vertex(VLocs(i+1)), WPath, FF);
1303         if( !stat ) {
1304           if(aCI) delete aCI;
1305           Standard_ConstructionError::Raise("Can not create correct pipe");
1306         }
1307       }
1308
1309       FindNextPairOfFaces(FS1, aMapEdgeFaces1, aMapEdgeFaces2, FF, aCI);
1310
1311
1312       // make pipe for each pair of faces
1313       for(j=1; j<=FF.Extent(); j++) {
1314         TopoDS_Shape F1 = FF.FindKey(j);
1315         if( F1.ShapeType() != TopAbs_FACE )
1316           continue;
1317         TopoDS_Shape F2 = FF.FindFromIndex(j);
1318         TopExp_Explorer aExpW1(F1,TopAbs_WIRE);
1319         TopoDS_Wire aWire1 = TopoDS::Wire(aExpW1.Current());
1320         TopExp_Explorer aExpW2(F2,TopAbs_WIRE);
1321         TopoDS_Wire aWire2 = TopoDS::Wire(aExpW2.Current());
1322         // make pipe using aWire1 and aWire2
1323         if( !aWire1.IsNull() && !aWire2.IsNull() ) {
1324           BRepOffsetAPI_MakePipeShell aBuilder(WPath);
1325           aBuilder.Add(aWire1, TopoDS::Vertex(VLocs(i)),
1326                        aWithContact, aWithCorrect);
1327           aBuilder.Add(aWire2, TopoDS::Vertex(VLocs(i+1)),
1328                        aWithContact, aWithCorrect);
1329           if(!aBuilder.IsReady()) {
1330             if(aCI) delete aCI;
1331             Standard_ConstructionError::Raise("Invalid input data for building PIPE: bases are invalid");
1332           }
1333           aBuilder.Build();
1334           TopoDS_Shape aShape = aBuilder.Shape();
1335           TopoDS_Shell aShell;
1336           B.MakeShell(aShell);
1337           for ( anExp.Init( aShape, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1338             B.Add(aShell,anExp.Current());
1339           }
1340
1341           B.Add(aShell,F1);
1342           B.Add(aShell,F2);
1343           // make sewing for this shell
1344           Handle(BRepBuilderAPI_Sewing) aSewing = new BRepBuilderAPI_Sewing;
1345           aSewing->SetTolerance(Precision::Confusion());
1346           aSewing->SetFaceMode(Standard_True);
1347           aSewing->SetFloatingEdgesMode(Standard_False);
1348           aSewing->SetNonManifoldMode(Standard_False);
1349           for ( anExp.Init( aShell, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1350             aSewing->Add(anExp.Current());
1351           }
1352           aSewing->Perform();
1353           const TopoDS_Shape aSewShape = aSewing->SewedShape();
1354           if( aSewShape.ShapeType() == TopAbs_SHELL ) {
1355             aShell = TopoDS::Shell(aSewShape);
1356             GProp_GProps aSystem;
1357             BRepGProp::VolumeProperties(aShell, aSystem);
1358             if(aSystem.Mass()<0) {
1359               //cout<<"aSewShape is reversed"<<endl;
1360               aShell.Reverse();
1361             }
1362             if(BRep_Tool::IsClosed(aShell)) {
1363               TopoDS_Solid aSolid;
1364               B.MakeSolid(aSolid);
1365               B.Add(aSolid,aShell);
1366               B.Add(aComp,aSolid);
1367             }
1368             else {
1369               B.Add(aComp,aShell);
1370             }
1371           }
1372           else {
1373             B.Add(aComp,aShell);
1374           }
1375         }
1376       }
1377
1378     }
1379   }
1380
1381   //BRepTools::Write(aComp,"/dn02/users_Linux/skl/work/Bugs/14857/comp.brep");
1382   return aComp;
1383 }
1384
1385
1386 //=======================================================================
1387 //function : CreatePipeShellsWithoutPath
1388 //purpose  : auxilary for Execute()
1389 //=======================================================================
1390 static TopoDS_Shape CreatePipeShellsWithoutPath(GEOMImpl_IPipe* aCI)
1391 {
1392   //cout<<"CreatePipeShellsWithoutPath"<<endl;
1393   int i,j;
1394   BRep_Builder B;
1395
1396   GEOMImpl_IPipeShellSect* aCIDS = (GEOMImpl_IPipeShellSect*)aCI;
1397   // shell sections
1398   Handle(TColStd_HSequenceOfTransient) aBasesObjs = aCIDS->GetBases();
1399   // vertex for recognition
1400   Handle(TColStd_HSequenceOfTransient) VObjs = aCIDS->GetLocations();
1401
1402   Standard_Integer nbBases = aBasesObjs->Length(),
1403     nbv = (VObjs.IsNull() ? 0 :VObjs->Length());
1404
1405   if( nbv != nbBases ) {
1406     if(aCI) delete aCI;
1407     Standard_ConstructionError::Raise("Number of shapes for recognition is invalid");
1408   }
1409
1410
1411   TopTools_SequenceOfShape SecVs,Bases;
1412   for(i=1; i<=nbBases; i++) {
1413     // vertex
1414     Handle(Standard_Transient) anItem = VObjs->Value(i);
1415     if(anItem.IsNull())
1416       continue;
1417     Handle(GEOM_Function) aRef = Handle(GEOM_Function)::DownCast(anItem);
1418     TopoDS_Shape V = aRef->GetValue();
1419     if(V.IsNull() || V.ShapeType() != TopAbs_VERTEX)
1420       continue;
1421     SecVs.Append(V);
1422     // section
1423     anItem = aBasesObjs->Value(i);
1424     if(anItem.IsNull())
1425       continue;
1426     aRef = Handle(GEOM_Function)::DownCast(anItem);
1427     TopoDS_Shape aSh = aRef->GetValue();
1428     if(aSh.IsNull())
1429       continue;
1430     Bases.Append(aSh);
1431   }
1432   nbv = SecVs.Length();
1433   nbBases = Bases.Length();
1434   if( nbv != nbBases ) {
1435     if(aCI) delete aCI;
1436     Standard_ConstructionError::Raise("One of shapes for recognition is not a vertex");
1437   }
1438
1439   TopoDS_Compound aComp;
1440   B.MakeCompound(aComp);
1441
1442   for(i=1 ; i<nbBases; i++) {
1443     MESSAGE ("Make pipe between sections "<<i<<" and "<<i+1);
1444     TopoDS_Shape aShBase1 = Bases.Value(i);
1445     TopoDS_Shape aShBase2 = Bases.Value(i+1);
1446     TopExp_Explorer anExp;
1447     Standard_Integer nbf1 = 0;
1448     for ( anExp.Init( aShBase1, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1449       nbf1++;
1450     }
1451     Standard_Integer nbf2 = 0;
1452     for ( anExp.Init( aShBase2, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1453       nbf2++;
1454     }
1455     //cout<<"nbf1="<<nbf1<<" nbf2="<<nbf2<<endl;
1456     if(nbf1!=nbf2) {
1457       if(aCI) delete aCI;
1458       Standard_ConstructionError::Raise("Different number of faces in the sections");
1459     }
1460
1461     TopTools_MapOfShape aFaces1,aFaces2;
1462     for ( anExp.Init( aShBase1, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1463       aFaces1.Add(anExp.Current());
1464     }
1465     for ( anExp.Init( aShBase2, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1466       aFaces2.Add(anExp.Current());
1467     }
1468
1469     // creating map of edge faces
1470     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces1;
1471     TopExp::MapShapesAndAncestors(aShBase1, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces1);
1472     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces2;
1473     TopExp::MapShapesAndAncestors(aShBase2, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces2);
1474
1475     // constuct map face->face (and subshapes)
1476     TopTools_IndexedDataMapOfShapeShape FF;
1477     //TopoDS_Shape FS1 = SecFs.Value(i), FS2 = SecFs.Value(i+1);
1478     TopoDS_Shape FS1, FS2;
1479     TopoDS_Vertex V1 = TopoDS::Vertex(SecVs(i));
1480     TopoDS_Vertex V2 = TopoDS::Vertex(SecVs(i+1));
1481     FindFirstPairFaces(aShBase1, aShBase2, V1, V2, FS1, FS2);
1482
1483     FF.Add(FS1,FS2);
1484     MESSAGE ("  first pair of corresponding faces is found");
1485
1486     // add pairs of edges and vertexes to FF
1487     bool stat =  FillCorrespondingEdges(FS1, FS2, V1, V2, FF);
1488     if( !stat ) {
1489       if(aCI) delete aCI;
1490       Standard_ConstructionError::Raise("Can not create correct pipe");
1491     }
1492     MESSAGE ("  correspondences for subshapes of first pair of faces is found");
1493
1494     FindNextPairOfFaces(FS1, aMapEdgeFaces1, aMapEdgeFaces2, FF, aCI);
1495     MESSAGE ("  other correspondences is found, make pipe for all pairs of faces");
1496
1497     // make pipe for each pair of faces
1498     // auxilary map vertex->edge for created pipe edges
1499     TopTools_IndexedDataMapOfShapeShape VPE;
1500     ShapeAnalysis_Edge sae;
1501     //cout<<"FF.Extent()="<<FF.Extent()<<endl;
1502     int nbff = 0;
1503     for(j=1; j<=FF.Extent(); j++) {
1504       TopoDS_Shape F1 = FF.FindKey(j);
1505       if( F1.ShapeType() != TopAbs_FACE )
1506         continue;
1507       TopoDS_Shape F2 = FF.FindFromIndex(j);
1508       nbff++;
1509
1510       //if(nbff!=3) continue;
1511
1512       MESSAGE ("    make pipe for "<<nbff<<" face");
1513
1514       Handle(Geom_Surface) S1 = BRep_Tool::Surface(TopoDS::Face(F1));
1515       if(S1->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
1516         Handle(Geom_RectangularTrimmedSurface) RTS =
1517           Handle(Geom_RectangularTrimmedSurface)::DownCast(S1);
1518         S1 = RTS->BasisSurface();
1519       }
1520       Handle(Geom_Plane) Pln1 = Handle(Geom_Plane)::DownCast(S1);
1521       if( Pln1.IsNull() ) {
1522         if(aCI) delete aCI;
1523         Standard_ConstructionError::Raise("Surface from face is not plane");
1524       }
1525       gp_Vec aDir1(Pln1->Axis().Direction());
1526
1527       Handle(Geom_Surface) S2 = BRep_Tool::Surface(TopoDS::Face(F2));
1528       if(S2->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
1529         Handle(Geom_RectangularTrimmedSurface) RTS =
1530           Handle(Geom_RectangularTrimmedSurface)::DownCast(S2);
1531         S2 = RTS->BasisSurface();
1532       }
1533       Handle(Geom_Plane) Pln2 =
1534           Handle(Geom_Plane)::DownCast(S2);
1535       if( Pln2.IsNull() ) {
1536         if(aCI) delete aCI;
1537         Standard_ConstructionError::Raise("Surface from face is not plane");
1538       }
1539       gp_Vec aDir2(Pln2->Axis().Direction());
1540
1541       gp_Pnt P1 = BRep_Tool::Pnt(TopoDS::Vertex(SecVs(i)));
1542       gp_Pnt P2 = BRep_Tool::Pnt(TopoDS::Vertex(SecVs(i+1)));
1543       gp_Vec aDir(P1,P2);
1544       if(fabs(aDir.Angle(aDir1))>PI/2.)
1545         aDir1.Reverse();
1546       if(fabs(aDir.Angle(aDir2))>PI/2.)
1547         aDir2.Reverse();
1548
1549       TopExp_Explorer anExpE(F1,TopAbs_EDGE);
1550       TopTools_SequenceOfShape aNewFs;
1551       //int nbee=0;
1552       for(; anExpE.More(); anExpE.Next()) {
1553         TopoDS_Edge E1 = TopoDS::Edge(anExpE.Current());
1554         //nbee++;
1555         if(!FF.Contains(E1))
1556           MESSAGE ("map FF not contains key E1");
1557
1558         if(VPE.Contains(E1)) {
1559           aNewFs.Append(VPE.FindFromKey(E1));
1560 #ifdef _DEBUG_
1561           MESSAGE ("    using existed face");
1562 #endif
1563           continue;
1564         }
1565
1566         TopoDS_Edge E3 = TopoDS::Edge(FF.FindFromKey(E1));
1567         TopoDS_Vertex V1 = sae.FirstVertex(E1);
1568         TopoDS_Vertex V2 = sae.LastVertex(E1);
1569         if(!FF.Contains(V1))
1570           MESSAGE ("map FF not contains key V1");
1571         if(!FF.Contains(V2))
1572           MESSAGE ("map FF not contains key V2");
1573         TopoDS_Vertex V3 = TopoDS::Vertex(FF.FindFromKey(V2));
1574         TopoDS_Vertex V4 = TopoDS::Vertex(FF.FindFromKey(V1));
1575         TopoDS_Vertex Vtmp = sae.FirstVertex(E3);
1576         if(Vtmp.IsSame(V4))
1577           E3.Reverse();
1578         gp_Pnt P1 = BRep_Tool::Pnt(V1);
1579         gp_Pnt P2 = BRep_Tool::Pnt(V2);
1580         gp_Pnt P3 = BRep_Tool::Pnt(V3);
1581         gp_Pnt P4 = BRep_Tool::Pnt(V4);
1582         // make E2
1583         TopoDS_Edge E2;
1584         Handle(Geom_BSplineCurve) C2;
1585         if(VPE.Contains(V2)) {
1586           E2 = TopoDS::Edge(VPE.FindFromKey(V2));
1587           double fp,lp;
1588           C2 = Handle(Geom_BSplineCurve)::DownCast(BRep_Tool::Curve(E2,fp,lp));
1589         }
1590         else {
1591           Handle(TColgp_HArray1OfPnt) HAP = new TColgp_HArray1OfPnt(1,2);
1592           HAP->SetValue(1,P2);
1593           HAP->SetValue(2,P3);
1594           GeomAPI_Interpolate anInt(HAP,Standard_False,1.e-7);
1595           anInt.Load(aDir1,aDir2);
1596           anInt.Perform();
1597           C2 = anInt.Curve();
1598           B.MakeEdge(E2,C2,1.e-7);
1599           B.Add(E2,TopoDS::Vertex(V2.Oriented(TopAbs_FORWARD)));
1600           B.Add(E2,TopoDS::Vertex(V3.Oriented(TopAbs_REVERSED)));
1601           VPE.Add(V2,E2);
1602         }
1603         // make E4
1604         TopoDS_Edge E4;
1605         Handle(Geom_BSplineCurve) C4;
1606         if(VPE.Contains(V1)) {
1607           E4 = TopoDS::Edge(VPE.FindFromKey(V1));
1608           double fp,lp;
1609           C4 = Handle(Geom_BSplineCurve)::DownCast(BRep_Tool::Curve(E4,fp,lp));
1610         }
1611         else {
1612           Handle(TColgp_HArray1OfPnt) HAP = new TColgp_HArray1OfPnt(1,2);
1613           HAP->SetValue(1,P1);
1614           HAP->SetValue(2,P4);
1615           GeomAPI_Interpolate anInt(HAP,Standard_False,1.e-7);
1616           anInt.Load(aDir1,aDir2);
1617           anInt.Perform();
1618           C4 = anInt.Curve();
1619           B.MakeEdge(E4,anInt.Curve(),1.e-7);
1620           B.Add(E4,TopoDS::Vertex(V1.Oriented(TopAbs_FORWARD)));
1621           B.Add(E4,TopoDS::Vertex(V4.Oriented(TopAbs_REVERSED)));
1622           VPE.Add(V1,E4);
1623         }
1624
1625         TopoDS_Wire W;
1626         B.MakeWire(W);
1627         B.Add(W,E1);
1628         B.Add(W,E2);
1629         B.Add(W,E3);
1630         B.Add(W,E4.Reversed());
1631         //cout<<"      wire for edge "<<nbee<<" is created"<<endl;
1632         //BRepTools::Write(W,"/dn02/users_Linux/skl/work/Bugs/14857/w.brep");
1633
1634         // make surface
1635
1636         double fp,lp;
1637         Handle(Geom_Curve) C1 = BRep_Tool::Curve(E1,fp,lp);
1638         //bool IsConicC1 = false;
1639         //if( C1->IsKind(STANDARD_TYPE(Geom_Conic)) ) {
1640         //  IsConicC1 = true;
1641         //  cout<<"C1 - Geom_Conic"<<endl;
1642         //}
1643         if( C1->IsKind(STANDARD_TYPE(Geom_Line)) || C1->IsKind(STANDARD_TYPE(Geom_Conic)) ) {
1644           C1 = new Geom_TrimmedCurve(C1,fp,lp);
1645         }
1646         //if(IsConicC1) {
1647         //  double tol = BRep_Tool::Tolerance(E1);
1648         //  GeomConvert_ApproxCurve ApxC1(C1,tol,GeomAbs_C1,10,5);
1649         //  C1 = ApxC1.Curve();
1650         //}
1651         Handle(Geom_Curve) C3 = BRep_Tool::Curve(E3,fp,lp);
1652         if( C3->IsKind(STANDARD_TYPE(Geom_Line)) || C3->IsKind(STANDARD_TYPE(Geom_Conic)) ) {
1653           C3 = new Geom_TrimmedCurve(C3,fp,lp);
1654         }
1655         //filebuf fic;
1656         //ostream os(&fic);
1657         //os.precision(15);
1658         Handle(Geom_BSplineCurve) CE1 =
1659           GeomConvert::CurveToBSplineCurve(C1,Convert_RationalC1);
1660         if(CE1->Degree()<3)
1661           CE1->IncreaseDegree(3);
1662         Handle(Geom_BSplineCurve) CE2 =
1663           GeomConvert::CurveToBSplineCurve(C2,Convert_RationalC1);
1664         if(CE2->Degree()<3)
1665           CE2->IncreaseDegree(3);
1666         Handle(Geom_BSplineCurve) CE3 =
1667           GeomConvert::CurveToBSplineCurve(C3,Convert_RationalC1);
1668         if(CE3->Degree()<3)
1669           CE3->IncreaseDegree(3);
1670         Handle(Geom_BSplineCurve) CE4 =
1671           GeomConvert::CurveToBSplineCurve(C4,Convert_RationalC1);
1672         if(CE4->Degree()<3)
1673           CE4->IncreaseDegree(3);
1674         //cout<<"CE1->Degree()="<<CE1->Degree()<<" CE2->Degree()="<<CE2->Degree()
1675         //    <<" CE3->Degree()="<<CE3->Degree()<<" CE4->Degree()="<<CE4->Degree()<<endl;
1676         //if(fic.open("/dn02/users_Linux/skl/work/Bugs/14857/ce1.brep",ios::out)) {
1677         //  os<<"DrawTrSurf_BSplineCurve"<<endl;
1678         //  GeomTools::Write(CE1,os);
1679         //  fic.close();
1680         //}
1681
1682         Handle(Geom_Surface) BS;
1683         try {
1684           GeomFill_BSplineCurves GF(CE1,CE2,CE3,CE4,GeomFill_CoonsStyle);
1685           //GeomFill_BSplineCurves GF(CE1,CE2,CE3,CE4,GeomFill_StretchStyle);
1686           BS = GF.Surface();
1687         }
1688         catch(...) {
1689           MESSAGE ("      can not create BSplineSurface - create Bezier");
1690           int NbP=26;
1691           TColgp_Array2OfPnt Points(1,NbP,1,NbP);
1692           double fp1,lp1,fp2,lp2;
1693           Handle(Geom_Curve) C1 = BRep_Tool::Curve(E1,fp1,lp1);
1694           Handle(Geom_Curve) C3 = BRep_Tool::Curve(E3,fp2,lp2);
1695           gp_Pnt P1C1,P2C1;
1696           C1->D0(fp1,P1C1);
1697           C1->D0(lp1,P2C1);
1698           gp_Pnt P1C3,P2C3;
1699           C3->D0(fp2,P1C3);
1700           C3->D0(lp2,P2C3);
1701           int n1,n2;
1702           double fp,lp;
1703           // get points from C1
1704           if(P1.Distance(P1C1)<1.e-6) {
1705             fp = fp1;
1706             lp = lp1;
1707           }
1708           else {
1709             fp = lp1;
1710             lp = fp1;
1711           }
1712           double step = (lp-fp)/(NbP-1);
1713           Points.SetValue(1,1,P1);
1714           double par = fp;
1715           for(n1=2; n1<NbP; n1++) {
1716             gp_Pnt P;
1717             par += step;
1718             C1->D0(par,P);
1719             Points.SetValue(1,n1,P);
1720           }
1721           Points.SetValue(1,NbP,P2);
1722           // get points from C3
1723           if(P4.Distance(P1C3)<1.e-6) {
1724             fp = fp2;
1725             lp = lp2;
1726           }
1727           else {
1728             fp = lp2;
1729             lp = fp2;
1730           }
1731           step = (lp-fp)/(NbP-1);
1732           Points.SetValue(NbP,1,P4);
1733           par = fp;
1734           for(n1=2; n1<NbP; n1++) {
1735             gp_Pnt P;
1736             par += step;
1737             C3->D0(par,P);
1738             Points.SetValue(NbP,n1,P);
1739           }
1740           Points.SetValue(NbP,NbP,P3);
1741           // create isolines and get points from them
1742           for(n1=1; n1<=NbP; n1++) {
1743             gp_Pnt PI1 = Points.Value(1,n1);
1744             gp_Pnt PI2 = Points.Value(NbP,n1);
1745             Handle(TColgp_HArray1OfPnt) HAP = new TColgp_HArray1OfPnt(1,2);
1746             HAP->SetValue(1,PI1);
1747             HAP->SetValue(2,PI2);
1748             GeomAPI_Interpolate anInt(HAP,Standard_False,1.e-7);
1749             anInt.Load(aDir1,aDir2);
1750             anInt.Perform();
1751             Handle(Geom_Curve) iso = anInt.Curve();
1752             fp = iso->FirstParameter();
1753             lp = iso->LastParameter();
1754             step = (lp-fp)/(NbP-1);
1755             par = fp;
1756             TopoDS_Compound VComp;
1757             B.MakeCompound(VComp);
1758             for(n2=2; n2<NbP; n2++) {
1759               gp_Pnt P;
1760               par += step;
1761               iso->D0(par,P);
1762               Points.SetValue(n2,n1,P);
1763             }
1764           }
1765           // create surface and face
1766           //Handle(Geom_BezierSurface) BS = new Geom_BezierSurface(Points);
1767           BS = new Geom_BezierSurface(Points);
1768         }
1769
1770         BRepBuilderAPI_MakeFace BB(BS,W);
1771         TopoDS_Face NewF = BB.Face();
1772         Handle(ShapeFix_Face) sff = new ShapeFix_Face(NewF);
1773         sff->Perform();
1774         sff->FixOrientation();
1775         TopoDS_Face FixedFace = sff->Face();
1776         aNewFs.Append(FixedFace);
1777         VPE.Add(E1,FixedFace);
1778         //cout<<"      face for edge "<<nbee<<" is created"<<endl;
1779         //BRepTools::Write(FixedFace,"/dn02/users_Linux/skl/work/Bugs/14857/f.brep");
1780       }
1781       // make shell
1782       TopoDS_Shell aShell;
1783       B.MakeShell(aShell);
1784       for(int nf=1; nf<=aNewFs.Length(); nf++) {
1785         B.Add(aShell,aNewFs(nf));
1786       }
1787       B.Add(aShell,F1);
1788       B.Add(aShell,F2);
1789
1790       // make sewing for this shell
1791       Handle(BRepBuilderAPI_Sewing) aSewing = new BRepBuilderAPI_Sewing;
1792       aSewing->SetTolerance(Precision::Confusion());
1793       aSewing->SetFaceMode(Standard_True);
1794       aSewing->SetFloatingEdgesMode(Standard_False);
1795       aSewing->SetNonManifoldMode(Standard_False);
1796       for ( anExp.Init( aShell, TopAbs_FACE ); anExp.More(); anExp.Next() ) {
1797         aSewing->Add(anExp.Current());
1798       }
1799       aSewing->Perform();
1800       MESSAGE ("    shell for face "<<nbff<<" is created");
1801       const TopoDS_Shape aSewShape = aSewing->SewedShape();
1802       //BRepTools::Write(aSewShape,"/dn02/users_Linux/skl/work/Bugs/14857/sew.brep");
1803       if( aSewShape.ShapeType() == TopAbs_SHELL ) {
1804         aShell = TopoDS::Shell(aSewShape);
1805         GProp_GProps aSystem;
1806         BRepGProp::VolumeProperties(aShell, aSystem);
1807         if(aSystem.Mass()<0) {
1808           //cout<<"aSewShape is reversed"<<endl;
1809           aShell.Reverse();
1810         }
1811         if(BRep_Tool::IsClosed(aShell)) {
1812           TopoDS_Solid aSolid;
1813           B.MakeSolid(aSolid);
1814           B.Add(aSolid,aShell);
1815           B.Add(aComp,aSolid);
1816           MESSAGE ("    solid for face "<<nbff<<" is created");
1817         }
1818         else {
1819           B.Add(aComp,aShell);
1820           MESSAGE ("    solid for face "<<nbff<<" is not created");
1821         }
1822       }
1823       else {
1824         B.Add(aComp,aShell);
1825         MESSAGE ("    solid for face "<<nbff<<" is not created");
1826       }
1827       //cout<<"    solid for face "<<nbff<<" is created"<<endl;
1828
1829       //Handle(ShapeFix_Shell) sfs = new ShapeFix_Shell(aShell);
1830       //sfs->Perform();
1831       //TopoDS_Shell FixedShell = sfs->Shell();
1832       /*
1833       GProp_GProps aSystem;
1834       BRepGProp::VolumeProperties(FixedShell, aSystem);
1835       if(aSystem.Mass()<0) {
1836         //cout<<"aSewShape is reversed"<<endl;
1837         FixedShell.Reverse();
1838       }
1839       if(BRep_Tool::IsClosed(FixedShell)) {
1840         TopoDS_Solid aSolid;
1841         B.MakeSolid(aSolid);
1842         B.Add(aSolid,aShell);
1843         B.Add(aComp,aSolid);
1844       }
1845       else {
1846         B.Add(aComp,FixedShell);
1847       }
1848       */
1849     }
1850   }
1851
1852   //BRepTools::Write(aComp,"/dn02/users_Linux/skl/work/Bugs/14857/comp.brep");
1853   return aComp;
1854 }
1855
1856
1857 //=======================================================================
1858 //function : CreatePipeBiNormalAlongVector
1859 //purpose  : auxilary for Execute()
1860 //=======================================================================
1861 static TopoDS_Shape CreatePipeBiNormalAlongVector(const TopoDS_Wire& aWirePath,
1862                                                   GEOMImpl_IPipe* aCI)
1863 {
1864   GEOMImpl_IPipeBiNormal* aCIBN = (GEOMImpl_IPipeBiNormal*)aCI;
1865
1866   Handle(GEOM_Function) aRefBase = aCIBN->GetBase();
1867   Handle(GEOM_Function) aRefVec = aCIBN->GetVector();
1868   TopoDS_Shape aShapeBase = aRefBase->GetValue();
1869   TopoDS_Shape aShapeVec = aRefVec->GetValue();
1870
1871   if (aShapeBase.IsNull()) {
1872     if(aCIBN) delete aCIBN;
1873     Standard_NullObject::Raise("MakePipe aborted : null base argument");
1874   }
1875
1876   TopoDS_Shape aProf;
1877   if( aShapeBase.ShapeType() == TopAbs_EDGE) {
1878     aProf = BRepBuilderAPI_MakeWire(TopoDS::Edge(aShapeBase)).Shape();
1879   }
1880   else if( aShapeBase.ShapeType() == TopAbs_WIRE) {
1881     aProf = aShapeBase;
1882   }
1883   else if( aShapeBase.ShapeType() == TopAbs_FACE) {
1884     TopExp_Explorer wexp(aShapeBase,TopAbs_WIRE);
1885     aProf = wexp.Current();
1886   }
1887   else {
1888     Standard_TypeMismatch::Raise
1889       ("MakePipe aborted : invalid type of base");
1890   }
1891   BRepOffsetAPI_MakePipeShell PipeBuilder(aWirePath);
1892   PipeBuilder.Add(aProf);
1893
1894   if (aShapeVec.IsNull()) {
1895     if(aCIBN) delete aCIBN;
1896     Standard_NullObject::Raise
1897       ("MakePipe aborted : null vector argument");
1898   }
1899   if (aShapeVec.ShapeType() != TopAbs_EDGE)
1900     Standard_TypeMismatch::Raise
1901       ("MakePipe aborted: invalid type of vector");
1902   TopoDS_Edge anEdge = TopoDS::Edge(aShapeVec);
1903   TopoDS_Vertex V1, V2;
1904   TopExp::Vertices(anEdge, V1, V2, Standard_True);
1905   if (V1.IsNull() || V2.IsNull())
1906     Standard_NullObject::Raise
1907       ("MakePipe aborted: vector is not defined");
1908   gp_Vec aVec(BRep_Tool::Pnt(V1), BRep_Tool::Pnt(V2));
1909   gp_Dir BiNormal(aVec);
1910   PipeBuilder.SetMode(BiNormal);
1911   PipeBuilder.Build();
1912   if( aShapeBase.ShapeType() == TopAbs_FACE) {
1913       PipeBuilder.MakeSolid();
1914   }
1915
1916   return PipeBuilder.Shape();
1917 }
1918
1919
1920 //=======================================================================
1921 //function : Execute
1922 //purpose  :
1923 //=======================================================================
1924 Standard_Integer GEOMImpl_PipeDriver::Execute(TFunction_Logbook& log) const
1925 {
1926   //cout<<"PipeDriver::Execute"<<endl;
1927   if (Label().IsNull()) return 0;
1928   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
1929   GEOMImpl_IPipe* aCI= 0;
1930   Standard_Integer aType = aFunction->GetType();
1931   if(aType == PIPE_BASE_PATH)
1932     aCI = new GEOMImpl_IPipe(aFunction);
1933   else if(aType == PIPE_DIFFERENT_SECTIONS)
1934     aCI = new GEOMImpl_IPipeDiffSect(aFunction);
1935   else if(aType == PIPE_SHELL_SECTIONS)
1936     aCI = new GEOMImpl_IPipeShellSect(aFunction);
1937   else if(aType == PIPE_SHELLS_WITHOUT_PATH)
1938     aCI = new GEOMImpl_IPipeShellSect(aFunction);
1939   else if(aType == PIPE_BI_NORMAL_ALONG_VECTOR)
1940     aCI = new GEOMImpl_IPipeBiNormal(aFunction);
1941   else
1942     return 0;
1943
1944   TopoDS_Wire aWirePath;
1945   if(aType != PIPE_SHELLS_WITHOUT_PATH) {
1946     // working with path
1947     Handle(GEOM_Function) aRefPath = aCI->GetPath();
1948     TopoDS_Shape aShapePath = aRefPath->GetValue();
1949
1950     if (aShapePath.IsNull()) {
1951       MESSAGE ("Driver : path is null");
1952       if(aCI) delete aCI;
1953       Standard_NullObject::Raise("MakePipe aborted : null path argument");
1954     }
1955
1956     // Get path contour
1957     if (aShapePath.ShapeType() == TopAbs_WIRE) {
1958       aWirePath = TopoDS::Wire(aShapePath);
1959     }
1960     else {
1961       if (aShapePath.ShapeType() == TopAbs_EDGE) {
1962         TopoDS_Edge anEdge = TopoDS::Edge(aShapePath);
1963         aWirePath = BRepBuilderAPI_MakeWire(anEdge);
1964       }
1965       else {
1966         if(aCI) delete aCI;
1967         Standard_TypeMismatch::Raise("MakePipe aborted : path shape is neither a wire nor an edge");
1968       }
1969     }
1970   }
1971
1972   TopoDS_Shape aShape;
1973
1974   if (aType == PIPE_BASE_PATH)
1975   {
1976     Handle(GEOM_Function) aRefBase = aCI->GetBase();
1977     TopoDS_Shape aShapeBase = aRefBase->GetValue();
1978
1979     if (aShapeBase.IsNull()) {
1980       if(aCI) delete aCI;
1981       Standard_NullObject::Raise("MakePipe aborted : null base argument");
1982     }
1983
1984     // Make pipe
1985     aShape = BRepOffsetAPI_MakePipe(aWirePath, aShapeBase);
1986   }
1987
1988   //building pipe with different sections
1989   else if (aType == PIPE_DIFFERENT_SECTIONS) {
1990     GEOMImpl_IPipeDiffSect* aCIDS = (GEOMImpl_IPipeDiffSect*)aCI;
1991     //GEOMImpl_IPipeDiffSect* aCIDS = static_cast<GEOMImpl_IPipeDiffSect*>(aCI);
1992     //BRepOffsetAPI_MakePipeShell aBuilder(aWirePath);
1993     Handle(TColStd_HSequenceOfTransient) aBasesObjs = aCIDS->GetBases ();
1994     Handle(TColStd_HSequenceOfTransient) aLocObjs = aCIDS->GetLocations ();
1995     Standard_Boolean aWithContact = (aCIDS->GetWithContactMode());
1996     Standard_Boolean aWithCorrect = (aCIDS->GetWithCorrectionMode());
1997
1998     Standard_Integer i =1, nbBases = aBasesObjs->Length(),
1999       nbLocs = (aLocObjs.IsNull() ? 0 :aLocObjs->Length());
2000
2001     if(nbLocs && nbLocs != nbBases) {
2002       if(aCI) delete aCI;
2003       Standard_ConstructionError::Raise("Number of sections is not equal to number of locations ");
2004     }
2005     TopTools_SequenceOfShape aSeqBases;
2006     TopTools_SequenceOfShape aSeqLocs;
2007     TopTools_SequenceOfShape aSeqFaces;
2008     for( ; i <= nbBases; i++) {
2009       Handle(Standard_Transient) anItem = aBasesObjs->Value(i);
2010       if(anItem.IsNull())
2011         continue;
2012       Handle(GEOM_Function) aRefBase = Handle(GEOM_Function)::DownCast(anItem);
2013       if(aRefBase.IsNull())
2014         continue;
2015       TopoDS_Shape aShapeBase = aRefBase->GetValue();
2016       if(aShapeBase.IsNull())
2017         continue;
2018       TopAbs_ShapeEnum aTypeBase = aShapeBase.ShapeType();
2019
2020       //if for section was specified face with a few wires then a few
2021       //    pipes were build and make solid
2022       Standard_Boolean NeedCreateSolid = Standard_False;
2023       if(aTypeBase == TopAbs_SHELL) {
2024         // create wire as boundary contour if shell is no closed
2025         // get free boundary shapes
2026         ShapeAnalysis_FreeBounds anAnalizer( aShapeBase );
2027         TopoDS_Compound aClosed = anAnalizer.GetClosedWires();
2028         TopExp_Explorer anExp;
2029         TopoDS_Shape aWire;
2030         Standard_Integer NbWires = 0;
2031         for ( anExp.Init( aClosed, TopAbs_WIRE ); anExp.More(); anExp.Next() ) {
2032           NbWires++;
2033           aWire = anExp.Current();
2034         }
2035         if(NbWires!=1) {
2036           // bad case
2037           if(aCI) delete aCI;
2038           Standard_ConstructionError::Raise("Bad shell is used as section ");
2039         }
2040         NeedCreateSolid = Standard_True;
2041         aSeqFaces.Append(aShapeBase);
2042         aSeqBases.Append(aWire);
2043       }
2044       else if(aTypeBase == TopAbs_FACE) {
2045         NeedCreateSolid = Standard_True;
2046         //for case one path should be used other type function
2047         aSeqFaces.Append(aShapeBase);
2048         TopExp_Explorer aExpW(aShapeBase,TopAbs_WIRE);
2049         for( ; aExpW.More(); aExpW.Next())
2050         {
2051           TopoDS_Shape aWireProf = aExpW.Current();
2052           aSeqBases.Append(aWireProf);
2053         }
2054       }
2055       else if(aTypeBase == TopAbs_WIRE || aTypeBase == TopAbs_VERTEX) {
2056         aSeqBases.Append(aShapeBase);
2057       }
2058       else if(aTypeBase == TopAbs_EDGE) {
2059         TopoDS_Edge anEdge = TopoDS::Edge(aShapeBase);
2060         TopoDS_Shape aWireProf = BRepBuilderAPI_MakeWire(anEdge);
2061         aSeqBases.Append(aWireProf);
2062       }
2063       if(nbLocs) {
2064         Handle(Standard_Transient) anItemLoc = aLocObjs->Value(i);
2065         if(anItemLoc.IsNull())
2066           continue;
2067         Handle(GEOM_Function) aRefLoc = Handle(GEOM_Function)::DownCast(anItemLoc);
2068         TopoDS_Shape aShapeLoc = aRefLoc->GetValue();
2069         if(aShapeLoc.IsNull() || aShapeLoc.ShapeType() != TopAbs_VERTEX)
2070           continue;
2071         aSeqLocs.Append(aShapeLoc);
2072       }
2073     }
2074
2075     nbLocs = aSeqLocs.Length();
2076
2077     // skl 02.05.2007
2078     TopTools_SequenceOfShape Edges;
2079     if(nbLocs>0) {
2080       // we have to check that each location shape is a vertex from
2081       // path and update aSeqLocs if it is needed (and possible)
2082       TColgp_SequenceOfPnt PLocs;
2083       for(i=1; i<=nbLocs; i++) {
2084         TopoDS_Vertex V = TopoDS::Vertex(aSeqLocs.Value(i));
2085         PLocs.Append(BRep_Tool::Pnt(V));
2086       }
2087       //TopTools_SequenceOfShape Edges;
2088       TopExp_Explorer anExp;
2089       for ( anExp.Init( aWirePath, TopAbs_EDGE ); anExp.More(); anExp.Next() ) {
2090         Edges.Append(anExp.Current());
2091       }
2092       int nbEdges = Edges.Length();
2093       ShapeAnalysis_Edge sae;
2094       TopoDS_Edge edge = TopoDS::Edge(Edges.First());
2095       double tol = BRep_Tool::Tolerance(edge);
2096       TopoDS_Vertex VF = sae.FirstVertex(edge);
2097       gp_Pnt PF = BRep_Tool::Pnt(VF);
2098       //cout<<"PF("<<PF.X()<<","<<PF.Y()<<","<<PF.Z()<<")"<<endl;
2099       if( PF.Distance(PLocs.First()) > tol ) {
2100         if(aCI) delete aCI;
2101         Standard_ConstructionError::Raise
2102           ("First location shapes is not coincided with first vertex of aWirePath");
2103       }
2104       aSeqLocs.ChangeValue(1) = VF;
2105       edge = TopoDS::Edge(Edges.Last());
2106       tol = BRep_Tool::Tolerance(edge);
2107       TopoDS_Vertex VL = sae.LastVertex(edge);
2108       gp_Pnt PL = BRep_Tool::Pnt(VL);
2109       if( PL.Distance(PLocs.Last()) > tol ) {
2110         if(aCI) delete aCI;
2111         Standard_ConstructionError::Raise
2112           ("Last location shapes is not coincided with last vertex of aWirePath");
2113       }
2114       aSeqLocs.ChangeValue(nbLocs) = VL;
2115       int jcurr = 2;
2116       for(i=1; i<=Edges.Length() && jcurr<nbLocs; i++) {
2117         TopoDS_Edge E = TopoDS::Edge(Edges.Value(i));
2118         tol = BRep_Tool::Tolerance(edge);
2119         TopoDS_Vertex V1 = sae.FirstVertex(E);
2120         TopoDS_Vertex V2 = sae.LastVertex(E);
2121         gp_Pnt P1 = BRep_Tool::Pnt(V1);
2122         gp_Pnt P2 = BRep_Tool::Pnt(V2);
2123         if( P2.Distance(PLocs.Value(jcurr)) < tol ) {
2124           aSeqLocs.ChangeValue(jcurr) = V2;
2125           jcurr++;
2126         }
2127         else {
2128           // find distance between E and aLocs(jcurr)
2129           double fp,lp;
2130           Handle(Geom_Curve) C = BRep_Tool::Curve(E,fp,lp);
2131           GeomAPI_ProjectPointOnCurve PPC (PLocs.Value(jcurr),C);
2132           if( PPC.NbPoints()>0 &&
2133               PLocs.Value(jcurr).Distance(PPC.Point(1)) < tol ) {
2134             double param = PPC.Parameter(1);
2135             gp_Pnt PC1;
2136             C->D0(param,PC1);
2137             // split current edge
2138             Handle(Geom_TrimmedCurve) tc1 = new Geom_TrimmedCurve(C,fp,param);
2139             Handle(Geom_TrimmedCurve) tc2 = new Geom_TrimmedCurve(C,param,lp);
2140             TopoDS_Edge E1,E2;
2141             BRep_Builder B;
2142             gp_Pnt Pfp;
2143             C->D0(fp,Pfp);
2144             if(Pfp.Distance(P1)<tol) {
2145               B.MakeEdge(E1,tc1,tol);
2146               B.Add(E1,V1);
2147               TopoDS_Shape tmpV = aSeqLocs.Value(jcurr).Oriented(TopAbs_REVERSED);
2148               B.Add(E1,TopoDS::Vertex(tmpV));
2149               B.MakeEdge(E2,tc2,tol);
2150               tmpV = aSeqLocs.Value(jcurr).Oriented(TopAbs_FORWARD);
2151               B.Add(E2,TopoDS::Vertex(tmpV));
2152               B.Add(E2,V2);
2153             }
2154             else {
2155               B.MakeEdge(E1,tc2,tol);
2156               TopoDS_Shape tmpV = aSeqLocs.Value(jcurr).Oriented(TopAbs_FORWARD);
2157               B.Add(E1,TopoDS::Vertex(tmpV));
2158               B.Add(E1,V1);
2159               E1.Reverse();
2160               B.MakeEdge(E2,tc1,tol);
2161               B.Add(E2,V2);
2162               tmpV = aSeqLocs.Value(jcurr).Oriented(TopAbs_REVERSED);
2163               B.Add(E2,TopoDS::Vertex(tmpV));
2164               E2.Reverse();
2165             }
2166             jcurr++;
2167             Edges.Remove(i);
2168             Edges.InsertAfter(i-1,E1);
2169             Edges.InsertAfter(i,E2);
2170           }
2171         }
2172       }
2173       if(nbEdges<Edges.Length()) {
2174         // one of edges was splitted => we have to update WirePath
2175         BRep_Builder B;
2176         TopoDS_Wire W;
2177         B.MakeWire(W);
2178         for(i=1; i<=Edges.Length(); i++) {
2179           B.Add(W,TopoDS::Edge(Edges.Value(i)));
2180         }
2181         aWirePath = W;
2182       }
2183     }
2184
2185     // check curvature of wire for condition that
2186     // max summary angle between directions along
2187     // wire path must be < 4*PI. If not - split wire
2188     // and seguences of shapes, perform pipe for each
2189     // and make sewing after that
2190     double fp,lp;
2191     Handle(Geom_Curve) C = BRep_Tool::Curve(TopoDS::Edge(Edges.Value(1)),fp,lp);
2192     gp_Pnt P1,P2;
2193     gp_Vec Vec1,Vec2;
2194     C->D1(fp,P1,Vec1);
2195     C->D1(lp,P2,Vec2);
2196     double SumAng = fabs(Vec1.Angle(Vec2));
2197     Vec1 = Vec2;
2198     P1 = P2;
2199     TColStd_SequenceOfInteger SplitEdgeNums,SplitLocNums;
2200     int LastLoc = 1;
2201     //cout<<"Edges.Length()="<<Edges.Length()<<endl;
2202     for(i=2; i<=Edges.Length(); i++) {
2203       TopoDS_Edge edge = TopoDS::Edge(Edges.Value(i));
2204       double tol = BRep_Tool::Tolerance(edge);
2205       Handle(Geom_Curve) C = BRep_Tool::Curve(edge,fp,lp);
2206       C->D1(lp,P2,Vec2);
2207       double ang = fabs(Vec1.Angle(Vec2));
2208       SumAng += ang;
2209       if(SumAng>4*PI) {
2210         SumAng = ang;
2211         SplitEdgeNums.Append(i-1);
2212         int j;
2213         for(j=LastLoc+1; j<=aSeqLocs.Length(); j++) {
2214           TopoDS_Vertex aVert = TopoDS::Vertex(aSeqLocs.Value(j));
2215           gp_Pnt P = BRep_Tool::Pnt(aVert);
2216           if( P1.Distance(P) < tol ) {
2217             SplitLocNums.Append(j);
2218             LastLoc = j;
2219             break;
2220           }
2221         }
2222       }
2223       Vec1 = Vec2;
2224       P1 = P2;
2225     }
2226
2227     //cout<<"SplitEdgeNums.Length()="<<SplitEdgeNums.Length()<<endl;
2228     //cout<<"SplitLocNums.Length()="<<SplitLocNums.Length()<<endl;
2229     if( SplitLocNums.Length()==SplitEdgeNums.Length() && SplitEdgeNums.Length()>0 ) {
2230       TopTools_SequenceOfShape aSeqRes;
2231       int nn, num1 = 1, num2 = 1;
2232       for(nn=1; nn<=SplitEdgeNums.Length(); nn++) {
2233         // create wirepath and sequences of shapes
2234         BRep_Builder B;
2235         TopoDS_Wire tmpW;
2236         B.MakeWire(tmpW);
2237         for(i=num1; i<=SplitEdgeNums.Value(nn); i++) {
2238           B.Add(tmpW,TopoDS::Edge(Edges.Value(i)));
2239         }
2240         num1 = SplitEdgeNums.Value(nn) + 1;
2241         TopTools_SequenceOfShape aTmpSeqBases;
2242         TopTools_SequenceOfShape aTmpSeqLocs;
2243         for(i=num2; i<=SplitLocNums.Value(nn); i++) {
2244           aTmpSeqBases.Append(aSeqBases.Value(i));
2245           aTmpSeqLocs.Append(aSeqLocs.Value(i));
2246         }
2247         num2 = SplitLocNums.Value(nn);
2248         // make pipe
2249         BRepOffsetAPI_MakePipeShell aBuilder(tmpW);
2250         Standard_Integer nbShapes = aTmpSeqBases.Length();
2251         for(i=1; i<=nbShapes; i++) {
2252           TopoDS_Shape aShapeLoc = aTmpSeqLocs.Value(i);
2253           TopoDS_Vertex aVert = TopoDS::Vertex(aShapeLoc);
2254           aBuilder.Add(aTmpSeqBases.Value(i), aVert, aWithContact, aWithCorrect);
2255         }
2256         if(!aBuilder.IsReady()) {
2257           if(aCI) delete aCI;
2258           Standard_ConstructionError::Raise("Invalid input data for building PIPE: bases are invalid");
2259         }
2260         aBuilder.Build();
2261         TopoDS_Shape resShape = aBuilder.Shape();
2262         aSeqRes.Append(resShape);
2263       }
2264       // create wirepath and sequences of shapes for last part
2265       BRep_Builder B;
2266       TopoDS_Wire tmpW;
2267       B.MakeWire(tmpW);
2268       for(i=num1; i<=Edges.Length(); i++) {
2269         B.Add(tmpW,TopoDS::Edge(Edges.Value(i)));
2270       }
2271       TopTools_SequenceOfShape aTmpSeqBases;
2272       TopTools_SequenceOfShape aTmpSeqLocs;
2273       for(i=num2; i<=aSeqLocs.Length(); i++) {
2274         aTmpSeqBases.Append(aSeqBases.Value(i));
2275         aTmpSeqLocs.Append(aSeqLocs.Value(i));
2276       }
2277       // make pipe for last part
2278       BRepOffsetAPI_MakePipeShell aBuilder(tmpW);
2279       Standard_Integer nbShapes = aTmpSeqBases.Length();
2280       for(i=1; i<=nbShapes; i++) {
2281         TopoDS_Shape aShapeLoc = aTmpSeqLocs.Value(i);
2282         TopoDS_Vertex aVert = TopoDS::Vertex(aShapeLoc);
2283         aBuilder.Add(aTmpSeqBases.Value(i), aVert, aWithContact, aWithCorrect);
2284       }
2285       if(!aBuilder.IsReady()) {
2286         if(aCI) delete aCI;
2287         Standard_ConstructionError::Raise("Invalid input data for building PIPE: bases are invalid");
2288       }
2289       aBuilder.Build();
2290       TopoDS_Shape resShape = aBuilder.Shape();
2291       aSeqRes.Append(resShape);
2292       // make sewing for result
2293       Handle(BRepBuilderAPI_Sewing) aSewing = new BRepBuilderAPI_Sewing;
2294       aSewing->SetTolerance(Precision::Confusion());
2295       aSewing->SetFaceMode(Standard_True);
2296       aSewing->SetFloatingEdgesMode(Standard_False);
2297       aSewing->SetNonManifoldMode(Standard_False);
2298       for(i=1; i<=aSeqRes.Length(); i++) {
2299         aSewing->Add(aSeqRes.Value(i));
2300       }
2301       aSewing->Perform();
2302       aShape = aSewing->SewedShape();
2303     }
2304     else {
2305       // old implementation without splitting
2306       BRepOffsetAPI_MakePipeShell aBuilder(aWirePath);
2307
2308       Standard_Integer nbShapes = aSeqBases.Length();
2309       Standard_Integer step = nbShapes/nbBases;
2310
2311       if(nbShapes < nbBases || fmod((double)nbShapes, (double)nbBases)) {
2312         if(aCI) delete aCI;
2313         Standard_ConstructionError::Raise("Invalid sections were specified for building pipe");
2314       }
2315       Standard_Integer ind =0;
2316       for( i=1; i  <= nbShapes && ind < nbShapes; i++) { //i+nbBases <= nbShapes
2317         TopTools_SequenceOfShape usedBases;
2318         Standard_Integer j = 1;
2319         for( ; j <= nbBases ; j++) {
2320           ind = i + (j-1)*step;
2321           TopoDS_Shape aWireProf = aSeqBases.Value(ind);
2322           usedBases.Append(aWireProf);
2323           if(nbLocs) {
2324             TopoDS_Shape aShapeLoc = aSeqLocs.Value(j);
2325             TopoDS_Vertex aVert = TopoDS::Vertex(aShapeLoc);
2326             aBuilder.Add(aWireProf,aVert,aWithContact,aWithCorrect);
2327           }
2328           else
2329             aBuilder.Add(aWireProf,aWithContact,aWithCorrect);
2330         }
2331       if(!aBuilder.IsReady()) {
2332         if(aCI) delete aCI;
2333         Standard_ConstructionError::Raise("Invalid input data for building PIPE: bases are invalid");
2334       }
2335       aBuilder.Build();
2336       aShape = aBuilder.Shape();
2337       aSeqFaces.Append(aShape);
2338       for( j = 1; j <=usedBases.Length(); j++)
2339         aBuilder.Delete(usedBases.Value(j));
2340       }
2341
2342       //for case if section is face
2343       if(aSeqFaces.Length() >1) {
2344         BRep_Builder aB;
2345         TopoDS_Compound aComp;
2346         aB.MakeCompound(aComp);
2347         for( i = 1; i <= aSeqFaces.Length(); i++)
2348           aB.Add(aComp,aSeqFaces.Value(i));
2349         aShape = aComp;
2350       }
2351     }
2352   }
2353
2354   //building pipe with shell sections
2355   else if (aType == PIPE_SHELL_SECTIONS) {
2356     aShape = CreatePipeForShellSections(aWirePath,aCI);
2357   }
2358
2359   //building pipe shell sections without path
2360   else if (aType == PIPE_SHELLS_WITHOUT_PATH) {
2361     aShape = CreatePipeShellsWithoutPath(aCI);
2362   }
2363
2364   //building a pipe with constant bi-normal along given vector
2365   else if (aType == PIPE_BI_NORMAL_ALONG_VECTOR) {
2366     aShape = CreatePipeBiNormalAlongVector(aWirePath, aCI);
2367   }
2368
2369   if (aCI) {
2370     delete aCI;
2371     aCI = 0;
2372   }
2373
2374   if (aShape.IsNull()) return 0;
2375
2376   BRepCheck_Analyzer ana (aShape, Standard_False);
2377   if (!ana.IsValid()) {
2378     ShapeFix_ShapeTolerance aSFT;
2379     aSFT.LimitTolerance(aShape,Precision::Confusion(),Precision::Confusion());
2380     Handle(ShapeFix_Shape) aSfs = new ShapeFix_Shape(aShape);
2381     aSfs->SetPrecision(Precision::Confusion());
2382     aSfs->Perform();
2383     aShape = aSfs->Shape();
2384
2385     ana.Init(aShape, Standard_False);
2386     if (!ana.IsValid())
2387       Standard_ConstructionError::Raise("Algorithm have produced an invalid shape result");
2388   }
2389
2390   // Glue (for bug 0020207)
2391   TopExp_Explorer anExpV (aShape, TopAbs_VERTEX);
2392   if (anExpV.More())
2393     aShape = GEOMImpl_GlueDriver::GlueFaces(aShape, Precision::Confusion(), Standard_True);
2394
2395   TopoDS_Shape aRes = GEOMImpl_IShapesOperations::CompsolidToCompound(aShape);
2396   aFunction->SetValue(aRes);
2397
2398   log.SetTouched(Label());
2399   return 1;
2400 }
2401
2402
2403 //=======================================================================
2404 //function :  GEOMImpl_PipeDriver_Type_
2405 //purpose  :
2406 //=======================================================================
2407 Standard_EXPORT Handle_Standard_Type& GEOMImpl_PipeDriver_Type_()
2408 {
2409
2410   static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);
2411   if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);
2412   static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);
2413   if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);
2414   static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);
2415   if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);
2416
2417
2418   static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};
2419   static Handle_Standard_Type _aType = new Standard_Type("GEOMImpl_PipeDriver",
2420                                                          sizeof(GEOMImpl_PipeDriver),
2421                                                          1,
2422                                                          (Standard_Address)_Ancestors,
2423                                                          (Standard_Address)NULL);
2424
2425   return _aType;
2426 }
2427
2428 //=======================================================================
2429 //function : DownCast
2430 //purpose  :
2431 //=======================================================================
2432 const Handle(GEOMImpl_PipeDriver) Handle(GEOMImpl_PipeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)
2433 {
2434   Handle(GEOMImpl_PipeDriver) _anOtherObject;
2435
2436   if (!AnObject.IsNull()) {
2437      if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_PipeDriver))) {
2438        _anOtherObject = Handle(GEOMImpl_PipeDriver)((Handle(GEOMImpl_PipeDriver)&)AnObject);
2439      }
2440   }
2441
2442   return _anOtherObject ;
2443 }
2444