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