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