Salome HOME
1bace844dae0e90846066518016aa9b9e604591f
[plugins/blsurfplugin.git] / src / BLSURFPlugin / BLSURFPlugin_BLSURF.cxx
1 // Copyright (C) 2007-2015  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, or (at your option) any later version.
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
20 // ---
21 // File    : BLSURFPlugin_BLSURF.cxx
22 // Authors : Francis KLOSS (OCC) & Patrick LAUG (INRIA) & Lioka RAZAFINDRAZAKA (CEA)
23 //           & Aurelien ALLEAUME (DISTENE)
24 //           Size maps developement: Nicolas GEIMER (OCC) & Gilles DAVID (EURIWARE)
25 // ---
26
27 #include "BLSURFPlugin_BLSURF.hxx"
28 #include "BLSURFPlugin_Hypothesis.hxx"
29 #include "BLSURFPlugin_Attractor.hxx"
30
31 extern "C"{
32 #include <meshgems/meshgems.h>
33 #include <meshgems/cadsurf.h>
34 #include <meshgems/precad.h>
35 }
36
37 #include <structmember.h>
38
39
40 #include <Basics_Utils.hxx>
41 #include <Basics_OCCTVersion.hxx>
42
43 #include <SMDS_EdgePosition.hxx>
44 #include <SMESHDS_Group.hxx>
45 #include <SMESH_Gen.hxx>
46 #include <SMESH_Group.hxx>
47 #include <SMESH_Mesh.hxx>
48 #include <SMESH_MeshEditor.hxx>
49 #include <SMESH_MesherHelper.hxx>
50 #include <StdMeshers_FaceSide.hxx>
51 #include <StdMeshers_ViscousLayers2D.hxx>
52
53 #include <utilities.h>
54
55 #include <limits>
56 #include <list>
57 #include <vector>
58 #include <set>
59 #include <cstdlib>
60
61 // OPENCASCADE includes
62 #include <BRepBuilderAPI_MakeFace.hxx>
63 #include <BRepBuilderAPI_MakePolygon.hxx>
64 //#include <BRepBuilderAPI_MakeVertex.hxx>
65 #include <BRepGProp.hxx>
66 #include <BRepTools.hxx>
67 #include <BRep_Builder.hxx>
68 #include <BRep_Tool.hxx>
69 #include <GProp_GProps.hxx>
70 #include <Geom2d_Curve.hxx>
71 #include <GeomAPI_ProjectPointOnCurve.hxx>
72 #include <GeomAPI_ProjectPointOnSurf.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Surface.hxx>
75 #include <NCollection_Map.hxx>
76 #include <Standard_ErrorHandler.hxx>
77 #include <TopExp.hxx>
78 #include <TopExp_Explorer.hxx>
79 #include <TopTools_DataMapOfShapeInteger.hxx>
80 #include <TopTools_IndexedMapOfShape.hxx>
81 #include <TopTools_MapOfShape.hxx>
82 #include <TopoDS.hxx>
83 #include <TopoDS_Compound.hxx>
84 #include <TopoDS_Edge.hxx>
85 #include <TopoDS_Face.hxx>
86 #include <TopoDS_Shape.hxx>
87 #include <TopoDS_Vertex.hxx>
88 #include <TopoDS_Wire.hxx>
89 #include <gp_Pnt.hxx>
90 #include <gp_Pnt2d.hxx>
91 #include <gp_XY.hxx>
92 #include <gp_XYZ.hxx>
93
94 #ifndef WIN32
95 #include <fenv.h>
96 #endif
97
98 /* ==================================
99  * ===========  PYTHON ==============
100  * ==================================*/
101
102 typedef struct {
103   PyObject_HEAD
104   int softspace;
105   std::string *out;
106   } PyStdOut;
107
108 static void
109 PyStdOut_dealloc(PyStdOut *self)
110 {
111   PyObject_Del(self);
112 }
113
114 static PyObject *
115 PyStdOut_write(PyStdOut *self, PyObject *args)
116 {
117   char *c;
118   int l;
119   if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
120     return NULL;
121
122   //std::cerr << c ;
123   *(self->out)=*(self->out)+c;
124
125   Py_INCREF(Py_None);
126   return Py_None;
127 }
128
129 static PyMethodDef PyStdOut_methods[] = {
130   {"write",  (PyCFunction)PyStdOut_write,  METH_VARARGS,
131     PyDoc_STR("write(string) -> None")},
132   {NULL,    NULL}   /* sentinel */
133 };
134
135 static PyMemberDef PyStdOut_memberlist[] = {
136   {(char*)"softspace", T_INT,  offsetof(PyStdOut, softspace), 0,
137    (char*)"flag indicating that a space needs to be printed; used by print"},
138   {NULL} /* Sentinel */
139 };
140
141 static PyTypeObject PyStdOut_Type = {
142   /* The ob_type field must be initialized in the module init function
143    * to be portable to Windows without using C++. */
144   PyObject_HEAD_INIT(NULL)
145   0,                            /*ob_size*/
146   "PyOut",                      /*tp_name*/
147   sizeof(PyStdOut),             /*tp_basicsize*/
148   0,                            /*tp_itemsize*/
149   /* methods */
150   (destructor)PyStdOut_dealloc, /*tp_dealloc*/
151   0,                            /*tp_print*/
152   0,                            /*tp_getattr*/
153   0,                            /*tp_setattr*/
154   0,                            /*tp_compare*/
155   0,                            /*tp_repr*/
156   0,                            /*tp_as_number*/
157   0,                            /*tp_as_sequence*/
158   0,                            /*tp_as_mapping*/
159   0,                            /*tp_hash*/
160   0,                            /*tp_call*/
161   0,                            /*tp_str*/
162   PyObject_GenericGetAttr,      /*tp_getattro*/
163   /* softspace is writable:  we must supply tp_setattro */
164   PyObject_GenericSetAttr,      /* tp_setattro */
165   0,                            /*tp_as_buffer*/
166   Py_TPFLAGS_DEFAULT,           /*tp_flags*/
167   0,                            /*tp_doc*/
168   0,                            /*tp_traverse*/
169   0,                            /*tp_clear*/
170   0,                            /*tp_richcompare*/
171   0,                            /*tp_weaklistoffset*/
172   0,                            /*tp_iter*/
173   0,                            /*tp_iternext*/
174   PyStdOut_methods,             /*tp_methods*/
175   PyStdOut_memberlist,          /*tp_members*/
176   0,                            /*tp_getset*/
177   0,                            /*tp_base*/
178   0,                            /*tp_dict*/
179   0,                            /*tp_descr_get*/
180   0,                            /*tp_descr_set*/
181   0,                            /*tp_dictoffset*/
182   0,                            /*tp_init*/
183   0,                            /*tp_alloc*/
184   0,                            /*tp_new*/
185   0,                            /*tp_free*/
186   0,                            /*tp_is_gc*/
187 };
188
189 PyObject * newPyStdOut( std::string& out )
190 {
191   PyStdOut *self;
192   self = PyObject_New(PyStdOut, &PyStdOut_Type);
193   if (self == NULL)
194     return NULL;
195   self->softspace = 0;
196   self->out=&out;
197   return (PyObject*)self;
198 }
199
200
201 ////////////////////////END PYTHON///////////////////////////
202
203 //////////////////MY MAPS////////////////////////////////////////
204 namespace {
205 TopTools_IndexedMapOfShape FacesWithSizeMap;
206 std::map<int,string> FaceId2SizeMap;
207 TopTools_IndexedMapOfShape EdgesWithSizeMap;
208 std::map<int,string> EdgeId2SizeMap;
209 TopTools_IndexedMapOfShape VerticesWithSizeMap;
210 std::map<int,string> VertexId2SizeMap;
211
212 std::map<int,PyObject*> FaceId2PythonSmp;
213 std::map<int,PyObject*> EdgeId2PythonSmp;
214 std::map<int,PyObject*> VertexId2PythonSmp;
215
216 typedef std::map<int, std::vector< BLSURFPlugin_Attractor* > > TId2ClsAttractorVec;
217 TId2ClsAttractorVec FaceId2ClassAttractor;
218 TId2ClsAttractorVec FaceIndex2ClassAttractor;
219 std::map<int,std::vector<double> > FaceId2AttractorCoords;
220 int theNbAttractors;
221
222 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
223 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
224 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
225 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
226
227 bool HasSizeMapOnFace=false;
228 bool HasSizeMapOnEdge=false;
229 bool HasSizeMapOnVertex=false;
230 //bool HasAttractorOnFace=false;
231 }
232 //=============================================================================
233 /*!
234  *
235  */
236 //=============================================================================
237
238 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
239                                                SMESH_Gen* gen)
240   : SMESH_2D_Algo(hypId, studyId, gen)
241 {
242   MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
243
244   _name = "MG-CADSurf";//"BLSURF";
245   _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
246   _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType());
247   _compatibleHypothesis.push_back(StdMeshers_ViscousLayers2D::GetHypType());
248   _requireDiscreteBoundary = false;
249   _onlyUnaryInput = false;
250   _hypothesis = NULL;
251   _supportSubmeshes = true;
252
253   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
254   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
255   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
256
257   MESSAGE("studyid = " << _studyId);
258
259   myStudy = NULL;
260   myStudy = aStudyMgr->GetStudyByID(_studyId);
261   if ( !myStudy->_is_nil() )
262     MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
263
264   /* Initialize the Python interpreter */
265   assert(Py_IsInitialized());
266   PyGILState_STATE gstate;
267   gstate = PyGILState_Ensure();
268
269   main_mod = NULL;
270   main_mod = PyImport_AddModule("__main__");
271
272   main_dict = NULL;
273   main_dict = PyModule_GetDict(main_mod);
274
275   PyRun_SimpleString("from math import *");
276   PyGILState_Release(gstate);
277
278   FacesWithSizeMap.Clear();
279   FaceId2SizeMap.clear();
280   EdgesWithSizeMap.Clear();
281   EdgeId2SizeMap.clear();
282   VerticesWithSizeMap.Clear();
283   VertexId2SizeMap.clear();
284   FaceId2PythonSmp.clear();
285   EdgeId2PythonSmp.clear();
286   VertexId2PythonSmp.clear();
287   FaceId2AttractorCoords.clear();
288   FaceId2ClassAttractor.clear();
289   FaceIndex2ClassAttractor.clear();
290   FacesWithEnforcedVertices.Clear();
291   FaceId2EnforcedVertexCoords.clear();
292   EnfVertexCoords2ProjVertex.clear();
293   EnfVertexCoords2EnfVertexList.clear();
294
295   _compute_canceled = false;
296 }
297
298 //=============================================================================
299 /*!
300  *
301  */
302 //=============================================================================
303
304 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
305 {
306   MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
307 }
308
309
310 //=============================================================================
311 /*!
312  *
313  */
314 //=============================================================================
315
316 bool BLSURFPlugin_BLSURF::CheckHypothesis
317                          (SMESH_Mesh&                          aMesh,
318                           const TopoDS_Shape&                  aShape,
319                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
320 {
321   _hypothesis        = NULL;
322   _haveViscousLayers = false;
323
324   list<const SMESHDS_Hypothesis*>::const_iterator itl;
325   const SMESHDS_Hypothesis* theHyp;
326
327   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape,
328                                                                   /*ignoreAuxiliary=*/false);
329   aStatus = SMESH_Hypothesis::HYP_OK;
330   if ( hyps.empty() )
331   {
332     return true;  // can work with no hypothesis
333   }
334
335   for ( itl = hyps.begin(); itl != hyps.end() && ( aStatus == HYP_OK ); ++itl )
336   {
337     theHyp = *itl;
338     string hypName = theHyp->GetName();
339     if ( hypName == BLSURFPlugin_Hypothesis::GetHypType() )
340     {
341       _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
342       ASSERT(_hypothesis);
343       if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
344            _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
345         //  hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
346         aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
347     }
348     else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
349     {
350       if ( !_haveViscousLayers )
351       {
352         if ( error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus )))
353           _haveViscousLayers = true;
354       }
355     }
356     else
357     {
358       aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
359     }
360   }
361   return aStatus == SMESH_Hypothesis::HYP_OK;
362 }
363
364 //=============================================================================
365 /*!
366  * Pass parameters to MG-CADSurf
367  */
368 //=============================================================================
369
370 inline std::string to_string(double d)
371 {
372    std::ostringstream o;
373    o << d;
374    return o.str();
375 }
376
377 inline std::string to_string_rel(double d)
378 {
379    std::ostringstream o;
380    o << d;
381    o << 'r';
382    return o.str();
383 }
384
385 inline std::string to_string(int i)
386 {
387    std::ostringstream o;
388    o << i;
389    return o.str();
390 }
391
392 inline std::string to_string_rel(int i)
393 {
394    std::ostringstream o;
395    o << i;
396    o << 'r';
397    return o.str();
398 }
399
400 double _smp_phy_size;
401 // #if BLSURF_VERSION_LONG >= "3.1.1"
402 // //   sizemap_t *geo_sizemap_e, *geo_sizemap_f;
403 //   sizemap_t *iso_sizemap_p, *iso_sizemap_e, *iso_sizemap_f;
404 // //   sizemap_t *clean_geo_sizemap_e, *clean_geo_sizemap_f;
405 //   sizemap_t *clean_iso_sizemap_p, *clean_iso_sizemap_e, *clean_iso_sizemap_f;
406 // #endif
407 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
408 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
409 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
410
411 typedef struct {
412         gp_XY uv;
413         gp_XYZ xyz;
414 } projectionPoint;
415 /////////////////////////////////////////////////////////
416 projectionPoint getProjectionPoint(const TopoDS_Face& face, const gp_Pnt& point)
417 {
418   projectionPoint myPoint;
419   Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
420   GeomAPI_ProjectPointOnSurf projector( point, surface );
421   if ( !projector.IsDone() || projector.NbPoints()==0 )
422     throw "getProjectionPoint: Can't project";
423
424   Quantity_Parameter u,v;
425   projector.LowerDistanceParameters(u,v);
426   myPoint.uv = gp_XY(u,v);
427   gp_Pnt aPnt = projector.NearestPoint();
428   myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
429   //return gp_XY(u,v);
430   return myPoint;
431 }
432 /////////////////////////////////////////////////////////
433
434 /////////////////////////////////////////////////////////
435 double getT(const TopoDS_Edge& edge, const gp_Pnt& point)
436 {
437   Standard_Real f,l;
438   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
439   GeomAPI_ProjectPointOnCurve projector( point, curve);
440   if ( projector.NbPoints() == 0 )
441     throw;
442   return projector.LowerDistanceParameter();
443 }
444
445 /////////////////////////////////////////////////////////
446 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
447 {
448   MESSAGE("BLSURFPlugin_BLSURF::entryToShape "<<entry );
449   GEOM::GEOM_Object_var aGeomObj;
450   TopoDS_Shape S = TopoDS_Shape();
451   SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
452   if (!aSObj->_is_nil()) {
453     CORBA::Object_var obj = aSObj->GetObject();
454     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
455     aSObj->UnRegister();
456   }
457   if ( !aGeomObj->_is_nil() )
458     S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
459   return S;
460 }
461
462 void _createEnforcedVertexOnFace(TopoDS_Face faceShape, gp_Pnt aPnt, BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex)
463 {
464   BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
465   enf_coords.clear();
466   coords.clear();
467   s_coords.clear();
468
469   // Get the (u,v) values of the enforced vertex on the face
470   projectionPoint myPoint = getProjectionPoint(faceShape,aPnt);
471
472   MESSAGE("Enforced Vertex: " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z());
473   MESSAGE("Projected Vertex: " << myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z());
474   MESSAGE("Parametric coordinates: " << myPoint.uv.X() << ", " << myPoint.uv.Y() );
475
476   enf_coords.push_back(aPnt.X());
477   enf_coords.push_back(aPnt.Y());
478   enf_coords.push_back(aPnt.Z());
479
480   coords.push_back(myPoint.uv.X());
481   coords.push_back(myPoint.uv.Y());
482   coords.push_back(myPoint.xyz.X());
483   coords.push_back(myPoint.xyz.Y());
484   coords.push_back(myPoint.xyz.Z());
485
486   s_coords.push_back(myPoint.xyz.X());
487   s_coords.push_back(myPoint.xyz.Y());
488   s_coords.push_back(myPoint.xyz.Z());
489
490   // Save pair projected vertex / enf vertex
491   MESSAGE("Storing pair projected vertex / enf vertex:");
492   MESSAGE("("<< myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z() <<") / (" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z()<<")");
493   EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
494   MESSAGE("Group name is: \"" << enfVertex->grpName << "\"");
495   pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
496   BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
497   ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
498   if (ret.second == false) {
499     it = ret.first;
500     (*it)->grpName = enfVertex->grpName;
501   }
502
503   int key = 0;
504   if (! FacesWithEnforcedVertices.Contains(faceShape)) {
505     key = FacesWithEnforcedVertices.Add(faceShape);
506   }
507   else {
508     key = FacesWithEnforcedVertices.FindIndex(faceShape);
509   }
510
511   // If a node is already created by an attractor, do not create enforced vertex
512   int attractorKey = FacesWithSizeMap.FindIndex(faceShape);
513   bool sameAttractor = false;
514   if (attractorKey >= 0)
515     if (FaceId2AttractorCoords.count(attractorKey) > 0)
516       if (FaceId2AttractorCoords[attractorKey] == coords)
517         sameAttractor = true;
518
519   if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
520     MESSAGE("Map of enf. vertex has key " << key)
521     MESSAGE("Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
522     if (! sameAttractor)
523       FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
524     else
525       MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
526     MESSAGE("New Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
527   }
528   else {
529     MESSAGE("Map of enf. vertex has not key " << key << ": creating it")
530     if (! sameAttractor) {
531       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
532       ens.insert(coords);
533       FaceId2EnforcedVertexCoords[key] = ens;
534     }
535     else
536       MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
537   }
538 }
539
540 /////////////////////////////////////////////////////////
541 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
542 {
543   BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex;
544   gp_Pnt aPnt;
545
546   BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfVertexListIt = enfVertexList.begin();
547
548   for( ; enfVertexListIt != enfVertexList.end() ; ++enfVertexListIt ) {
549     enfVertex = *enfVertexListIt;
550     // Case of manual coords
551     if (enfVertex->coords.size() != 0) {
552       aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
553       _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
554     }
555
556     // Case of geom vertex coords
557     if (enfVertex->geomEntry != "") {
558       TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
559       TopAbs_ShapeEnum GeomType  = GeomShape.ShapeType();
560        if (GeomType == TopAbs_VERTEX){
561          aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
562          _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
563        }
564        // Group Management
565        if (GeomType == TopAbs_COMPOUND){
566          for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
567            if (it.Value().ShapeType() == TopAbs_VERTEX){
568              aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
569              _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
570            }
571          }
572        }
573     }
574   }
575 }
576
577 /////////////////////////////////////////////////////////
578 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction, double defaultSize)
579 {
580   MESSAGE("Attractor function: "<< AttractorFunction);
581   double xa, ya, za; // Coordinates of attractor point
582   double a, b;       // Attractor parameter
583   double d = 0.;
584   bool createNode=false; // To create a node on attractor projection
585   int pos1, pos2;
586   const char *sep = ";";
587   // atIt->second has the following pattern:
588   // ATTRACTOR(xa;ya;za;a;b;True|False;d)
589   // where:
590   // xa;ya;za : coordinates of  attractor
591   // a        : desired size on attractor
592   // b        : distance of influence of attractor
593   // d        : distance until which the size remains constant
594   //
595   // We search the parameters in the string
596   // xa
597   pos1 = AttractorFunction.find(sep);
598   if (pos1!=string::npos)
599   xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
600   // ya
601   pos2 = AttractorFunction.find(sep, pos1+1);
602   if (pos2!=string::npos) {
603   ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
604   pos1 = pos2;
605   }
606   // za
607   pos2 = AttractorFunction.find(sep, pos1+1);
608   if (pos2!=string::npos) {
609   za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
610   pos1 = pos2;
611   }
612   // a
613   pos2 = AttractorFunction.find(sep, pos1+1);
614   if (pos2!=string::npos) {
615   a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
616   pos1 = pos2;
617   }
618   // b
619   pos2 = AttractorFunction.find(sep, pos1+1);
620   if (pos2!=string::npos) {
621   b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
622   pos1 = pos2;
623   }
624   // createNode
625   pos2 = AttractorFunction.find(sep, pos1+1);
626   if (pos2!=string::npos) {
627     string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
628     MESSAGE("createNode: " << createNodeStr);
629     createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
630     pos1=pos2;
631   }
632   // d
633   pos2 = AttractorFunction.find(")");
634   if (pos2!=string::npos) {
635   d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
636   }
637
638   // Get the (u,v) values of the attractor on the face
639   projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
640   gp_XY uvPoint = myPoint.uv;
641   gp_XYZ xyzPoint = myPoint.xyz;
642   Standard_Real u0 = uvPoint.X();
643   Standard_Real v0 = uvPoint.Y();
644   Standard_Real x0 = xyzPoint.X();
645   Standard_Real y0 = xyzPoint.Y();
646   Standard_Real z0 = xyzPoint.Z();
647   std::vector<double> coords;
648   coords.push_back(u0);
649   coords.push_back(v0);
650   coords.push_back(x0);
651   coords.push_back(y0);
652   coords.push_back(z0);
653   // We construct the python function
654   ostringstream attractorFunctionStream;
655   attractorFunctionStream << "def f(u,v): return ";
656   attractorFunctionStream << defaultSize << "-(" << defaultSize <<"-" << a << ")";
657   //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
658   // rnc: make possible to keep the size constant until
659   // a defined distance. Distance is expressed as the positiv part
660   // of r-d where r is the distance to (u0,v0)
661   attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
662
663   MESSAGE("Python function for attractor:" << std::endl << attractorFunctionStream.str());
664
665   int key;
666   if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
667     key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
668   }
669   else {
670     key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
671   }
672   FaceId2SizeMap[key] =attractorFunctionStream.str();
673   if (createNode) {
674     MESSAGE("Creating node on ("<<x0<<","<<y0<<","<<z0<<")");
675     FaceId2AttractorCoords[key] = coords;
676   }
677 //   // Test for new attractors
678 //   gp_Pnt myP(xyzPoint);
679 //   TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
680 //   BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
681 //   myAttractor.SetParameters(a, defaultSize, b, d);
682 //   myAttractor.SetType(1);
683 //   FaceId2ClassAttractor[key] = myAttractor;
684 //   if(FaceId2ClassAttractor[key].GetFace().IsNull()){
685 //     MESSAGE("face nulle ");
686 //   }
687 //   else
688 //     MESSAGE("face OK");
689 //
690 //   if (FaceId2ClassAttractor[key].GetAttractorShape().IsNull()){
691 //     MESSAGE("pas de point");
692 //   }
693 //   else
694 //     MESSAGE("point OK");
695 }
696
697 // One sub-shape to get ids from
698 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(TopoDS_Shape theMainShape, TopoDS_Shape theSubShape,
699     TopAbs_ShapeEnum theShapeType)
700 {
701   BLSURFPlugin_BLSURF::TListOfIDs face_ids;
702   TopTools_IndexedMapOfShape anIndices;
703   anIndices.Clear();
704   TopExp::MapShapes(theMainShape, theShapeType, anIndices);
705
706 //  Standard_Boolean result = BRepTools::Write(theMainShape,"main_shape.brep");
707
708   for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
709     {
710       int face_id = anIndices.FindIndex(face_iter.Current());
711       if (face_id == 0)
712         throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
713       face_ids.push_back(face_id);
714 //      std::ostringstream o;
715 //      o << "face_" << face_id << ".brep";
716 //      std::string face_name = o.str();
717 //      const TopoDS_Face& face = TopoDS::Face(face_iter.Current());
718 //      Standard_Boolean result = BRepTools::Write(face,face_name.c_str());
719     }
720
721   return face_ids;
722 }
723
724 void BLSURFPlugin_BLSURF::addCoordsFromVertices(const std::vector<std::string> &theVerticesEntries, std::vector<double> &theVerticesCoords)
725 {
726   for (std::vector<std::string>::const_iterator it = theVerticesEntries.begin(); it != theVerticesEntries.end(); it++)
727     {
728       BLSURFPlugin_Hypothesis::TEntry theVertexEntry = *it;
729       MESSAGE("Vertex entry " << theVertexEntry);
730       addCoordsFromVertex(theVertexEntry, theVerticesCoords);
731     }
732 }
733
734
735 void BLSURFPlugin_BLSURF::addCoordsFromVertex(BLSURFPlugin_Hypothesis::TEntry theVertexEntry, std::vector<double> &theVerticesCoords)
736 {
737   if (theVertexEntry!="")
738     {
739       TopoDS_Shape aShape = entryToShape(theVertexEntry);
740
741       gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex( aShape ) );
742       double theX, theY, theZ;
743       theX = aPnt.X();
744       theY = aPnt.Y();
745       theZ = aPnt.Z();
746
747       theVerticesCoords.push_back(theX);
748       theVerticesCoords.push_back(theY);
749       theVerticesCoords.push_back(theZ);
750     }
751 }
752
753 /////////////////////////////////////////////////////////
754 void BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
755 {
756   MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity");
757
758   TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
759   TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
760
761   TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_FACE);
762   TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_FACE);
763
764   TPreCadPeriodicityIDs preCadFacesPeriodicityIDs;
765   preCadFacesPeriodicityIDs.shape1IDs = theFace1_ids;
766   preCadFacesPeriodicityIDs.shape2IDs = theFace2_ids;
767
768   MESSAGE("preCadPeriodicity.theSourceVerticesEntries.size(): " << preCadPeriodicity.theSourceVerticesEntries.size());
769   MESSAGE("preCadPeriodicity.theTargetVerticesEntries.size(): " << preCadPeriodicity.theTargetVerticesEntries.size());
770
771   addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadFacesPeriodicityIDs.theSourceVerticesCoords);
772   addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadFacesPeriodicityIDs.theTargetVerticesCoords);
773
774   MESSAGE("preCadFacesPeriodicityIDs.theSourceVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theSourceVerticesCoords.size());
775   MESSAGE("preCadFacesPeriodicityIDs.theTargetVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theTargetVerticesCoords.size());
776
777   _preCadFacesIDsPeriodicityVector.push_back(preCadFacesPeriodicityIDs);
778   MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
779   MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity END");
780
781 }
782
783 /////////////////////////////////////////////////////////
784 void BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
785 {
786   MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity");
787
788   TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
789   TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
790
791   TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_EDGE);
792   TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_EDGE);
793
794   TPreCadPeriodicityIDs preCadEdgesPeriodicityIDs;
795   preCadEdgesPeriodicityIDs.shape1IDs = theEdge1_ids;
796   preCadEdgesPeriodicityIDs.shape2IDs = theEdge2_ids;
797
798   addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadEdgesPeriodicityIDs.theSourceVerticesCoords);
799   addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadEdgesPeriodicityIDs.theTargetVerticesCoords);
800
801   _preCadEdgesIDsPeriodicityVector.push_back(preCadEdgesPeriodicityIDs);
802   MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
803   MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity END");
804
805 }
806
807 /////////////////////////////////////////////////////////
808 void BLSURFPlugin_BLSURF::createFacesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theFace1,  BLSURFPlugin_Hypothesis::TEntry theFace2)
809 {
810   MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity");
811
812   TopoDS_Shape GeomShape1 = entryToShape(theFace1);
813   TopoDS_Shape GeomShape2 = entryToShape(theFace2);
814
815   TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomShape1, TopAbs_FACE);
816   TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomShape2, TopAbs_FACE);
817
818   // Only one face id, since only a face can be selected
819   int theFace1_id = theFace1_ids[0];
820   int theFace2_id = theFace2_ids[0];
821
822   std::pair<int, int> pairOfFacesID = std::make_pair(theFace1_id, theFace2_id);
823
824   _facesIDsPeriodicityVector.push_back(pairOfFacesID);
825   MESSAGE("_facesIDsPeriodicityVector.size() = " << _facesIDsPeriodicityVector.size());
826   MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity END");
827
828 }
829
830
831 /////////////////////////////////////////////////////////
832 void BLSURFPlugin_BLSURF::createEdgesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theFace1, BLSURFPlugin_Hypothesis::TEntry theEdge1,
833     BLSURFPlugin_Hypothesis::TEntry theFace2, BLSURFPlugin_Hypothesis::TEntry theEdge2, int edge_orientation)
834 {
835   MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity");
836
837   TEdgePeriodicityIDs edgePeriodicityIDs;
838
839   if (theFace1 != "")
840     {
841       TopoDS_Shape GeomFace1 = entryToShape(theFace1);
842       TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomFace1, TopAbs_FACE);
843       // Only one face id, since only a face can be selected
844       edgePeriodicityIDs.theFace1ID = theFace1_ids[0];
845     }
846   else
847     edgePeriodicityIDs.theFace1ID = 0;
848   if (theFace2 != "")
849     {
850       TopoDS_Shape GeomFace2 = entryToShape(theFace2);
851       TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomFace2, TopAbs_FACE);
852       edgePeriodicityIDs.theFace2ID = theFace2_ids[0];
853     }
854   else
855     edgePeriodicityIDs.theFace2ID = 0;
856
857   TopoDS_Shape GeomEdge1 = entryToShape(theEdge1);
858   TopoDS_Shape GeomEdge2 = entryToShape(theEdge2);
859
860   TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge1, TopAbs_EDGE);
861   TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge2, TopAbs_EDGE);
862
863   if (edge_orientation == 0 && GeomEdge1.Closed())
864     {
865       // if edge is closed, we have to set its orientation
866       MESSAGE("GeomEdge1.Orientation() = " << GeomEdge1.Orientation());
867       MESSAGE("GeomEdge2.Orientation() = " << GeomEdge2.Orientation());
868       if(GeomEdge1.Orientation() == TopAbs_FORWARD)
869         edge_orientation = CAD_ORIENTATION_REVERSED;
870       else
871         edge_orientation = CAD_ORIENTATION_FORWARD;
872     }
873
874   // Only one edge id, since only a edge can be selected
875   edgePeriodicityIDs.theEdge1ID = theEdge1_ids[0];
876   edgePeriodicityIDs.theEdge2ID = theEdge2_ids[0];
877   edgePeriodicityIDs.edge_orientation = edge_orientation;
878
879   _edgesIDsPeriodicityVector.push_back(edgePeriodicityIDs);
880   MESSAGE("_edgesIDsPeriodicityVector.size() = " << _edgesIDsPeriodicityVector.size());
881   MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity END");
882
883 }
884
885
886 /////////////////////////////////////////////////////////
887 void BLSURFPlugin_BLSURF::createVerticesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theEdge1, BLSURFPlugin_Hypothesis::TEntry theVertex1,
888     BLSURFPlugin_Hypothesis::TEntry theEdge2, BLSURFPlugin_Hypothesis::TEntry theVertex2)
889 {
890   MESSAGE("BLSURFPlugin_BLSURF::createVerticesPeriodicity");
891
892   TopoDS_Shape GeomEdge1 = entryToShape(theEdge1);
893   TopoDS_Shape GeomVertex1 = entryToShape(theVertex1);
894   TopoDS_Shape GeomEdge2 = entryToShape(theEdge2);
895   TopoDS_Shape GeomVertex2 = entryToShape(theVertex2);
896
897   TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge1, TopAbs_EDGE);
898   TListOfIDs vertices1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomVertex1, TopAbs_VERTEX);
899   TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge2, TopAbs_EDGE);
900   TListOfIDs vertices2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomVertex2, TopAbs_VERTEX);
901
902   // Only one vertex id, since only a vertex can be selected
903   TVertexPeriodicityIDs vertexPeriodicityIDs;
904   vertexPeriodicityIDs.theEdge1ID = theEdge1_ids[0];
905   vertexPeriodicityIDs.theVertex1ID = vertices1_ids[0];
906   vertexPeriodicityIDs.theEdge2ID = theEdge2_ids[0];
907   vertexPeriodicityIDs.theVertex2ID = vertices2_ids[0];
908
909   _verticesIDsPeriodicityVector.push_back(vertexPeriodicityIDs);
910   MESSAGE("_verticesIDsPeriodicityVector.size() = " << _verticesIDsPeriodicityVector.size());
911   MESSAGE("BLSURFPlugin_BLSURF::createVerticesPeriodicity END");
912
913 }
914
915 /////////////////////////////////////////////////////////
916
917 void BLSURFPlugin_BLSURF::SetParameters(
918 // #if BLSURF_VERSION_LONG >= "3.1.1"
919 //                                         cad_t *                          c,
920 // #endif
921                                         const BLSURFPlugin_Hypothesis* hyp,
922                                         cadsurf_session_t *            css,
923                                         precad_session_t *             pcs,
924                                         const TopoDS_Shape&            theGeomShape,
925                                         bool *                  use_precad
926                                        )
927 {
928   // rnc : Bug 1457
929   // Clear map so that it is not stored in the algorithm with old enforced vertices in it
930   EnfVertexCoords2EnfVertexList.clear();
931   
932    double diagonal               = SMESH_Mesh::GetShapeDiagonalSize( theGeomShape );
933    double bbSegmentation         = _gen->GetBoundaryBoxSegmentation();
934    int    _physicalMesh          = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
935    int    _geometricMesh         = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
936    double _phySize               = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
937    bool   _phySizeRel            = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
938    double _minSize               = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
939    bool   _minSizeRel            = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
940    double _maxSize               = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
941    bool   _maxSizeRel            = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
942    double _gradation             = BLSURFPlugin_Hypothesis::GetDefaultGradation();
943    bool   _quadAllowed           = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
944    double _angleMesh             = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
945    double _chordalError          = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
946    bool   _anisotropic           = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
947    double _anisotropicRatio      = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
948    bool   _removeTinyEdges       = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
949    double _tinyEdgeLength        = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
950    bool   _badElementRemoval     = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
951    double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
952    bool   _optimizeMesh          = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
953    bool   _quadraticMesh         = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
954    int    _verb                  = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
955    int    _topology              = BLSURFPlugin_Hypothesis::GetDefaultTopology();
956
957   // PreCAD
958    int _precadMergeEdges         = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
959    int _precadProcess3DTopology  = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
960    int _precadDiscardInput       = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
961
962
963   if (hyp) {
964     MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
965     _physicalMesh  = (int) hyp->GetPhysicalMesh();
966     _geometricMesh = (int) hyp->GetGeometricMesh();
967     if (hyp->GetPhySize() > 0) {
968       _phySize       = hyp->GetPhySize();
969       // if user size is not explicitly specified, "relative" flag is ignored
970       _phySizeRel    = hyp->IsPhySizeRel();
971     }
972     if (hyp->GetMinSize() > 0) {
973       _minSize       = hyp->GetMinSize();
974       // if min size is not explicitly specified, "relative" flag is ignored
975       _minSizeRel    = hyp->IsMinSizeRel();
976     }
977     if (hyp->GetMaxSize() > 0) {
978       _maxSize       = hyp->GetMaxSize();
979       // if max size is not explicitly specified, "relative" flag is ignored
980       _maxSizeRel    = hyp->IsMaxSizeRel();
981     }
982     if (hyp->GetGradation() > 0)
983       _gradation     = hyp->GetGradation();
984     _quadAllowed   = hyp->GetQuadAllowed();
985      if (hyp->GetAngleMesh() > 0)
986      _angleMesh     = hyp->GetAngleMesh();
987      if (hyp->GetChordalError() > 0)
988        _chordalError           = hyp->GetChordalError();
989      _anisotropic            = hyp->GetAnisotropic();
990      if (hyp->GetAnisotropicRatio() >= 0)
991        _anisotropicRatio       = hyp->GetAnisotropicRatio();
992      _removeTinyEdges        = hyp->GetRemoveTinyEdges();
993      if (hyp->GetTinyEdgeLength() > 0)
994        _tinyEdgeLength         = hyp->GetTinyEdgeLength();
995      _badElementRemoval      = hyp->GetBadElementRemoval();
996      if (hyp->GetBadElementAspectRatio() >= 0)
997        _badElementAspectRatio  = hyp->GetBadElementAspectRatio();
998      _optimizeMesh  = hyp->GetOptimizeMesh();
999      _quadraticMesh = hyp->GetQuadraticMesh();
1000     _verb          = hyp->GetVerbosity();
1001      _topology      = (int) hyp->GetTopology();
1002      // PreCAD
1003      _precadMergeEdges = hyp->GetPreCADMergeEdges();
1004      _precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
1005      _precadDiscardInput = hyp->GetPreCADDiscardInput();
1006
1007     const BLSURFPlugin_Hypothesis::TOptionValues& opts = hyp->GetOptionValues();
1008     BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
1009     for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
1010       if ( !opIt->second.empty() ) {
1011         MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
1012         set_param(css, opIt->first.c_str(), opIt->second.c_str());
1013       }
1014       
1015     const BLSURFPlugin_Hypothesis::TOptionValues& custom_opts = hyp->GetCustomOptionValues();
1016     for ( opIt = custom_opts.begin(); opIt != custom_opts.end(); ++opIt )
1017       if ( !opIt->second.empty() ) {
1018         MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
1019         set_param(css, opIt->first.c_str(), opIt->second.c_str());
1020      }
1021
1022     const BLSURFPlugin_Hypothesis::TOptionValues& preCADopts = hyp->GetPreCADOptionValues();
1023     for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
1024       if ( !opIt->second.empty() ) {
1025         *use_precad = true;
1026         MESSAGE("precad_set_param(): " << opIt->first << " = " << opIt->second);
1027         precad_set_param(pcs, opIt->first.c_str(), opIt->second.c_str());
1028       }
1029
1030     const BLSURFPlugin_Hypothesis::TOptionValues& custom_preCADopts = hyp->GetCustomPreCADOptionValues();
1031     for ( opIt = custom_preCADopts.begin(); opIt != custom_preCADopts.end(); ++opIt )
1032       if ( !opIt->second.empty() ) {
1033         *use_precad = true;
1034         MESSAGE("precad_set_param(): " << opIt->first << " = " << opIt->second);
1035         precad_set_param(pcs, opIt->first.c_str(), opIt->second.c_str());
1036       }
1037   }
1038 //   else {
1039 //     //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
1040 //     // GetDefaultPhySize() sometimes leads to computation failure
1041 //     // GDD 26/07/2012 From Distene documentation, global physical size default value = diag/100
1042 //     _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal);
1043 //     _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
1044 //     _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
1045 //     _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
1046 //     _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
1047 //     MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
1048 //   }
1049
1050   // PreCAD
1051   if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
1052     *use_precad = true;
1053     precad_set_param(pcs, "verbose",                to_string(_verb).c_str());
1054     precad_set_param(pcs, "merge_edges",            _precadMergeEdges ? "1" : "0");
1055     precad_set_param(pcs, "process_3d_topology",    _precadProcess3DTopology ? "1" : "0");
1056     precad_set_param(pcs, "discard_input_topology", _precadDiscardInput ? "1" : "0");
1057   }
1058   // unlimit mesh size (issue 0022266)
1059   set_param(css, "max_number_of_points_per_patch", "1000000");
1060   
1061    bool useGradation = false;
1062    switch (_physicalMesh)
1063    {
1064      case BLSURFPlugin_Hypothesis::PhysicalGlobalSize:
1065        set_param(css, "physical_size_mode", "global");
1066        set_param(css, "global_physical_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1067        break;
1068      case BLSURFPlugin_Hypothesis::PhysicalLocalSize:
1069        set_param(css, "physical_size_mode", "local");
1070        set_param(css, "global_physical_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1071        useGradation = true;
1072        break;
1073      default:
1074        set_param(css, "physical_size_mode", "none");
1075    }
1076
1077    switch (_geometricMesh)
1078    {
1079      case BLSURFPlugin_Hypothesis::GeometricalGlobalSize:
1080        set_param(css, "geometric_size_mode", "global");
1081        set_param(css, "geometric_approximation", to_string(_angleMesh).c_str());
1082        set_param(css, "chordal_error", to_string(_chordalError).c_str());
1083        useGradation = true;
1084        break;
1085      case BLSURFPlugin_Hypothesis::GeometricalLocalSize:
1086        set_param(css, "geometric_size_mode", "local");
1087        set_param(css, "geometric_approximation", to_string(_angleMesh).c_str());
1088        set_param(css, "chordal_error", to_string(_chordalError).c_str());
1089        useGradation = true;
1090        break;
1091      default:
1092        set_param(css, "geometric_size_mode", "none");
1093    }
1094
1095    if ( hyp && hyp->GetPhySize() > 0 ) {
1096      // user size is explicitly specified via hypothesis parameters
1097      // min and max sizes should be compared with explicitly specified user size
1098      // - compute absolute min size
1099      double mins = _minSizeRel ? _minSize * diagonal : _minSize;
1100      // - min size should not be greater than user size
1101      if ( _phySize < mins )
1102        set_param(css, "min_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1103      else
1104        set_param(css, "min_size", _minSizeRel ? to_string_rel(_minSize).c_str() : to_string(_minSize).c_str());
1105      // - compute absolute max size
1106      double maxs = _maxSizeRel ? _maxSize * diagonal : _maxSize;
1107      // - max size should not be less than user size
1108      if ( _phySize > maxs )
1109        set_param(css, "max_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1110      else
1111        set_param(css, "max_size", _maxSizeRel ? to_string_rel(_maxSize).c_str() : to_string(_maxSize).c_str());
1112    }
1113    else {
1114      // user size is not explicitly specified
1115      // - if minsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1116      set_param(css, "min_size", _minSizeRel ? to_string_rel(_minSize).c_str() : to_string(_minSize).c_str());
1117      // - if maxsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1118      set_param(css, "max_size", _maxSizeRel ? to_string_rel(_maxSize).c_str() : to_string(_maxSize).c_str());
1119    }
1120    // anisotropic and quadrangle mesh requires disabling gradation
1121    if ( _anisotropic && _quadAllowed )
1122      useGradation = false; // limitation of V1.3
1123    if ( useGradation )
1124      set_param(css, "gradation",                         to_string(_gradation).c_str());
1125    set_param(css, "element_generation",                _quadAllowed ? "quad_dominant" : "triangle");
1126
1127
1128    set_param(css, "metric",                            _anisotropic ? "anisotropic" : "isotropic");
1129    if ( _anisotropic )
1130      set_param(css, "anisotropic_ratio",                 to_string(_anisotropicRatio).c_str());
1131    set_param(css, "remove_tiny_edges",                 _removeTinyEdges ? "1" : "0");
1132    if ( _removeTinyEdges )
1133      set_param(css, "tiny_edge_length",                  to_string(_tinyEdgeLength).c_str());
1134    set_param(css, "force_bad_surface_element_removal", _badElementRemoval ? "1" : "0");
1135    if ( _badElementRemoval )
1136      set_param(css, "bad_surface_element_aspect_ratio",  to_string(_badElementAspectRatio).c_str());
1137    set_param(css, "optimisation",                      _optimizeMesh ? "yes" : "no");
1138    set_param(css, "element_order",                     _quadraticMesh ? "quadratic" : "linear");
1139    set_param(css, "verbose",                           to_string(_verb).c_str());
1140
1141    _smp_phy_size = _phySizeRel ? _phySize*diagonal : _phySize;
1142    if ( _verb > 0 )
1143      std::cout << "_smp_phy_size = " << _smp_phy_size << std::endl;
1144
1145    if (_physicalMesh == BLSURFPlugin_Hypothesis::PhysicalLocalSize){
1146     TopoDS_Shape GeomShape;
1147     TopoDS_Shape AttShape;
1148     TopAbs_ShapeEnum GeomType;
1149     //
1150     // Standard Size Maps
1151     //
1152     MESSAGE("Setting a Size Map");
1153     const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
1154     BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
1155     for ( ; smIt != sizeMaps.end(); ++smIt ) {
1156       if ( !smIt->second.empty() ) {
1157         MESSAGE("cadsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
1158         GeomShape = entryToShape(smIt->first);
1159         GeomType  = GeomShape.ShapeType();
1160         MESSAGE("Geomtype is " << GeomType);
1161         int key = -1;
1162         // Group Management
1163         if (GeomType == TopAbs_COMPOUND){
1164           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1165             // Group of faces
1166             if (it.Value().ShapeType() == TopAbs_FACE){
1167               HasSizeMapOnFace = true;
1168               if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
1169                 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
1170               }
1171               else {
1172                 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
1173 //                 MESSAGE("Face with key " << key << " already in map");
1174               }
1175               FaceId2SizeMap[key] = smIt->second;
1176             }
1177             // Group of edges
1178             if (it.Value().ShapeType() == TopAbs_EDGE){
1179               HasSizeMapOnEdge = true;
1180               HasSizeMapOnFace = true;
1181               if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
1182                 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
1183               }
1184               else {
1185                 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
1186 //                 MESSAGE("Edge with key " << key << " already in map");
1187               }
1188               EdgeId2SizeMap[key] = smIt->second;
1189             }
1190             // Group of vertices
1191             if (it.Value().ShapeType() == TopAbs_VERTEX){
1192               HasSizeMapOnVertex = true;
1193               HasSizeMapOnEdge = true;
1194               HasSizeMapOnFace = true;
1195               if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
1196                 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
1197               }
1198               else {
1199                 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
1200                 MESSAGE("Group of vertices with key " << key << " already in map");
1201               }
1202               MESSAGE("Group of vertices with key " << key << " has a size map: " << smIt->second);
1203               VertexId2SizeMap[key] = smIt->second;
1204             }
1205           }
1206         }
1207         // Single face
1208         if (GeomType == TopAbs_FACE){
1209           HasSizeMapOnFace = true;
1210           if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
1211             key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
1212           }
1213           else {
1214             key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
1215 //             MESSAGE("Face with key " << key << " already in map");
1216           }
1217           FaceId2SizeMap[key] = smIt->second;
1218         }
1219         // Single edge
1220         if (GeomType == TopAbs_EDGE){
1221           HasSizeMapOnEdge = true;
1222           HasSizeMapOnFace = true;
1223           if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
1224             key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
1225           }
1226           else {
1227             key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
1228 //             MESSAGE("Edge with key " << key << " already in map");
1229           }
1230           EdgeId2SizeMap[key] = smIt->second;
1231         }
1232         // Single vertex
1233         if (GeomType == TopAbs_VERTEX){
1234           HasSizeMapOnVertex = true;
1235           HasSizeMapOnEdge   = true;
1236           HasSizeMapOnFace   = true;
1237           if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
1238             key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
1239           }
1240           else {
1241             key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
1242              MESSAGE("Vertex with key " << key << " already in map");
1243           }
1244           MESSAGE("Vertex with key " << key << " has a size map: " << smIt->second);
1245           VertexId2SizeMap[key] = smIt->second;
1246         }
1247       }
1248     }
1249
1250     //
1251     // Attractors
1252     //
1253     // TODO appeler le constructeur des attracteurs directement ici
1254     MESSAGE("Setting Attractors");
1255 //     if ( !_phySizeRel ) {
1256       const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
1257       BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
1258       for ( ; atIt != attractors.end(); ++atIt ) {
1259         if ( !atIt->second.empty() ) {
1260           MESSAGE("cadsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
1261           GeomShape = entryToShape(atIt->first);
1262           GeomType  = GeomShape.ShapeType();
1263           // Group Management
1264           if (GeomType == TopAbs_COMPOUND){
1265             for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1266               if (it.Value().ShapeType() == TopAbs_FACE){
1267                 HasSizeMapOnFace = true;
1268                 createAttractorOnFace(it.Value(), atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1269               }
1270             }
1271           }
1272
1273           if (GeomType == TopAbs_FACE){
1274             HasSizeMapOnFace = true;
1275             createAttractorOnFace(GeomShape, atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1276           }
1277   /*
1278           if (GeomType == TopAbs_EDGE){
1279             HasSizeMapOnEdge = true;
1280             HasSizeMapOnFace = true;
1281           EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
1282           }
1283           if (GeomType == TopAbs_VERTEX){
1284             HasSizeMapOnVertex = true;
1285             HasSizeMapOnEdge   = true;
1286             HasSizeMapOnFace   = true;
1287           VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
1288           }
1289   */
1290         }
1291       }
1292 //     }
1293 //     else
1294 //       MESSAGE("Impossible to create the attractors when the physical size is relative");
1295
1296     // Class Attractors
1297     // temporary commented out for testing
1298     // TODO
1299     //  - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
1300     //  - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
1301     //  - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
1302     //  OR, even better:
1303     //  - Construct the attractors with an empty dist. map in the hypothesis
1304     //  - build the map here for each face with an attractor set and only if the attractor shape as changed since the last call to _buildmap()
1305     //  -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap()  OK
1306
1307       theNbAttractors = 0;
1308     const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
1309     int key=-1;
1310     BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
1311     for ( ; AtIt != class_attractors.end(); ++AtIt ) {
1312       if ( !AtIt->second->Empty() ) {
1313        // MESSAGE("cadsurf_set_attractor(): " << AtIt->first << " = " << AtIt->second);
1314         GeomShape = entryToShape(AtIt->first);
1315         if ( !SMESH_MesherHelper::IsSubShape( GeomShape, theGeomShape ))
1316           continue;
1317         AttShape = AtIt->second->GetAttractorShape();
1318         GeomType  = GeomShape.ShapeType();
1319         // Group Management
1320 //         if (GeomType == TopAbs_COMPOUND){
1321 //           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1322 //             if (it.Value().ShapeType() == TopAbs_FACE){
1323 //               HasAttractorOnFace = true;
1324 //               myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
1325 //             }
1326 //           }
1327 //         }
1328
1329         if (GeomType == TopAbs_FACE
1330           && (AttShape.ShapeType() == TopAbs_VERTEX
1331            || AttShape.ShapeType() == TopAbs_EDGE
1332            || AttShape.ShapeType() == TopAbs_WIRE
1333            || AttShape.ShapeType() == TopAbs_COMPOUND) ){
1334             HasSizeMapOnFace = true;
1335
1336             key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
1337
1338             FaceId2ClassAttractor[key].push_back( AtIt->second );
1339             ++theNbAttractors;
1340         }
1341         else{
1342           MESSAGE("Wrong shape type !!")
1343         }
1344
1345       }
1346     }
1347
1348
1349     //
1350     // Enforced Vertices
1351     //
1352     MESSAGE("Setting Enforced Vertices");
1353     const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
1354     BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
1355     for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
1356       if ( !enfIt->second.empty() ) {
1357         GeomShape = entryToShape(enfIt->first);
1358         GeomType  = GeomShape.ShapeType();
1359         // Group Management
1360         if (GeomType == TopAbs_COMPOUND){
1361           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1362             if (it.Value().ShapeType() == TopAbs_FACE){
1363               HasSizeMapOnFace = true;
1364               createEnforcedVertexOnFace(it.Value(), enfIt->second);
1365             }
1366           }
1367         }
1368
1369         if (GeomType == TopAbs_FACE){
1370           HasSizeMapOnFace = true;
1371           createEnforcedVertexOnFace(GeomShape, enfIt->second);
1372         }
1373       }
1374     }
1375
1376     // Internal vertices
1377     bool useInternalVertexAllFaces = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFaces(hyp);
1378     if (useInternalVertexAllFaces) {
1379       std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
1380       MESSAGE("Setting Internal Enforced Vertices");
1381       gp_Pnt aPnt;
1382       TopExp_Explorer exp (theGeomShape, TopAbs_FACE);
1383       for (; exp.More(); exp.Next()){
1384         MESSAGE("Iterating shapes. Shape type is " << exp.Current().ShapeType());
1385         TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX, TopAbs_EDGE);
1386         for (; exp_face.More(); exp_face.Next())
1387         {
1388           // Get coords of vertex
1389           // Check if current coords is already in enfVertexList
1390           // If coords not in enfVertexList, add new enfVertex
1391           aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1392           MESSAGE("Found vertex on face at " << aPnt.X() <<", "<<aPnt.Y()<<", "<<aPnt.Z());
1393           BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1394           enfVertex->coords.push_back(aPnt.X());
1395           enfVertex->coords.push_back(aPnt.Y());
1396           enfVertex->coords.push_back(aPnt.Z());
1397           enfVertex->name = "";
1398           enfVertex->faceEntries.clear();
1399           enfVertex->geomEntry = "";
1400           enfVertex->grpName = grpName;
1401           enfVertex->vertex = TopoDS::Vertex( exp_face.Current() );
1402           _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()),  aPnt, enfVertex);
1403           HasSizeMapOnFace = true;
1404         }
1405       }
1406     }
1407
1408     MESSAGE("Setting Size Map on FACES ");
1409 // #if BLSURF_VERSION_LONG < "3.1.1"
1410     cadsurf_data_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
1411 // #else
1412 //     if (*use_precad)
1413 //       iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1414 //     else
1415 //       clean_iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1416 // #endif
1417
1418     if (HasSizeMapOnEdge){
1419       MESSAGE("Setting Size Map on EDGES ");
1420 // #if BLSURF_VERSION_LONG < "3.1.1"
1421       cadsurf_data_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
1422 // #else
1423 //       if (*use_precad)
1424 //         iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1425 //       else
1426 //         clean_iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1427 // #endif
1428     }
1429     if (HasSizeMapOnVertex){
1430       MESSAGE("Setting Size Map on VERTICES ");
1431 // #if BLSURF_VERSION_LONG < "3.1.1"
1432       cadsurf_data_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
1433 // #else
1434 //       if (*use_precad)
1435 //         iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1436 //       else
1437 //         clean_iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1438 // #endif
1439     }
1440   }
1441
1442   // PERIODICITY
1443
1444    // reset vectors
1445    _preCadFacesIDsPeriodicityVector.clear();
1446    _preCadEdgesIDsPeriodicityVector.clear();
1447    _facesIDsPeriodicityVector.clear();
1448    _edgesIDsPeriodicityVector.clear();
1449    _verticesIDsPeriodicityVector.clear();
1450
1451   MESSAGE("SetParameters preCadFacesPeriodicityVector");
1452   const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadFacesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadFacesPeriodicityVector(hyp);
1453
1454   for (std::size_t i = 0; i<preCadFacesPeriodicityVector.size(); i++){
1455     MESSAGE("SetParameters preCadFacesPeriodicityVector[" << i << "]");
1456     createPreCadFacesPeriodicity(theGeomShape, preCadFacesPeriodicityVector[i]);
1457   }
1458   MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
1459
1460   MESSAGE("SetParameters preCadEdgesPeriodicityVector");
1461   const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadEdgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadEdgesPeriodicityVector(hyp);
1462
1463   for (std::size_t i = 0; i<preCadEdgesPeriodicityVector.size(); i++){
1464     MESSAGE("SetParameters preCadEdgesPeriodicityVector[" << i << "]");
1465     createPreCadEdgesPeriodicity(theGeomShape, preCadEdgesPeriodicityVector[i]);
1466   }
1467   MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
1468
1469   if ( _preCadFacesIDsPeriodicityVector.size() > 0 || _preCadEdgesIDsPeriodicityVector.size() > 0 )
1470     {
1471       MESSAGE("USING PRECAD FOR PERIODICITY")
1472       *use_precad = true;
1473       precad_set_param(pcs, "verbose",                to_string(_verb).c_str());
1474     }
1475
1476   MESSAGE("SetParameters facesPeriodicityVector");
1477   const BLSURFPlugin_Hypothesis::TFacesPeriodicityVector facesPeriodicityVector = BLSURFPlugin_Hypothesis::GetFacesPeriodicityVector(hyp);
1478
1479   for (std::size_t i = 0; i<facesPeriodicityVector.size(); i++){
1480     MESSAGE("SetParameters facesPeriodicityVector[" << i << "]");
1481     createFacesPeriodicity(theGeomShape, facesPeriodicityVector[i].first, facesPeriodicityVector[i].second);
1482   }
1483   MESSAGE("_facesIDsPeriodicityVector.size() = " << _facesIDsPeriodicityVector.size());
1484
1485
1486   MESSAGE("SetParameters edgesPeriodicityVector");
1487   const BLSURFPlugin_Hypothesis::TEdgesPeriodicityVector edgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetEdgesPeriodicityVector(hyp);
1488
1489   for (std::size_t i = 0; i<edgesPeriodicityVector.size(); i++){
1490     MESSAGE("SetParameters edgesPeriodicityVector[" << i << "]");
1491     // TODO: passer directement en paramètre edgesPeriodicityVector[i] plutôt que tous ces attributs
1492     createEdgesPeriodicity(theGeomShape, edgesPeriodicityVector[i].theFace1Entry, edgesPeriodicityVector[i].theEdge1Entry,
1493         edgesPeriodicityVector[i].theFace2Entry, edgesPeriodicityVector[i].theEdge2Entry, edgesPeriodicityVector[i].edge_orientation);
1494   }
1495   MESSAGE("_edgesIDsPeriodicityVector.size() = " << _edgesIDsPeriodicityVector.size());
1496
1497   MESSAGE("SetParameters verticesPeriodicityVector");
1498   const BLSURFPlugin_Hypothesis::TVerticesPeriodicityVector verticesPeriodicityVector = BLSURFPlugin_Hypothesis::GetVerticesPeriodicityVector(hyp);
1499
1500   for (std::size_t i = 0; i<verticesPeriodicityVector.size(); i++){
1501     MESSAGE("SetParameters verticesPeriodicityVector[" << i << "]");
1502     // TODO: passer directement en paramètre verticesPeriodicityVector[i] plutôt que tous ces attributs
1503     createVerticesPeriodicity(theGeomShape, verticesPeriodicityVector[i].theEdge1Entry, verticesPeriodicityVector[i].theVertex1Entry,
1504         verticesPeriodicityVector[i].theEdge2Entry, verticesPeriodicityVector[i].theVertex2Entry);
1505   }
1506   MESSAGE("_verticesIDsPeriodicityVector.size() = " << _verticesIDsPeriodicityVector.size());
1507 }
1508
1509 //================================================================================
1510 /*!
1511  * \brief Throws an exception if a parameter name is wrong
1512  */
1513 //================================================================================
1514
1515 void BLSURFPlugin_BLSURF::set_param(cadsurf_session_t *css,
1516                                     const char *       option_name,
1517                                     const char *       option_value)
1518 {
1519   status_t status = cadsurf_set_param(css, option_name, option_value );
1520   if ( status != MESHGEMS_STATUS_OK )
1521   {
1522     if ( status == MESHGEMS_STATUS_UNKNOWN_PARAMETER ) {
1523       throw SALOME_Exception
1524         ( SMESH_Comment("Invalid name of CADSURF parameter: ") << option_name );
1525     }
1526     else if ( status == MESHGEMS_STATUS_NOLICENSE )
1527       throw SALOME_Exception
1528         ( "No valid license available" );
1529     else
1530       throw SALOME_Exception
1531         ( SMESH_Comment("Unacceptable value of CADSURF parameter '")
1532           << option_name << "': " << option_value);
1533   }
1534 }
1535
1536 namespace
1537 {
1538   // --------------------------------------------------------------------------
1539   /*!
1540    * \brief Class correctly terminating usage of MG-CADSurf library at destruction
1541    */
1542   class BLSURF_Cleaner
1543   {
1544     context_t *       _ctx;
1545     cadsurf_session_t* _css;
1546     cad_t *           _cad;
1547     dcad_t *          _dcad;
1548     cad_t *           _cleanc;
1549     dcad_t *          _cleandc;
1550   public:
1551     BLSURF_Cleaner(context_t *       ctx,
1552                    cadsurf_session_t* css,
1553                    cad_t *           cad,
1554                    dcad_t *          dcad,
1555                    cad_t *           cleanc,
1556                    dcad_t *          cleandc)
1557       : _ctx ( ctx  ),
1558         _css ( css  ),
1559         _cad ( cad  ),
1560         _dcad( dcad ),
1561         _cleanc( cleanc ),
1562         _cleandc( cleandc )
1563     {
1564     }
1565     ~BLSURF_Cleaner()
1566     {
1567       Clean( /*exceptContext=*/false );
1568     }
1569     void Clean(const bool exceptContext)
1570     {
1571       if ( _css )
1572       {
1573         cadsurf_session_delete(_css); _css = 0;
1574
1575         // #if BLSURF_VERSION_LONG >= "3.1.1"
1576         // //     if(geo_sizemap_e)
1577         // //       distene_sizemap_delete(geo_sizemap_e);
1578         // //     if(geo_sizemap_f)
1579         // //       distene_sizemap_delete(geo_sizemap_f);
1580         //     if(iso_sizemap_p)
1581         //       distene_sizemap_delete(iso_sizemap_p);
1582         //     if(iso_sizemap_e)
1583         //       distene_sizemap_delete(iso_sizemap_e);
1584         //     if(iso_sizemap_f)
1585         //       distene_sizemap_delete(iso_sizemap_f);
1586         // 
1587         // //     if(clean_geo_sizemap_e)
1588         // //       distene_sizemap_delete(clean_geo_sizemap_e);
1589         // //     if(clean_geo_sizemap_f)
1590         // //       distene_sizemap_delete(clean_geo_sizemap_f);
1591         //     if(clean_iso_sizemap_p)
1592         //       distene_sizemap_delete(clean_iso_sizemap_p);
1593         //     if(clean_iso_sizemap_e)
1594         //       distene_sizemap_delete(clean_iso_sizemap_e);
1595         //     if(clean_iso_sizemap_f)
1596         //       distene_sizemap_delete(clean_iso_sizemap_f);
1597         // #endif
1598
1599         cad_delete(_cad); _cad = 0;
1600         dcad_delete(_dcad); _dcad = 0;
1601         cad_delete(_cleanc); _cleanc = 0;
1602         dcad_delete(_cleandc); _cleandc = 0;
1603         if ( !exceptContext )
1604         {
1605           context_delete(_ctx); _ctx = 0;
1606         }
1607       }
1608     }
1609   };
1610
1611   // --------------------------------------------------------------------------
1612   // comparator to sort nodes and sub-meshes
1613   struct ShapeTypeCompare
1614   {
1615     // sort nodes by position in the following order:
1616     // SMDS_TOP_FACE=2, SMDS_TOP_EDGE=1, SMDS_TOP_VERTEX=0, SMDS_TOP_3DSPACE=3
1617     bool operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
1618     {
1619       // NEW ORDER: nodes earlier added to sub-mesh are considered "less"
1620       return n1->getIdInShape() < n2->getIdInShape();
1621       // SMDS_TypeOfPosition pos1 = n1->GetPosition()->GetTypeOfPosition();
1622       // SMDS_TypeOfPosition pos2 = n2->GetPosition()->GetTypeOfPosition();
1623       // if ( pos1 == pos2 ) return 0;
1624       // if ( pos1 < pos2 || pos1 == SMDS_TOP_3DSPACE ) return 1;
1625       // return -1;
1626     }
1627     // sort sub-meshes in order: EDGE, VERTEX
1628     bool operator()( const SMESHDS_SubMesh* s1, const SMESHDS_SubMesh* s2 ) const
1629     {
1630       int isVertex1 = ( s1 && s1->NbElements() == 0 );
1631       int isVertex2 = ( s2 && s2->NbElements() == 0 );
1632       if ( isVertex1 == isVertex2 )
1633         return s1 < s2;
1634       return isVertex1 < isVertex2;
1635     }
1636   };
1637
1638   //================================================================================
1639   /*!
1640    * \brief Fills groups of nodes to be merged
1641    */
1642   //================================================================================
1643
1644   void getNodeGroupsToMerge( const SMESHDS_SubMesh*                smDS,
1645                              const TopoDS_Shape&                   shape,
1646                              SMESH_MeshEditor::TListOfListOfNodes& nodeGroupsToMerge)
1647   {
1648     SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1649     switch ( shape.ShapeType() )
1650     {
1651     case TopAbs_VERTEX: {
1652       std::list< const SMDS_MeshNode* > nodes;
1653       while ( nIt->more() )
1654         nodes.push_back( nIt->next() );
1655       if ( nodes.size() > 1 )
1656         nodeGroupsToMerge.push_back( nodes );
1657       break;
1658     }
1659     case TopAbs_EDGE: {
1660       std::multimap< double, const SMDS_MeshNode* > u2node;
1661       const SMDS_EdgePosition* ePos;
1662       while ( nIt->more() )
1663       {
1664         const SMDS_MeshNode* n = nIt->next();
1665         if (( ePos = dynamic_cast< const SMDS_EdgePosition* >( n->GetPosition() )))
1666           u2node.insert( make_pair( ePos->GetUParameter(), n ));
1667       }
1668       if ( u2node.size() < 2 ) return;
1669
1670       //double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
1671       Standard_Real f,l;
1672       BRep_Tool::Range( TopoDS::Edge( shape ), f,l );
1673       double tol = (( l - f ) / 20.) / u2node.size();
1674
1675       std::multimap< double, const SMDS_MeshNode* >::iterator un2, un1;
1676       for ( un2 = u2node.begin(), un1 = un2++; un2 != u2node.end(); un1 = un2++ )
1677       {
1678         if (( un2->first - un1->first ) <= tol )
1679         {
1680           std::list< const SMDS_MeshNode* > nodes;
1681           nodes.push_back( un1->second );
1682           while (( un2->first - un1->first ) <= tol )
1683           {
1684             nodes.push_back( un2->second );
1685             if ( ++un2 == u2node.end()) {
1686               --un2;
1687               break;
1688             }
1689           }
1690           // make nodes created on the boundary of viscous layer replace nodes created
1691           // by MG-CADSurf as their SMDS_Position is more correct
1692           nodes.sort( ShapeTypeCompare() );
1693           nodeGroupsToMerge.push_back( nodes );
1694         }
1695       }
1696       break;
1697     }
1698     default: ;
1699     }
1700     // SMESH_MeshEditor::TListOfListOfNodes::const_iterator nll = nodeGroupsToMerge.begin();
1701     // for ( ; nll != nodeGroupsToMerge.end(); ++nll )
1702     // {
1703     //   cout << "Merge ";
1704     //   const std::list< const SMDS_MeshNode* >& nl = *nll;
1705     //   std::list< const SMDS_MeshNode* >::const_iterator nIt = nl.begin();
1706     //   for ( ; nIt != nl.end(); ++nIt )
1707     //     cout << (*nIt) << " ";
1708     //   cout << endl;
1709     // }
1710     // cout << endl;
1711   }
1712
1713   //================================================================================
1714   /*!
1715    * \brief A temporary mesh used to compute mesh on a proxy FACE
1716    */
1717   //================================================================================
1718
1719   struct TmpMesh: public SMESH_Mesh
1720   {
1721     typedef std::map<const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
1722     TN2NMap     _tmp2origNN;
1723     TopoDS_Face _proxyFace;
1724
1725     TmpMesh()
1726     {
1727       _myMeshDS = new SMESHDS_Mesh( _id, true );
1728     }
1729     //--------------------------------------------------------------------------------
1730     /*!
1731      * \brief Creates a FACE bound by viscous layers and mesh each its EDGE with 1 segment
1732      */
1733     //--------------------------------------------------------------------------------
1734
1735     const TopoDS_Face& makeProxyFace( SMESH_ProxyMesh::Ptr& viscousMesh,
1736                                       const TopoDS_Face&    origFace)
1737     {
1738       // get data of nodes on inner boundary of viscous layers
1739       SMESH_Mesh* origMesh = viscousMesh->GetMesh();
1740       TError err;
1741       TSideVector wireVec = StdMeshers_FaceSide::GetFaceWires(origFace, *origMesh,
1742                                                               /*skipMediumNodes = */true,
1743                                                               err, viscousMesh );
1744       if ( err && err->IsKO() )
1745         throw *err.get(); // it should be caught at SMESH_subMesh
1746
1747       // proxy nodes and corresponding tmp VERTEXes
1748       std::vector<const SMDS_MeshNode*> origNodes;
1749       std::vector<TopoDS_Vertex>        tmpVertex;
1750
1751       // create a proxy FACE
1752       TopoDS_Shape origFaceCopy = origFace.EmptyCopied();
1753       BRepBuilderAPI_MakeFace newFace( TopoDS::Face( origFaceCopy ));
1754       for ( size_t iW = 0; iW != wireVec.size(); ++iW )
1755       {
1756         StdMeshers_FaceSidePtr& wireData = wireVec[iW];
1757         const UVPtStructVec& wirePoints = wireData->GetUVPtStruct();
1758         if ( wirePoints.size() < 3 )
1759           continue;
1760
1761         BRepBuilderAPI_MakePolygon wire;
1762         const size_t i0 = tmpVertex.size();
1763         for ( size_t iN = 1; iN < wirePoints.size(); ++iN )
1764         {
1765           wire.Add( SMESH_TNodeXYZ( wirePoints[ iN ].node ));
1766           origNodes.push_back( wirePoints[ iN ].node );
1767           tmpVertex.push_back( wire.LastVertex() );
1768         }
1769         tmpVertex[ i0 ] = wire.FirstVertex(); // wire.LastVertex()==NULL for 1 vertex in wire
1770         wire.Close();
1771         if ( !wire.IsDone() )
1772           throw SALOME_Exception("BLSURFPlugin_BLSURF: BRepBuilderAPI_MakePolygon failed");
1773         newFace.Add( wire );
1774       }
1775       _proxyFace = newFace;
1776
1777       // set a new shape to mesh
1778       TopoDS_Compound auxCompoundToMesh;
1779       BRep_Builder shapeBuilder;
1780       shapeBuilder.MakeCompound( auxCompoundToMesh );
1781       shapeBuilder.Add( auxCompoundToMesh, _proxyFace );
1782       shapeBuilder.Add( auxCompoundToMesh, origMesh->GetShapeToMesh() );
1783
1784       ShapeToMesh( auxCompoundToMesh );
1785
1786       //TopExp_Explorer fExp( auxCompoundToMesh, TopAbs_FACE );
1787       //_proxyFace = TopoDS::Face( fExp.Current() );
1788
1789
1790       // Make input mesh for MG-CADSurf: segments on EDGE's of newFace
1791
1792       // make nodes and fill in _tmp2origNN
1793       //
1794       SMESHDS_Mesh* tmpMeshDS = GetMeshDS();
1795       for ( size_t i = 0; i < origNodes.size(); ++i )
1796       {
1797         GetSubMesh( tmpVertex[i] )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1798         if ( const SMDS_MeshNode* tmpN = SMESH_Algo::VertexNode( tmpVertex[i], tmpMeshDS ))
1799           _tmp2origNN.insert( _tmp2origNN.end(), make_pair( tmpN, origNodes[i] ));
1800         else
1801           throw SALOME_Exception("BLSURFPlugin_BLSURF: a proxy vertex not meshed");
1802       }
1803
1804       // make segments
1805       TopoDS_Vertex v1, v2;
1806       for ( TopExp_Explorer edge( _proxyFace, TopAbs_EDGE ); edge.More(); edge.Next() )
1807       {
1808         const TopoDS_Edge& E = TopoDS::Edge( edge.Current() );
1809         TopExp::Vertices( E, v1, v2 );
1810         const SMDS_MeshNode* n1 = SMESH_Algo::VertexNode( v1, tmpMeshDS );
1811         const SMDS_MeshNode* n2 = SMESH_Algo::VertexNode( v2, tmpMeshDS );
1812
1813         if ( SMDS_MeshElement* seg = tmpMeshDS->AddEdge( n1, n2 ))
1814           tmpMeshDS->SetMeshElementOnShape( seg, E );
1815       }
1816
1817       return _proxyFace;
1818     }
1819
1820     //--------------------------------------------------------------------------------
1821     /*!
1822      * \brief Fill in the origMesh with faces computed by MG-CADSurf in this tmp mesh
1823      */
1824     //--------------------------------------------------------------------------------
1825
1826     void FillInOrigMesh( SMESH_Mesh&        origMesh,
1827                          const TopoDS_Face& origFace )
1828     {
1829       SMESH_MesherHelper helper( origMesh );
1830       helper.SetSubShape( origFace );
1831       helper.SetElementsOnShape( true );
1832
1833       SMESH_MesherHelper tmpHelper( *this );
1834       tmpHelper.SetSubShape( _proxyFace );
1835
1836       // iterate over tmp faces and copy them in origMesh
1837       const SMDS_MeshNode* nodes[27];
1838       const SMDS_MeshNode* nullNode = 0;
1839       double xyz[3];
1840       SMDS_FaceIteratorPtr fIt = GetMeshDS()->facesIterator(/*idInceasingOrder=*/true);
1841       while ( fIt->more() )
1842       {
1843         const SMDS_MeshElement* f = fIt->next();
1844         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
1845         int nbN = 0;
1846         for ( ; nIt->more(); ++nbN )
1847         {
1848           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
1849           TN2NMap::iterator n2nIt = 
1850             _tmp2origNN.insert( _tmp2origNN.end(), make_pair( n, nullNode ));
1851           if ( !n2nIt->second ) {
1852             n->GetXYZ( xyz );
1853             gp_XY uv = tmpHelper.GetNodeUV( _proxyFace, n );
1854             n2nIt->second = helper.AddNode( xyz[0], xyz[1], xyz[2], uv.X(), uv.Y() );
1855           }
1856           nodes[ nbN ] = n2nIt->second;
1857         }
1858         switch( nbN ) {
1859         case 3: helper.AddFace( nodes[0], nodes[1], nodes[2] ); break;
1860         // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
1861         //                         nodes[3], nodes[4], nodes[5]); break;
1862         case 4: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
1863         // case 9: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1864         //                         nodes[4], nodes[5], nodes[6], nodes[7], nodes[8]); break;
1865         // case 8: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1866         //                         nodes[4], nodes[5], nodes[6], nodes[7]); break;
1867         }
1868       }
1869     }
1870   };
1871
1872   /*!
1873    * \brief A structure holding an error description and a verbisity level
1874    */
1875   struct message_cb_user_data
1876   {
1877     std::string * _error;
1878     int           _verbosity;
1879     double *      _progress;
1880   };
1881
1882
1883 } // namespace
1884
1885 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1886 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1887                   real *duu, real *duv, real *dvv, void *user_data);
1888 status_t message_cb(message_t *msg, void *user_data);
1889 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1890
1891 //=============================================================================
1892 /*!
1893  *
1894  */
1895 //=============================================================================
1896
1897 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
1898
1899   MESSAGE("BLSURFPlugin_BLSURF::Compute");
1900
1901   // Fix problem with locales
1902   Kernel_Utils::Localizer aLocalizer;
1903
1904   this->SMESH_Algo::_progress = 1e-3; // prevent progress advancment while computing attractors
1905
1906   if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1907     return false;
1908
1909   if ( _haveViscousLayers )
1910   {
1911     // Compute viscous layers
1912
1913     TopTools_MapOfShape map;
1914     for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1915     {
1916       const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1917       if ( !map.Add( F )) continue;
1918       SMESH_ProxyMesh::Ptr viscousMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
1919       if ( !viscousMesh )
1920         return false; // error in StdMeshers_ViscousLayers2D::Compute()
1921
1922       // Compute MG-CADSurf mesh on viscous layers
1923
1924       if ( viscousMesh->NbProxySubMeshes() > 0 )
1925       {
1926         TmpMesh tmpMesh;
1927         const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
1928         if ( !compute( tmpMesh, proxyFace, /*allowSubMeshClearing=*/false ))
1929           return false;
1930         tmpMesh.FillInOrigMesh( aMesh, F );
1931       }
1932     }
1933
1934     // Re-compute MG-CADSurf mesh on the rest faces if the mesh was cleared
1935
1936     for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1937     {
1938       const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1939       SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
1940       if ( fSM->IsMeshComputed() ) continue;
1941
1942       if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1943         return false;
1944       break;
1945     }
1946   }
1947   return true;
1948 }
1949
1950 //=============================================================================
1951 /*!
1952  *
1953  */
1954 //=============================================================================
1955
1956 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
1957                                   const TopoDS_Shape& aShape,
1958                                   bool                allowSubMeshClearing)
1959 {
1960   /* create a distene context (generic object) */
1961   status_t status = STATUS_ERROR;
1962
1963   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1964   SMESH_MesherHelper helper( aMesh );
1965   // do not call helper.IsQuadraticSubMesh() because sub-meshes
1966   // may be cleaned and helper.myTLinkNodeMap gets invalid in such a case
1967   bool haveQuadraticSubMesh = SMESH_MesherHelper( aMesh ).IsQuadraticSubMesh( aShape );
1968   bool quadraticSubMeshAndViscousLayer = false;
1969   bool needMerge = false;
1970   typedef set< SMESHDS_SubMesh*, ShapeTypeCompare > TSubMeshSet;
1971   TSubMeshSet edgeSubmeshes;
1972   TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
1973
1974   TopTools_IndexedMapOfShape emap;
1975   TopTools_IndexedMapOfShape pmap;
1976
1977   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1978 #ifndef WIN32
1979   feclearexcept( FE_ALL_EXCEPT );
1980   int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1981 #endif
1982
1983   context_t *ctx =  context_new();
1984
1985   /* Set the message callback in the working context */
1986   message_cb_user_data mcud;
1987   mcud._error     = & this->SMESH_Algo::_comment;
1988   mcud._progress  = & this->SMESH_Algo::_progress;
1989   mcud._verbosity =
1990     _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
1991   context_set_message_callback(ctx, message_cb, &mcud);
1992
1993   /* set the interruption callback */
1994   _compute_canceled = false;
1995   context_set_interrupt_callback(ctx, interrupt_cb, this);
1996
1997   /* create the CAD object we will work on. It is associated to the context ctx. */
1998   cad_t *c     = cad_new(ctx);
1999   dcad_t *dcad = dcad_new(c);
2000
2001   FacesWithSizeMap.Clear();
2002   FaceId2SizeMap.clear();
2003   FaceId2ClassAttractor.clear();
2004   FaceIndex2ClassAttractor.clear();
2005   EdgesWithSizeMap.Clear();
2006   EdgeId2SizeMap.clear();
2007   VerticesWithSizeMap.Clear();
2008   VertexId2SizeMap.clear();
2009
2010   /* Now fill the CAD object with data from your CAD
2011    * environement. This is the most complex part of a successfull
2012    * integration.
2013    */
2014
2015   // PreCAD
2016   // If user requests it, send the CAD through Distene preprocessor : PreCAD
2017   cad_t *cleanc = NULL; // preprocessed cad
2018   dcad_t *cleandc = NULL; // preprocessed dcad
2019   precad_session_t *pcs = precad_session_new(ctx);
2020   // Give both dcad and cad to precad
2021   precad_data_set_dcad(pcs, dcad);
2022   precad_data_set_cad(pcs, c);
2023
2024   cadsurf_session_t *css = cadsurf_session_new(ctx);
2025
2026   // an object that correctly deletes all cadsurf objects at destruction
2027   BLSURF_Cleaner cleaner( ctx,css,c,dcad,cleanc,cleandc );
2028
2029   MESSAGE("BEGIN SetParameters");
2030   bool use_precad = false;
2031   SetParameters(
2032                 // #if BLSURF_VERSION_LONG >= "3.1.1"
2033                 //     c,
2034                 // #endif
2035                 _hypothesis, css, pcs, aShape, &use_precad);
2036   MESSAGE("END SetParameters");
2037
2038   MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
2039
2040   haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis != NULL && _hypothesis->GetQuadraticMesh());
2041   helper.SetIsQuadratic( haveQuadraticSubMesh );
2042
2043   // To remove as soon as quadratic mesh is allowed - BEGIN
2044   // GDD: Viscous layer is not allowed with quadratic mesh
2045   if (_haveViscousLayers && haveQuadraticSubMesh ) {
2046     quadraticSubMeshAndViscousLayer = true;
2047     _haveViscousLayers = !haveQuadraticSubMesh;
2048     _comment += "Warning: Viscous layer is not possible with a quadratic mesh, it is ignored.";
2049     error(COMPERR_WARNING, _comment);
2050   }
2051   // To remove as soon as quadratic mesh is allowed - END
2052
2053   // needed to prevent the opencascade memory managmement from freeing things
2054   vector<Handle(Geom2d_Curve)> curves;
2055   vector<Handle(Geom_Surface)> surfaces;
2056
2057   emap.Clear();
2058   pmap.Clear();
2059   FaceId2PythonSmp.clear();
2060   EdgeId2PythonSmp.clear();
2061   VertexId2PythonSmp.clear();
2062
2063   /****************************************************************************************
2064                                           FACES
2065   *****************************************************************************************/
2066   int iface = 0;
2067   string bad_end = "return";
2068   int faceKey = -1;
2069   TopTools_IndexedMapOfShape _map;
2070   TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
2071   int ienf = _map.Extent();
2072
2073   assert(Py_IsInitialized());
2074   PyGILState_STATE gstate;
2075
2076   string theSizeMapStr;
2077
2078   for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
2079   {
2080     TopoDS_Face f = TopoDS::Face(face_iter.Current());
2081
2082     SMESH_subMesh* fSM = aMesh.GetSubMesh( f );
2083     if ( !fSM->IsEmpty() ) continue; // skip already meshed FACE with viscous layers
2084
2085     // make INTERNAL face oriented FORWARD (issue 0020993)
2086     if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
2087       f.Orientation(TopAbs_FORWARD);
2088
2089     iface = meshDS->ShapeToIndex(f);
2090 //    std::string aFileName = "fmap_face_";
2091 //    aFileName.append(to_string(iface));
2092 //    aFileName.append(".brep");
2093 //    BRepTools::Write(f,aFileName.c_str());
2094
2095     surfaces.push_back(BRep_Tool::Surface(f));
2096
2097     /* create an object representing the face for cadsurf */
2098     /* where face_id is an integer identifying the face.
2099      * surf_function is the function that defines the surface
2100      * (For this face, it will be called by cadsurf with your_face_object_ptr
2101      * as last parameter.
2102      */
2103     cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
2104
2105     /* by default a face has no tag (color).
2106        The following call sets it to the same value as the face_id : */
2107     cad_face_set_tag(fce, iface);
2108
2109     /* Set face orientation (optional if you want a well oriented output mesh)*/
2110     if(f.Orientation() != TopAbs_FORWARD)
2111       cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
2112     else
2113       cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
2114
2115     if (HasSizeMapOnFace /*&& !use_precad*/) //22903: use_precad seems not to interfere
2116     {
2117       // -----------------
2118       // Classic size map
2119       // -----------------
2120       faceKey = FacesWithSizeMap.FindIndex(f);
2121
2122
2123       if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()) {
2124         MESSAGE("A size map is defined on face :"<<faceKey)
2125           theSizeMapStr = FaceId2SizeMap[faceKey];
2126         // check if function ends with "return"
2127         if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2128           continue;
2129         // Expr To Python function, verification is performed at validation in GUI
2130         gstate = PyGILState_Ensure();
2131         PyObject * obj = NULL;
2132         obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2133         Py_DECREF(obj);
2134         PyObject * func = NULL;
2135         func = PyObject_GetAttrString(main_mod, "f");
2136         FaceId2PythonSmp[iface]=func;
2137         FaceId2SizeMap.erase(faceKey);
2138         PyGILState_Release(gstate);
2139       }
2140
2141       // Specific size map = Attractor
2142       std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
2143
2144       for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
2145         if (attractor_iter->first == faceKey) {
2146           MESSAGE("Face indice: " << iface);
2147           MESSAGE("Adding attractor");
2148
2149           double xyzCoords[3]  = {attractor_iter->second[2],
2150                                   attractor_iter->second[3],
2151                                   attractor_iter->second[4]};
2152
2153           MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
2154           gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2155           BRepClass_FaceClassifier scl(f,P,1e-7);
2156           // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
2157           // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
2158           // OCC 6.5.2: scl.Perform() is not bugged anymore
2159           scl.Perform(f, P, 1e-7);
2160           TopAbs_State result = scl.State();
2161           MESSAGE("Position of point on face: "<<result);
2162           if ( result == TopAbs_OUT )
2163             MESSAGE("Point is out of face: node is not created");
2164           if ( result == TopAbs_UNKNOWN )
2165             MESSAGE("Point position on face is unknown: node is not created");
2166           if ( result == TopAbs_ON )
2167             MESSAGE("Point is on border of face: node is not created");
2168           if ( result == TopAbs_IN )
2169           {
2170             // Point is inside face and not on border
2171             MESSAGE("Point is in face: node is created");
2172             double uvCoords[2] = {attractor_iter->second[0],attractor_iter->second[1]};
2173             ienf++;
2174             MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2175             cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2176             cad_point_set_tag(point_p, ienf);
2177           }
2178           FaceId2AttractorCoords.erase(faceKey);
2179         }
2180       }
2181
2182       // -----------------
2183       // Class Attractors
2184       // -----------------
2185       TId2ClsAttractorVec::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
2186       if (clAttractor_iter != FaceId2ClassAttractor.end()){
2187         MESSAGE("Face indice: " << iface);
2188         MESSAGE("Adding attractor");
2189         std::vector< BLSURFPlugin_Attractor* > & attVec = clAttractor_iter->second;
2190         for ( size_t i = 0; i < attVec.size(); ++i )
2191           if ( !attVec[i]->IsMapBuilt() ) {
2192             std::cout<<"Compute " << theNbAttractors-- << "-th attractor" <<std::endl;
2193             attVec[i]->BuildMap();
2194           }
2195         FaceIndex2ClassAttractor[iface].swap( attVec );
2196         FaceId2ClassAttractor.erase(clAttractor_iter);
2197       }
2198     } // if (HasSizeMapOnFace && !use_precad)
2199
2200       // ------------------
2201       // Enforced Vertices
2202       // ------------------
2203     faceKey = FacesWithEnforcedVertices.FindIndex(f);
2204     std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
2205     if (evmIt != FaceId2EnforcedVertexCoords.end()) {
2206       MESSAGE("Some enforced vertices are defined");
2207       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl;
2208       MESSAGE("Face indice: " << iface);
2209       MESSAGE("Adding enforced vertices");
2210       evl = evmIt->second;
2211       MESSAGE("Number of vertices to add: "<< evl.size());
2212       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
2213       for (; evlIt != evl.end(); ++evlIt) {
2214         BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
2215         xyzCoords.push_back(evlIt->at(2));
2216         xyzCoords.push_back(evlIt->at(3));
2217         xyzCoords.push_back(evlIt->at(4));
2218         MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
2219         gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2220         BRepClass_FaceClassifier scl(f,P,1e-7);
2221         // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
2222         // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
2223         // OCC 6.5.2: scl.Perform() is not bugged anymore
2224         scl.Perform(f, P, 1e-7);
2225         TopAbs_State result = scl.State();
2226         MESSAGE("Position of point on face: "<<result);
2227         if ( result == TopAbs_OUT ) {
2228           MESSAGE("Point is out of face: node is not created");
2229           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2230             EnfVertexCoords2ProjVertex.erase(xyzCoords);
2231             // isssue 22783. Do not erase as this point can be IN other face of a group
2232             //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2233           }
2234         }
2235         if ( result == TopAbs_UNKNOWN ) {
2236           MESSAGE("Point position on face is unknown: node is not created");
2237           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2238             EnfVertexCoords2ProjVertex.erase(xyzCoords);
2239             //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2240           }
2241         }
2242         if ( result == TopAbs_ON ) {
2243           MESSAGE("Point is on border of face: node is not created");
2244           if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2245             EnfVertexCoords2ProjVertex.erase(xyzCoords);
2246             //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2247           }
2248         }
2249         if ( result == TopAbs_IN )
2250         {
2251           // Point is inside face and not on border
2252           MESSAGE("Point is in face: node is created");
2253           double uvCoords[2]   = {evlIt->at(0),evlIt->at(1)};
2254           ienf++;
2255           MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2256           cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2257           int tag = 0;
2258           std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(xyzCoords);
2259           if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end() &&
2260               !enfCoordsIt->second.empty() )
2261           {
2262             // to merge nodes of an INTERNAL vertex belonging to several faces
2263             TopoDS_Vertex     v = (*enfCoordsIt->second.begin())->vertex;
2264             if ( v.IsNull() ) v = (*enfCoordsIt->second.rbegin())->vertex;
2265             if ( !v.IsNull() ) {
2266               tag = pmap.Add( v );
2267               SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
2268               vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2269               mergeSubmeshes.insert( vSM->GetSubMeshDS() );
2270               // //if ( tag != pmap.Extent() )
2271               // needMerge = true;
2272             }
2273           }
2274           if ( tag == 0 ) tag = ienf;
2275           cad_point_set_tag(point_p, tag);
2276         }
2277       }
2278       FaceId2EnforcedVertexCoords.erase(faceKey);
2279
2280     }
2281
2282     /****************************************************************************************
2283                                            EDGES
2284                         now create the edges associated to this face
2285     *****************************************************************************************/
2286     int edgeKey = -1;
2287     for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next())
2288     {
2289       TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
2290       int ic = emap.FindIndex(e);
2291       if (ic <= 0)
2292         ic = emap.Add(e);
2293
2294 //      std::string aFileName = "fmap_edge_";
2295 //      aFileName.append(to_string(ic));
2296 //      aFileName.append(".brep");
2297 //      BRepTools::Write(e,aFileName.c_str());
2298
2299       double tmin,tmax;
2300       curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
2301
2302       if (HasSizeMapOnEdge){
2303         edgeKey = EdgesWithSizeMap.FindIndex(e);
2304         if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
2305           MESSAGE("Sizemap defined on edge with index " << edgeKey);
2306           theSizeMapStr = EdgeId2SizeMap[edgeKey];
2307           if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2308             continue;
2309           // Expr To Python function, verification is performed at validation in GUI
2310           gstate = PyGILState_Ensure();
2311           PyObject * obj = NULL;
2312           obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2313           Py_DECREF(obj);
2314           PyObject * func = NULL;
2315           func = PyObject_GetAttrString(main_mod, "f");
2316           EdgeId2PythonSmp[ic]=func;
2317           EdgeId2SizeMap.erase(edgeKey);
2318           PyGILState_Release(gstate);
2319         }
2320       }
2321       /* data of nodes existing on the edge */
2322       StdMeshers_FaceSidePtr nodeData;
2323       SMESH_subMesh* sm = aMesh.GetSubMesh( e );
2324       if ( !sm->IsEmpty() )
2325       {
2326         // SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
2327         //                                                              /*complexFirst=*/false);
2328         // while ( subsmIt->more() )
2329         //   edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
2330         edgeSubmeshes.insert( sm->GetSubMeshDS() );
2331
2332         nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
2333                                                  /*ignoreMedium=*/haveQuadraticSubMesh));
2334         if ( nodeData->MissVertexNode() )
2335           return error(COMPERR_BAD_INPUT_MESH,"No node on vertex");
2336
2337         const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2338         if ( !nodeDataVec.empty() )
2339         {
2340           if ( Abs( nodeDataVec[0].param - tmin ) > Abs( nodeDataVec.back().param - tmin ))
2341           {
2342             nodeData->Reverse();
2343             nodeData->GetUVPtStruct(); // nodeData recomputes nodeDataVec
2344           }
2345           // tmin and tmax can change in case of viscous layer on an adjacent edge
2346           tmin = nodeDataVec.front().param;
2347           tmax = nodeDataVec.back().param;
2348         }
2349         else
2350         {
2351           cout << "---------------- Invalid nodeData" << endl;
2352           nodeData.reset();
2353         }
2354       }
2355
2356       /* attach the edge to the current cadsurf face */
2357       cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
2358
2359       /* by default an edge has no tag (color).
2360          The following call sets it to the same value as the edge_id : */
2361       cad_edge_set_tag(edg, ic);
2362
2363       /* by default, an edge does not necessalry appear in the resulting mesh,
2364          unless the following property is set :
2365       */
2366       cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
2367
2368       /* by default an edge is a boundary edge */
2369       if (e.Orientation() == TopAbs_INTERNAL)
2370         cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
2371
2372       // pass existing nodes of sub-meshes to MG-CADSurf
2373       if ( nodeData )
2374       {
2375         const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2376         const int                      nbNodes     = nodeDataVec.size();
2377
2378         dcad_edge_discretization_t *dedge;
2379         dcad_get_edge_discretization(dcad, edg, &dedge);
2380         dcad_edge_discretization_set_vertex_count( dedge, nbNodes );
2381
2382         // cout << endl << " EDGE " << ic << endl;
2383         // cout << "tmin = "<<tmin << ", tmax = "<< tmax << endl;
2384         for ( int iN = 0; iN < nbNodes; ++iN )
2385         {
2386           const UVPtStruct& nData = nodeDataVec[ iN ];
2387           double t                = nData.param;
2388           real uv[2]              = { nData.u, nData.v };
2389           SMESH_TNodeXYZ nXYZ( nData.node );
2390           // cout << "\tt = " << t
2391           //      << "\t uv = ( " << uv[0] << ","<< uv[1] << " ) "
2392           //      << "\t u = " << nData.param
2393           //      << "\t ID = " << nData.node->GetID() << endl;
2394           dcad_edge_discretization_set_vertex_coordinates( dedge, iN+1, t, uv, nXYZ._xyz );
2395         }
2396         dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2397       }
2398
2399       /****************************************************************************************
2400                                       VERTICES
2401       *****************************************************************************************/
2402
2403       int npts = 0;
2404       int ip1, ip2, *ip;
2405       gp_Pnt2d e0 = curves.back()->Value(tmin);
2406       gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
2407       Standard_Real d1=0,d2=0;
2408
2409       int vertexKey = -1;
2410       for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
2411         TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
2412         ++npts;
2413         if (npts == 1){
2414           ip = &ip1;
2415           d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2416         } else {
2417           ip = &ip2;
2418           d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2419         }
2420         *ip = pmap.FindIndex(v);
2421         if(*ip <= 0) {
2422           *ip = pmap.Add(v);
2423           // SMESH_subMesh* sm = aMesh.GetSubMesh(v);
2424           // if ( sm->IsMeshComputed() )
2425           //   edgeSubmeshes.insert( sm->GetSubMeshDS() );
2426         }
2427
2428 //        std::string aFileName = "fmap_vertex_";
2429 //        aFileName.append(to_string(*ip));
2430 //        aFileName.append(".brep");
2431 //        BRepTools::Write(v,aFileName.c_str());
2432
2433         if (HasSizeMapOnVertex){
2434           vertexKey = VerticesWithSizeMap.FindIndex(v);
2435           if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
2436             theSizeMapStr = VertexId2SizeMap[vertexKey];
2437             //MESSAGE("VertexId2SizeMap[faceKey]: " << VertexId2SizeMap[vertexKey]);
2438             if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2439               continue;
2440             // Expr To Python function, verification is performed at validation in GUI
2441             gstate = PyGILState_Ensure();
2442             PyObject * obj = NULL;
2443             obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2444             Py_DECREF(obj);
2445             PyObject * func = NULL;
2446             func = PyObject_GetAttrString(main_mod, "f");
2447             VertexId2PythonSmp[*ip]=func;
2448             VertexId2SizeMap.erase(vertexKey);   // do not erase if using a vector
2449             PyGILState_Release(gstate);
2450           }
2451         }
2452       }
2453       if (npts != 2) {
2454         // should not happen
2455         MESSAGE("An edge does not have 2 extremities.");
2456       } else {
2457         if (d1 < d2) {
2458           // This defines the curves extremity connectivity
2459           cad_edge_set_extremities(edg, ip1, ip2);
2460           /* set the tag (color) to the same value as the extremity id : */
2461           cad_edge_set_extremities_tag(edg, ip1, ip2);
2462         }
2463         else {
2464           cad_edge_set_extremities(edg, ip2, ip1);
2465           cad_edge_set_extremities_tag(edg, ip2, ip1);
2466         }
2467       }
2468     } // for edge
2469   } //for face
2470
2471   // Clear mesh from already meshed edges if possible else
2472   // remember that merge is needed
2473   TSubMeshSet::iterator smIt = edgeSubmeshes.begin();
2474   for ( ; smIt != edgeSubmeshes.end(); ++smIt ) // loop on already meshed EDGEs
2475   {
2476     SMESHDS_SubMesh* smDS = *smIt;
2477     if ( !smDS ) continue;
2478     SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2479     if ( nIt->more() )
2480     {
2481       const SMDS_MeshNode* n = nIt->next();
2482       if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
2483       {
2484         needMerge = true; // to correctly sew with viscous mesh
2485         // add existing medium nodes to helper
2486         if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
2487         {
2488           SMDS_ElemIteratorPtr edgeIt = smDS->GetElements();
2489           while ( edgeIt->more() )
2490             helper.AddTLinks( static_cast<const SMDS_MeshEdge*>(edgeIt->next()));
2491         }
2492         continue;
2493       }
2494     }
2495     if ( allowSubMeshClearing )
2496     {
2497       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2498       while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), 0 );
2499       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2500       while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), 0 );
2501       smDS->Clear();
2502     }
2503     else
2504     {
2505       needMerge = true;
2506     }
2507   }
2508
2509   ///////////////////////
2510   // PERIODICITY       //
2511   ///////////////////////
2512
2513   MESSAGE("BEFORE PERIODICITY");
2514   MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
2515   if (! _preCadFacesIDsPeriodicityVector.empty()) {
2516     MESSAGE("INTO PRECAD FACES PERIODICITY");
2517     for (std::size_t i=0; i < _preCadFacesIDsPeriodicityVector.size(); i++){
2518       std::vector<int> theFace1_ids = _preCadFacesIDsPeriodicityVector[i].shape1IDs;
2519       std::vector<int> theFace2_ids = _preCadFacesIDsPeriodicityVector[i].shape2IDs;
2520       int* theFace1_ids_c = &theFace1_ids[0];
2521       int* theFace2_ids_c = &theFace2_ids[0];
2522       std::ostringstream o;
2523       o << "_preCadFacesIDsPeriodicityVector[" << i << "] = [";
2524       for (std::size_t j=0; j < theFace1_ids.size(); j++)
2525         o << theFace1_ids[j] << ", ";
2526       o << "], [";
2527       for (std::size_t j=0; j < theFace2_ids.size(); j++)
2528         o << theFace2_ids[j] << ", ";
2529       o << "]";
2530       MESSAGE(o.str());
2531       MESSAGE("theFace1_ids.size(): " << theFace1_ids.size());
2532       MESSAGE("theFace2_ids.size(): " << theFace2_ids.size());
2533       if (_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2534         {
2535           // If no source points, call peridoicity without transformation function
2536           MESSAGE("periodicity without transformation function");
2537           meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2538           status = cad_add_face_multiple_periodicity_with_transformation_function(c, theFace1_ids_c, theFace1_ids.size(),
2539               theFace2_ids_c, theFace2_ids.size(), periodicity_transformation, NULL);
2540           if(status != STATUS_OK)
2541             cout << "cad_add_face_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2542         }
2543       else
2544         {
2545           // get the transformation vertices
2546           MESSAGE("periodicity with transformation vertices");
2547           double* theSourceVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2548           double* theTargetVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2549           int nbSourceVertices = _preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2550           int nbTargetVertices = _preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2551
2552           MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2553
2554           status = cad_add_face_multiple_periodicity_with_transformation_function_by_points(c, theFace1_ids_c, theFace1_ids.size(),
2555               theFace2_ids_c, theFace2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2556           if(status != STATUS_OK)
2557             cout << "cad_add_face_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2558         }
2559     }
2560
2561     MESSAGE("END PRECAD FACES PERIODICITY");
2562   }
2563
2564   MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
2565   if (! _preCadEdgesIDsPeriodicityVector.empty()) {
2566     MESSAGE("INTO PRECAD EDGES PERIODICITY");
2567     for (std::size_t i=0; i < _preCadEdgesIDsPeriodicityVector.size(); i++){
2568       std::vector<int> theEdge1_ids = _preCadEdgesIDsPeriodicityVector[i].shape1IDs;
2569       std::vector<int> theEdge2_ids = _preCadEdgesIDsPeriodicityVector[i].shape2IDs;
2570       // Use the address of the first element of the vector to initialise the array
2571       int* theEdge1_ids_c = &theEdge1_ids[0];
2572       int* theEdge2_ids_c = &theEdge2_ids[0];
2573
2574       std::ostringstream o;
2575       o << "_preCadEdgesIDsPeriodicityVector[" << i << "] = [";
2576       for (std::size_t j=0; j < theEdge1_ids.size(); j++)
2577         o << theEdge1_ids[j] << ", ";
2578       o << "], [";
2579       for (std::size_t j=0; j < theEdge2_ids.size(); j++)
2580         o << theEdge2_ids[j] << ", ";
2581       o << "]";
2582       MESSAGE(o.str());
2583       MESSAGE("theEdge1_ids.size(): " << theEdge1_ids.size());
2584       MESSAGE("theEdge2_ids.size(): " << theEdge2_ids.size());
2585
2586       if (_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2587         {
2588           // If no source points, call peridoicity without transformation function
2589           MESSAGE("periodicity without transformation function");
2590           meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2591           status = cad_add_edge_multiple_periodicity_with_transformation_function(c, theEdge1_ids_c, theEdge1_ids.size(),
2592               theEdge2_ids_c, theEdge2_ids.size(), periodicity_transformation, NULL);
2593           if(status != STATUS_OK)
2594             cout << "cad_add_edge_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2595         }
2596       else
2597         {
2598           // get the transformation vertices
2599           MESSAGE("periodicity with transformation vertices");
2600           double* theSourceVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2601           double* theTargetVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2602           int nbSourceVertices = _preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2603           int nbTargetVertices = _preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2604
2605           MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2606
2607           status = cad_add_edge_multiple_periodicity_with_transformation_function_by_points(c, theEdge1_ids_c, theEdge1_ids.size(),
2608               theEdge2_ids_c, theEdge2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2609           if(status != STATUS_OK)
2610             cout << "cad_add_edge_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2611           else
2612             MESSAGE("cad_add_edge_multiple_periodicity_with_transformation_function_by_points succeeded.\n");
2613         }
2614     }
2615
2616     MESSAGE("END PRECAD EDGES PERIODICITY");
2617   }
2618
2619   if (! _facesIDsPeriodicityVector.empty()){
2620     MESSAGE("INTO FACE PERIODICITY");
2621     for (std::size_t i=0; i < _facesIDsPeriodicityVector.size(); i++){
2622       int theFace1 = _facesIDsPeriodicityVector[i].first;
2623       int theFace2 = _facesIDsPeriodicityVector[i].second;
2624       MESSAGE("_facesIDsPeriodicityVector[" << i << "] = (" << theFace1 << ", " << theFace2 << ")");
2625       status = cad_add_face_periodicity(c, theFace1, theFace2);
2626       if(status != STATUS_OK){
2627         cout << "cad_add_face_periodicity failed with error code " << status << "\n";
2628       }
2629     }
2630     MESSAGE("END FACE PERIODICITY");
2631   }
2632
2633
2634   if (! _edgesIDsPeriodicityVector.empty()){
2635     MESSAGE("INTO EDGE PERIODICITY");
2636     for (std::size_t i=0; i < _edgesIDsPeriodicityVector.size(); i++){
2637       int theFace1 = _edgesIDsPeriodicityVector[i].theFace1ID;
2638       int theEdge1 = _edgesIDsPeriodicityVector[i].theEdge1ID;
2639       int theFace2 = _edgesIDsPeriodicityVector[i].theFace2ID;
2640       int theEdge2 = _edgesIDsPeriodicityVector[i].theEdge2ID;
2641       int edge_orientation = _edgesIDsPeriodicityVector[i].edge_orientation;
2642       MESSAGE("_edgesIDsPeriodicityVector[" << i << "] = (" << theFace1 << ", " << theEdge1 << ", " << theFace2 << ", " << theEdge2 << ", " << edge_orientation << ")");
2643       status = cad_add_edge_periodicity(c, theFace1, theEdge1, theFace2, theEdge2, edge_orientation);
2644       if(status != STATUS_OK){
2645         cout << "cad_add_edge_periodicity failed with error code " << status << "\n";
2646       }
2647     }
2648     MESSAGE("END EDGE PERIODICITY");
2649   }
2650
2651   if (! _verticesIDsPeriodicityVector.empty()){
2652     MESSAGE("INTO VERTEX PERIODICITY");
2653     for (std::size_t i=0; i < _verticesIDsPeriodicityVector.size(); i++){
2654       int theEdge1 = _verticesIDsPeriodicityVector[i].theEdge1ID;
2655       int theVertex1 = _verticesIDsPeriodicityVector[i].theVertex1ID;
2656       int theEdge2 = _verticesIDsPeriodicityVector[i].theEdge2ID;
2657       int theVertex2 = _verticesIDsPeriodicityVector[i].theVertex2ID;
2658       MESSAGE("_verticesIDsPeriodicityVector[" << i << "] = (" << theEdge1 << ", " << theVertex1 << ", " << theEdge2 << ", " << theVertex2 << ")");
2659       status = cad_add_point_periodicity(c, theEdge1, theVertex1, theEdge2, theVertex2);
2660       if(status != STATUS_OK){
2661         cout << "cad_add_vertex_periodicity failed with error code " << status << "\n";
2662       }
2663     }
2664     MESSAGE("END VERTEX PERIODICITY");
2665   }
2666
2667     ////
2668
2669   if (use_precad) {
2670     MESSAGE("use_precad");
2671     /* Now launch the PreCAD process */
2672     status = precad_process(pcs);
2673     if(status != STATUS_OK){
2674       // TODO: raise an error if status < 0.
2675       cout << "================ WARNING =================== \n";
2676       stringstream msg;
2677       msg << "PreCAD processing failed with error code " << status << "\n";
2678       msg << *mcud._error;
2679       cout << msg.str();
2680       cout << "============================================ \n";
2681       // the text of _comment is set in message_cb by mcud->_error
2682       // => No need to append msg to _comment
2683       if (status > 0)
2684         {
2685           // TODO: fix the SIGSEGV of COMPERR_WARNING with 2 launches
2686           error(COMPERR_WARNING, _comment);
2687         }
2688       if (status < 0)
2689         {
2690           error(_comment);
2691         }
2692     }
2693     else {
2694       // retrieve the pre-processed CAD object
2695
2696       // dcad
2697       cleandc = precad_new_dcad(pcs);
2698       if(!cleandc){
2699         cout << "Unable to retrieve PreCAD result on dcad \n";
2700       }
2701       else
2702         cout << "PreCAD processing successfull on dcad \n";
2703
2704       // cad
2705       cleanc = precad_new_cad(pcs);
2706       if(!cleanc){
2707         cout << "Unable to retrieve PreCAD result on cad \n";
2708       }
2709       else
2710         cout << "PreCAD processing successfull on cad \n";
2711
2712       // #if BLSURF_VERSION_LONG >= "3.1.1"
2713       //       /* We can now get the updated sizemaps (if any) */
2714       // //       if(geo_sizemap_e)
2715       // //         clean_geo_sizemap_e = precad_new_sizemap(pcs, geo_sizemap_e);
2716       // // 
2717       // //       if(geo_sizemap_f)
2718       // //         clean_geo_sizemap_f = precad_new_sizemap(pcs, geo_sizemap_f);
2719       //
2720       //       if(iso_sizemap_p)
2721       //         clean_iso_sizemap_p = precad_new_sizemap(pcs, iso_sizemap_p);
2722       //
2723       //       if(iso_sizemap_e)
2724       //         clean_iso_sizemap_e = precad_new_sizemap(pcs, iso_sizemap_e);
2725       //
2726       //       if(iso_sizemap_f)
2727       //         clean_iso_sizemap_f = precad_new_sizemap(pcs, iso_sizemap_f);
2728       // #endif
2729     }
2730     // Now we can delete the PreCAD session
2731     precad_session_delete(pcs);
2732   }
2733
2734   if (cleandc) {
2735     cout << "Give the pre-processed dcad object to the current MG-CADSurf session \n";
2736     cadsurf_data_set_dcad(css, cleandc);
2737   }
2738   else {
2739     // Use the original one
2740     cadsurf_data_set_dcad(css, dcad);
2741   }
2742
2743   if (cleanc) {
2744     // Give the pre-processed CAD object to the current MG-CADSurf session
2745     cout << "Give the pre-processed CAD object to the current MG-CADSurf session \n";
2746     cadsurf_data_set_cad(css, cleanc);
2747   }
2748   else {
2749     // Use the original one
2750     cadsurf_data_set_cad(css, c);
2751   }
2752
2753   std::cout << std::endl;
2754   std::cout << "Beginning of Surface Mesh generation" << std::endl;
2755   std::cout << std::endl;
2756
2757   try {
2758     OCC_CATCH_SIGNALS;
2759
2760     status = cadsurf_compute_mesh(css);
2761
2762   }
2763   catch ( std::exception& exc ) {
2764     _comment += exc.what();
2765   }
2766   catch (Standard_Failure& ex) {
2767     _comment += ex.DynamicType()->Name();
2768     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
2769       _comment += ": ";
2770       _comment += ex.GetMessageString();
2771     }
2772   }
2773   catch (...) {
2774     if ( _comment.empty() )
2775       _comment = "Exception in cadsurf_compute_mesh()";
2776   }
2777
2778   std::cout << std::endl;
2779   std::cout << "End of Surface Mesh generation" << std::endl;
2780   std::cout << std::endl;
2781
2782   mesh_t *msh = NULL;
2783   cadsurf_data_get_mesh(css, &msh);
2784   if(!msh){
2785     /* release the mesh object */
2786     cadsurf_data_regain_mesh(css, msh);
2787     return error(_comment);
2788   }
2789
2790   std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
2791   if (_hypothesis)
2792     GMFFileName = _hypothesis->GetGMFFile();
2793   if (GMFFileName != "") {
2794     //     bool GMFFileMode = _hypothesis->GetGMFFileMode();
2795     bool asciiFound = (GMFFileName.find(".mesh",GMFFileName.length()-5) != std::string::npos);
2796     bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
2797     if (!asciiFound && !binaryFound)
2798       GMFFileName.append(".mesh");
2799     mesh_write_mesh(msh, GMFFileName.c_str());
2800   }
2801
2802   /* retrieve mesh data (see meshgems/mesh.h) */
2803   integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
2804   integer *evedg, *evtri, *evquad, *tags_buff, type;
2805   real xyz[3];
2806
2807   mesh_get_vertex_count(msh, &nv);
2808   mesh_get_edge_count(msh, &ne);
2809   mesh_get_triangle_count(msh, &nt);
2810   mesh_get_quadrangle_count(msh, &nq);
2811
2812   evedg  = (integer *)mesh_calloc_generic_buffer(msh);
2813   evtri  = (integer *)mesh_calloc_generic_buffer(msh);
2814   evquad = (integer *)mesh_calloc_generic_buffer(msh);
2815   tags_buff = (integer*)mesh_calloc_generic_buffer(msh);
2816
2817   std::vector<const SMDS_MeshNode*> nodes(nv+1);
2818   std::vector<bool>                  tags(nv+1);
2819
2820   /* enumerated vertices */
2821   for(int iv=1;iv<=nv;iv++) {
2822     mesh_get_vertex_coordinates(msh, iv, xyz);
2823     mesh_get_vertex_tag(msh, iv, &tag);
2824     // Issue 0020656. Use vertex coordinates
2825     nodes[iv] = NULL;
2826     if ( tag > 0 && tag <= pmap.Extent() ) {
2827       TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
2828       double tol = BRep_Tool::Tolerance( v );
2829       gp_Pnt p = BRep_Tool::Pnt( v );
2830       if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
2831         xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
2832       else
2833         tag = 0; // enforced or attracted vertex
2834       nodes[iv] = SMESH_Algo::VertexNode( v, meshDS );
2835     }
2836     if ( !nodes[iv] )
2837       nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
2838
2839     // Create group of enforced vertices if requested
2840     BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
2841     projVertex.clear();
2842     projVertex.push_back((double)xyz[0]);
2843     projVertex.push_back((double)xyz[1]);
2844     projVertex.push_back((double)xyz[2]);
2845     std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
2846     if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end()) {
2847       MESSAGE("Found enforced vertex @ " << xyz[0] << ", " << xyz[1] << ", " << xyz[2]);
2848       BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
2849       BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
2850       for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
2851         currentEnfVertex = (*enfListIt);
2852         if (currentEnfVertex->grpName != "") {
2853           bool groupDone = false;
2854           SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
2855           MESSAGE("currentEnfVertex->grpName: " << currentEnfVertex->grpName);
2856           MESSAGE("Parsing the groups of the mesh");
2857           while (grIt->more()) {
2858             SMESH_Group * group = grIt->next();
2859             if ( !group ) continue;
2860             MESSAGE("Group: " << group->GetName());
2861             SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2862             if ( !groupDS ) continue;
2863             MESSAGE("group->SMDSGroup().GetType(): " << (groupDS->GetType()));
2864             MESSAGE("group->SMDSGroup().GetType()==SMDSAbs_Node: " << (groupDS->GetType()==SMDSAbs_Node));
2865             MESSAGE("currentEnfVertex->grpName.compare(group->GetStoreName())==0: " << (currentEnfVertex->grpName.compare(group->GetName())==0));
2866             if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
2867               SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
2868               aGroupDS->SMDSGroup().Add(nodes[iv]);
2869               MESSAGE("Node ID: " << nodes[iv]->GetID());
2870               // How can I inform the hypothesis ?
2871               //                 _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
2872               groupDone = true;
2873               MESSAGE("Successfully added enforced vertex to existing group " << currentEnfVertex->grpName);
2874               break;
2875             }
2876           }
2877           if (!groupDone)
2878           {
2879             int groupId;
2880             SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
2881             aGroup->SetName( currentEnfVertex->grpName.c_str() );
2882             SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2883             aGroupDS->SMDSGroup().Add(nodes[iv]);
2884             MESSAGE("Successfully created enforced vertex group " << currentEnfVertex->grpName);
2885             groupDone = true;
2886           }
2887           if (!groupDone)
2888             throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
2889         }
2890         else
2891           MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
2892       }
2893     }
2894
2895     // internal points are tagged to zero
2896     if(tag > 0 && tag <= pmap.Extent() ){
2897       meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
2898       tags[iv] = false;
2899     } else {
2900       tags[iv] = true;
2901     }
2902   }
2903
2904   /* enumerate edges */
2905   for(int it=1;it<=ne;it++) {
2906     SMDS_MeshEdge* edg;
2907     mesh_get_edge_vertices(msh, it, vtx);
2908     mesh_get_edge_extra_vertices(msh, it, &type, evedg);
2909     mesh_get_edge_tag(msh, it, &tag);
2910
2911     // If PreCAD performed some cleaning operations (remove tiny edges,
2912     // merge edges ...) an output tag can indeed represent several original tags.
2913     // Get the initial tags corresponding to the output tag and redefine the tag as 
2914     // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
2915     mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
2916     if(nb_tag > 1)  
2917       tag=tags_buff[nb_tag-1];
2918     if ( tag > emap.Extent() )
2919     {
2920       std::cerr << "MG-CADSurf BUG:::: Edge tag " << tag
2921                 << " more than nb CAD egdes (" << emap.Extent() << ")" << std::endl;
2922       continue;
2923     }
2924     if (tags[vtx[0]]) {
2925       Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
2926       tags[vtx[0]] = false;
2927     };
2928     if (tags[vtx[1]]) {
2929       Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
2930       tags[vtx[1]] = false;
2931     };
2932     if (type == MESHGEMS_MESH_ELEMENT_TYPE_EDGE3) {
2933       // QUADRATIC EDGE
2934       if (tags[evedg[0]]) {
2935         Set_NodeOnEdge(meshDS, nodes[evedg[0]], emap(tag));
2936         tags[evedg[0]] = false;
2937       }
2938       edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]], nodes[evedg[0]]);
2939     }
2940     else {
2941       edg = helper.AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
2942     }
2943     meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
2944   }
2945
2946   /* enumerate triangles */
2947   for(int it=1;it<=nt;it++) {
2948     SMDS_MeshFace* tri;
2949     mesh_get_triangle_vertices(msh, it, vtx);
2950     mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
2951     mesh_get_triangle_tag(msh, it, &tag);
2952     if (tags[vtx[0]]) {
2953       meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2954       tags[vtx[0]] = false;
2955     };
2956     if (tags[vtx[1]]) {
2957       meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2958       tags[vtx[1]] = false;
2959     };
2960     if (tags[vtx[2]]) {
2961       meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
2962       tags[vtx[2]] = false;
2963     };
2964     if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
2965       // QUADRATIC TRIANGLE
2966       if (tags[evtri[0]]) {
2967         meshDS->SetNodeOnFace(nodes[evtri[0]], tag);
2968         tags[evtri[0]] = false;
2969       }
2970       if (tags[evtri[1]]) {
2971         meshDS->SetNodeOnFace(nodes[evtri[1]], tag);
2972         tags[evtri[1]] = false;
2973       }
2974       if (tags[evtri[2]]) {
2975         meshDS->SetNodeOnFace(nodes[evtri[2]], tag);
2976         tags[evtri[2]] = false;
2977       }
2978       tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
2979                             nodes[evtri[0]], nodes[evtri[1]], nodes[evtri[2]]);
2980     }
2981     else {
2982       tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
2983     }
2984     meshDS->SetMeshElementOnShape(tri, tag);
2985   }
2986
2987   /* enumerate quadrangles */
2988   for(int it=1;it<=nq;it++) {
2989     SMDS_MeshFace* quad;
2990     mesh_get_quadrangle_vertices(msh, it, vtx);
2991     mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
2992     mesh_get_quadrangle_tag(msh, it, &tag);
2993     if (tags[vtx[0]]) {
2994       meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2995       tags[vtx[0]] = false;
2996     };
2997     if (tags[vtx[1]]) {
2998       meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2999       tags[vtx[1]] = false;
3000     };
3001     if (tags[vtx[2]]) {
3002       meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
3003       tags[vtx[2]] = false;
3004     };
3005     if (tags[vtx[3]]) {
3006       meshDS->SetNodeOnFace(nodes[vtx[3]], tag);
3007       tags[vtx[3]] = false;
3008     };
3009     if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
3010       // QUADRATIC QUADRANGLE
3011       std::cout << "This is a quadratic quadrangle" << std::endl;
3012       if (tags[evquad[0]]) {
3013         meshDS->SetNodeOnFace(nodes[evquad[0]], tag);
3014         tags[evquad[0]] = false;
3015       }
3016       if (tags[evquad[1]]) {
3017         meshDS->SetNodeOnFace(nodes[evquad[1]], tag);
3018         tags[evquad[1]] = false;
3019       }
3020       if (tags[evquad[2]]) {
3021         meshDS->SetNodeOnFace(nodes[evquad[2]], tag);
3022         tags[evquad[2]] = false;
3023       }
3024       if (tags[evquad[3]]) {
3025         meshDS->SetNodeOnFace(nodes[evquad[3]], tag);
3026         tags[evquad[3]] = false;
3027       }
3028       if (tags[evquad[4]]) {
3029         meshDS->SetNodeOnFace(nodes[evquad[4]], tag);
3030         tags[evquad[4]] = false;
3031       }
3032       quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
3033                              nodes[evquad[0]], nodes[evquad[1]], nodes[evquad[2]], nodes[evquad[3]],
3034                              nodes[evquad[4]]);
3035     }
3036     else {
3037       quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
3038     }
3039     meshDS->SetMeshElementOnShape(quad, tag);
3040   }
3041
3042   /* release the mesh object, the rest is released by cleaner */
3043   cadsurf_data_regain_mesh(css, msh);
3044
3045   if ( needMerge ) // sew mesh computed by MG-CADSurf with pre-existing mesh
3046   {
3047     SMESH_MeshEditor editor( &aMesh );
3048     SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
3049     TIDSortedElemSet segementsOnEdge;
3050     TSubMeshSet::iterator smIt;
3051     SMESHDS_SubMesh* smDS;
3052
3053     // merge nodes on EDGE's with ones computed by MG-CADSurf
3054     for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
3055     {
3056       if (! (smDS = *smIt) ) continue;
3057       getNodeGroupsToMerge( smDS, meshDS->IndexToShape((*smIt)->GetID()), nodeGroupsToMerge );
3058
3059       SMDS_ElemIteratorPtr segIt = smDS->GetElements();
3060       while ( segIt->more() )
3061         segementsOnEdge.insert( segIt->next() );
3062     }
3063     // merge nodes
3064     editor.MergeNodes( nodeGroupsToMerge );
3065
3066     // merge segments
3067     SMESH_MeshEditor::TListOfListOfElementsID equalSegments;
3068     editor.FindEqualElements( segementsOnEdge, equalSegments );
3069     editor.MergeElements( equalSegments );
3070
3071     // remove excess segments created on the boundary of viscous layers
3072     const SMDS_TypeOfPosition onFace = SMDS_TOP_FACE;
3073     for ( int i = 1; i <= emap.Extent(); ++i )
3074     {
3075       if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( emap( i )))
3076       {
3077         SMDS_ElemIteratorPtr segIt = smDS->GetElements();
3078         while ( segIt->more() )
3079         {
3080           const SMDS_MeshElement* seg = segIt->next();
3081           if ( seg->GetNode(0)->GetPosition()->GetTypeOfPosition() == onFace ||
3082                seg->GetNode(1)->GetPosition()->GetTypeOfPosition() == onFace )
3083             meshDS->RemoveFreeElement( seg, smDS );
3084         }
3085       }
3086     }
3087   }
3088
3089   // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
3090   TopLoc_Location loc; double f,l;
3091   for (int i = 1; i <= emap.Extent(); i++)
3092     if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
3093       sm->SetIsAlwaysComputed( true );
3094   for (int i = 1; i <= pmap.Extent(); i++)
3095     if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
3096       if ( !sm->IsMeshComputed() )
3097         sm->SetIsAlwaysComputed( true );
3098
3099   // Set error to FACE's w/o elements
3100   SMESH_ComputeErrorName err = COMPERR_ALGO_FAILED;
3101   if ( _comment.empty() && status == STATUS_OK )
3102   {
3103     err      = COMPERR_WARNING;
3104     _comment = "No mesh elements assigned to a face";
3105   }
3106   bool badFaceFound = false;
3107   for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
3108   {
3109     TopoDS_Face f = TopoDS::Face(face_iter.Current());
3110     SMESH_subMesh* sm = aMesh.GetSubMesh( f );
3111     if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
3112     {
3113       sm->GetComputeError().reset( new SMESH_ComputeError( err, _comment, this ));
3114       badFaceFound = true;
3115     }
3116   }
3117   if ( err == COMPERR_WARNING )
3118   {
3119     _comment.clear();
3120   }
3121   if ( status != STATUS_OK && !badFaceFound ) {
3122     error(_comment);
3123   }
3124
3125   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
3126 #ifndef WIN32
3127   if ( oldFEFlags > 0 )
3128     feenableexcept( oldFEFlags );
3129   feclearexcept( FE_ALL_EXCEPT );
3130 #endif
3131
3132   /*
3133     std::cout << "FacesWithSizeMap" << std::endl;
3134     FacesWithSizeMap.Statistics(std::cout);
3135     std::cout << "EdgesWithSizeMap" << std::endl;
3136     EdgesWithSizeMap.Statistics(std::cout);
3137     std::cout << "VerticesWithSizeMap" << std::endl;
3138     VerticesWithSizeMap.Statistics(std::cout);
3139     std::cout << "FacesWithEnforcedVertices" << std::endl;
3140     FacesWithEnforcedVertices.Statistics(std::cout);
3141   */
3142
3143   MESSAGE("END OF BLSURFPlugin_BLSURF::Compute()");
3144   return ( status == STATUS_OK && !quadraticSubMeshAndViscousLayer );
3145 }
3146
3147 //================================================================================
3148 /*!
3149  * \brief Terminates computation
3150  */
3151 //================================================================================
3152
3153 void BLSURFPlugin_BLSURF::CancelCompute()
3154 {
3155   _compute_canceled = true;
3156 }
3157
3158 //=============================================================================
3159 /*!
3160  *  SetNodeOnEdge
3161  */
3162 //=============================================================================
3163
3164 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, const SMDS_MeshNode* node, const TopoDS_Shape& ed) {
3165   const TopoDS_Edge edge = TopoDS::Edge(ed);
3166
3167   gp_Pnt pnt(node->X(), node->Y(), node->Z());
3168
3169   Standard_Real p0 = 0.0;
3170   Standard_Real p1 = 1.0;
3171   TopLoc_Location loc;
3172   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
3173   if ( curve.IsNull() )
3174   {
3175     // issue 22499. Node at a sphere apex
3176     meshDS->SetNodeOnEdge(node, edge, p0);
3177     return;
3178   }
3179
3180   if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
3181   GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
3182
3183   double pa = 0.;
3184   if ( proj.NbPoints() > 0 )
3185   {
3186     pa = (double)proj.LowerDistanceParameter();
3187     // Issue 0020656. Move node if it is too far from edge
3188     gp_Pnt curve_pnt = curve->Value( pa );
3189     double dist2     = pnt.SquareDistance( curve_pnt );
3190     double tol       = BRep_Tool::Tolerance( edge );
3191     if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
3192     {
3193       curve_pnt.Transform( loc );
3194       meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
3195     }
3196   }
3197
3198   meshDS->SetNodeOnEdge(node, edge, pa);
3199 }
3200
3201 /* Curve definition function See cad_curv_t in file meshgems/cad.h for
3202  * more information.
3203  * NOTE : if when your CAD systems evaluates second
3204  * order derivatives it also computes first order derivatives and
3205  * function evaluation, you can optimize this example by making only
3206  * one CAD call and filling the necessary uv, dt, dtt arrays.
3207  */
3208 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
3209 {
3210   /* t is given. It contains the t (time) 1D parametric coordintaes
3211      of the point PreCAD/MG-CADSurf is querying on the curve */
3212
3213   /* user_data identifies the edge PreCAD/MG-CADSurf is querying
3214    * (see cad_edge_new later in this example) */
3215   const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
3216
3217   if (uv){
3218    /* MG-CADSurf is querying the function evaluation */
3219     gp_Pnt2d P;
3220     P=pargeo->Value(t);
3221     uv[0]=P.X(); uv[1]=P.Y();
3222   }
3223
3224   if(dt) {
3225    /* query for the first order derivatives */
3226     gp_Vec2d V1;
3227     V1=pargeo->DN(t,1);
3228     dt[0]=V1.X(); dt[1]=V1.Y();
3229   }
3230
3231   if(dtt){
3232     /* query for the second order derivatives */
3233     gp_Vec2d V2;
3234     V2=pargeo->DN(t,2);
3235     dtt[0]=V2.X(); dtt[1]=V2.Y();
3236   }
3237
3238   return STATUS_OK;
3239 }
3240
3241 /* Surface definition function.
3242  * See cad_surf_t in file meshgems/cad.h for more information.
3243  * NOTE : if when your CAD systems evaluates second order derivatives it also
3244  * computes first order derivatives and function evaluation, you can optimize
3245  * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
3246  * arrays.
3247  */
3248 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
3249                   real *duu, real *duv, real *dvv, void *user_data)
3250 {
3251   /* uv[2] is given. It contains the u,v coordinates of the point
3252    * PreCAD/MG-CADSurf is querying on the surface */
3253
3254   /* user_data identifies the face PreCAD/MG-CADSurf is querying (see
3255    * cad_face_new later in this example)*/
3256   const Geom_Surface* geometry = (const Geom_Surface*) user_data;
3257
3258   if(xyz){
3259    gp_Pnt P;
3260    P=geometry->Value(uv[0],uv[1]);   // S.D0(U,V,P);
3261    xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
3262   }
3263
3264   if(du && dv){
3265     gp_Pnt P;
3266     gp_Vec D1U,D1V;
3267
3268     geometry->D1(uv[0],uv[1],P,D1U,D1V);
3269     du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
3270     dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
3271   }
3272
3273   if(duu && duv && dvv){
3274
3275     gp_Pnt P;
3276     gp_Vec D1U,D1V;
3277     gp_Vec D2U,D2V,D2UV;
3278
3279     geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
3280     duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
3281     duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
3282     dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
3283   }
3284
3285   return STATUS_OK;
3286 }
3287
3288
3289 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
3290 {
3291   //MESSAGE("size_on_surface")
3292   TId2ClsAttractorVec::iterator f2attVec;
3293   if (FaceId2PythonSmp.count(face_id) != 0){
3294     //MESSAGE("A size map is used to calculate size on face : "<<face_id)
3295     PyObject * pyresult = NULL;
3296     PyObject* new_stderr = NULL;
3297     assert(Py_IsInitialized());
3298     PyGILState_STATE gstate;
3299     gstate = PyGILState_Ensure();
3300     pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
3301     real result;
3302     if ( pyresult != NULL) {
3303       result = PyFloat_AsDouble(pyresult);
3304       Py_DECREF(pyresult);
3305 //       *size = result;
3306     }
3307     else{
3308       fflush(stderr);
3309       string err_description="";
3310       new_stderr = newPyStdOut(err_description);
3311       PySys_SetObject((char*)"stderr", new_stderr);
3312       PyErr_Print();
3313       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
3314       Py_DECREF(new_stderr);
3315       MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
3316       result = *((real*)user_data);
3317     }
3318     *size = result;
3319     PyGILState_Release(gstate);
3320   }
3321   else if (( f2attVec = FaceIndex2ClassAttractor.find(face_id)) != FaceIndex2ClassAttractor.end() && !f2attVec->second.empty()){
3322 //    MESSAGE("attractor used on face :"<<face_id)
3323     // MESSAGE("List of attractor is not empty")
3324     // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
3325     real result = 0;
3326     result = 1e100;
3327     std::vector< BLSURFPlugin_Attractor* > & attVec = f2attVec->second;
3328     for ( size_t i = 0; i < attVec.size(); ++i )
3329     {
3330       //result += attVec[i]->GetSize(uv[0],uv[1]);
3331       result = Min( result, attVec[i]->GetSize(uv[0],uv[1]));
3332     }
3333     //*size = result / attVec.size(); // mean of sizes defined by all attractors
3334     *size = result;
3335   }
3336   else {
3337     // MESSAGE("List of attractor is empty !!!")
3338     *size = *((real*)user_data);
3339   }
3340 //   std::cout << "Size_on_surface sur la face " << face_id << " donne une size de: " << *size << std::endl;
3341   return STATUS_OK;
3342 }
3343
3344 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
3345 {
3346   if (EdgeId2PythonSmp.count(edge_id) != 0){
3347     PyObject * pyresult = NULL;
3348     PyObject* new_stderr = NULL;
3349     assert(Py_IsInitialized());
3350     PyGILState_STATE gstate;
3351     gstate = PyGILState_Ensure();
3352     pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
3353     real result;
3354     if ( pyresult != NULL) {
3355       result = PyFloat_AsDouble(pyresult);
3356       Py_DECREF(pyresult);
3357 //       *size = result;
3358     }
3359     else{
3360       fflush(stderr);
3361       string err_description="";
3362       new_stderr = newPyStdOut(err_description);
3363       PySys_SetObject((char*)"stderr", new_stderr);
3364       PyErr_Print();
3365       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
3366       Py_DECREF(new_stderr);
3367       MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
3368       result = *((real*)user_data);
3369     }
3370     *size = result;
3371     PyGILState_Release(gstate);
3372   }
3373   else {
3374     *size = *((real*)user_data);
3375   }
3376   return STATUS_OK;
3377 }
3378
3379 status_t size_on_vertex(integer point_id, real *size, void *user_data)
3380 {
3381   if (VertexId2PythonSmp.count(point_id) != 0){
3382     PyObject * pyresult = NULL;
3383     PyObject* new_stderr = NULL;
3384     assert(Py_IsInitialized());
3385     PyGILState_STATE gstate;
3386     gstate = PyGILState_Ensure();
3387     pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
3388     real result;
3389     if ( pyresult != NULL) {
3390       result = PyFloat_AsDouble(pyresult);
3391       Py_DECREF(pyresult);
3392 //       *size = result;
3393     }
3394     else {
3395       fflush(stderr);
3396       string err_description="";
3397       new_stderr = newPyStdOut(err_description);
3398       PySys_SetObject((char*)"stderr", new_stderr);
3399       PyErr_Print();
3400       PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
3401       Py_DECREF(new_stderr);
3402       MESSAGE("Can't evaluate f()" << " error is " << err_description);
3403       result = *((real*)user_data);
3404     }
3405     *size = result;
3406     PyGILState_Release(gstate);
3407   }
3408   else {
3409     *size = *((real*)user_data);
3410   }
3411  return STATUS_OK;
3412 }
3413
3414 /*
3415  * The following function will be called for PreCAD/MG-CADSurf message
3416  * printing.  See context_set_message_callback (later in this
3417  * template) for how to set user_data.
3418  */
3419 status_t message_cb(message_t *msg, void *user_data)
3420 {
3421   integer errnumber = 0;
3422   char *desc;
3423   message_get_number(msg, &errnumber);
3424   message_get_description(msg, &desc);
3425   string err( desc );
3426   message_cb_user_data * mcud = (message_cb_user_data*)user_data;
3427   // Get all the error message and some warning messages related to license and periodicity
3428   if ( errnumber < 0 ||
3429        err.find("license"    ) != string::npos ||
3430        err.find("periodicity") != string::npos )
3431   {
3432     // remove ^A from the tail
3433     int len = strlen( desc );
3434     while (len > 0 && desc[len-1] != '\n')
3435       len--;
3436     mcud->_error->append( desc, len );
3437   }
3438   else {
3439     if ( errnumber == 3009001 )
3440       * mcud->_progress = atof( desc + 11 ) / 100.;
3441     if ( mcud->_verbosity > 0 )
3442       std::cout << desc << std::endl;
3443   }
3444   return STATUS_OK;
3445 }
3446
3447 /* This is the interrupt callback. PreCAD/MG-CADSurf will call this
3448  * function regularily. See the file meshgems/interrupt.h
3449  */
3450 status_t interrupt_cb(integer *interrupt_status, void *user_data)
3451 {
3452   integer you_want_to_continue = 1;
3453   BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
3454   you_want_to_continue = !tmp->computeCanceled();
3455
3456   if(you_want_to_continue)
3457   {
3458     *interrupt_status = INTERRUPT_CONTINUE;
3459     return STATUS_OK;
3460   }
3461   else /* you want to stop MG-CADSurf */
3462   {
3463     *interrupt_status = INTERRUPT_STOP;
3464     return STATUS_ERROR;
3465   }
3466 }
3467
3468 //=============================================================================
3469 /*!
3470  *
3471  */
3472 //=============================================================================
3473 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh&         aMesh,
3474                                    const TopoDS_Shape& aShape,
3475                                    MapShapeNbElems&    aResMap)
3476 {
3477   double diagonal       = aMesh.GetShapeDiagonalSize();
3478   double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
3479   int    _physicalMesh  = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
3480   double _phySize       = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
3481   bool   _phySizeRel    = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
3482   //int    _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
3483   double _angleMesh     = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
3484   bool   _quadAllowed   = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
3485   if(_hypothesis) {
3486     _physicalMesh  = (int) _hypothesis->GetPhysicalMesh();
3487     _phySizeRel         = _hypothesis->IsPhySizeRel();
3488     if ( _hypothesis->GetPhySize() > 0)
3489       _phySize          = _phySizeRel ? diagonal*_hypothesis->GetPhySize() : _hypothesis->GetPhySize();
3490     //_geometricMesh = (int) hyp->GetGeometricMesh();
3491     if (_hypothesis->GetAngleMesh() > 0)
3492       _angleMesh        = _hypothesis->GetAngleMesh();
3493     _quadAllowed        = _hypothesis->GetQuadAllowed();
3494   } else {
3495     //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
3496     // GetDefaultPhySize() sometimes leads to computation failure
3497     _phySize = aMesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
3498     MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
3499   }
3500
3501   bool IsQuadratic = _quadraticMesh;
3502
3503   // ----------------
3504   // evaluate 1D
3505   // ----------------
3506   TopTools_DataMapOfShapeInteger EdgesMap;
3507   double fullLen = 0.0;
3508   double fullNbSeg = 0;
3509   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
3510     TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3511     if( EdgesMap.IsBound(E) )
3512       continue;
3513     SMESH_subMesh *sm = aMesh.GetSubMesh(E);
3514     double aLen = SMESH_Algo::EdgeLength(E);
3515     fullLen += aLen;
3516     int nb1d = 0;
3517     if(_physicalMesh==1) {
3518        nb1d = (int)( aLen/_phySize + 1 );
3519     }
3520     else {
3521       // use geometry
3522       double f,l;
3523       Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
3524       double fullAng = 0.0;
3525       double dp = (l-f)/200;
3526       gp_Pnt P1,P2,P3;
3527       C->D0(f,P1);
3528       C->D0(f+dp,P2);
3529       gp_Vec V1(P1,P2);
3530       for(int j=2; j<=200; j++) {
3531         C->D0(f+dp*j,P3);
3532         gp_Vec V2(P2,P3);
3533         fullAng += fabs(V1.Angle(V2));
3534         V1 = V2;
3535         P2 = P3;
3536       }
3537       nb1d = (int)( fullAng/_angleMesh + 1 );
3538     }
3539     fullNbSeg += nb1d;
3540     std::vector<int> aVec(SMDSEntity_Last);
3541     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3542     if( IsQuadratic > 0 ) {
3543       aVec[SMDSEntity_Node] = 2*nb1d - 1;
3544       aVec[SMDSEntity_Quad_Edge] = nb1d;
3545     }
3546     else {
3547       aVec[SMDSEntity_Node] = nb1d - 1;
3548       aVec[SMDSEntity_Edge] = nb1d;
3549     }
3550     aResMap.insert(std::make_pair(sm,aVec));
3551     EdgesMap.Bind(E,nb1d);
3552   }
3553   double ELen = fullLen/fullNbSeg;
3554   // ----------------
3555   // evaluate 2D
3556   // ----------------
3557   // try to evaluate as in MEFISTO
3558   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
3559     TopoDS_Face F = TopoDS::Face( exp.Current() );
3560     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
3561     GProp_GProps G;
3562     BRepGProp::SurfaceProperties(F,G);
3563     double anArea = G.Mass();
3564     int nb1d = 0;
3565     std::vector<int> nb1dVec;
3566     for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
3567       int nbSeg = EdgesMap.Find(exp1.Current());
3568       nb1d += nbSeg;
3569       nb1dVec.push_back( nbSeg );
3570     }
3571     int nbQuad = 0;
3572     int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
3573     int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
3574     if ( _quadAllowed )
3575     {
3576       if ( nb1dVec.size() == 4 ) // quadrangle geom face
3577       {
3578         int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
3579         nbQuad = n1 * n2;
3580         nbNodes = (n1 + 1) * (n2 + 1);
3581         nbTria = 0;
3582       }
3583       else
3584       {
3585         nbTria = nbQuad = nbTria / 3 + 1;
3586       }
3587     }
3588     std::vector<int> aVec(SMDSEntity_Last,0);
3589     if( IsQuadratic ) {
3590       int nb1d_in = (nbTria*3 - nb1d) / 2;
3591       aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3592       aVec[SMDSEntity_Quad_Triangle] = nbTria;
3593       aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
3594     }
3595     else {
3596       aVec[SMDSEntity_Node] = nbNodes;
3597       aVec[SMDSEntity_Triangle] = nbTria;
3598       aVec[SMDSEntity_Quadrangle] = nbQuad;
3599     }
3600     aResMap.insert(std::make_pair(sm,aVec));
3601   }
3602
3603   // ----------------
3604   // evaluate 3D
3605   // ----------------
3606   GProp_GProps G;
3607   BRepGProp::VolumeProperties(aShape,G);
3608   double aVolume = G.Mass();
3609   double tetrVol = 0.1179*ELen*ELen*ELen;
3610   int nbVols  = int(aVolume/tetrVol);
3611   int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3612   std::vector<int> aVec(SMDSEntity_Last);
3613   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3614   if( IsQuadratic ) {
3615     aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3616     aVec[SMDSEntity_Quad_Tetra] = nbVols;
3617   }
3618   else {
3619     aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3620     aVec[SMDSEntity_Tetra] = nbVols;
3621   }
3622   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3623   aResMap.insert(std::make_pair(sm,aVec));
3624
3625   return true;
3626 }