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