Salome HOME
Merge from V6_main 11/02/2013
[tools/medcoupling.git] / src / INTERP_KERNEL / Geometric2D / InterpKernelGeo2DQuadraticPolygon.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // Author : Anthony Geay (CEA/DEN)
20
21 #include "InterpKernelGeo2DQuadraticPolygon.hxx"
22 #include "InterpKernelGeo2DElementaryEdge.hxx"
23 #include "InterpKernelGeo2DEdgeArcCircle.hxx"
24 #include "InterpKernelGeo2DAbstractEdge.hxx"
25 #include "InterpKernelGeo2DEdgeLin.hxx"
26 #include "InterpKernelGeo2DBounds.hxx"
27 #include "InterpKernelGeo2DEdge.txx"
28
29 #include "NormalizedUnstructuredMesh.hxx"
30
31 #include <fstream>
32 #include <sstream>
33 #include <iomanip>
34 #include <cstring>
35 #include <limits>
36
37 using namespace INTERP_KERNEL;
38
39 namespace INTERP_KERNEL
40 {
41   const unsigned MAX_SIZE_OF_LINE_XFIG_FILE=1024;
42 }
43
44 QuadraticPolygon::QuadraticPolygon(const char *file)
45 {
46   char currentLine[MAX_SIZE_OF_LINE_XFIG_FILE];
47   std::ifstream stream(file);
48   stream.exceptions(std::ios_base::eofbit);
49   try
50     {
51       do
52         stream.getline(currentLine,MAX_SIZE_OF_LINE_XFIG_FILE);
53       while(strcmp(currentLine,"1200 2")!=0);
54       do
55         {
56           Edge *newEdge=Edge::BuildFromXfigLine(stream);
57           if(!empty())
58             newEdge->changeStartNodeWith(back()->getEndNode());
59           pushBack(newEdge);
60         }
61       while(1);
62     }
63   catch(std::ifstream::failure&)
64     {
65     }
66   front()->changeStartNodeWith(back()->getEndNode());
67 }
68
69 QuadraticPolygon::~QuadraticPolygon()
70 {
71 }
72
73 QuadraticPolygon *QuadraticPolygon::BuildLinearPolygon(std::vector<Node *>& nodes)
74 {
75   QuadraticPolygon *ret=new QuadraticPolygon;
76   std::size_t size=nodes.size();
77   for(std::size_t i=0;i<size;i++)
78     {
79       ret->pushBack(new EdgeLin(nodes[i],nodes[(i+1)%size]));
80       nodes[i]->decrRef();
81     }
82   return ret;
83 }
84
85 QuadraticPolygon *QuadraticPolygon::BuildArcCirclePolygon(std::vector<Node *>& nodes)
86 {
87   QuadraticPolygon *ret=new QuadraticPolygon;
88   std::size_t size=nodes.size();
89   for(std::size_t i=0;i<size/2;i++)
90     {
91       EdgeLin *e1,*e2;
92       e1=new EdgeLin(nodes[i],nodes[i+size/2]);
93       e2=new EdgeLin(nodes[i+size/2],nodes[(i+1)%(size/2)]);
94       SegSegIntersector inters(*e1,*e2);
95       bool colinearity=inters.areColinears();
96       delete e1; delete e2;
97       if(colinearity)
98         ret->pushBack(new EdgeLin(nodes[i],nodes[(i+1)%(size/2)]));
99       else
100         ret->pushBack(new EdgeArcCircle(nodes[i],nodes[i+size/2],nodes[(i+1)%(size/2)]));
101       nodes[i]->decrRef(); nodes[i+size/2]->decrRef();
102     }
103   return ret;
104 }
105
106 void QuadraticPolygon::BuildDbgFile(const std::vector<Node *>& nodes, const char *fileName)
107 {
108   std::ofstream file(fileName);
109   file << std::setprecision(16);
110   file << "  double coords[]=" << std::endl << "    { ";
111   for(std::vector<Node *>::const_iterator iter=nodes.begin();iter!=nodes.end();iter++)
112     {
113       if(iter!=nodes.begin())
114         file << "," << std::endl << "      ";
115       file << (*(*iter))[0] << ", " << (*(*iter))[1];
116     }
117   file << "};" << std::endl;
118 }
119
120 void QuadraticPolygon::closeMe() const
121 {
122   if(!front()->changeStartNodeWith(back()->getEndNode()))
123     throw(Exception("big error: not closed polygon..."));
124 }
125
126 void QuadraticPolygon::circularPermute()
127 {
128   if(_sub_edges.size()>1)
129     {
130       ElementaryEdge *first=_sub_edges.front();
131       _sub_edges.pop_front();
132       _sub_edges.push_back(first);
133     }
134 }
135
136 bool QuadraticPolygon::isButterflyAbs()
137 {
138   INTERP_KERNEL::Bounds b;
139   double xBary,yBary;
140   b.prepareForAggregation();
141   fillBounds(b); 
142   double dimChar=b.getCaracteristicDim();
143   b.getBarycenter(xBary,yBary);
144   applyGlobalSimilarity(xBary,yBary,dimChar);
145   //
146   return isButterfly();
147 }
148
149 bool QuadraticPolygon::isButterfly() const
150 {
151   for(std::list<ElementaryEdge *>::const_iterator it=_sub_edges.begin();it!=_sub_edges.end();it++)
152     {
153       Edge *e1=(*it)->getPtr();
154       std::list<ElementaryEdge *>::const_iterator it2=it;
155       it2++;
156       for(;it2!=_sub_edges.end();it2++)
157         {
158           MergePoints commonNode;
159           ComposedEdge *outVal1=new ComposedEdge;
160           ComposedEdge *outVal2=new ComposedEdge;
161           Edge *e2=(*it2)->getPtr();
162           if(e1->intersectWith(e2,commonNode,*outVal1,*outVal2))
163             {
164               Delete(outVal1);
165               Delete(outVal2);
166               return true;
167             }
168           Delete(outVal1);
169           Delete(outVal2);
170         }
171     }
172   return false;
173 }
174
175 void QuadraticPolygon::dumpInXfigFileWithOther(const ComposedEdge& other, const char *fileName) const
176 {
177   std::ofstream file(fileName);
178   const int resolution=1200;
179   Bounds box;
180   box.prepareForAggregation();
181   fillBounds(box);
182   other.fillBounds(box);
183   dumpInXfigFile(file,resolution,box);
184   other.ComposedEdge::dumpInXfigFile(file,resolution,box);
185 }
186
187 void QuadraticPolygon::dumpInXfigFile(const char *fileName) const
188 {
189   std::ofstream file(fileName);
190   const int resolution=1200;
191   Bounds box;
192   box.prepareForAggregation();
193   fillBounds(box);
194   dumpInXfigFile(file,resolution,box);
195 }
196
197 void QuadraticPolygon::dumpInXfigFile(std::ostream& stream, int resolution, const Bounds& box) const
198 {
199   stream << "#FIG 3.2  Produced by xfig version 3.2.5-alpha5" << std::endl;
200   stream << "Landscape" << std::endl;
201   stream << "Center" << std::endl;
202   stream << "Metric" << std::endl;
203   stream << "Letter" << std::endl;
204   stream << "100.00" << std::endl;
205   stream << "Single" << std::endl;
206   stream << "-2" << std::endl;
207   stream << resolution << " 2" << std::endl;
208   ComposedEdge::dumpInXfigFile(stream,resolution,box);
209 }
210
211 /*!
212  * Warning contrary to intersectWith method this method is \b NOT const. 'this' and 'other' are modified after call of this method.
213  */
214 double QuadraticPolygon::intersectWithAbs(QuadraticPolygon& other)
215 {
216   double ret=0.,xBaryBB,yBaryBB;
217   double fact=normalize(&other,xBaryBB,yBaryBB);
218   std::vector<QuadraticPolygon *> polygs=intersectMySelfWith(other);
219   for(std::vector<QuadraticPolygon *>::iterator iter=polygs.begin();iter!=polygs.end();iter++)
220     {
221       ret+=fabs((*iter)->getArea());
222       delete *iter;
223     }
224   return ret*fact*fact;
225 }
226
227 /*!
228  * This method splits 'this' with 'other' into smaller pieces localizable. 'mapThis' is a map that gives the correspondance between nodes contained in 'this' and node ids in a global mesh.
229  * In the same way, 'mapOther' gives the correspondance between nodes contained in 'other' and node ids in a global mesh from wich 'other' is extracted.
230  * This method has 1 out paramater : 'edgesThis', After the call of this method contains nodal connectivity (including type) of 'this' into globlal "this mesh".
231  * This method has 2 in/out parameters : 'subDivOther' and 'addCoo'.'otherEdgeIds' is useful to put values in 'edgesThis', 'subDivOther' and 'addCoo'.
232  * Size of 'otherEdgeIds' has to be equal to number of ElementaryEdges in 'other'. No check of that will be done.
233  * @param offset1 is the number of nodes contained in global mesh from which 'this' is extracted.
234  * @param offset2 is the sum of nodes contained in global mesh from which 'this' is extracted and 'other' is extracted.
235  * @param edgesInOtherColinearWithThis will be appended at the end of the vector with colinear edge ids of other (if any)
236  * @otherEdgeIds is a vector with the same size than other before calling this method. It gives in the same order the cell id in global other mesh.
237  */
238 void QuadraticPolygon::splitAbs(QuadraticPolygon& other, const std::map<INTERP_KERNEL::Node *,int>& mapThis, const std::map<INTERP_KERNEL::Node *,int>& mapOther, int offset1, int offset2 , const std::vector<int>& otherEdgeIds,
239                                 std::vector<int>& edgesThis, int cellIdThis, std::vector< std::vector<int> >& edgesInOtherColinearWithThis, std::vector< std::vector<int> >& subDivOther, std::vector<double>& addCoo)
240 {
241   double xBaryBB, yBaryBB;
242   double fact=normalizeExt(&other, xBaryBB, yBaryBB);
243   //
244   IteratorOnComposedEdge it1(this),it3(&other);
245   MergePoints merge;
246   ComposedEdge *c1=new ComposedEdge;
247   ComposedEdge *c2=new ComposedEdge;
248   int i=0;
249   std::map<INTERP_KERNEL::Node *,int> mapAddCoo;
250   for(it3.first();!it3.finished();it3.next(),i++)//iteration over 'other' _sub_edges
251     {
252       QuadraticPolygon otherTmp;
253       ElementaryEdge* curE3=it3.current();
254       otherTmp.pushBack(new ElementaryEdge(curE3->getPtr(),curE3->getDirection())); curE3->getPtr()->incrRef();
255       IteratorOnComposedEdge it2(&otherTmp);
256       for(it2.first();!it2.finished();it2.next())//iteration on subedges of 'other->_sub_edge'
257         {
258           ElementaryEdge* curE2=it2.current();
259           if(!curE2->isThereStartPoint())
260             it1.first();
261           else
262             it1=curE2->getIterator();
263           for(;!it1.finished();)//iteration over 'this' _sub_edges
264             {
265               ElementaryEdge* curE1=it1.current();
266               merge.clear();
267               if(curE1->getPtr()->intersectWith(curE2->getPtr(),merge,*c1,*c2))
268                 {
269                   if(!curE1->getDirection()) c1->reverse();
270                   if(!curE2->getDirection()) c2->reverse();
271                   UpdateNeighbours(merge,it1,it2,c1,c2);
272                   //Substitution of simple edge by sub-edges.
273                   delete curE1; // <-- destroying simple edge coming from pol1
274                   delete curE2; // <-- destroying simple edge coming from pol2
275                   it1.insertElemEdges(c1,true);// <-- 2nd param is true to go next.
276                   it2.insertElemEdges(c2,false);// <-- 2nd param is false to avoid to go next.
277                   curE2=it2.current();
278                   //
279                   it1.assignMySelfToAllElems(c2);//To avoid that others
280                   SoftDelete(c1);
281                   SoftDelete(c2);
282                   c1=new ComposedEdge;
283                   c2=new ComposedEdge;
284                 }
285               else
286                 {
287                   UpdateNeighbours(merge,it1,it2,curE1,curE2);
288                   it1.next();
289                 }
290             }
291         }
292       if(otherTmp.presenceOfOn())
293         edgesInOtherColinearWithThis[otherEdgeIds[i]].push_back(cellIdThis);
294       if(otherTmp._sub_edges.size()>1)
295         {
296           for(std::list<ElementaryEdge *>::const_iterator it=otherTmp._sub_edges.begin();it!=otherTmp._sub_edges.end();it++)
297             (*it)->fillGlobalInfoAbs2(mapThis,mapOther,offset1,offset2,/**/fact,xBaryBB,yBaryBB,/**/subDivOther[otherEdgeIds[i]],addCoo,mapAddCoo);
298         }
299     }
300   Delete(c1);
301   Delete(c2);
302   //
303   for(std::list<ElementaryEdge *>::const_iterator it=_sub_edges.begin();it!=_sub_edges.end();it++)
304     (*it)->fillGlobalInfoAbs(mapThis,mapOther,offset1,offset2,/**/fact,xBaryBB,yBaryBB,/**/edgesThis,addCoo,mapAddCoo);
305   //
306 }
307
308 /*!
309  * This method builds from descending conn of a quadratic polygon stored in crude mode (MEDCoupling). Descending conn is in FORTRAN relative mode in order to give the
310  * orientation of edge.
311  */
312 void QuadraticPolygon::buildFromCrudeDataArray(const std::map<int,INTERP_KERNEL::Node *>& mapp, bool isQuad, const int *nodalBg, const double *coords,
313                                                const int *descBg, const int *descEnd, const std::vector<std::vector<int> >& intersectEdges)
314 {
315   std::size_t nbOfSeg=std::distance(descBg,descEnd);
316   for(std::size_t i=0;i<nbOfSeg;i++)
317     {
318       appendEdgeFromCrudeDataArray(i,mapp,isQuad,nodalBg,coords,descBg,descEnd,intersectEdges);
319     }
320 }
321
322 void QuadraticPolygon::appendEdgeFromCrudeDataArray(std::size_t edgePos, const std::map<int,INTERP_KERNEL::Node *>& mapp, bool isQuad, const int *nodalBg, const double *coords,
323                                                     const int *descBg, const int *descEnd, const std::vector<std::vector<int> >& intersectEdges)
324 {
325   if(!isQuad)
326     {
327       bool direct=descBg[edgePos]>0;
328       int edgeId=abs(descBg[edgePos])-1;
329       const std::vector<int>& subEdge=intersectEdges[edgeId];
330       std::size_t nbOfSubEdges=subEdge.size()/2;
331       for(std::size_t j=0;j<nbOfSubEdges;j++)
332         appendSubEdgeFromCrudeDataArray(0,j,direct,edgeId,subEdge,mapp);
333     }
334   else
335     {
336       std::size_t nbOfSeg=std::distance(descBg,descEnd);
337       const double *st=coords+2*(nodalBg[edgePos]); 
338       INTERP_KERNEL::Node *st0=new INTERP_KERNEL::Node(st[0],st[1]);
339       const double *endd=coords+2*(nodalBg[(edgePos+1)%nbOfSeg]);
340       INTERP_KERNEL::Node *endd0=new INTERP_KERNEL::Node(endd[0],endd[1]);
341       const double *middle=coords+2*(nodalBg[edgePos+nbOfSeg]);
342       INTERP_KERNEL::Node *middle0=new INTERP_KERNEL::Node(middle[0],middle[1]);
343       EdgeLin *e1,*e2;
344       e1=new EdgeLin(st0,middle0);
345       e2=new EdgeLin(middle0,endd0);
346       SegSegIntersector inters(*e1,*e2);
347       bool colinearity=inters.areColinears();
348       delete e1; delete e2;
349       //
350       bool direct=descBg[edgePos]>0;
351       int edgeId=abs(descBg[edgePos])-1;
352       const std::vector<int>& subEdge=intersectEdges[edgeId];
353       std::size_t nbOfSubEdges=subEdge.size()/2;
354       if(colinearity)
355         {   
356           for(std::size_t j=0;j<nbOfSubEdges;j++)
357             appendSubEdgeFromCrudeDataArray(0,j,direct,edgeId,subEdge,mapp);
358         }
359       else
360         {
361           Edge *e=new EdgeArcCircle(st0,middle0,endd0,true);
362           for(std::size_t j=0;j<nbOfSubEdges;j++)
363             appendSubEdgeFromCrudeDataArray(e,j,direct,edgeId,subEdge,mapp);
364           e->decrRef();
365         }
366       st0->decrRef(); endd0->decrRef(); middle0->decrRef();
367     }
368 }
369
370 void QuadraticPolygon::appendSubEdgeFromCrudeDataArray(Edge *baseEdge, std::size_t j, bool direct, int edgeId, const std::vector<int>& subEdge, const std::map<int,INTERP_KERNEL::Node *>& mapp)
371 {
372   std::size_t nbOfSubEdges=subEdge.size()/2;
373   if(!baseEdge)
374     {//it is not a quadratic subedge
375       Node *start=(*mapp.find(direct?subEdge[2*j]:subEdge[2*nbOfSubEdges-2*j-1])).second;
376       Node *end=(*mapp.find(direct?subEdge[2*j+1]:subEdge[2*nbOfSubEdges-2*j-2])).second;
377       ElementaryEdge *e=ElementaryEdge::BuildEdgeFromCrudeDataArray(true,start,end);
378       pushBack(e);
379     }
380   else
381     {//it is a quadratic subedge
382       Node *start=(*mapp.find(direct?subEdge[2*j]:subEdge[2*nbOfSubEdges-2*j-1])).second;
383       Node *end=(*mapp.find(direct?subEdge[2*j+1]:subEdge[2*nbOfSubEdges-2*j-2])).second;
384       Edge *ee=baseEdge->buildEdgeLyingOnMe(start,end);
385       ElementaryEdge *eee=new ElementaryEdge(ee,true);
386       pushBack(eee);
387     }
388 }
389
390 /*!
391  * This method builds from descending conn of a quadratic polygon stored in crude mode (MEDCoupling). Descending conn is in FORTRAN relative mode in order to give the
392  * orientation of edge.
393  */
394 void QuadraticPolygon::buildFromCrudeDataArray2(const std::map<int,INTERP_KERNEL::Node *>& mapp, bool isQuad, const int *nodalBg, const double *coords, const int *descBg, const int *descEnd, const std::vector<std::vector<int> >& intersectEdges,
395                                                 const INTERP_KERNEL::QuadraticPolygon& pol1, const int *descBg1, const int *descEnd1, const std::vector<std::vector<int> >& intersectEdges1,
396                                                 const std::vector< std::vector<int> >& colinear1,
397                                                 std::map<int,std::vector<INTERP_KERNEL::ElementaryEdge *> >& alreadyExistingIn2)
398 {
399   std::size_t nbOfSeg=std::distance(descBg,descEnd);
400   for(std::size_t i=0;i<nbOfSeg;i++)//loop over all edges of pol2
401     {
402       bool direct=descBg[i]>0;
403       int edgeId=abs(descBg[i])-1;//current edge id of pol2
404       std::map<int,std::vector<INTERP_KERNEL::ElementaryEdge *> >::const_iterator it1=alreadyExistingIn2.find(descBg[i]),it2=alreadyExistingIn2.find(-descBg[i]);
405       if(it1!=alreadyExistingIn2.end() || it2!=alreadyExistingIn2.end())
406         {
407           bool sameDir=(it1!=alreadyExistingIn2.end());
408           const std::vector<INTERP_KERNEL::ElementaryEdge *>& edgesAlreadyBuilt=sameDir?(*it1).second:(*it2).second;
409           if(sameDir)
410             {
411               for(std::vector<INTERP_KERNEL::ElementaryEdge *>::const_iterator it3=edgesAlreadyBuilt.begin();it3!=edgesAlreadyBuilt.end();it3++)
412                 {
413                   Edge *ee=(*it3)->getPtr(); ee->incrRef();
414                   pushBack(new ElementaryEdge(ee,(*it3)->getDirection()));
415                 }
416             }
417           else
418             {
419               for(std::vector<INTERP_KERNEL::ElementaryEdge *>::const_reverse_iterator it4=edgesAlreadyBuilt.rbegin();it4!=edgesAlreadyBuilt.rend();it4++)
420                 {
421                   Edge *ee=(*it4)->getPtr(); ee->incrRef();
422                   pushBack(new ElementaryEdge(ee,!(*it4)->getDirection()));
423                 }
424             }
425           continue;
426         }
427       bool directos=colinear1[edgeId].empty();
428       std::vector<std::pair<int,std::pair<bool,int> > > idIns1;
429       int offset1=0;
430       if(!directos)
431         {// if the current edge of pol2 has one or more colinear edges part into pol1
432           const std::vector<int>& c=colinear1[edgeId];
433           std::size_t nbOfEdgesIn1=std::distance(descBg1,descEnd1);
434           for(std::size_t j=0;j<nbOfEdgesIn1;j++)
435             {
436               int edgeId1=abs(descBg1[j])-1;
437               if(std::find(c.begin(),c.end(),edgeId1)!=c.end())
438                 {
439                   idIns1.push_back(std::pair<int,std::pair<bool,int> >(edgeId1,std::pair<bool,int>(descBg1[j]>0,offset1)));// it exists an edge into pol1 given by tuple (idIn1,direct1) that is colinear at edge 'edgeId' in pol2
440                   //std::pair<edgeId1); direct1=descBg1[j]>0;
441                 }
442               offset1+=intersectEdges1[edgeId1].size()/2;//offset1 is used to find the INTERP_KERNEL::Edge * instance into pol1 that will be part of edge into pol2
443             }
444           directos=idIns1.empty();
445         }
446       if(directos)
447         {//no subpart of edge 'edgeId' of pol2 is in pol1 so let's operate the same thing that QuadraticPolygon::buildFromCrudeDataArray method
448           std::size_t oldSz=_sub_edges.size();
449           appendEdgeFromCrudeDataArray(i,mapp,isQuad,nodalBg,coords,descBg,descEnd,intersectEdges);
450           std::size_t newSz=_sub_edges.size();
451           std::size_t zeSz=newSz-oldSz;
452           alreadyExistingIn2[descBg[i]].resize(zeSz);
453           std::list<ElementaryEdge *>::const_reverse_iterator it5=_sub_edges.rbegin();
454           for(std::size_t p=0;p<zeSz;p++,it5++)
455             alreadyExistingIn2[descBg[i]][zeSz-p-1]=*it5;
456         }
457       else
458         {//there is subpart of edge 'edgeId' of pol2 inside pol1
459           const std::vector<int>& subEdge=intersectEdges[edgeId];
460           std::size_t nbOfSubEdges=subEdge.size()/2;
461           for(std::size_t j=0;j<nbOfSubEdges;j++)
462             {
463               int idBg=direct?subEdge[2*j]:subEdge[2*nbOfSubEdges-2*j-1];
464               int idEnd=direct?subEdge[2*j+1]:subEdge[2*nbOfSubEdges-2*j-2];
465               bool direction11,found=false;
466               bool direct1;//store if needed the direction in 1
467               int offset2;
468               std::size_t nbOfSubEdges1;
469               for(std::vector<std::pair<int,std::pair<bool,int> > >::const_iterator it=idIns1.begin();it!=idIns1.end() && !found;it++)
470                 {
471                   int idIn1=(*it).first;//store if needed the cell id in 1
472                   direct1=(*it).second.first;
473                   offset1=(*it).second.second;
474                   const std::vector<int>& subEdge1PossiblyAlreadyIn1=intersectEdges1[idIn1];
475                   nbOfSubEdges1=subEdge1PossiblyAlreadyIn1.size()/2;
476                   offset2=0;
477                   for(std::size_t k=0;k<nbOfSubEdges1 && !found;k++)
478                     {//perform a loop on all subedges of pol1 that includes edge 'edgeId' of pol2. For the moment we iterate only on subedges of ['idIn1']... To improve
479                       if(subEdge1PossiblyAlreadyIn1[2*k]==idBg && subEdge1PossiblyAlreadyIn1[2*k+1]==idEnd)
480                         { direction11=true; found=true; }
481                       else if(subEdge1PossiblyAlreadyIn1[2*k]==idEnd && subEdge1PossiblyAlreadyIn1[2*k+1]==idBg)
482                         { direction11=false; found=true; }
483                       else
484                         offset2++;
485                     }
486                 }
487               if(!found)
488                 {//the current subedge of edge 'edgeId' of pol2 is not a part of the colinear edge 'idIn1' of pol1 -> build new Edge instance
489                   //appendEdgeFromCrudeDataArray(j,mapp,isQuad,nodalBg,coords,descBg,descEnd,intersectEdges);
490                   Node *start=(*mapp.find(idBg)).second;
491                   Node *end=(*mapp.find(idEnd)).second;
492                   ElementaryEdge *e=ElementaryEdge::BuildEdgeFromCrudeDataArray(true,start,end);
493                   pushBack(e);
494                   alreadyExistingIn2[descBg[i]].push_back(e);
495                 }
496               else
497                 {//the current subedge of edge 'edgeId' of pol2 is part of the colinear edge 'idIn1' of pol1 -> reuse Edge instance of pol1
498                   ElementaryEdge *e=pol1[offset1+(direct1?offset2:nbOfSubEdges1-offset2-1)];
499                   Edge *ee=e->getPtr();
500                   ee->incrRef();
501                   ElementaryEdge *e2=new ElementaryEdge(ee,!(direct1^direction11));
502                   pushBack(e2);
503                   alreadyExistingIn2[descBg[i]].push_back(e2);
504                 }
505             }
506         }
507     }
508 }
509
510 /*!
511  * Method expected to be called on pol2. Every params not suffixed by numbered are supposed to refer to pol2 (this).
512  */
513 void QuadraticPolygon::updateLocOfEdgeFromCrudeDataArray2(const int *descBg, const int *descEnd, const std::vector<std::vector<int> >& intersectEdges, const INTERP_KERNEL::QuadraticPolygon& pol1, const int *descBg1, const int *descEnd1, const std::vector<std::vector<int> >& intersectEdges1, const std::vector< std::vector<int> >& colinear1) const
514 {
515   std::size_t nbOfSeg=std::distance(descBg,descEnd);
516   for(std::size_t i=0;i<nbOfSeg;i++)//loop over all edges of pol2
517     {
518       bool direct=descBg[i]>0;
519       int edgeId=abs(descBg[i])-1;//current edge id of pol2
520       const std::vector<int>& c=colinear1[edgeId];
521       if(c.empty())
522         continue;
523       const std::vector<int>& subEdge=intersectEdges[edgeId];
524       std::size_t nbOfSubEdges=subEdge.size()/2;
525       //
526       std::size_t nbOfEdgesIn1=std::distance(descBg1,descEnd1);
527       int offset1=0;
528       for(std::size_t j=0;j<nbOfEdgesIn1;j++)
529         {
530           int edgeId1=abs(descBg1[j])-1;
531           if(std::find(c.begin(),c.end(),edgeId1)!=c.end())
532             {
533               for(std::size_t k=0;k<nbOfSubEdges;k++)
534                 {
535                   int idBg=direct?subEdge[2*k]:subEdge[2*nbOfSubEdges-2*k-1];
536                   int idEnd=direct?subEdge[2*k+1]:subEdge[2*nbOfSubEdges-2*k-2];
537                   int idIn1=edgeId1;
538                   bool direct1=descBg1[j]>0;
539                   const std::vector<int>& subEdge1PossiblyAlreadyIn1=intersectEdges1[idIn1];
540                   std::size_t nbOfSubEdges1=subEdge1PossiblyAlreadyIn1.size()/2;
541                   int offset2=0;
542                   bool found=false;
543                   for(std::size_t kk=0;kk<nbOfSubEdges1 && !found;kk++)
544                     {
545                       found=(subEdge1PossiblyAlreadyIn1[2*kk]==idBg && subEdge1PossiblyAlreadyIn1[2*kk+1]==idEnd) || (subEdge1PossiblyAlreadyIn1[2*kk]==idEnd && subEdge1PossiblyAlreadyIn1[2*kk+1]==idBg);
546                       if(!found)
547                         offset2++;
548                     }
549                   if(found)
550                     {
551                       ElementaryEdge *e=pol1[offset1+(direct1?offset2:nbOfSubEdges1-offset2-1)];
552                       e->getPtr()->declareOn();
553                     }
554                 }
555             }
556           offset1+=intersectEdges1[edgeId1].size()/2;//offset1 is used to find the INTERP_KERNEL::Edge * instance into pol1 that will be part of edge into pol2
557         }
558     }
559 }
560
561 void QuadraticPolygon::appendCrudeData(const std::map<INTERP_KERNEL::Node *,int>& mapp, double xBary, double yBary, double fact, int offset, std::vector<double>& addCoordsQuadratic, std::vector<int>& conn, std::vector<int>& connI) const
562 {
563   int nbOfNodesInPg=0;
564   bool presenceOfQuadratic=presenceOfQuadraticEdge();
565   conn.push_back(presenceOfQuadratic?NORM_QPOLYG:NORM_POLYGON);
566   for(std::list<ElementaryEdge *>::const_iterator it=_sub_edges.begin();it!=_sub_edges.end();it++)
567     {
568       Node *tmp=0;
569       tmp=(*it)->getStartNode();
570       std::map<INTERP_KERNEL::Node *,int>::const_iterator it1=mapp.find(tmp);
571       conn.push_back((*it1).second);
572       nbOfNodesInPg++;
573     }
574   if(presenceOfQuadratic)
575     {
576       int j=0;
577       int off=offset+((int)addCoordsQuadratic.size())/2;
578       for(std::list<ElementaryEdge *>::const_iterator it=_sub_edges.begin();it!=_sub_edges.end();it++,j++,nbOfNodesInPg++)
579         {
580           INTERP_KERNEL::Node *node=(*it)->getPtr()->buildRepresentantOfMySelf();
581           node->unApplySimilarity(xBary,yBary,fact);
582           addCoordsQuadratic.push_back((*node)[0]);
583           addCoordsQuadratic.push_back((*node)[1]);
584           conn.push_back(off+j);
585           node->decrRef();
586         }
587     }
588   connI.push_back(connI.back()+nbOfNodesInPg+1);
589 }
590
591 /*!
592  * This method make the hypothesis that 'this' and 'other' are splited at the minimum into edges that are fully IN, OUT or ON.
593  * This method returns newly created polygons in 'conn' and 'connI' and the corresponding ids ('idThis','idOther') are stored respectively into 'nbThis' and 'nbOther'.
594  * @param [in,out] edgesThis, parameter that keep informed the caller abount the edges in this not shared by the result of intersection of \a this with \a other
595  * @param [in,out] edgesBoundaryOther, parameter that strores all edges in result of intersection that are not 
596  */
597 void QuadraticPolygon::buildPartitionsAbs(QuadraticPolygon& other, std::set<INTERP_KERNEL::Edge *>& edgesThis, std::set<INTERP_KERNEL::Edge *>& edgesBoundaryOther, const std::map<INTERP_KERNEL::Node *,int>& mapp, int idThis, int idOther, int offset, std::vector<double>& addCoordsQuadratic, std::vector<int>& conn, std::vector<int>& connI, std::vector<int>& nbThis, std::vector<int>& nbOther)
598 {
599   double xBaryBB, yBaryBB;
600   double fact=normalizeExt(&other, xBaryBB, yBaryBB);
601   //Locate 'this' relative to 'other'
602   other.performLocatingOperationSlow(*this);
603   std::vector<QuadraticPolygon *> res=buildIntersectionPolygons(other,*this);
604   for(std::vector<QuadraticPolygon *>::iterator it=res.begin();it!=res.end();it++)
605     {
606       (*it)->appendCrudeData(mapp,xBaryBB,yBaryBB,fact,offset,addCoordsQuadratic,conn,connI);
607       INTERP_KERNEL::IteratorOnComposedEdge it1(*it);
608       for(it1.first();!it1.finished();it1.next())
609         {
610           Edge *e=it1.current()->getPtr();
611           if(edgesThis.find(e)!=edgesThis.end())
612             edgesThis.erase(e);
613           else
614             {
615               if(edgesBoundaryOther.find(e)!=edgesBoundaryOther.end())
616                 edgesBoundaryOther.erase(e);
617               else
618                 edgesBoundaryOther.insert(e);
619             }
620         }
621       nbThis.push_back(idThis);
622       nbOther.push_back(idOther);
623       delete *it;
624     }
625   unApplyGlobalSimilarityExt(other,xBaryBB,yBaryBB,fact);
626 }
627
628 /*!
629  * Warning This method is \b NOT const. 'this' and 'other' are modified after call of this method.
630  * 'other' is a QuadraticPolygon of \b non closed edges.
631  */
632 double QuadraticPolygon::intersectWithAbs1D(QuadraticPolygon& other, bool& isColinear)
633 {
634   double ret = 0., xBaryBB, yBaryBB;
635   double fact = normalize(&other, xBaryBB, yBaryBB);
636
637   QuadraticPolygon cpyOfThis(*this);
638   QuadraticPolygon cpyOfOther(other);
639   int nbOfSplits = 0;
640   SplitPolygonsEachOther(cpyOfThis, cpyOfOther, nbOfSplits);
641   //At this point cpyOfThis and cpyOfOther have been splited at maximum edge so that in/out can been done.
642   performLocatingOperation(cpyOfOther);
643   isColinear = false;
644   for(std::list<ElementaryEdge *>::const_iterator it=cpyOfOther._sub_edges.begin();it!=cpyOfOther._sub_edges.end();it++)
645     {
646       switch((*it)->getLoc())
647         {
648         case FULL_IN_1:
649           {
650             ret += fabs((*it)->getPtr()->getCurveLength());
651             break;
652           }
653         case FULL_ON_1:
654           {
655             isColinear=true;
656             ret += fabs((*it)->getPtr()->getCurveLength());
657             break;
658           }
659         default:
660           {
661           }
662         }
663     }
664   return ret * fact;
665 }
666
667 /*!
668  * Warning contrary to intersectWith method this method is \b NOT const. 'this' and 'other' are modified after call of this method.
669  */
670 double QuadraticPolygon::intersectWithAbs(QuadraticPolygon& other, double* barycenter)
671 {
672   double ret=0.,bary[2],area,xBaryBB,yBaryBB;
673   barycenter[0] = barycenter[1] = 0.;
674   double fact=normalize(&other,xBaryBB,yBaryBB);
675   std::vector<QuadraticPolygon *> polygs=intersectMySelfWith(other);
676   for(std::vector<QuadraticPolygon *>::iterator iter=polygs.begin();iter!=polygs.end();iter++)
677     {
678       area=fabs((*iter)->getArea());
679       (*iter)->getBarycenter(bary);
680       delete *iter;
681       ret+=area;
682       barycenter[0] += bary[0]*area;
683       barycenter[1] += bary[1]*area;
684     }
685   if ( ret > std::numeric_limits<double>::min() )
686     {
687       barycenter[0]=barycenter[0]/ret*fact+xBaryBB;
688       barycenter[1]=barycenter[1]/ret*fact+yBaryBB;
689       
690     }
691   return ret*fact*fact;
692 }
693
694 /*!
695  * \b WARNING this method is const and other is const too. \b BUT location of Edges in 'this' and 'other' are nevertheless modified.
696  * This is possible because loc attribute in Edge class is mutable.
697  * This implies that if 'this' or/and 'other' are reused for intersect* method initLocations has to be called on each of this/them.
698  */
699 double QuadraticPolygon::intersectWith(const QuadraticPolygon& other) const
700 {
701   double ret=0.;
702   std::vector<QuadraticPolygon *> polygs=intersectMySelfWith(other);
703   for(std::vector<QuadraticPolygon *>::iterator iter=polygs.begin();iter!=polygs.end();iter++)
704     {
705       ret+=fabs((*iter)->getArea());
706       delete *iter;
707     }
708   return ret;
709 }
710
711 /*!
712  * \b WARNING this method is const and other is const too. \b BUT location of Edges in 'this' and 'other' are nevertheless modified.
713  * This is possible because loc attribute in Edge class is mutable.
714  * This implies that if 'this' or/and 'other' are reused for intersect* method initLocations has to be called on each of this/them.
715  */
716 double QuadraticPolygon::intersectWith(const QuadraticPolygon& other, double* barycenter) const
717 {
718   double ret=0., bary[2];
719   barycenter[0] = barycenter[1] = 0.;
720   std::vector<QuadraticPolygon *> polygs=intersectMySelfWith(other);
721   for(std::vector<QuadraticPolygon *>::iterator iter=polygs.begin();iter!=polygs.end();iter++)
722     {
723       double area = fabs((*iter)->getArea());
724       (*iter)->getBarycenter(bary);
725       delete *iter;
726       ret+=area;
727       barycenter[0] += bary[0]*area;
728       barycenter[1] += bary[1]*area;
729     }
730   if ( ret > std::numeric_limits<double>::min() )
731     {
732       barycenter[0] /= ret;
733       barycenter[1] /= ret;
734     }
735   return ret;
736 }
737
738 /*!
739  * \b WARNING this method is const and other is const too. \b BUT location of Edges in 'this' and 'other' are nevertheless modified.
740  * This is possible because loc attribute in Edge class is mutable.
741  * This implies that if 'this' or/and 'other' are reused for intersect* method initLocations has to be called on each of this/them.
742  */
743 void QuadraticPolygon::intersectForPerimeter(const QuadraticPolygon& other, double& perimeterThisPart, double& perimeterOtherPart, double& perimeterCommonPart) const
744 {
745   perimeterThisPart=0.; perimeterOtherPart=0.; perimeterCommonPart=0.;
746   QuadraticPolygon cpyOfThis(*this);
747   QuadraticPolygon cpyOfOther(other); int nbOfSplits=0;
748   SplitPolygonsEachOther(cpyOfThis,cpyOfOther,nbOfSplits);
749   performLocatingOperation(cpyOfOther);
750   other.performLocatingOperation(cpyOfThis);
751   cpyOfThis.dispatchPerimeterExcl(perimeterThisPart,perimeterCommonPart);
752   cpyOfOther.dispatchPerimeterExcl(perimeterOtherPart,perimeterCommonPart);
753   perimeterCommonPart/=2.;
754 }
755
756 /*!
757  * \b WARNING this method is const and other is const too. \b BUT location of Edges in 'this' and 'other' are nevertheless modified.
758  * This is possible because loc attribute in Edge class is mutable.
759  * This implies that if 'this' or/and 'other' are reused for intersect* method initLocations has to be called on each of this/them.
760  *
761  * polThis.size()==this->size() and polOther.size()==other.size().
762  * For each ElementaryEdge of 'this', the corresponding contribution in resulting polygon is in 'polThis'.
763  * For each ElementaryEdge of 'other', the corresponding contribution in resulting polygon is in 'polOther'.
764  * As consequence common part are counted twice (in polThis \b and in polOther).
765  */
766 void QuadraticPolygon::intersectForPerimeterAdvanced(const QuadraticPolygon& other, std::vector< double >& polThis, std::vector< double >& polOther) const
767 {
768   polThis.resize(size());
769   polOther.resize(other.size());
770   IteratorOnComposedEdge it1(const_cast<QuadraticPolygon *>(this));
771   int edgeId=0;
772   for(it1.first();!it1.finished();it1.next(),edgeId++)
773     {
774       ElementaryEdge* curE1=it1.current();
775       QuadraticPolygon cpyOfOther(other);
776       QuadraticPolygon tmp;
777       tmp.pushBack(curE1->clone());
778       int tmp2;
779       SplitPolygonsEachOther(tmp,cpyOfOther,tmp2);
780       other.performLocatingOperation(tmp);
781       tmp.dispatchPerimeter(polThis[edgeId]);
782     }
783   //
784   IteratorOnComposedEdge it2(const_cast<QuadraticPolygon *>(&other));
785   edgeId=0;
786   for(it2.first();!it2.finished();it2.next(),edgeId++)
787     {
788       ElementaryEdge* curE2=it2.current();
789       QuadraticPolygon cpyOfThis(*this);
790       QuadraticPolygon tmp;
791       tmp.pushBack(curE2->clone());
792       int tmp2;
793       SplitPolygonsEachOther(tmp,cpyOfThis,tmp2);
794       performLocatingOperation(tmp);
795       tmp.dispatchPerimeter(polOther[edgeId]);
796     }
797 }
798
799
800 /*!
801  * numberOfCreatedPointsPerEdge is resized to the number of edges of 'this'.
802  * This method returns in ordered maner the number of newly created points per edge.
803  * This method performs a split process between 'this' and 'other' that gives the result PThis.
804  * Then for each edges of 'this' this method counts how many edges in Pthis have the same id.
805  */
806 void QuadraticPolygon::intersectForPoint(const QuadraticPolygon& other, std::vector< int >& numberOfCreatedPointsPerEdge) const
807 {
808   numberOfCreatedPointsPerEdge.resize(size());
809   IteratorOnComposedEdge it1(const_cast<QuadraticPolygon *>(this));
810   int edgeId=0;
811   for(it1.first();!it1.finished();it1.next(),edgeId++)
812     {
813       ElementaryEdge* curE1=it1.current();
814       QuadraticPolygon cpyOfOther(other);
815       QuadraticPolygon tmp;
816       tmp.pushBack(curE1->clone());
817       int tmp2;
818       SplitPolygonsEachOther(tmp,cpyOfOther,tmp2);
819       numberOfCreatedPointsPerEdge[edgeId]=tmp.recursiveSize()-1;
820     }
821 }
822
823 /*!
824  * \b WARNING this method is const and other is const too. \b BUT location of Edges in 'this' and 'other' are nevertheless modified.
825  * This is possible because loc attribute in Edge class is mutable.
826  * This implies that if 'this' or/and 'other' are reused for intersect* method initLocations has to be called on each of this/them.
827  */
828 std::vector<QuadraticPolygon *> QuadraticPolygon::intersectMySelfWith(const QuadraticPolygon& other) const
829 {
830   QuadraticPolygon cpyOfThis(*this);
831   QuadraticPolygon cpyOfOther(other); int nbOfSplits=0;
832   SplitPolygonsEachOther(cpyOfThis,cpyOfOther,nbOfSplits);
833   //At this point cpyOfThis and cpyOfOther have been splited at maximum edge so that in/out can been done.
834   performLocatingOperation(cpyOfOther);
835   return other.buildIntersectionPolygons(cpyOfThis,cpyOfOther);
836 }
837
838 /*!
839  * This method is typically the first step of boolean operations between pol1 and pol2.
840  * This method perform the minimal splitting so that at the end each edges constituting pol1 are fully either IN or OUT or ON.
841  * @param pol1 IN/OUT param that is equal to 'this' when called.
842  */
843 void QuadraticPolygon::SplitPolygonsEachOther(QuadraticPolygon& pol1, QuadraticPolygon& pol2, int& nbOfSplits)
844 {
845   IteratorOnComposedEdge it1(&pol1),it2(&pol2);
846   MergePoints merge;
847   ComposedEdge *c1=new ComposedEdge;
848   ComposedEdge *c2=new ComposedEdge;
849   for(it2.first();!it2.finished();it2.next())
850     {
851       ElementaryEdge* curE2=it2.current();
852       if(!curE2->isThereStartPoint())
853         it1.first();
854       else
855         it1=curE2->getIterator();
856       for(;!it1.finished();)
857         {
858           
859           ElementaryEdge* curE1=it1.current();
860           merge.clear(); nbOfSplits++;
861           if(curE1->getPtr()->intersectWith(curE2->getPtr(),merge,*c1,*c2))
862             {
863               if(!curE1->getDirection()) c1->reverse();
864               if(!curE2->getDirection()) c2->reverse();
865               UpdateNeighbours(merge,it1,it2,c1,c2);
866               //Substitution of simple edge by sub-edges.
867               delete curE1; // <-- destroying simple edge coming from pol1
868               delete curE2; // <-- destroying simple edge coming from pol2
869               it1.insertElemEdges(c1,true);// <-- 2nd param is true to go next.
870               it2.insertElemEdges(c2,false);// <-- 2nd param is false to avoid to go next.
871               curE2=it2.current();
872               //
873               it1.assignMySelfToAllElems(c2);//To avoid that others
874               SoftDelete(c1);
875               SoftDelete(c2);
876               c1=new ComposedEdge;
877               c2=new ComposedEdge;
878             }
879           else
880             {
881               UpdateNeighbours(merge,it1,it2,curE1,curE2);
882               it1.next();
883             }
884         }
885     }
886   Delete(c1);
887   Delete(c2);
888 }
889
890 void QuadraticPolygon::performLocatingOperation(QuadraticPolygon& pol2) const
891 {
892   IteratorOnComposedEdge it(&pol2);
893   TypeOfEdgeLocInPolygon loc=FULL_ON_1;
894   for(it.first();!it.finished();it.next())
895     {
896       ElementaryEdge *cur=it.current();
897       loc=cur->locateFullyMySelf(*this,loc);
898     }
899 }
900
901 void QuadraticPolygon::performLocatingOperationSlow(QuadraticPolygon& pol2) const
902 {
903   IteratorOnComposedEdge it(&pol2);
904   for(it.first();!it.finished();it.next())
905     {
906       ElementaryEdge *cur=it.current();
907       cur->locateFullyMySelfAbsolute(*this);
908     }
909 }
910
911 /*!
912  * Given 2 polygons 'pol1' and 'pol2' (localized) the resulting polygons are returned.
913  *
914  * this : pol2 simplified.
915  * @param pol1 pol1 split.
916  * @param pol2 pol2 split.
917  */
918 std::vector<QuadraticPolygon *> QuadraticPolygon::buildIntersectionPolygons(const QuadraticPolygon& pol1, const QuadraticPolygon& pol2) const
919 {
920   std::vector<QuadraticPolygon *> ret;
921   std::list<QuadraticPolygon *> pol2Zip=pol2.zipConsecutiveInSegments();
922   if(!pol2Zip.empty())
923     closePolygons(pol2Zip,pol1,ret);
924   else
925     {//borders of pol2 do not cross pol1,and pol2 borders are outside of pol1. That is to say, either pol2 and pol1
926       //do not overlap or  pol1 is fully inside pol2. So in the first case no intersection, in the other case
927       //the intersection is pol1.
928       ElementaryEdge *e1FromPol1=pol1[0];
929       TypeOfEdgeLocInPolygon loc=FULL_ON_1;
930       loc=e1FromPol1->locateFullyMySelf(*this,loc);
931       if(loc==FULL_IN_1)
932         ret.push_back(new QuadraticPolygon(pol1));
933     }
934   return ret;
935 }
936
937 /*!
938  * Returns parts of potentially non closed-polygons. Each returned polygons are not mergeable.
939  * this : pol2 split and locallized.
940  */
941 std::list<QuadraticPolygon *> QuadraticPolygon::zipConsecutiveInSegments() const
942 {
943   std::list<QuadraticPolygon *> ret;
944   IteratorOnComposedEdge it(const_cast<QuadraticPolygon *>(this));
945   int nbOfTurns=recursiveSize();
946   int i=0;
947   if(!it.goToNextInOn(false,i,nbOfTurns))
948     return ret;
949   i=0;
950   //
951   while(i<nbOfTurns)
952     {
953       QuadraticPolygon *tmp1=new QuadraticPolygon;
954       TypeOfEdgeLocInPolygon loc=it.current()->getLoc();
955       while(loc!=FULL_OUT_1 && i<nbOfTurns)
956         {
957           ElementaryEdge *tmp3=it.current()->clone();
958           tmp1->pushBack(tmp3);
959           it.nextLoop(); i++;
960           loc=it.current()->getLoc();
961         }
962       if(tmp1->empty())
963         {
964           delete tmp1;
965           continue;
966         }
967       ret.push_back(tmp1);
968       it.goToNextInOn(true,i,nbOfTurns);
969     }
970   return ret;
971 }
972
973 /*!
974  * 'this' should be considered as pol2Simplified.
975  * @param pol2zip is a list of set of edges (openned polygon) coming from split polygon 2.
976  * @param pol1 is split pol1.
977  * @param results the resulting \b CLOSED polygons.
978  */
979 void QuadraticPolygon::closePolygons(std::list<QuadraticPolygon *>& pol2Zip, const QuadraticPolygon& pol1,
980                                      std::vector<QuadraticPolygon *>& results) const
981 {
982   bool directionKnownInPol1=false;
983   bool directionInPol1;
984   for(std::list<QuadraticPolygon *>::iterator iter=pol2Zip.begin();iter!=pol2Zip.end();)
985     {
986       if((*iter)->completed())
987         {
988           results.push_back(*iter);
989           directionKnownInPol1=false;
990           iter=pol2Zip.erase(iter);
991           continue;
992         }
993       if(!directionKnownInPol1)
994         {
995           if(!(*iter)->amIAChanceToBeCompletedBy(pol1,*this,directionInPol1))
996             { delete *iter; iter=pol2Zip.erase(iter); continue; }
997           else
998             directionKnownInPol1=true;
999         }
1000       std::list<QuadraticPolygon *>::iterator iter2=iter; iter2++;
1001       std::list<QuadraticPolygon *>::iterator iter3=(*iter)->fillAsMuchAsPossibleWith(pol1,iter2,pol2Zip.end(),directionInPol1);
1002       if(iter3!=pol2Zip.end())
1003         {
1004           (*iter)->pushBack(*iter3);
1005           SoftDelete(*iter3);
1006           pol2Zip.erase(iter3);
1007         }
1008     }
1009 }
1010
1011 /*!
1012  * 'this' is expected to be set of edges (not closed) of pol2 split.
1013  */
1014 bool QuadraticPolygon::amIAChanceToBeCompletedBy(const QuadraticPolygon& pol1Splitted,const QuadraticPolygon& pol2NotSplitted, bool& direction)
1015 {
1016   IteratorOnComposedEdge it(const_cast<QuadraticPolygon *>(&pol1Splitted));
1017   bool found=false;
1018   Node *n=getEndNode();
1019   ElementaryEdge *cur=it.current();
1020   for(it.first();!it.finished() && !found;)
1021     {
1022       cur=it.current();
1023       found=(cur->getStartNode()==n);
1024       if(!found)
1025         it.next();
1026     }
1027   if(!found)
1028     throw Exception("Internal error : polygons uncompatible each others. Should never happend");
1029   //Ok we found correspondance between this and pol1. Searching for right direction to close polygon.
1030   ElementaryEdge *e=_sub_edges.back();
1031   if(e->getLoc()==FULL_ON_1)
1032     {
1033       if(e->getPtr()==cur->getPtr())
1034         {
1035           direction=false;
1036           it.previousLoop();
1037           cur=it.current();
1038           Node *repr=cur->getPtr()->buildRepresentantOfMySelf();
1039           bool ret=pol2NotSplitted.isInOrOut(repr);
1040           repr->decrRef();
1041           return ret;
1042         }
1043       else
1044         {
1045           direction=true;
1046           Node *repr=cur->getPtr()->buildRepresentantOfMySelf();
1047           bool ret=pol2NotSplitted.isInOrOut(repr);
1048           repr->decrRef();
1049           return ret;
1050         }
1051     }
1052   else
1053     direction=cur->locateFullyMySelfAbsolute(pol2NotSplitted)==FULL_IN_1;
1054   return true;
1055 }
1056
1057 /*!
1058  * This method fills as much as possible 'this' (part of pol2 split) with edges of 'pol1Splitted'.
1059  */
1060 std::list<QuadraticPolygon *>::iterator QuadraticPolygon::fillAsMuchAsPossibleWith(const QuadraticPolygon& pol1Splitted,
1061                                                                                    std::list<QuadraticPolygon *>::iterator iStart,
1062                                                                                    std::list<QuadraticPolygon *>::iterator iEnd,
1063                                                                                    bool direction)
1064 {
1065   IteratorOnComposedEdge it(const_cast<QuadraticPolygon *>(&pol1Splitted));
1066   bool found=false;
1067   Node *n=getEndNode();
1068   ElementaryEdge *cur;
1069   for(it.first();!it.finished() && !found;)
1070     {
1071       cur=it.current();
1072       found=(cur->getStartNode()==n);
1073       if(!found)
1074         it.next();
1075     }
1076   if(!direction)
1077     it.previousLoop();
1078   Node *nodeToTest;
1079   std::list<QuadraticPolygon *>::iterator ret;
1080   do
1081     {
1082       cur=it.current();
1083       ElementaryEdge *tmp=cur->clone();
1084       if(!direction)
1085         tmp->reverse();
1086       pushBack(tmp);
1087       nodeToTest=tmp->getEndNode();
1088       direction?it.nextLoop():it.previousLoop();
1089       ret=CheckInList(nodeToTest,iStart,iEnd);
1090       if(completed())
1091         return iEnd;
1092     }
1093   while(ret==iEnd);
1094   return ret;
1095 }
1096
1097 std::list<QuadraticPolygon *>::iterator QuadraticPolygon::CheckInList(Node *n, std::list<QuadraticPolygon *>::iterator iStart,
1098                                                                       std::list<QuadraticPolygon *>::iterator iEnd)
1099 {
1100   for(std::list<QuadraticPolygon *>::iterator iter=iStart;iter!=iEnd;iter++)
1101     if((*iter)->isNodeIn(n))
1102       return iter;
1103   return iEnd;
1104 }
1105
1106 void QuadraticPolygon::ComputeResidual(const QuadraticPolygon& pol1, const std::set<Edge *>& notUsedInPol1, const std::set<Edge *>& edgesInPol2OnBoundary, const std::map<INTERP_KERNEL::Node *,int>& mapp, int offset, int idThis,
1107                                        std::vector<double>& addCoordsQuadratic, std::vector<int>& conn, std::vector<int>& connI, std::vector<int>& nb1, std::vector<int>& nb2)
1108 {
1109   pol1.initLocations();
1110   for(std::set<Edge *>::const_iterator it=notUsedInPol1.begin();it!=notUsedInPol1.end();it++)
1111     { (*it)->initLocs(); (*it)->declareOn(); }
1112   for(std::set<Edge *>::const_iterator it=edgesInPol2OnBoundary.begin();it!=edgesInPol2OnBoundary.end();it++)
1113     { (*it)->initLocs(); (*it)->declareIn(); }
1114   ////
1115   std::set<Edge *> notUsedInPol1L(notUsedInPol1);
1116   IteratorOnComposedEdge it(const_cast<QuadraticPolygon *>(&pol1));
1117   int sz=pol1.size();
1118   std::list<QuadraticPolygon *> pol1Zip;
1119   if(pol1.size()==(int)notUsedInPol1.size() && edgesInPol2OnBoundary.empty())
1120     {
1121       pol1.appendCrudeData(mapp,0.,0.,1.,offset,addCoordsQuadratic,conn,connI); nb1.push_back(idThis); nb2.push_back(-1);
1122       return ;
1123     }
1124   while(!notUsedInPol1L.empty())
1125     {
1126       for(int i=0;i<sz && (it.current()->getStartNode()->getLoc()!=IN_1 || it.current()->getLoc()!=FULL_ON_1);i++)
1127         it.nextLoop();
1128       if(it.current()->getStartNode()->getLoc()!=IN_1 || it.current()->getLoc()!=FULL_ON_1)
1129         throw INTERP_KERNEL::Exception("Presence of a target polygon fully included in source polygon ! The partition of this leads to a non simply connex cell (with hole) ! Impossible ! Such resulting cell cannot be stored in MED cell format !");
1130       QuadraticPolygon *tmp1=new QuadraticPolygon;
1131       do
1132         {
1133           Edge *ee=it.current()->getPtr();
1134           if(ee->getLoc()==FULL_ON_1)
1135             {
1136               ee->incrRef(); notUsedInPol1L.erase(ee);
1137               tmp1->pushBack(new ElementaryEdge(ee,it.current()->getDirection()));    
1138             }
1139           it.nextLoop();
1140         }
1141       while(it.current()->getStartNode()->getLoc()!=IN_1 && !notUsedInPol1L.empty());
1142       pol1Zip.push_back(tmp1);
1143     }
1144   ////
1145   std::list<QuadraticPolygon *> retPolsUnderContruction;
1146   std::list<Edge *> edgesInPol2OnBoundaryL(edgesInPol2OnBoundary.begin(),edgesInPol2OnBoundary.end());
1147   std::map<QuadraticPolygon *, std::list<QuadraticPolygon *> > pol1ZipConsumed;
1148   std::size_t maxNbOfTurn=edgesInPol2OnBoundaryL.size(),nbOfTurn=0,iiMNT=0;
1149   for(std::list<QuadraticPolygon *>::const_iterator itMNT=pol1Zip.begin();itMNT!=pol1Zip.end();itMNT++,iiMNT++)
1150     nbOfTurn+=(*itMNT)->size();
1151   maxNbOfTurn=maxNbOfTurn*nbOfTurn; maxNbOfTurn*=maxNbOfTurn;
1152   nbOfTurn=0;
1153   while(nbOfTurn<maxNbOfTurn && ((!pol1Zip.empty() || !edgesInPol2OnBoundaryL.empty())))
1154     {
1155       for(std::list<QuadraticPolygon *>::iterator it1=retPolsUnderContruction.begin();it1!=retPolsUnderContruction.end();)
1156         {
1157           if((*it1)->getStartNode()==(*it1)->getEndNode())
1158             {
1159               it1++;
1160               continue;
1161             }
1162           Node *curN=(*it1)->getEndNode();
1163           bool smthHappened=false;
1164           for(std::list<Edge *>::iterator it2=edgesInPol2OnBoundaryL.begin();it2!=edgesInPol2OnBoundaryL.end();)
1165             {
1166               if(curN==(*it2)->getStartNode())
1167                 { (*it2)->incrRef(); (*it1)->pushBack(new ElementaryEdge(*it2,true)); curN=(*it2)->getEndNode(); smthHappened=true; it2=edgesInPol2OnBoundaryL.erase(it2); }
1168               else if(curN==(*it2)->getEndNode())
1169                 { (*it2)->incrRef(); (*it1)->pushBack(new ElementaryEdge(*it2,false)); curN=(*it2)->getStartNode(); smthHappened=true; it2=edgesInPol2OnBoundaryL.erase(it2); }
1170               else
1171                 it2++;
1172             }
1173           if(smthHappened)
1174             {
1175               for(std::list<QuadraticPolygon *>::iterator it3=pol1Zip.begin();it3!=pol1Zip.end();)
1176                 {
1177                   if(curN==(*it3)->getStartNode())
1178                     {
1179                       for(std::list<ElementaryEdge *>::const_iterator it4=(*it3)->_sub_edges.begin();it4!=(*it3)->_sub_edges.end();it4++)
1180                         { (*it4)->getPtr()->incrRef(); bool dir=(*it4)->getDirection(); (*it1)->pushBack(new ElementaryEdge((*it4)->getPtr(),dir)); }
1181                       smthHappened=true;
1182                       pol1ZipConsumed[*it1].push_back(*it3);
1183                       curN=(*it3)->getEndNode();
1184                       it3=pol1Zip.erase(it3);
1185                     }
1186                   else
1187                     it3++;
1188                 }
1189             }
1190           if(!smthHappened)
1191             {
1192               for(std::list<ElementaryEdge *>::const_iterator it5=(*it1)->_sub_edges.begin();it5!=(*it1)->_sub_edges.end();it5++)
1193                 {
1194                   Edge *ee=(*it5)->getPtr();
1195                   if(edgesInPol2OnBoundary.find(ee)!=edgesInPol2OnBoundary.end())
1196                     edgesInPol2OnBoundaryL.push_back(ee);
1197                 }
1198               for(std::list<QuadraticPolygon *>::iterator it6=pol1ZipConsumed[*it1].begin();it6!=pol1ZipConsumed[*it1].end();it6++)
1199                 pol1Zip.push_front(*it6);
1200               pol1ZipConsumed.erase(*it1);
1201               delete *it1;
1202               it1=retPolsUnderContruction.erase(it1);
1203             }
1204         }
1205       if(!pol1Zip.empty())
1206         {
1207           QuadraticPolygon *tmp=new QuadraticPolygon;
1208           QuadraticPolygon *first=*(pol1Zip.begin());
1209           for(std::list<ElementaryEdge *>::const_iterator it4=first->_sub_edges.begin();it4!=first->_sub_edges.end();it4++)
1210             { (*it4)->getPtr()->incrRef(); bool dir=(*it4)->getDirection(); tmp->pushBack(new ElementaryEdge((*it4)->getPtr(),dir)); }
1211           pol1ZipConsumed[tmp].push_back(first);
1212           retPolsUnderContruction.push_back(tmp);
1213           pol1Zip.erase(pol1Zip.begin());
1214         }
1215       nbOfTurn++;
1216     }
1217   if(nbOfTurn==maxNbOfTurn)
1218     {
1219       std::ostringstream oss; oss << "Error during reconstruction of residual of cell ! It appears that either source or/and target mesh is/are not conform !";
1220       oss << " Number of turns is = " << nbOfTurn << " !";
1221       throw INTERP_KERNEL::Exception(oss.str().c_str());
1222     }
1223   for(std::list<QuadraticPolygon *>::iterator it1=retPolsUnderContruction.begin();it1!=retPolsUnderContruction.end();it1++)
1224     {
1225       if((*it1)->getStartNode()==(*it1)->getEndNode())
1226         {
1227           (*it1)->appendCrudeData(mapp,0.,0.,1.,offset,addCoordsQuadratic,conn,connI); nb1.push_back(idThis); nb2.push_back(-1);
1228           for(std::list<QuadraticPolygon *>::iterator it6=pol1ZipConsumed[*it1].begin();it6!=pol1ZipConsumed[*it1].end();it6++)
1229             delete *it6;
1230           delete *it1;
1231         }
1232     }
1233 }