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