1 // Copyright (C) 2007-2013 CEA/DEN, EDF R&D
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
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)
27 #include "BLSURFPlugin_BLSURF.hxx"
28 #include "BLSURFPlugin_Hypothesis.hxx"
29 #include "BLSURFPlugin_Attractor.hxx"
32 #include <meshgems/meshgems.h>
33 #include <meshgems/cadsurf.h>
34 #include <meshgems/precad.h>
37 #include <structmember.h>
40 #include <Basics_Utils.hxx>
41 #include <Basics_OCCTVersion.hxx>
43 #include <SMDS_EdgePosition.hxx>
44 #include <SMESHDS_Group.hxx>
45 #include <SMESH_Gen.hxx>
46 #include <SMESH_Group.hxx>
47 #include <SMESH_Mesh.hxx>
48 #include <SMESH_MeshEditor.hxx>
49 #include <SMESH_MesherHelper.hxx>
50 #include <StdMeshers_FaceSide.hxx>
51 #include <StdMeshers_ViscousLayers2D.hxx>
53 #include <utilities.h>
61 // OPENCASCADE includes
62 #include <BRepBuilderAPI_MakeFace.hxx>
63 #include <BRepBuilderAPI_MakePolygon.hxx>
64 //#include <BRepBuilderAPI_MakeVertex.hxx>
65 #include <BRepGProp.hxx>
66 #include <BRepTools.hxx>
67 #include <BRep_Builder.hxx>
68 #include <BRep_Tool.hxx>
69 #include <GProp_GProps.hxx>
70 #include <Geom2d_Curve.hxx>
71 #include <GeomAPI_ProjectPointOnCurve.hxx>
72 #include <GeomAPI_ProjectPointOnSurf.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Surface.hxx>
75 #include <NCollection_Map.hxx>
76 #include <Standard_ErrorHandler.hxx>
78 #include <TopExp_Explorer.hxx>
79 #include <TopTools_DataMapOfShapeInteger.hxx>
80 #include <TopTools_IndexedMapOfShape.hxx>
81 #include <TopTools_MapOfShape.hxx>
83 #include <TopoDS_Compound.hxx>
84 #include <TopoDS_Edge.hxx>
85 #include <TopoDS_Face.hxx>
86 #include <TopoDS_Shape.hxx>
87 #include <TopoDS_Vertex.hxx>
88 #include <TopoDS_Wire.hxx>
90 #include <gp_Pnt2d.hxx>
98 /* ==================================
99 * =========== PYTHON ==============
100 * ==================================*/
109 PyStdOut_dealloc(PyStdOut *self)
115 PyStdOut_write(PyStdOut *self, PyObject *args)
119 if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
123 *(self->out)=*(self->out)+c;
129 static PyMethodDef PyStdOut_methods[] = {
130 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
131 PyDoc_STR("write(string) -> None")},
132 {NULL, NULL} /* sentinel */
135 static PyMemberDef PyStdOut_memberlist[] = {
136 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
137 (char*)"flag indicating that a space needs to be printed; used by print"},
138 {NULL} /* Sentinel */
141 static PyTypeObject PyStdOut_Type = {
142 /* The ob_type field must be initialized in the module init function
143 * to be portable to Windows without using C++. */
144 PyObject_HEAD_INIT(NULL)
147 sizeof(PyStdOut), /*tp_basicsize*/
150 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
157 0, /*tp_as_sequence*/
162 PyObject_GenericGetAttr, /*tp_getattro*/
163 /* softspace is writable: we must supply tp_setattro */
164 PyObject_GenericSetAttr, /* tp_setattro */
166 Py_TPFLAGS_DEFAULT, /*tp_flags*/
170 0, /*tp_richcompare*/
171 0, /*tp_weaklistoffset*/
174 PyStdOut_methods, /*tp_methods*/
175 PyStdOut_memberlist, /*tp_members*/
189 PyObject * newPyStdOut( std::string& out )
192 self = PyObject_New(PyStdOut, &PyStdOut_Type);
197 return (PyObject*)self;
201 ////////////////////////END PYTHON///////////////////////////
203 //////////////////MY MAPS////////////////////////////////////////
204 TopTools_IndexedMapOfShape FacesWithSizeMap;
205 std::map<int,string> FaceId2SizeMap;
206 TopTools_IndexedMapOfShape EdgesWithSizeMap;
207 std::map<int,string> EdgeId2SizeMap;
208 TopTools_IndexedMapOfShape VerticesWithSizeMap;
209 std::map<int,string> VertexId2SizeMap;
211 std::map<int,PyObject*> FaceId2PythonSmp;
212 std::map<int,PyObject*> EdgeId2PythonSmp;
213 std::map<int,PyObject*> VertexId2PythonSmp;
215 std::map<int,std::vector<double> > FaceId2AttractorCoords;
216 std::map<int,BLSURFPlugin_Attractor*> FaceId2ClassAttractor;
217 std::map<int,BLSURFPlugin_Attractor*> FaceIndex2ClassAttractor;
219 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
220 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
221 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
222 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
224 bool HasSizeMapOnFace=false;
225 bool HasSizeMapOnEdge=false;
226 bool HasSizeMapOnVertex=false;
227 //bool HasAttractorOnFace=false;
229 //=============================================================================
233 //=============================================================================
235 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
237 : SMESH_2D_Algo(hypId, studyId, gen)
239 MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
242 _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
243 _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType());
244 _compatibleHypothesis.push_back(StdMeshers_ViscousLayers2D::GetHypType());
245 _requireDiscreteBoundary = false;
246 _onlyUnaryInput = false;
248 _supportSubmeshes = true;
250 smeshGen_i = SMESH_Gen_i::GetSMESHGen();
251 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
252 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
254 MESSAGE("studyid = " << _studyId);
257 myStudy = aStudyMgr->GetStudyByID(_studyId);
259 MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
261 /* Initialize the Python interpreter */
262 assert(Py_IsInitialized());
263 PyGILState_STATE gstate;
264 gstate = PyGILState_Ensure();
267 main_mod = PyImport_AddModule("__main__");
270 main_dict = PyModule_GetDict(main_mod);
272 PyRun_SimpleString("from math import *");
273 PyGILState_Release(gstate);
275 FacesWithSizeMap.Clear();
276 FaceId2SizeMap.clear();
277 EdgesWithSizeMap.Clear();
278 EdgeId2SizeMap.clear();
279 VerticesWithSizeMap.Clear();
280 VertexId2SizeMap.clear();
281 FaceId2PythonSmp.clear();
282 EdgeId2PythonSmp.clear();
283 VertexId2PythonSmp.clear();
284 FaceId2AttractorCoords.clear();
285 FaceId2ClassAttractor.clear();
286 FaceIndex2ClassAttractor.clear();
287 FacesWithEnforcedVertices.Clear();
288 FaceId2EnforcedVertexCoords.clear();
289 EnfVertexCoords2ProjVertex.clear();
290 EnfVertexCoords2EnfVertexList.clear();
292 _compute_canceled = false;
295 //=============================================================================
299 //=============================================================================
301 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
303 MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
307 //=============================================================================
311 //=============================================================================
313 bool BLSURFPlugin_BLSURF::CheckHypothesis
315 const TopoDS_Shape& aShape,
316 SMESH_Hypothesis::Hypothesis_Status& aStatus)
319 _haveViscousLayers = false;
321 list<const SMESHDS_Hypothesis*>::const_iterator itl;
322 const SMESHDS_Hypothesis* theHyp;
324 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape,
325 /*ignoreAuxiliary=*/false);
326 aStatus = SMESH_Hypothesis::HYP_OK;
329 return true; // can work with no hypothesis
332 for ( itl = hyps.begin(); itl != hyps.end(); ++itl )
335 string hypName = theHyp->GetName();
336 if ( hypName == BLSURFPlugin_Hypothesis::GetHypType() )
338 _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
340 if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
341 _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
342 // hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
343 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
345 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
347 _haveViscousLayers = true;
351 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
354 return aStatus == SMESH_Hypothesis::HYP_OK;
357 //=============================================================================
359 * Pass parameters to BLSURF
361 //=============================================================================
363 inline std::string to_string(double d)
365 std::ostringstream o;
370 inline std::string to_string_rel(double d)
372 std::ostringstream o;
378 inline std::string to_string(int i)
380 std::ostringstream o;
385 inline std::string to_string_rel(int i)
387 std::ostringstream o;
393 double _smp_phy_size;
394 // #if BLSURF_VERSION_LONG >= "3.1.1"
395 // // sizemap_t *geo_sizemap_e, *geo_sizemap_f;
396 // sizemap_t *iso_sizemap_p, *iso_sizemap_e, *iso_sizemap_f;
397 // // sizemap_t *clean_geo_sizemap_e, *clean_geo_sizemap_f;
398 // sizemap_t *clean_iso_sizemap_p, *clean_iso_sizemap_e, *clean_iso_sizemap_f;
400 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
401 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
402 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
408 /////////////////////////////////////////////////////////
409 projectionPoint getProjectionPoint(const TopoDS_Face& face, const gp_Pnt& point)
411 projectionPoint myPoint;
412 Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
413 GeomAPI_ProjectPointOnSurf projector( point, surface );
414 if ( !projector.IsDone() || projector.NbPoints()==0 )
415 throw "getProjectionPoint: Can't project";
417 Quantity_Parameter u,v;
418 projector.LowerDistanceParameters(u,v);
419 myPoint.uv = gp_XY(u,v);
420 gp_Pnt aPnt = projector.NearestPoint();
421 myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
425 /////////////////////////////////////////////////////////
427 /////////////////////////////////////////////////////////
428 double getT(const TopoDS_Edge& edge, const gp_Pnt& point)
431 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
432 GeomAPI_ProjectPointOnCurve projector( point, curve);
433 if ( projector.NbPoints() == 0 )
435 return projector.LowerDistanceParameter();
438 /////////////////////////////////////////////////////////
439 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
441 MESSAGE("BLSURFPlugin_BLSURF::entryToShape "<<entry );
442 GEOM::GEOM_Object_var aGeomObj;
443 TopoDS_Shape S = TopoDS_Shape();
444 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
445 if (!aSObj->_is_nil()) {
446 CORBA::Object_var obj = aSObj->GetObject();
447 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
450 if ( !aGeomObj->_is_nil() )
451 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
455 void _createEnforcedVertexOnFace(TopoDS_Face faceShape, gp_Pnt aPnt, BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex)
457 BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
462 // Get the (u,v) values of the enforced vertex on the face
463 projectionPoint myPoint = getProjectionPoint(faceShape,aPnt);
465 MESSAGE("Enforced Vertex: " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z());
466 MESSAGE("Projected Vertex: " << myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z());
467 MESSAGE("Parametric coordinates: " << myPoint.uv.X() << ", " << myPoint.uv.Y() );
469 enf_coords.push_back(aPnt.X());
470 enf_coords.push_back(aPnt.Y());
471 enf_coords.push_back(aPnt.Z());
473 coords.push_back(myPoint.uv.X());
474 coords.push_back(myPoint.uv.Y());
475 coords.push_back(myPoint.xyz.X());
476 coords.push_back(myPoint.xyz.Y());
477 coords.push_back(myPoint.xyz.Z());
479 s_coords.push_back(myPoint.xyz.X());
480 s_coords.push_back(myPoint.xyz.Y());
481 s_coords.push_back(myPoint.xyz.Z());
483 // Save pair projected vertex / enf vertex
484 MESSAGE("Storing pair projected vertex / enf vertex:");
485 MESSAGE("("<< myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z() <<") / (" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z()<<")");
486 EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
487 MESSAGE("Group name is: \"" << enfVertex->grpName << "\"");
488 pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
489 BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
490 ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
491 if (ret.second == false) {
493 (*it)->grpName = enfVertex->grpName;
497 if (! FacesWithEnforcedVertices.Contains(faceShape)) {
498 key = FacesWithEnforcedVertices.Add(faceShape);
501 key = FacesWithEnforcedVertices.FindIndex(faceShape);
504 // If a node is already created by an attractor, do not create enforced vertex
505 int attractorKey = FacesWithSizeMap.FindIndex(faceShape);
506 bool sameAttractor = false;
507 if (attractorKey >= 0)
508 if (FaceId2AttractorCoords.count(attractorKey) > 0)
509 if (FaceId2AttractorCoords[attractorKey] == coords)
510 sameAttractor = true;
512 if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
513 MESSAGE("Map of enf. vertex has key " << key)
514 MESSAGE("Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
516 FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
518 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
519 MESSAGE("New Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
522 MESSAGE("Map of enf. vertex has not key " << key << ": creating it")
523 if (! sameAttractor) {
524 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
526 FaceId2EnforcedVertexCoords[key] = ens;
529 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
533 /////////////////////////////////////////////////////////
534 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
536 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex;
539 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfVertexListIt = enfVertexList.begin();
541 for( ; enfVertexListIt != enfVertexList.end() ; ++enfVertexListIt ) {
542 enfVertex = *enfVertexListIt;
543 // Case of manual coords
544 if (enfVertex->coords.size() != 0) {
545 aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
546 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
549 // Case of geom vertex coords
550 if (enfVertex->geomEntry != "") {
551 TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
552 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
553 if (GeomType == TopAbs_VERTEX){
554 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
555 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
558 if (GeomType == TopAbs_COMPOUND){
559 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
560 if (it.Value().ShapeType() == TopAbs_VERTEX){
561 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
562 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
570 /////////////////////////////////////////////////////////
571 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction, double defaultSize)
573 MESSAGE("Attractor function: "<< AttractorFunction);
574 double xa, ya, za; // Coordinates of attractor point
575 double a, b; // Attractor parameter
577 bool createNode=false; // To create a node on attractor projection
579 const char *sep = ";";
580 // atIt->second has the following pattern:
581 // ATTRACTOR(xa;ya;za;a;b;True|False;d)
583 // xa;ya;za : coordinates of attractor
584 // a : desired size on attractor
585 // b : distance of influence of attractor
586 // d : distance until which the size remains constant
588 // We search the parameters in the string
590 pos1 = AttractorFunction.find(sep);
591 if (pos1!=string::npos)
592 xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
594 pos2 = AttractorFunction.find(sep, pos1+1);
595 if (pos2!=string::npos) {
596 ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
600 pos2 = AttractorFunction.find(sep, pos1+1);
601 if (pos2!=string::npos) {
602 za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
606 pos2 = AttractorFunction.find(sep, pos1+1);
607 if (pos2!=string::npos) {
608 a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
612 pos2 = AttractorFunction.find(sep, pos1+1);
613 if (pos2!=string::npos) {
614 b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
618 pos2 = AttractorFunction.find(sep, pos1+1);
619 if (pos2!=string::npos) {
620 string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
621 MESSAGE("createNode: " << createNodeStr);
622 createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
626 pos2 = AttractorFunction.find(")");
627 if (pos2!=string::npos) {
628 d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
631 // Get the (u,v) values of the attractor on the face
632 projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
633 gp_XY uvPoint = myPoint.uv;
634 gp_XYZ xyzPoint = myPoint.xyz;
635 Standard_Real u0 = uvPoint.X();
636 Standard_Real v0 = uvPoint.Y();
637 Standard_Real x0 = xyzPoint.X();
638 Standard_Real y0 = xyzPoint.Y();
639 Standard_Real z0 = xyzPoint.Z();
640 std::vector<double> coords;
641 coords.push_back(u0);
642 coords.push_back(v0);
643 coords.push_back(x0);
644 coords.push_back(y0);
645 coords.push_back(z0);
646 // We construct the python function
647 ostringstream attractorFunctionStream;
648 attractorFunctionStream << "def f(u,v): return ";
649 attractorFunctionStream << defaultSize << "-(" << defaultSize <<"-" << a << ")";
650 //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
651 // rnc: make possible to keep the size constant until
652 // a defined distance. Distance is expressed as the positiv part
653 // of r-d where r is the distance to (u0,v0)
654 attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
656 MESSAGE("Python function for attractor:" << std::endl << attractorFunctionStream.str());
659 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
660 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
663 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
665 FaceId2SizeMap[key] =attractorFunctionStream.str();
667 MESSAGE("Creating node on ("<<x0<<","<<y0<<","<<z0<<")");
668 FaceId2AttractorCoords[key] = coords;
670 // // Test for new attractors
671 // gp_Pnt myP(xyzPoint);
672 // TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
673 // BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
674 // myAttractor.SetParameters(a, defaultSize, b, d);
675 // myAttractor.SetType(1);
676 // FaceId2ClassAttractor[key] = myAttractor;
677 // if(FaceId2ClassAttractor[key].GetFace().IsNull()){
678 // MESSAGE("face nulle ");
681 // MESSAGE("face OK");
683 // if (FaceId2ClassAttractor[key].GetAttractorShape().IsNull()){
684 // MESSAGE("pas de point");
687 // MESSAGE("point OK");
690 // One sub-shape to get ids from
691 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(TopoDS_Shape theMainShape, TopoDS_Shape theSubShape,
692 TopAbs_ShapeEnum theShapeType)
694 BLSURFPlugin_BLSURF::TListOfIDs face_ids;
695 TopTools_IndexedMapOfShape anIndices;
697 TopExp::MapShapes(theMainShape, theShapeType, anIndices);
699 // Standard_Boolean result = BRepTools::Write(theMainShape,"main_shape.brep");
701 for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
703 int face_id = anIndices.FindIndex(face_iter.Current());
705 throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
706 face_ids.push_back(face_id);
707 // std::ostringstream o;
708 // o << "face_" << face_id << ".brep";
709 // std::string face_name = o.str();
710 // const TopoDS_Face& face = TopoDS::Face(face_iter.Current());
711 // Standard_Boolean result = BRepTools::Write(face,face_name.c_str());
717 void BLSURFPlugin_BLSURF::addCoordsFromVertices(const std::vector<std::string> &theVerticesEntries, std::vector<double> &theVerticesCoords)
719 for (std::vector<std::string>::const_iterator it = theVerticesEntries.begin(); it != theVerticesEntries.end(); it++)
721 BLSURFPlugin_Hypothesis::TEntry theVertexEntry = *it;
722 MESSAGE("Vertex entry " << theVertexEntry);
723 addCoordsFromVertex(theVertexEntry, theVerticesCoords);
728 void BLSURFPlugin_BLSURF::addCoordsFromVertex(BLSURFPlugin_Hypothesis::TEntry theVertexEntry, std::vector<double> &theVerticesCoords)
730 if (theVertexEntry!="")
732 TopoDS_Shape aShape = entryToShape(theVertexEntry);
734 gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex( aShape ) );
735 double theX, theY, theZ;
740 theVerticesCoords.push_back(theX);
741 theVerticesCoords.push_back(theY);
742 theVerticesCoords.push_back(theZ);
746 /////////////////////////////////////////////////////////
747 void BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
749 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity");
751 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
752 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
754 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_FACE);
755 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_FACE);
757 TPreCadPeriodicityIDs preCadFacesPeriodicityIDs;
758 preCadFacesPeriodicityIDs.shape1IDs = theFace1_ids;
759 preCadFacesPeriodicityIDs.shape2IDs = theFace2_ids;
761 MESSAGE("preCadPeriodicity.theSourceVerticesEntries.size(): " << preCadPeriodicity.theSourceVerticesEntries.size());
762 MESSAGE("preCadPeriodicity.theTargetVerticesEntries.size(): " << preCadPeriodicity.theTargetVerticesEntries.size());
764 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadFacesPeriodicityIDs.theSourceVerticesCoords);
765 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadFacesPeriodicityIDs.theTargetVerticesCoords);
767 MESSAGE("preCadFacesPeriodicityIDs.theSourceVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theSourceVerticesCoords.size());
768 MESSAGE("preCadFacesPeriodicityIDs.theTargetVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theTargetVerticesCoords.size());
770 _preCadFacesIDsPeriodicityVector.push_back(preCadFacesPeriodicityIDs);
771 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
772 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity END");
776 /////////////////////////////////////////////////////////
777 void BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
779 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity");
781 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
782 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
784 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_EDGE);
785 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_EDGE);
787 TPreCadPeriodicityIDs preCadEdgesPeriodicityIDs;
788 preCadEdgesPeriodicityIDs.shape1IDs = theEdge1_ids;
789 preCadEdgesPeriodicityIDs.shape2IDs = theEdge2_ids;
791 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadEdgesPeriodicityIDs.theSourceVerticesCoords);
792 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadEdgesPeriodicityIDs.theTargetVerticesCoords);
794 _preCadEdgesIDsPeriodicityVector.push_back(preCadEdgesPeriodicityIDs);
795 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
796 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity END");
800 /////////////////////////////////////////////////////////
801 void BLSURFPlugin_BLSURF::createFacesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theFace1, BLSURFPlugin_Hypothesis::TEntry theFace2)
803 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity");
805 TopoDS_Shape GeomShape1 = entryToShape(theFace1);
806 TopoDS_Shape GeomShape2 = entryToShape(theFace2);
808 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomShape1, TopAbs_FACE);
809 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomShape2, TopAbs_FACE);
811 // Only one face id, since only a face can be selected
812 int theFace1_id = theFace1_ids[0];
813 int theFace2_id = theFace2_ids[0];
815 std::pair<int, int> pairOfFacesID = std::make_pair(theFace1_id, theFace2_id);
817 _facesIDsPeriodicityVector.push_back(pairOfFacesID);
818 MESSAGE("_facesIDsPeriodicityVector.size() = " << _facesIDsPeriodicityVector.size());
819 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity END");
824 /////////////////////////////////////////////////////////
825 void BLSURFPlugin_BLSURF::createEdgesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theFace1, BLSURFPlugin_Hypothesis::TEntry theEdge1,
826 BLSURFPlugin_Hypothesis::TEntry theFace2, BLSURFPlugin_Hypothesis::TEntry theEdge2, int edge_orientation)
828 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity");
830 TEdgePeriodicityIDs edgePeriodicityIDs;
834 TopoDS_Shape GeomFace1 = entryToShape(theFace1);
835 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomFace1, TopAbs_FACE);
836 // Only one face id, since only a face can be selected
837 edgePeriodicityIDs.theFace1ID = theFace1_ids[0];
840 edgePeriodicityIDs.theFace1ID = 0;
843 TopoDS_Shape GeomFace2 = entryToShape(theFace2);
844 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomFace2, TopAbs_FACE);
845 edgePeriodicityIDs.theFace2ID = theFace2_ids[0];
848 edgePeriodicityIDs.theFace2ID = 0;
850 TopoDS_Shape GeomEdge1 = entryToShape(theEdge1);
851 TopoDS_Shape GeomEdge2 = entryToShape(theEdge2);
853 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge1, TopAbs_EDGE);
854 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge2, TopAbs_EDGE);
856 if (edge_orientation == 0 && GeomEdge1.Closed())
858 // if edge is closed, we have to set its orientation
859 MESSAGE("GeomEdge1.Orientation() = " << GeomEdge1.Orientation());
860 MESSAGE("GeomEdge2.Orientation() = " << GeomEdge2.Orientation());
861 if(GeomEdge1.Orientation() == TopAbs_FORWARD)
862 edge_orientation = CAD_ORIENTATION_REVERSED;
864 edge_orientation = CAD_ORIENTATION_FORWARD;
867 // Only one edge id, since only a edge can be selected
868 edgePeriodicityIDs.theEdge1ID = theEdge1_ids[0];
869 edgePeriodicityIDs.theEdge2ID = theEdge2_ids[0];
870 edgePeriodicityIDs.edge_orientation = edge_orientation;
872 _edgesIDsPeriodicityVector.push_back(edgePeriodicityIDs);
873 MESSAGE("_edgesIDsPeriodicityVector.size() = " << _edgesIDsPeriodicityVector.size());
874 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity END");
879 /////////////////////////////////////////////////////////
880 void BLSURFPlugin_BLSURF::createVerticesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theEdge1, BLSURFPlugin_Hypothesis::TEntry theVertex1,
881 BLSURFPlugin_Hypothesis::TEntry theEdge2, BLSURFPlugin_Hypothesis::TEntry theVertex2)
883 MESSAGE("BLSURFPlugin_BLSURF::createVerticesPeriodicity");
885 TopoDS_Shape GeomEdge1 = entryToShape(theEdge1);
886 TopoDS_Shape GeomVertex1 = entryToShape(theVertex1);
887 TopoDS_Shape GeomEdge2 = entryToShape(theEdge2);
888 TopoDS_Shape GeomVertex2 = entryToShape(theVertex2);
890 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge1, TopAbs_EDGE);
891 TListOfIDs vertices1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomVertex1, TopAbs_VERTEX);
892 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge2, TopAbs_EDGE);
893 TListOfIDs vertices2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomVertex2, TopAbs_VERTEX);
895 // Only one vertex id, since only a vertex can be selected
896 TVertexPeriodicityIDs vertexPeriodicityIDs;
897 vertexPeriodicityIDs.theEdge1ID = theEdge1_ids[0];
898 vertexPeriodicityIDs.theVertex1ID = vertices1_ids[0];
899 vertexPeriodicityIDs.theEdge2ID = theEdge2_ids[0];
900 vertexPeriodicityIDs.theVertex2ID = vertices2_ids[0];
902 _verticesIDsPeriodicityVector.push_back(vertexPeriodicityIDs);
903 MESSAGE("_verticesIDsPeriodicityVector.size() = " << _verticesIDsPeriodicityVector.size());
904 MESSAGE("BLSURFPlugin_BLSURF::createVerticesPeriodicity END");
908 /////////////////////////////////////////////////////////
910 void BLSURFPlugin_BLSURF::SetParameters(
911 // #if BLSURF_VERSION_LONG >= "3.1.1"
914 const BLSURFPlugin_Hypothesis* hyp,
915 cadsurf_session_t * css,
916 precad_session_t * pcs,
917 const TopoDS_Shape& theGeomShape,
922 // Clear map so that it is not stored in the algorithm with old enforced vertices in it
923 EnfVertexCoords2EnfVertexList.clear();
925 double diagonal = SMESH_Mesh::GetShapeDiagonalSize( theGeomShape );
926 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
927 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
928 int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
929 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
930 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
931 double _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
932 bool _minSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
933 double _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
934 bool _maxSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
935 double _gradation = BLSURFPlugin_Hypothesis::GetDefaultGradation();
936 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
937 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
938 double _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
939 bool _anisotropic = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
940 double _anisotropicRatio = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
941 bool _removeTinyEdges = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
942 double _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
943 bool _badElementRemoval = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
944 double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
945 bool _optimizeMesh = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
946 bool _quadraticMesh = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
947 int _verb = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
948 int _topology = BLSURFPlugin_Hypothesis::GetDefaultTopology();
951 int _precadMergeEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
952 int _precadProcess3DTopology = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
953 int _precadDiscardInput = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
957 MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
958 _physicalMesh = (int) hyp->GetPhysicalMesh();
959 _geometricMesh = (int) hyp->GetGeometricMesh();
960 if (hyp->GetPhySize() > 0) {
961 _phySize = hyp->GetPhySize();
962 // if user size is not explicitly specified, "relative" flag is ignored
963 _phySizeRel = hyp->IsPhySizeRel();
965 if (hyp->GetMinSize() > 0) {
966 _minSize = hyp->GetMinSize();
967 // if min size is not explicitly specified, "relative" flag is ignored
968 _minSizeRel = hyp->IsMinSizeRel();
970 if (hyp->GetMaxSize() > 0) {
971 _maxSize = hyp->GetMaxSize();
972 // if max size is not explicitly specified, "relative" flag is ignored
973 _maxSizeRel = hyp->IsMaxSizeRel();
975 if (hyp->GetGradation() > 0)
976 _gradation = hyp->GetGradation();
977 _quadAllowed = hyp->GetQuadAllowed();
978 if (hyp->GetAngleMesh() > 0)
979 _angleMesh = hyp->GetAngleMesh();
980 if (hyp->GetChordalError() > 0)
981 _chordalError = hyp->GetChordalError();
982 _anisotropic = hyp->GetAnisotropic();
983 if (hyp->GetAnisotropicRatio() >= 0)
984 _anisotropicRatio = hyp->GetAnisotropicRatio();
985 _removeTinyEdges = hyp->GetRemoveTinyEdges();
986 if (hyp->GetTinyEdgeLength() > 0)
987 _tinyEdgeLength = hyp->GetTinyEdgeLength();
988 _badElementRemoval = hyp->GetBadElementRemoval();
989 if (hyp->GetBadElementAspectRatio() >= 0)
990 _badElementAspectRatio = hyp->GetBadElementAspectRatio();
991 _optimizeMesh = hyp->GetOptimizeMesh();
992 _quadraticMesh = hyp->GetQuadraticMesh();
993 _verb = hyp->GetVerbosity();
994 _topology = (int) hyp->GetTopology();
996 _precadMergeEdges = hyp->GetPreCADMergeEdges();
997 _precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
998 _precadDiscardInput = hyp->GetPreCADDiscardInput();
1000 const BLSURFPlugin_Hypothesis::TOptionValues & opts = hyp->GetOptionValues();
1001 BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
1002 for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
1003 if ( !opIt->second.empty() ) {
1004 MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
1005 set_param(css, opIt->first.c_str(), opIt->second.c_str());
1008 const BLSURFPlugin_Hypothesis::TOptionValues & preCADopts = hyp->GetPreCADOptionValues();
1009 for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
1010 if ( !opIt->second.empty() ) {
1012 MESSAGE("precad_set_param(): " << opIt->first << " = " << opIt->second);
1013 precad_set_param(pcs, opIt->first.c_str(), opIt->second.c_str());
1017 // //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
1018 // // GetDefaultPhySize() sometimes leads to computation failure
1019 // // GDD 26/07/2012 From Distene documentation, global physical size default value = diag/100
1020 // _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal);
1021 // _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
1022 // _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
1023 // _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
1024 // _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
1025 // MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
1029 if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
1031 precad_set_param(pcs, "verbose", to_string(_verb).c_str());
1032 precad_set_param(pcs, "merge_edges", _precadMergeEdges ? "1" : "0");
1033 precad_set_param(pcs, "process_3d_topology", _precadProcess3DTopology ? "1" : "0");
1034 precad_set_param(pcs, "discard_input_topology", _precadDiscardInput ? "1" : "0");
1036 // unlimit mesh size (issue 0022266)
1037 set_param(css, "max_number_of_points_per_patch", "1000000");
1039 bool useGradation = false;
1040 switch (_physicalMesh)
1042 case BLSURFPlugin_Hypothesis::PhysicalGlobalSize:
1043 set_param(css, "physical_size_mode", "global");
1044 set_param(css, "global_physical_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1046 case BLSURFPlugin_Hypothesis::PhysicalLocalSize:
1047 set_param(css, "physical_size_mode", "local");
1048 set_param(css, "global_physical_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1049 useGradation = true;
1052 set_param(css, "physical_size_mode", "none");
1055 switch (_geometricMesh)
1057 case BLSURFPlugin_Hypothesis::GeometricalGlobalSize:
1058 set_param(css, "geometric_size_mode", "global");
1059 set_param(css, "geometric_approximation", to_string(_angleMesh).c_str());
1060 set_param(css, "chordal_error", to_string(_chordalError).c_str());
1061 useGradation = true;
1063 case BLSURFPlugin_Hypothesis::GeometricalLocalSize:
1064 set_param(css, "geometric_size_mode", "local");
1065 set_param(css, "geometric_approximation", to_string(_angleMesh).c_str());
1066 set_param(css, "chordal_error", to_string(_chordalError).c_str());
1067 useGradation = true;
1070 set_param(css, "geometric_size_mode", "none");
1073 if ( hyp && hyp->GetPhySize() > 0 ) {
1074 // user size is explicitly specified via hypothesis parameters
1075 // min and max sizes should be compared with explicitly specified user size
1076 // - compute absolute min size
1077 double mins = _minSizeRel ? _minSize * diagonal : _minSize;
1078 // - min size should not be greater than user size
1079 if ( _phySize < mins )
1080 set_param(css, "min_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1082 set_param(css, "min_size", _minSizeRel ? to_string_rel(_minSize).c_str() : to_string(_minSize).c_str());
1083 // - compute absolute max size
1084 double maxs = _maxSizeRel ? _maxSize * diagonal : _maxSize;
1085 // - max size should not be less than user size
1086 if ( _phySize > maxs )
1087 set_param(css, "max_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1089 set_param(css, "max_size", _maxSizeRel ? to_string_rel(_maxSize).c_str() : to_string(_maxSize).c_str());
1092 // user size is not explicitly specified
1093 // - if minsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1094 set_param(css, "min_size", _minSizeRel ? to_string_rel(_minSize).c_str() : to_string(_minSize).c_str());
1095 // - if maxsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1096 set_param(css, "max_size", _maxSizeRel ? to_string_rel(_maxSize).c_str() : to_string(_maxSize).c_str());
1100 set_param(css, "gradation", to_string(_gradation).c_str());
1101 set_param(css, "element_generation", _quadAllowed ? "quad_dominant" : "triangle");
1104 set_param(css, "metric", _anisotropic ? "anisotropic" : "isotropic");
1106 set_param(css, "anisotropic_ratio", to_string(_anisotropicRatio).c_str());
1107 set_param(css, "remove_tiny_edges", _removeTinyEdges ? "1" : "0");
1108 if ( _removeTinyEdges )
1109 set_param(css, "tiny_edge_length", to_string(_tinyEdgeLength).c_str());
1110 set_param(css, "force_bad_surface_element_removal", _badElementRemoval ? "1" : "0");
1111 if ( _badElementRemoval )
1112 set_param(css, "bad_surface_element_aspect_ratio", to_string(_badElementAspectRatio).c_str());
1113 set_param(css, "optimisation", _optimizeMesh ? "yes" : "no");
1114 set_param(css, "element_order", _quadraticMesh ? "quadratic" : "linear");
1115 set_param(css, "verbose", to_string(_verb).c_str());
1117 _smp_phy_size = _phySizeRel ? _phySize*diagonal : _phySize;
1119 std::cout << "_smp_phy_size = " << _smp_phy_size << std::endl;
1121 if (_physicalMesh == BLSURFPlugin_Hypothesis::PhysicalLocalSize){
1122 TopoDS_Shape GeomShape;
1123 TopoDS_Shape AttShape;
1124 TopAbs_ShapeEnum GeomType;
1126 // Standard Size Maps
1128 MESSAGE("Setting a Size Map");
1129 const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
1130 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
1131 for ( ; smIt != sizeMaps.end(); ++smIt ) {
1132 if ( !smIt->second.empty() ) {
1133 MESSAGE("cadsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
1134 GeomShape = entryToShape(smIt->first);
1135 GeomType = GeomShape.ShapeType();
1136 MESSAGE("Geomtype is " << GeomType);
1139 if (GeomType == TopAbs_COMPOUND){
1140 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1142 if (it.Value().ShapeType() == TopAbs_FACE){
1143 HasSizeMapOnFace = true;
1144 if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
1145 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
1148 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
1149 // MESSAGE("Face with key " << key << " already in map");
1151 FaceId2SizeMap[key] = smIt->second;
1154 if (it.Value().ShapeType() == TopAbs_EDGE){
1155 HasSizeMapOnEdge = true;
1156 HasSizeMapOnFace = true;
1157 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
1158 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
1161 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
1162 // MESSAGE("Edge with key " << key << " already in map");
1164 EdgeId2SizeMap[key] = smIt->second;
1166 // Group of vertices
1167 if (it.Value().ShapeType() == TopAbs_VERTEX){
1168 HasSizeMapOnVertex = true;
1169 HasSizeMapOnEdge = true;
1170 HasSizeMapOnFace = true;
1171 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
1172 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
1175 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
1176 MESSAGE("Group of vertices with key " << key << " already in map");
1178 MESSAGE("Group of vertices with key " << key << " has a size map: " << smIt->second);
1179 VertexId2SizeMap[key] = smIt->second;
1184 if (GeomType == TopAbs_FACE){
1185 HasSizeMapOnFace = true;
1186 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
1187 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
1190 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
1191 // MESSAGE("Face with key " << key << " already in map");
1193 FaceId2SizeMap[key] = smIt->second;
1196 if (GeomType == TopAbs_EDGE){
1197 HasSizeMapOnEdge = true;
1198 HasSizeMapOnFace = true;
1199 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
1200 key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
1203 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
1204 // MESSAGE("Edge with key " << key << " already in map");
1206 EdgeId2SizeMap[key] = smIt->second;
1209 if (GeomType == TopAbs_VERTEX){
1210 HasSizeMapOnVertex = true;
1211 HasSizeMapOnEdge = true;
1212 HasSizeMapOnFace = true;
1213 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
1214 key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
1217 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
1218 MESSAGE("Vertex with key " << key << " already in map");
1220 MESSAGE("Vertex with key " << key << " has a size map: " << smIt->second);
1221 VertexId2SizeMap[key] = smIt->second;
1229 // TODO appeler le constructeur des attracteurs directement ici
1230 MESSAGE("Setting Attractors");
1231 // if ( !_phySizeRel ) {
1232 const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
1233 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
1234 for ( ; atIt != attractors.end(); ++atIt ) {
1235 if ( !atIt->second.empty() ) {
1236 MESSAGE("cadsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
1237 GeomShape = entryToShape(atIt->first);
1238 GeomType = GeomShape.ShapeType();
1240 if (GeomType == TopAbs_COMPOUND){
1241 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1242 if (it.Value().ShapeType() == TopAbs_FACE){
1243 HasSizeMapOnFace = true;
1244 createAttractorOnFace(it.Value(), atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1249 if (GeomType == TopAbs_FACE){
1250 HasSizeMapOnFace = true;
1251 createAttractorOnFace(GeomShape, atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1254 if (GeomType == TopAbs_EDGE){
1255 HasSizeMapOnEdge = true;
1256 HasSizeMapOnFace = true;
1257 EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
1259 if (GeomType == TopAbs_VERTEX){
1260 HasSizeMapOnVertex = true;
1261 HasSizeMapOnEdge = true;
1262 HasSizeMapOnFace = true;
1263 VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
1270 // MESSAGE("Impossible to create the attractors when the physical size is relative");
1273 // temporary commented out for testing
1275 // - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
1276 // - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
1277 // - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
1279 // - Construct the attractors with an empty dist. map in the hypothesis
1280 // - 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()
1281 // -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap() OK
1283 const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
1285 BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
1286 for ( ; AtIt != class_attractors.end(); ++AtIt ) {
1287 if ( !AtIt->second->Empty() ) {
1288 // MESSAGE("cadsurf_set_attractor(): " << AtIt->first << " = " << AtIt->second);
1289 GeomShape = entryToShape(AtIt->first);
1290 AttShape = AtIt->second->GetAttractorShape();
1291 GeomType = GeomShape.ShapeType();
1293 // if (GeomType == TopAbs_COMPOUND){
1294 // for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1295 // if (it.Value().ShapeType() == TopAbs_FACE){
1296 // HasAttractorOnFace = true;
1297 // myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
1302 if (GeomType == TopAbs_FACE
1303 && (AttShape.ShapeType() == TopAbs_VERTEX
1304 || AttShape.ShapeType() == TopAbs_EDGE
1305 || AttShape.ShapeType() == TopAbs_WIRE
1306 || AttShape.ShapeType() == TopAbs_COMPOUND) ){
1307 HasSizeMapOnFace = true;
1309 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape)) ) {
1310 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
1313 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
1314 // MESSAGE("Face with key " << key << " already in map");
1317 FaceId2ClassAttractor[key] = AtIt->second;
1320 MESSAGE("Wrong shape type !!")
1328 // Enforced Vertices
1330 MESSAGE("Setting Enforced Vertices");
1331 const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
1332 BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
1333 for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
1334 if ( !enfIt->second.empty() ) {
1335 GeomShape = entryToShape(enfIt->first);
1336 GeomType = GeomShape.ShapeType();
1338 if (GeomType == TopAbs_COMPOUND){
1339 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1340 if (it.Value().ShapeType() == TopAbs_FACE){
1341 HasSizeMapOnFace = true;
1342 createEnforcedVertexOnFace(it.Value(), enfIt->second);
1347 if (GeomType == TopAbs_FACE){
1348 HasSizeMapOnFace = true;
1349 createEnforcedVertexOnFace(GeomShape, enfIt->second);
1354 // Internal vertices
1355 bool useInternalVertexAllFaces = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFaces(hyp);
1356 if (useInternalVertexAllFaces) {
1357 std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
1358 MESSAGE("Setting Internal Enforced Vertices");
1360 TopExp_Explorer exp (theGeomShape, TopAbs_FACE);
1361 for (; exp.More(); exp.Next()){
1362 MESSAGE("Iterating shapes. Shape type is " << exp.Current().ShapeType());
1363 TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX, TopAbs_EDGE);
1364 for (; exp_face.More(); exp_face.Next())
1366 // Get coords of vertex
1367 // Check if current coords is already in enfVertexList
1368 // If coords not in enfVertexList, add new enfVertex
1369 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1370 MESSAGE("Found vertex on face at " << aPnt.X() <<", "<<aPnt.Y()<<", "<<aPnt.Z());
1371 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1372 enfVertex->coords.push_back(aPnt.X());
1373 enfVertex->coords.push_back(aPnt.Y());
1374 enfVertex->coords.push_back(aPnt.Z());
1375 enfVertex->name = "";
1376 enfVertex->faceEntries.clear();
1377 enfVertex->geomEntry = "";
1378 enfVertex->grpName = grpName;
1379 enfVertex->vertex = TopoDS::Vertex( exp_face.Current() );
1380 _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()), aPnt, enfVertex);
1381 HasSizeMapOnFace = true;
1386 MESSAGE("Setting Size Map on FACES ");
1387 // #if BLSURF_VERSION_LONG < "3.1.1"
1388 cadsurf_data_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
1391 // iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1393 // clean_iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1396 if (HasSizeMapOnEdge){
1397 MESSAGE("Setting Size Map on EDGES ");
1398 // #if BLSURF_VERSION_LONG < "3.1.1"
1399 cadsurf_data_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
1402 // iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1404 // clean_iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1407 if (HasSizeMapOnVertex){
1408 MESSAGE("Setting Size Map on VERTICES ");
1409 // #if BLSURF_VERSION_LONG < "3.1.1"
1410 cadsurf_data_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
1413 // iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1415 // clean_iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1423 _preCadFacesIDsPeriodicityVector.clear();
1424 _preCadEdgesIDsPeriodicityVector.clear();
1425 _facesIDsPeriodicityVector.clear();
1426 _edgesIDsPeriodicityVector.clear();
1427 _verticesIDsPeriodicityVector.clear();
1429 MESSAGE("SetParameters preCadFacesPeriodicityVector");
1430 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadFacesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadFacesPeriodicityVector(hyp);
1432 for (std::size_t i = 0; i<preCadFacesPeriodicityVector.size(); i++){
1433 MESSAGE("SetParameters preCadFacesPeriodicityVector[" << i << "]");
1434 createPreCadFacesPeriodicity(theGeomShape, preCadFacesPeriodicityVector[i]);
1436 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
1438 MESSAGE("SetParameters preCadEdgesPeriodicityVector");
1439 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadEdgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadEdgesPeriodicityVector(hyp);
1441 for (std::size_t i = 0; i<preCadEdgesPeriodicityVector.size(); i++){
1442 MESSAGE("SetParameters preCadEdgesPeriodicityVector[" << i << "]");
1443 createPreCadEdgesPeriodicity(theGeomShape, preCadEdgesPeriodicityVector[i]);
1445 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
1447 if ( _preCadFacesIDsPeriodicityVector.size() > 0 || _preCadEdgesIDsPeriodicityVector.size() > 0 )
1449 MESSAGE("USING PRECAD FOR PERIODICITY")
1451 precad_set_param(pcs, "verbose", to_string(_verb).c_str());
1454 MESSAGE("SetParameters facesPeriodicityVector");
1455 const BLSURFPlugin_Hypothesis::TFacesPeriodicityVector facesPeriodicityVector = BLSURFPlugin_Hypothesis::GetFacesPeriodicityVector(hyp);
1457 for (std::size_t i = 0; i<facesPeriodicityVector.size(); i++){
1458 MESSAGE("SetParameters facesPeriodicityVector[" << i << "]");
1459 createFacesPeriodicity(theGeomShape, facesPeriodicityVector[i].first, facesPeriodicityVector[i].second);
1461 MESSAGE("_facesIDsPeriodicityVector.size() = " << _facesIDsPeriodicityVector.size());
1464 MESSAGE("SetParameters edgesPeriodicityVector");
1465 const BLSURFPlugin_Hypothesis::TEdgesPeriodicityVector edgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetEdgesPeriodicityVector(hyp);
1467 for (std::size_t i = 0; i<edgesPeriodicityVector.size(); i++){
1468 MESSAGE("SetParameters edgesPeriodicityVector[" << i << "]");
1469 // TODO: passer directement en paramètre edgesPeriodicityVector[i] plutôt que tous ces attributs
1470 createEdgesPeriodicity(theGeomShape, edgesPeriodicityVector[i].theFace1Entry, edgesPeriodicityVector[i].theEdge1Entry,
1471 edgesPeriodicityVector[i].theFace2Entry, edgesPeriodicityVector[i].theEdge2Entry, edgesPeriodicityVector[i].edge_orientation);
1473 MESSAGE("_edgesIDsPeriodicityVector.size() = " << _edgesIDsPeriodicityVector.size());
1475 MESSAGE("SetParameters verticesPeriodicityVector");
1476 const BLSURFPlugin_Hypothesis::TVerticesPeriodicityVector verticesPeriodicityVector = BLSURFPlugin_Hypothesis::GetVerticesPeriodicityVector(hyp);
1478 for (std::size_t i = 0; i<verticesPeriodicityVector.size(); i++){
1479 MESSAGE("SetParameters verticesPeriodicityVector[" << i << "]");
1480 // TODO: passer directement en paramètre verticesPeriodicityVector[i] plutôt que tous ces attributs
1481 createVerticesPeriodicity(theGeomShape, verticesPeriodicityVector[i].theEdge1Entry, verticesPeriodicityVector[i].theVertex1Entry,
1482 verticesPeriodicityVector[i].theEdge2Entry, verticesPeriodicityVector[i].theVertex2Entry);
1484 MESSAGE("_verticesIDsPeriodicityVector.size() = " << _verticesIDsPeriodicityVector.size());
1487 //================================================================================
1489 * \brief Throws an exception if a parameter name is wrong
1491 //================================================================================
1493 void BLSURFPlugin_BLSURF::set_param(cadsurf_session_t *css,
1494 const char * option_name,
1495 const char * option_value)
1497 status_t status = cadsurf_set_param(css, option_name, option_value );
1498 if ( status != MESHGEMS_STATUS_OK )
1500 if ( status == MESHGEMS_STATUS_UNKNOWN_PARAMETER ) {
1501 throw SALOME_Exception
1502 ( SMESH_Comment("Invalid name of CADSURF parameter: ") << option_name );
1504 else if ( status == MESHGEMS_STATUS_NOLICENSE )
1505 throw SALOME_Exception
1506 ( "No valid license available" );
1508 throw SALOME_Exception
1509 ( SMESH_Comment("Unacceptable value of CADSURF parameter '")
1510 << option_name << "': " << option_value);
1516 // --------------------------------------------------------------------------
1518 * \brief Class correctly terminating usage of BLSURF library at destruction
1520 class BLSURF_Cleaner
1523 cadsurf_session_t* _css;
1529 BLSURF_Cleaner(context_t * ctx,
1530 cadsurf_session_t* css,
1545 Clean( /*exceptContext=*/false );
1547 void Clean(const bool exceptContext)
1551 cadsurf_session_delete(_css); _css = 0;
1553 // #if BLSURF_VERSION_LONG >= "3.1.1"
1554 // // if(geo_sizemap_e)
1555 // // distene_sizemap_delete(geo_sizemap_e);
1556 // // if(geo_sizemap_f)
1557 // // distene_sizemap_delete(geo_sizemap_f);
1558 // if(iso_sizemap_p)
1559 // distene_sizemap_delete(iso_sizemap_p);
1560 // if(iso_sizemap_e)
1561 // distene_sizemap_delete(iso_sizemap_e);
1562 // if(iso_sizemap_f)
1563 // distene_sizemap_delete(iso_sizemap_f);
1565 // // if(clean_geo_sizemap_e)
1566 // // distene_sizemap_delete(clean_geo_sizemap_e);
1567 // // if(clean_geo_sizemap_f)
1568 // // distene_sizemap_delete(clean_geo_sizemap_f);
1569 // if(clean_iso_sizemap_p)
1570 // distene_sizemap_delete(clean_iso_sizemap_p);
1571 // if(clean_iso_sizemap_e)
1572 // distene_sizemap_delete(clean_iso_sizemap_e);
1573 // if(clean_iso_sizemap_f)
1574 // distene_sizemap_delete(clean_iso_sizemap_f);
1577 cad_delete(_cad); _cad = 0;
1578 dcad_delete(_dcad); _dcad = 0;
1579 cad_delete(_cleanc); _cleanc = 0;
1580 dcad_delete(_cleandc); _cleandc = 0;
1581 if ( !exceptContext )
1583 context_delete(_ctx); _ctx = 0;
1589 // --------------------------------------------------------------------------
1590 // comparator to sort nodes and sub-meshes
1591 struct ShapeTypeCompare
1593 // sort nodes by position in the following order:
1594 // SMDS_TOP_FACE=2, SMDS_TOP_EDGE=1, SMDS_TOP_VERTEX=0, SMDS_TOP_3DSPACE=3
1595 bool operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
1597 // NEW ORDER: nodes earlier added to sub-mesh are considered "less"
1598 return n1->getIdInShape() < n2->getIdInShape();
1599 // SMDS_TypeOfPosition pos1 = n1->GetPosition()->GetTypeOfPosition();
1600 // SMDS_TypeOfPosition pos2 = n2->GetPosition()->GetTypeOfPosition();
1601 // if ( pos1 == pos2 ) return 0;
1602 // if ( pos1 < pos2 || pos1 == SMDS_TOP_3DSPACE ) return 1;
1605 // sort sub-meshes in order: EDGE, VERTEX
1606 bool operator()( const SMESHDS_SubMesh* s1, const SMESHDS_SubMesh* s2 ) const
1608 int isVertex1 = ( s1 && s1->NbElements() == 0 );
1609 int isVertex2 = ( s2 && s2->NbElements() == 0 );
1610 if ( isVertex1 == isVertex2 )
1612 return isVertex1 < isVertex2;
1616 //================================================================================
1618 * \brief Fills groups on nodes to be merged
1620 //================================================================================
1622 void getNodeGroupsToMerge( const SMESHDS_SubMesh* smDS,
1623 const TopoDS_Shape& shape,
1624 SMESH_MeshEditor::TListOfListOfNodes& nodeGroupsToMerge)
1626 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1627 switch ( shape.ShapeType() )
1629 case TopAbs_VERTEX: {
1630 std::list< const SMDS_MeshNode* > nodes;
1631 while ( nIt->more() )
1632 nodes.push_back( nIt->next() );
1633 if ( nodes.size() > 1 )
1634 nodeGroupsToMerge.push_back( nodes );
1638 std::multimap< double, const SMDS_MeshNode* > u2node;
1639 const SMDS_EdgePosition* ePos;
1640 while ( nIt->more() )
1642 const SMDS_MeshNode* n = nIt->next();
1643 if (( ePos = dynamic_cast< const SMDS_EdgePosition* >( n->GetPosition() )))
1644 u2node.insert( make_pair( ePos->GetUParameter(), n ));
1646 if ( u2node.size() < 2 ) return;
1648 double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
1649 std::multimap< double, const SMDS_MeshNode* >::iterator un2, un1;
1650 for ( un2 = u2node.begin(), un1 = un2++; un2 != u2node.end(); un1 = un2++ )
1652 if (( un2->first - un1->first ) <= tol )
1654 std::list< const SMDS_MeshNode* > nodes;
1655 nodes.push_back( un1->second );
1656 while (( un2->first - un1->first ) <= tol )
1658 nodes.push_back( un2->second );
1659 if ( ++un2 == u2node.end()) {
1664 // make nodes created on the boundary of viscous layer replace nodes created
1665 // by BLSURF as their SMDS_Position is more correct
1666 nodes.sort( ShapeTypeCompare() );
1667 nodeGroupsToMerge.push_back( nodes );
1674 // SMESH_MeshEditor::TListOfListOfNodes::const_iterator nll = nodeGroupsToMerge.begin();
1675 // for ( ; nll != nodeGroupsToMerge.end(); ++nll )
1677 // cout << "Merge ";
1678 // const std::list< const SMDS_MeshNode* >& nl = *nll;
1679 // std::list< const SMDS_MeshNode* >::const_iterator nIt = nl.begin();
1680 // for ( ; nIt != nl.end(); ++nIt )
1681 // cout << (*nIt) << " ";
1687 //================================================================================
1689 * \brief A temporary mesh used to compute mesh on a proxy FACE
1691 //================================================================================
1693 struct TmpMesh: public SMESH_Mesh
1695 typedef std::map<const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
1696 TN2NMap _tmp2origNN;
1697 TopoDS_Face _proxyFace;
1701 _myMeshDS = new SMESHDS_Mesh( _id, true );
1703 //--------------------------------------------------------------------------------
1705 * \brief Creates a FACE bound by viscous layers and mesh each its EDGE with 1 segment
1707 //--------------------------------------------------------------------------------
1709 const TopoDS_Face& makeProxyFace( SMESH_ProxyMesh::Ptr& viscousMesh,
1710 const TopoDS_Face& origFace)
1712 // get data of nodes on inner boundary of viscous layers
1713 SMESH_Mesh* origMesh = viscousMesh->GetMesh();
1715 TSideVector wireVec = StdMeshers_FaceSide::GetFaceWires(origFace, *origMesh,
1716 /*skipMediumNodes = */true,
1718 if ( err && err->IsKO() )
1719 throw *err.get(); // it should be caught at SMESH_subMesh
1721 // proxy nodes and corresponding tmp VERTEXes
1722 std::vector<const SMDS_MeshNode*> origNodes;
1723 std::vector<TopoDS_Vertex> tmpVertex;
1725 // create a proxy FACE
1726 TopoDS_Shape origFaceCopy = origFace.EmptyCopied();
1727 BRepBuilderAPI_MakeFace newFace( TopoDS::Face( origFaceCopy ));
1728 for ( size_t iW = 0; iW != wireVec.size(); ++iW )
1730 StdMeshers_FaceSidePtr& wireData = wireVec[iW];
1731 const UVPtStructVec& wirePoints = wireData->GetUVPtStruct();
1732 if ( wirePoints.size() < 3 )
1735 BRepBuilderAPI_MakePolygon wire;
1736 const size_t i0 = tmpVertex.size();
1737 for ( size_t iN = 1; iN < wirePoints.size(); ++iN )
1739 wire.Add( SMESH_TNodeXYZ( wirePoints[ iN ].node ));
1740 origNodes.push_back( wirePoints[ iN ].node );
1741 tmpVertex.push_back( wire.LastVertex() );
1743 tmpVertex[ i0 ] = wire.FirstVertex(); // wire.LastVertex()==NULL for 1 vertex in wire
1745 if ( !wire.IsDone() )
1746 throw SALOME_Exception("BLSURFPlugin_BLSURF: BRepBuilderAPI_MakePolygon failed");
1747 newFace.Add( wire );
1749 _proxyFace = newFace;
1751 // set a new shape to mesh
1752 TopoDS_Compound auxCompoundToMesh;
1753 BRep_Builder shapeBuilder;
1754 shapeBuilder.MakeCompound( auxCompoundToMesh );
1755 shapeBuilder.Add( auxCompoundToMesh, _proxyFace );
1756 shapeBuilder.Add( auxCompoundToMesh, origMesh->GetShapeToMesh() );
1758 ShapeToMesh( auxCompoundToMesh );
1760 //TopExp_Explorer fExp( auxCompoundToMesh, TopAbs_FACE );
1761 //_proxyFace = TopoDS::Face( fExp.Current() );
1764 // Make input mesh for BLSURF: segments on EDGE's of newFace
1766 // make nodes and fill in _tmp2origNN
1768 SMESHDS_Mesh* tmpMeshDS = GetMeshDS();
1769 for ( size_t i = 0; i < origNodes.size(); ++i )
1771 GetSubMesh( tmpVertex[i] )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1772 if ( const SMDS_MeshNode* tmpN = SMESH_Algo::VertexNode( tmpVertex[i], tmpMeshDS ))
1773 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( tmpN, origNodes[i] ));
1775 throw SALOME_Exception("BLSURFPlugin_BLSURF: a proxy vertex not meshed");
1779 TopoDS_Vertex v1, v2;
1780 for ( TopExp_Explorer edge( _proxyFace, TopAbs_EDGE ); edge.More(); edge.Next() )
1782 const TopoDS_Edge& E = TopoDS::Edge( edge.Current() );
1783 TopExp::Vertices( E, v1, v2 );
1784 const SMDS_MeshNode* n1 = SMESH_Algo::VertexNode( v1, tmpMeshDS );
1785 const SMDS_MeshNode* n2 = SMESH_Algo::VertexNode( v2, tmpMeshDS );
1787 if ( SMDS_MeshElement* seg = tmpMeshDS->AddEdge( n1, n2 ))
1788 tmpMeshDS->SetMeshElementOnShape( seg, E );
1794 //--------------------------------------------------------------------------------
1796 * \brief Fill in the origMesh with faces computed by BLSURF in this tmp mesh
1798 //--------------------------------------------------------------------------------
1800 void FillInOrigMesh( SMESH_Mesh& origMesh,
1801 const TopoDS_Face& origFace )
1803 SMESH_MesherHelper helper( origMesh );
1804 helper.SetSubShape( origFace );
1805 helper.SetElementsOnShape( true );
1807 SMESH_MesherHelper tmpHelper( *this );
1808 tmpHelper.SetSubShape( _proxyFace );
1810 // iterate over tmp faces and copy them in origMesh
1811 const SMDS_MeshNode* nodes[27];
1812 const SMDS_MeshNode* nullNode = 0;
1814 SMDS_FaceIteratorPtr fIt = GetMeshDS()->facesIterator(/*idInceasingOrder=*/true);
1815 while ( fIt->more() )
1817 const SMDS_MeshElement* f = fIt->next();
1818 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
1820 for ( ; nIt->more(); ++nbN )
1822 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
1823 TN2NMap::iterator n2nIt =
1824 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( n, nullNode ));
1825 if ( !n2nIt->second ) {
1827 gp_XY uv = tmpHelper.GetNodeUV( _proxyFace, n );
1828 n2nIt->second = helper.AddNode( xyz[0], xyz[1], xyz[2], uv.X(), uv.Y() );
1830 nodes[ nbN ] = n2nIt->second;
1833 case 3: helper.AddFace( nodes[0], nodes[1], nodes[2] ); break;
1834 // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
1835 // nodes[3], nodes[4], nodes[5]); break;
1836 case 4: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
1837 // case 9: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1838 // nodes[4], nodes[5], nodes[6], nodes[7], nodes[8]); break;
1839 // case 8: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1840 // nodes[4], nodes[5], nodes[6], nodes[7]); break;
1847 * \brief A structure holding an error description and a verbisity level
1849 struct message_cb_user_data
1851 std::string * _error;
1859 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1860 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1861 real *duu, real *duv, real *dvv, void *user_data);
1862 status_t message_cb(message_t *msg, void *user_data);
1863 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1865 //=============================================================================
1869 //=============================================================================
1871 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
1873 MESSAGE("BLSURFPlugin_BLSURF::Compute");
1875 // Fix problem with locales
1876 Kernel_Utils::Localizer aLocalizer;
1878 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1881 if ( _haveViscousLayers )
1883 // Compute viscous layers
1885 TopTools_MapOfShape map;
1886 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1888 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1889 if ( !map.Add( F )) continue;
1890 SMESH_ProxyMesh::Ptr viscousMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
1892 return false; // error in StdMeshers_ViscousLayers2D::Compute()
1894 // Compute BLSURF mesh on viscous layers
1896 if ( viscousMesh->NbProxySubMeshes() > 0 )
1899 const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
1900 if ( !compute( tmpMesh, proxyFace, /*allowSubMeshClearing=*/false ))
1902 tmpMesh.FillInOrigMesh( aMesh, F );
1906 // Re-compute BLSURF mesh on the rest faces if the mesh was cleared
1908 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1910 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1911 SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
1912 if ( fSM->IsMeshComputed() ) continue;
1914 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1922 //=============================================================================
1926 //=============================================================================
1928 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh& aMesh,
1929 const TopoDS_Shape& aShape,
1930 bool allowSubMeshClearing)
1932 /* create a distene context (generic object) */
1933 status_t status = STATUS_ERROR;
1935 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1936 SMESH_MesherHelper helper( aMesh );
1937 // do not call helper.IsQuadraticSubMesh() because sub-meshes
1938 // may be cleaned and helper.myTLinkNodeMap gets invalid in such a case
1939 bool haveQuadraticSubMesh = SMESH_MesherHelper( aMesh ).IsQuadraticSubMesh( aShape );
1940 bool quadraticSubMeshAndViscousLayer = false;
1941 bool needMerge = false;
1942 typedef set< SMESHDS_SubMesh*, ShapeTypeCompare > TSubMeshSet;
1943 TSubMeshSet edgeSubmeshes;
1944 TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
1946 TopTools_IndexedMapOfShape fmap;
1947 TopTools_IndexedMapOfShape emap;
1948 TopTools_IndexedMapOfShape pmap;
1950 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1952 feclearexcept( FE_ALL_EXCEPT );
1953 int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1956 context_t *ctx = context_new();
1958 /* Set the message callback in the working context */
1959 message_cb_user_data mcud;
1960 mcud._error = & this->SMESH_Algo::_comment;
1961 mcud._progress = & this->SMESH_Algo::_progress;
1963 _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
1964 context_set_message_callback(ctx, message_cb, &mcud);
1966 /* set the interruption callback */
1967 _compute_canceled = false;
1968 context_set_interrupt_callback(ctx, interrupt_cb, this);
1970 /* create the CAD object we will work on. It is associated to the context ctx. */
1971 cad_t *c = cad_new(ctx);
1972 dcad_t *dcad = dcad_new(c);
1974 FacesWithSizeMap.Clear();
1975 FaceId2SizeMap.clear();
1976 FaceId2ClassAttractor.clear();
1977 FaceIndex2ClassAttractor.clear();
1978 EdgesWithSizeMap.Clear();
1979 EdgeId2SizeMap.clear();
1980 VerticesWithSizeMap.Clear();
1981 VertexId2SizeMap.clear();
1983 /* Now fill the CAD object with data from your CAD
1984 * environement. This is the most complex part of a successfull
1989 // If user requests it, send the CAD through Distene preprocessor : PreCAD
1990 cad_t *cleanc = NULL; // preprocessed cad
1991 dcad_t *cleandc = NULL; // preprocessed dcad
1992 precad_session_t *pcs = precad_session_new(ctx);
1993 // Give both dcad and cad to precad
1994 precad_data_set_dcad(pcs, dcad);
1995 precad_data_set_cad(pcs, c);
1997 cadsurf_session_t *css = cadsurf_session_new(ctx);
1999 // an object that correctly deletes all cadsurf objects at destruction
2000 BLSURF_Cleaner cleaner( ctx,css,c,dcad,cleanc,cleandc );
2002 MESSAGE("BEGIN SetParameters");
2003 bool use_precad = false;
2005 // #if BLSURF_VERSION_LONG >= "3.1.1"
2008 _hypothesis, css, pcs, aShape, &use_precad);
2009 MESSAGE("END SetParameters");
2011 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
2013 haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis != NULL && _hypothesis->GetQuadraticMesh());
2014 helper.SetIsQuadratic( haveQuadraticSubMesh );
2016 // To remove as soon as quadratic mesh is allowed - BEGIN
2017 // GDD: Viscous layer is not allowed with quadratic mesh
2018 if (_haveViscousLayers && haveQuadraticSubMesh ) {
2019 quadraticSubMeshAndViscousLayer = true;
2020 _haveViscousLayers = !haveQuadraticSubMesh;
2021 _comment += "Warning: Viscous layer is not possible with a quadratic mesh, it is ignored.";
2022 error(COMPERR_WARNING, _comment);
2024 // To remove as soon as quadratic mesh is allowed - END
2026 // needed to prevent the opencascade memory managmement from freeing things
2027 vector<Handle(Geom2d_Curve)> curves;
2028 vector<Handle(Geom_Surface)> surfaces;
2033 FaceId2PythonSmp.clear();
2034 EdgeId2PythonSmp.clear();
2035 VertexId2PythonSmp.clear();
2037 /****************************************************************************************
2039 *****************************************************************************************/
2041 string bad_end = "return";
2043 TopTools_IndexedMapOfShape _map;
2044 TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
2045 int ienf = _map.Extent();
2047 assert(Py_IsInitialized());
2048 PyGILState_STATE gstate;
2050 string theSizeMapStr;
2052 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
2054 TopoDS_Face f = TopoDS::Face(face_iter.Current());
2056 SMESH_subMesh* fSM = aMesh.GetSubMesh( f );
2057 if ( !fSM->IsEmpty() ) continue; // skip already meshed FACE with viscous layers
2059 // make INTERNAL face oriented FORWARD (issue 0020993)
2060 if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
2061 f.Orientation(TopAbs_FORWARD);
2063 if (fmap.FindIndex(f) > 0)
2065 iface = fmap.Add(f);
2066 // std::string aFileName = "fmap_face_";
2067 // aFileName.append(to_string(iface));
2068 // aFileName.append(".brep");
2069 // BRepTools::Write(f,aFileName.c_str());
2071 surfaces.push_back(BRep_Tool::Surface(f));
2073 /* create an object representing the face for cadsurf */
2074 /* where face_id is an integer identifying the face.
2075 * surf_function is the function that defines the surface
2076 * (For this face, it will be called by cadsurf with your_face_object_ptr
2077 * as last parameter.
2079 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
2081 /* by default a face has no tag (color).
2082 The following call sets it to the same value as the face_id : */
2083 cad_face_set_tag(fce, iface);
2085 /* Set face orientation (optional if you want a well oriented output mesh)*/
2086 if(f.Orientation() != TopAbs_FORWARD)
2087 cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
2089 cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
2091 if (HasSizeMapOnFace && !use_precad)
2093 // -----------------
2095 // -----------------
2096 faceKey = FacesWithSizeMap.FindIndex(f);
2099 if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()) {
2100 MESSAGE("A size map is defined on face :"<<faceKey)
2101 theSizeMapStr = FaceId2SizeMap[faceKey];
2102 // check if function ends with "return"
2103 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2105 // Expr To Python function, verification is performed at validation in GUI
2106 gstate = PyGILState_Ensure();
2107 PyObject * obj = NULL;
2108 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2110 PyObject * func = NULL;
2111 func = PyObject_GetAttrString(main_mod, "f");
2112 FaceId2PythonSmp[iface]=func;
2113 FaceId2SizeMap.erase(faceKey);
2114 PyGILState_Release(gstate);
2117 // Specific size map = Attractor
2118 std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
2120 for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
2121 if (attractor_iter->first == faceKey) {
2122 MESSAGE("Face indice: " << iface);
2123 MESSAGE("Adding attractor");
2125 double xyzCoords[3] = {attractor_iter->second[2],
2126 attractor_iter->second[3],
2127 attractor_iter->second[4]};
2129 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
2130 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2131 BRepClass_FaceClassifier scl(f,P,1e-7);
2132 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
2133 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
2134 // OCC 6.5.2: scl.Perform() is not bugged anymore
2135 scl.Perform(f, P, 1e-7);
2136 TopAbs_State result = scl.State();
2137 MESSAGE("Position of point on face: "<<result);
2138 if ( result == TopAbs_OUT )
2139 MESSAGE("Point is out of face: node is not created");
2140 if ( result == TopAbs_UNKNOWN )
2141 MESSAGE("Point position on face is unknown: node is not created");
2142 if ( result == TopAbs_ON )
2143 MESSAGE("Point is on border of face: node is not created");
2144 if ( result == TopAbs_IN )
2146 // Point is inside face and not on border
2147 MESSAGE("Point is in face: node is created");
2148 double uvCoords[2] = {attractor_iter->second[0],attractor_iter->second[1]};
2150 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2151 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2152 cad_point_set_tag(point_p, ienf);
2154 FaceId2AttractorCoords.erase(faceKey);
2158 // -----------------
2160 // -----------------
2161 std::map<int,BLSURFPlugin_Attractor* >::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
2162 if (clAttractor_iter != FaceId2ClassAttractor.end()){
2163 MESSAGE("Face indice: " << iface);
2164 MESSAGE("Adding attractor");
2165 FaceIndex2ClassAttractor[iface]=clAttractor_iter->second;
2166 FaceId2ClassAttractor.erase(clAttractor_iter);
2168 } // if (HasSizeMapOnFace && !use_precad)
2170 // ------------------
2171 // Enforced Vertices
2172 // ------------------
2173 faceKey = FacesWithEnforcedVertices.FindIndex(f);
2174 std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
2175 if (evmIt != FaceId2EnforcedVertexCoords.end()) {
2176 MESSAGE("Some enforced vertices are defined");
2177 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl;
2178 MESSAGE("Face indice: " << iface);
2179 MESSAGE("Adding enforced vertices");
2180 evl = evmIt->second;
2181 MESSAGE("Number of vertices to add: "<< evl.size());
2182 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
2183 for (; evlIt != evl.end(); ++evlIt) {
2184 BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
2185 xyzCoords.push_back(evlIt->at(2));
2186 xyzCoords.push_back(evlIt->at(3));
2187 xyzCoords.push_back(evlIt->at(4));
2188 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
2189 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2190 BRepClass_FaceClassifier scl(f,P,1e-7);
2191 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
2192 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
2193 // OCC 6.5.2: scl.Perform() is not bugged anymore
2194 scl.Perform(f, P, 1e-7);
2195 TopAbs_State result = scl.State();
2196 MESSAGE("Position of point on face: "<<result);
2197 if ( result == TopAbs_OUT ) {
2198 MESSAGE("Point is out of face: node is not created");
2199 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2200 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2201 EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2204 if ( result == TopAbs_UNKNOWN ) {
2205 MESSAGE("Point position on face is unknown: node is not created");
2206 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2207 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2208 EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2211 if ( result == TopAbs_ON ) {
2212 MESSAGE("Point is on border of face: node is not created");
2213 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2214 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2215 EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2218 if ( result == TopAbs_IN )
2220 // Point is inside face and not on border
2221 MESSAGE("Point is in face: node is created");
2222 double uvCoords[2] = {evlIt->at(0),evlIt->at(1)};
2224 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2225 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2227 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(xyzCoords);
2228 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end() &&
2229 !enfCoordsIt->second.empty() )
2231 // to merge nodes of an INTERNAL vertex belonging to several faces
2232 TopoDS_Vertex v = (*enfCoordsIt->second.begin())->vertex;
2233 if ( v.IsNull() ) v = (*enfCoordsIt->second.rbegin())->vertex;
2234 if ( !v.IsNull() ) {
2235 tag = pmap.Add( v );
2236 SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
2237 vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2238 mergeSubmeshes.insert( vSM->GetSubMeshDS() );
2239 // //if ( tag != pmap.Extent() )
2240 // needMerge = true;
2243 if ( tag == 0 ) tag = ienf;
2244 cad_point_set_tag(point_p, tag);
2247 FaceId2EnforcedVertexCoords.erase(faceKey);
2251 /****************************************************************************************
2253 now create the edges associated to this face
2254 *****************************************************************************************/
2256 for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next())
2258 TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
2259 int ic = emap.FindIndex(e);
2263 // std::string aFileName = "fmap_edge_";
2264 // aFileName.append(to_string(ic));
2265 // aFileName.append(".brep");
2266 // BRepTools::Write(e,aFileName.c_str());
2269 curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
2271 if (HasSizeMapOnEdge){
2272 edgeKey = EdgesWithSizeMap.FindIndex(e);
2273 if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
2274 MESSAGE("Sizemap defined on edge with index " << edgeKey);
2275 theSizeMapStr = EdgeId2SizeMap[edgeKey];
2276 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2278 // Expr To Python function, verification is performed at validation in GUI
2279 gstate = PyGILState_Ensure();
2280 PyObject * obj = NULL;
2281 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2283 PyObject * func = NULL;
2284 func = PyObject_GetAttrString(main_mod, "f");
2285 EdgeId2PythonSmp[ic]=func;
2286 EdgeId2SizeMap.erase(edgeKey);
2287 PyGILState_Release(gstate);
2290 /* data of nodes existing on the edge */
2291 StdMeshers_FaceSidePtr nodeData;
2292 SMESH_subMesh* sm = aMesh.GetSubMesh( e );
2293 if ( !sm->IsEmpty() )
2295 // SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
2296 // /*complexFirst=*/false);
2297 // while ( subsmIt->more() )
2298 // edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
2299 edgeSubmeshes.insert( sm->GetSubMeshDS() );
2301 nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
2302 /*ignoreMedium=*/haveQuadraticSubMesh));
2303 if ( nodeData->MissVertexNode() )
2304 return error(COMPERR_BAD_INPUT_MESH,"No node on vertex");
2306 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2307 if ( !nodeDataVec.empty() )
2309 if ( Abs( nodeDataVec[0].param - tmin ) > Abs( nodeDataVec.back().param - tmin ))
2311 nodeData->Reverse();
2312 nodeData->GetUVPtStruct(); // nodeData recomputes nodeDataVec
2314 // tmin and tmax can change in case of viscous layer on an adjacent edge
2315 tmin = nodeDataVec.front().param;
2316 tmax = nodeDataVec.back().param;
2320 cout << "---------------- Invalid nodeData" << endl;
2325 /* attach the edge to the current cadsurf face */
2326 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
2328 /* by default an edge has no tag (color).
2329 The following call sets it to the same value as the edge_id : */
2330 cad_edge_set_tag(edg, ic);
2332 /* by default, an edge does not necessalry appear in the resulting mesh,
2333 unless the following property is set :
2335 cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
2337 /* by default an edge is a boundary edge */
2338 if (e.Orientation() == TopAbs_INTERNAL)
2339 cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
2341 // pass existing nodes of sub-meshes to BLSURF
2344 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2345 const int nbNodes = nodeDataVec.size();
2347 dcad_edge_discretization_t *dedge;
2348 dcad_get_edge_discretization(dcad, edg, &dedge);
2349 dcad_edge_discretization_set_vertex_count( dedge, nbNodes );
2351 // cout << endl << " EDGE " << ic << endl;
2352 // cout << "tmin = "<<tmin << ", tmax = "<< tmax << endl;
2353 for ( int iN = 0; iN < nbNodes; ++iN )
2355 const UVPtStruct& nData = nodeDataVec[ iN ];
2356 double t = nData.param;
2357 real uv[2] = { nData.u, nData.v };
2358 SMESH_TNodeXYZ nXYZ( nData.node );
2359 // cout << "\tt = " << t
2360 // << "\t uv = ( " << uv[0] << ","<< uv[1] << " ) "
2361 // << "\t u = " << nData.param
2362 // << "\t ID = " << nData.node->GetID() << endl;
2363 dcad_edge_discretization_set_vertex_coordinates( dedge, iN+1, t, uv, nXYZ._xyz );
2365 dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2368 /****************************************************************************************
2370 *****************************************************************************************/
2374 gp_Pnt2d e0 = curves.back()->Value(tmin);
2375 gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
2376 Standard_Real d1=0,d2=0;
2379 for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
2380 TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
2384 d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2387 d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2389 *ip = pmap.FindIndex(v);
2392 // SMESH_subMesh* sm = aMesh.GetSubMesh(v);
2393 // if ( sm->IsMeshComputed() )
2394 // edgeSubmeshes.insert( sm->GetSubMeshDS() );
2397 // std::string aFileName = "fmap_vertex_";
2398 // aFileName.append(to_string(*ip));
2399 // aFileName.append(".brep");
2400 // BRepTools::Write(v,aFileName.c_str());
2402 if (HasSizeMapOnVertex){
2403 vertexKey = VerticesWithSizeMap.FindIndex(v);
2404 if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
2405 theSizeMapStr = VertexId2SizeMap[vertexKey];
2406 //MESSAGE("VertexId2SizeMap[faceKey]: " << VertexId2SizeMap[vertexKey]);
2407 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2409 // Expr To Python function, verification is performed at validation in GUI
2410 gstate = PyGILState_Ensure();
2411 PyObject * obj = NULL;
2412 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2414 PyObject * func = NULL;
2415 func = PyObject_GetAttrString(main_mod, "f");
2416 VertexId2PythonSmp[*ip]=func;
2417 VertexId2SizeMap.erase(vertexKey); // do not erase if using a vector
2418 PyGILState_Release(gstate);
2423 // should not happen
2424 MESSAGE("An edge does not have 2 extremities.");
2427 // This defines the curves extremity connectivity
2428 cad_edge_set_extremities(edg, ip1, ip2);
2429 /* set the tag (color) to the same value as the extremity id : */
2430 cad_edge_set_extremities_tag(edg, ip1, ip2);
2433 cad_edge_set_extremities(edg, ip2, ip1);
2434 cad_edge_set_extremities_tag(edg, ip2, ip1);
2440 // Clear mesh from already meshed edges if possible else
2441 // remember that merge is needed
2442 TSubMeshSet::iterator smIt = edgeSubmeshes.begin();
2443 for ( ; smIt != edgeSubmeshes.end(); ++smIt ) // loop on already meshed EDGEs
2445 SMESHDS_SubMesh* smDS = *smIt;
2446 if ( !smDS ) continue;
2447 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2450 const SMDS_MeshNode* n = nIt->next();
2451 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
2453 needMerge = true; // to correctly sew with viscous mesh
2454 // add existing medium nodes to helper
2455 if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
2457 SMDS_ElemIteratorPtr edgeIt = smDS->GetElements();
2458 while ( edgeIt->more() )
2459 helper.AddTLinks( static_cast<const SMDS_MeshEdge*>(edgeIt->next()));
2464 if ( allowSubMeshClearing )
2466 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2467 while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), 0 );
2468 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2469 while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), 0 );
2478 ///////////////////////
2480 ///////////////////////
2482 MESSAGE("BEFORE PERIODICITY");
2483 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
2484 if (! _preCadFacesIDsPeriodicityVector.empty()){
2485 MESSAGE("INTO PRECAD FACES PERIODICITY");
2486 for (std::size_t i=0; i < _preCadFacesIDsPeriodicityVector.size(); i++){
2487 std::vector<int> theFace1_ids = _preCadFacesIDsPeriodicityVector[i].shape1IDs;
2488 std::vector<int> theFace2_ids = _preCadFacesIDsPeriodicityVector[i].shape2IDs;
2489 int* theFace1_ids_c = &theFace1_ids[0];
2490 int* theFace2_ids_c = &theFace2_ids[0];
2491 std::ostringstream o;
2492 o << "_preCadFacesIDsPeriodicityVector[" << i << "] = [";
2493 for (std::size_t j=0; j < theFace1_ids.size(); j++)
2494 o << theFace1_ids[j] << ", ";
2496 for (std::size_t j=0; j < theFace2_ids.size(); j++)
2497 o << theFace2_ids[j] << ", ";
2500 MESSAGE("theFace1_ids.size(): " << theFace1_ids.size());
2501 MESSAGE("theFace2_ids.size(): " << theFace2_ids.size());
2502 if (_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2504 // If no source points, call peridoicity without transformation function
2505 MESSAGE("periodicity without transformation function");
2506 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2507 status = cad_add_face_multiple_periodicity_with_transformation_function(c, theFace1_ids_c, theFace1_ids.size(),
2508 theFace2_ids_c, theFace2_ids.size(), periodicity_transformation, NULL);
2509 if(status != STATUS_OK)
2510 cout << "cad_add_face_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2514 // get the transformation vertices
2515 MESSAGE("periodicity with transformation vertices");
2516 double* theSourceVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2517 double* theTargetVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2518 int nbSourceVertices = _preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2519 int nbTargetVertices = _preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2521 MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2523 status = cad_add_face_multiple_periodicity_with_transformation_function_by_points(c, theFace1_ids_c, theFace1_ids.size(),
2524 theFace2_ids_c, theFace2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2525 if(status != STATUS_OK)
2526 cout << "cad_add_face_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2530 MESSAGE("END PRECAD FACES PERIODICITY");
2533 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
2534 if (! _preCadEdgesIDsPeriodicityVector.empty()){
2535 MESSAGE("INTO PRECAD EDGES PERIODICITY");
2536 for (std::size_t i=0; i < _preCadEdgesIDsPeriodicityVector.size(); i++){
2537 std::vector<int> theEdge1_ids = _preCadEdgesIDsPeriodicityVector[i].shape1IDs;
2538 std::vector<int> theEdge2_ids = _preCadEdgesIDsPeriodicityVector[i].shape2IDs;
2539 // Use the address of the first element of the vector to initialise the array
2540 int* theEdge1_ids_c = &theEdge1_ids[0];
2541 int* theEdge2_ids_c = &theEdge2_ids[0];
2543 std::ostringstream o;
2544 o << "_preCadEdgesIDsPeriodicityVector[" << i << "] = [";
2545 for (std::size_t j=0; j < theEdge1_ids.size(); j++)
2546 o << theEdge1_ids[j] << ", ";
2548 for (std::size_t j=0; j < theEdge2_ids.size(); j++)
2549 o << theEdge2_ids[j] << ", ";
2552 MESSAGE("theEdge1_ids.size(): " << theEdge1_ids.size());
2553 MESSAGE("theEdge2_ids.size(): " << theEdge2_ids.size());
2555 if (_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2557 // If no source points, call peridoicity without transformation function
2558 MESSAGE("periodicity without transformation function");
2559 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2560 status = cad_add_edge_multiple_periodicity_with_transformation_function(c, theEdge1_ids_c, theEdge1_ids.size(),
2561 theEdge2_ids_c, theEdge2_ids.size(), periodicity_transformation, NULL);
2562 if(status != STATUS_OK)
2563 cout << "cad_add_edge_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2567 // get the transformation vertices
2568 MESSAGE("periodicity with transformation vertices");
2569 double* theSourceVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2570 double* theTargetVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2571 int nbSourceVertices = _preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2572 int nbTargetVertices = _preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2574 MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2576 status = cad_add_edge_multiple_periodicity_with_transformation_function_by_points(c, theEdge1_ids_c, theEdge1_ids.size(),
2577 theEdge2_ids_c, theEdge2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2578 if(status != STATUS_OK)
2579 cout << "cad_add_edge_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2581 MESSAGE("cad_add_edge_multiple_periodicity_with_transformation_function_by_points succeeded.\n");
2585 MESSAGE("END PRECAD EDGES PERIODICITY");
2588 if (! _facesIDsPeriodicityVector.empty()){
2589 MESSAGE("INTO FACE PERIODICITY");
2590 for (std::size_t i=0; i < _facesIDsPeriodicityVector.size(); i++){
2591 int theFace1 = _facesIDsPeriodicityVector[i].first;
2592 int theFace2 = _facesIDsPeriodicityVector[i].second;
2593 MESSAGE("_facesIDsPeriodicityVector[" << i << "] = (" << theFace1 << ", " << theFace2 << ")");
2594 status = cad_add_face_periodicity(c, theFace1, theFace2);
2595 if(status != STATUS_OK){
2596 cout << "cad_add_face_periodicity failed with error code " << status << "\n";
2599 MESSAGE("END FACE PERIODICITY");
2603 if (! _edgesIDsPeriodicityVector.empty()){
2604 MESSAGE("INTO EDGE PERIODICITY");
2605 for (std::size_t i=0; i < _edgesIDsPeriodicityVector.size(); i++){
2606 int theFace1 = _edgesIDsPeriodicityVector[i].theFace1ID;
2607 int theEdge1 = _edgesIDsPeriodicityVector[i].theEdge1ID;
2608 int theFace2 = _edgesIDsPeriodicityVector[i].theFace2ID;
2609 int theEdge2 = _edgesIDsPeriodicityVector[i].theEdge2ID;
2610 int edge_orientation = _edgesIDsPeriodicityVector[i].edge_orientation;
2611 MESSAGE("_edgesIDsPeriodicityVector[" << i << "] = (" << theFace1 << ", " << theEdge1 << ", " << theFace2 << ", " << theEdge2 << ", " << edge_orientation << ")");
2612 status = cad_add_edge_periodicity(c, theFace1, theEdge1, theFace2, theEdge2, edge_orientation);
2613 if(status != STATUS_OK){
2614 cout << "cad_add_edge_periodicity failed with error code " << status << "\n";
2617 MESSAGE("END EDGE PERIODICITY");
2620 if (! _verticesIDsPeriodicityVector.empty()){
2621 MESSAGE("INTO VERTEX PERIODICITY");
2622 for (std::size_t i=0; i < _verticesIDsPeriodicityVector.size(); i++){
2623 int theEdge1 = _verticesIDsPeriodicityVector[i].theEdge1ID;
2624 int theVertex1 = _verticesIDsPeriodicityVector[i].theVertex1ID;
2625 int theEdge2 = _verticesIDsPeriodicityVector[i].theEdge2ID;
2626 int theVertex2 = _verticesIDsPeriodicityVector[i].theVertex2ID;
2627 MESSAGE("_verticesIDsPeriodicityVector[" << i << "] = (" << theEdge1 << ", " << theVertex1 << ", " << theEdge2 << ", " << theVertex2 << ")");
2628 status = cad_add_point_periodicity(c, theEdge1, theVertex1, theEdge2, theVertex2);
2629 if(status != STATUS_OK){
2630 cout << "cad_add_vertex_periodicity failed with error code " << status << "\n";
2633 MESSAGE("END VERTEX PERIODICITY");
2639 MESSAGE("use_precad");
2640 /* Now launch the PreCAD process */
2641 status = precad_process(pcs);
2642 if(status != STATUS_OK){
2643 // TODO: raise an error if status < 0.
2644 cout << "================ WARNING =================== \n";
2646 msg << "PreCAD processing failed with error code " << status << "\n";
2647 msg << *mcud._error;
2649 cout << "============================================ \n";
2650 // the text of _comment is set in message_cb by mcud->_error
2651 // => No need to append msg to _comment
2654 // TODO: fix the SIGSEGV of COMPERR_WARNING with 2 launches
2655 error(COMPERR_WARNING, _comment);
2663 // retrieve the pre-processed CAD object
2666 cleandc = precad_new_dcad(pcs);
2668 cout << "Unable to retrieve PreCAD result on dcad \n";
2671 cout << "PreCAD processing successfull on dcad \n";
2674 cleanc = precad_new_cad(pcs);
2676 cout << "Unable to retrieve PreCAD result on cad \n";
2679 cout << "PreCAD processing successfull on cad \n";
2681 // #if BLSURF_VERSION_LONG >= "3.1.1"
2682 // /* We can now get the updated sizemaps (if any) */
2683 // // if(geo_sizemap_e)
2684 // // clean_geo_sizemap_e = precad_new_sizemap(pcs, geo_sizemap_e);
2686 // // if(geo_sizemap_f)
2687 // // clean_geo_sizemap_f = precad_new_sizemap(pcs, geo_sizemap_f);
2689 // if(iso_sizemap_p)
2690 // clean_iso_sizemap_p = precad_new_sizemap(pcs, iso_sizemap_p);
2692 // if(iso_sizemap_e)
2693 // clean_iso_sizemap_e = precad_new_sizemap(pcs, iso_sizemap_e);
2695 // if(iso_sizemap_f)
2696 // clean_iso_sizemap_f = precad_new_sizemap(pcs, iso_sizemap_f);
2699 // Now we can delete the PreCAD session
2700 precad_session_delete(pcs);
2704 cout << "Give the pre-processed dcad object to the current BLSurf session \n";
2705 cadsurf_data_set_dcad(css, cleandc);
2708 // Use the original one
2709 cadsurf_data_set_dcad(css, dcad);
2713 // Give the pre-processed CAD object to the current BLSurf session
2714 cout << "Give the pre-processed CAD object to the current BLSurf session \n";
2715 cadsurf_data_set_cad(css, cleanc);
2718 // Use the original one
2719 cadsurf_data_set_cad(css, c);
2722 std::cout << std::endl;
2723 std::cout << "Beginning of Surface Mesh generation" << std::endl;
2724 std::cout << std::endl;
2729 status = cadsurf_compute_mesh(css);
2732 catch ( std::exception& exc ) {
2733 _comment += exc.what();
2735 catch (Standard_Failure& ex) {
2736 _comment += ex.DynamicType()->Name();
2737 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
2739 _comment += ex.GetMessageString();
2743 if ( _comment.empty() )
2744 _comment = "Exception in cadsurf_compute_mesh()";
2746 if ( status != STATUS_OK) {
2747 // There was an error while meshing
2751 std::cout << std::endl;
2752 std::cout << "End of Surface Mesh generation" << std::endl;
2753 std::cout << std::endl;
2756 cadsurf_data_get_mesh(css, &msh);
2758 /* release the mesh object */
2759 cadsurf_data_regain_mesh(css, msh);
2760 return error(_comment);
2763 std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
2765 GMFFileName = _hypothesis->GetGMFFile();
2766 if (GMFFileName != "") {
2767 // bool GMFFileMode = _hypothesis->GetGMFFileMode();
2768 bool asciiFound = (GMFFileName.find(".mesh",GMFFileName.length()-5) != std::string::npos);
2769 bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
2770 if (!asciiFound && !binaryFound)
2771 GMFFileName.append(".mesh");
2772 mesh_write_mesh(msh, GMFFileName.c_str());
2775 /* retrieve mesh data (see meshgems/mesh.h) */
2776 integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
2777 integer *evedg, *evtri, *evquad, *tags_buff, type;
2780 mesh_get_vertex_count(msh, &nv);
2781 mesh_get_edge_count(msh, &ne);
2782 mesh_get_triangle_count(msh, &nt);
2783 mesh_get_quadrangle_count(msh, &nq);
2785 evedg = (integer *)mesh_calloc_generic_buffer(msh);
2786 evtri = (integer *)mesh_calloc_generic_buffer(msh);
2787 evquad = (integer *)mesh_calloc_generic_buffer(msh);
2788 tags_buff = (integer*)mesh_calloc_generic_buffer(msh);
2790 std::vector<const SMDS_MeshNode*> nodes(nv+1);
2791 std::vector<bool> tags(nv+1);
2793 /* enumerated vertices */
2794 for(int iv=1;iv<=nv;iv++) {
2795 mesh_get_vertex_coordinates(msh, iv, xyz);
2796 mesh_get_vertex_tag(msh, iv, &tag);
2797 // Issue 0020656. Use vertex coordinates
2799 if ( tag > 0 && tag <= pmap.Extent() ) {
2800 TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
2801 double tol = BRep_Tool::Tolerance( v );
2802 gp_Pnt p = BRep_Tool::Pnt( v );
2803 if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
2804 xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
2806 tag = 0; // enforced or attracted vertex
2807 nodes[iv] = SMESH_Algo::VertexNode( v, meshDS );
2810 nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
2812 // Create group of enforced vertices if requested
2813 BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
2815 projVertex.push_back((double)xyz[0]);
2816 projVertex.push_back((double)xyz[1]);
2817 projVertex.push_back((double)xyz[2]);
2818 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
2819 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end()) {
2820 MESSAGE("Found enforced vertex @ " << xyz[0] << ", " << xyz[1] << ", " << xyz[2]);
2821 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
2822 BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
2823 for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
2824 currentEnfVertex = (*enfListIt);
2825 if (currentEnfVertex->grpName != "") {
2826 bool groupDone = false;
2827 SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
2828 MESSAGE("currentEnfVertex->grpName: " << currentEnfVertex->grpName);
2829 MESSAGE("Parsing the groups of the mesh");
2830 while (grIt->more()) {
2831 SMESH_Group * group = grIt->next();
2832 if ( !group ) continue;
2833 MESSAGE("Group: " << group->GetName());
2834 SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2835 if ( !groupDS ) continue;
2836 MESSAGE("group->SMDSGroup().GetType(): " << (groupDS->GetType()));
2837 MESSAGE("group->SMDSGroup().GetType()==SMDSAbs_Node: " << (groupDS->GetType()==SMDSAbs_Node));
2838 MESSAGE("currentEnfVertex->grpName.compare(group->GetStoreName())==0: " << (currentEnfVertex->grpName.compare(group->GetName())==0));
2839 if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
2840 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
2841 aGroupDS->SMDSGroup().Add(nodes[iv]);
2842 MESSAGE("Node ID: " << nodes[iv]->GetID());
2843 // How can I inform the hypothesis ?
2844 // _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
2846 MESSAGE("Successfully added enforced vertex to existing group " << currentEnfVertex->grpName);
2853 SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
2854 aGroup->SetName( currentEnfVertex->grpName.c_str() );
2855 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2856 aGroupDS->SMDSGroup().Add(nodes[iv]);
2857 MESSAGE("Successfully created enforced vertex group " << currentEnfVertex->grpName);
2861 throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
2864 MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
2868 // internal points are tagged to zero
2869 if(tag > 0 && tag <= pmap.Extent() ){
2870 meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
2877 /* enumerate edges */
2878 for(int it=1;it<=ne;it++) {
2880 mesh_get_edge_vertices(msh, it, vtx);
2881 mesh_get_edge_extra_vertices(msh, it, &type, evedg);
2882 mesh_get_edge_tag(msh, it, &tag);
2884 // If PreCAD performed some cleaning operations (remove tiny edges,
2885 // merge edges ...) an output tag can indeed represent several original tags.
2886 // Get the initial tags corresponding to the output tag and redefine the tag as
2887 // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
2888 mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
2890 tag=tags_buff[nb_tag-1];
2893 Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
2894 tags[vtx[0]] = false;
2897 Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
2898 tags[vtx[1]] = false;
2900 if (type == MESHGEMS_MESH_ELEMENT_TYPE_EDGE3) {
2902 if (tags[evedg[0]]) {
2903 Set_NodeOnEdge(meshDS, nodes[evedg[0]], emap(tag));
2904 tags[evedg[0]] = false;
2906 edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]], nodes[evedg[0]]);
2909 edg = helper.AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
2911 meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
2914 /* enumerate triangles */
2915 for(int it=1;it<=nt;it++) {
2917 mesh_get_triangle_vertices(msh, it, vtx);
2918 mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
2919 mesh_get_triangle_tag(msh, it, &tag);
2921 meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
2922 tags[vtx[0]] = false;
2925 meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
2926 tags[vtx[1]] = false;
2929 meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
2930 tags[vtx[2]] = false;
2932 if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
2933 // QUADRATIC TRIANGLE
2934 if (tags[evtri[0]]) {
2935 meshDS->SetNodeOnFace(nodes[evtri[0]], TopoDS::Face(fmap(tag)));
2936 tags[evtri[0]] = false;
2938 if (tags[evtri[1]]) {
2939 meshDS->SetNodeOnFace(nodes[evtri[1]], TopoDS::Face(fmap(tag)));
2940 tags[evtri[1]] = false;
2942 if (tags[evtri[2]]) {
2943 meshDS->SetNodeOnFace(nodes[evtri[2]], TopoDS::Face(fmap(tag)));
2944 tags[evtri[2]] = false;
2946 tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
2947 nodes[evtri[0]], nodes[evtri[1]], nodes[evtri[2]]);
2950 tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
2952 meshDS->SetMeshElementOnShape(tri, TopoDS::Face(fmap(tag)));
2955 /* enumerate quadrangles */
2956 for(int it=1;it<=nq;it++) {
2957 SMDS_MeshFace* quad;
2958 mesh_get_quadrangle_vertices(msh, it, vtx);
2959 mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
2960 mesh_get_quadrangle_tag(msh, it, &tag);
2962 meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
2963 tags[vtx[0]] = false;
2966 meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
2967 tags[vtx[1]] = false;
2970 meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
2971 tags[vtx[2]] = false;
2974 meshDS->SetNodeOnFace(nodes[vtx[3]], TopoDS::Face(fmap(tag)));
2975 tags[vtx[3]] = false;
2977 if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
2978 // QUADRATIC QUADRANGLE
2979 std::cout << "This is a quadratic quadrangle" << std::endl;
2980 if (tags[evquad[0]]) {
2981 meshDS->SetNodeOnFace(nodes[evquad[0]], TopoDS::Face(fmap(tag)));
2982 tags[evquad[0]] = false;
2984 if (tags[evquad[1]]) {
2985 meshDS->SetNodeOnFace(nodes[evquad[1]], TopoDS::Face(fmap(tag)));
2986 tags[evquad[1]] = false;
2988 if (tags[evquad[2]]) {
2989 meshDS->SetNodeOnFace(nodes[evquad[2]], TopoDS::Face(fmap(tag)));
2990 tags[evquad[2]] = false;
2992 if (tags[evquad[3]]) {
2993 meshDS->SetNodeOnFace(nodes[evquad[3]], TopoDS::Face(fmap(tag)));
2994 tags[evquad[3]] = false;
2996 if (tags[evquad[4]]) {
2997 meshDS->SetNodeOnFace(nodes[evquad[4]], TopoDS::Face(fmap(tag)));
2998 tags[evquad[4]] = false;
3000 quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
3001 nodes[evquad[0]], nodes[evquad[1]], nodes[evquad[2]], nodes[evquad[3]],
3005 quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
3007 meshDS->SetMeshElementOnShape(quad, TopoDS::Face(fmap(tag)));
3010 /* release the mesh object, the rest is released by cleaner */
3011 cadsurf_data_regain_mesh(css, msh);
3013 if ( needMerge ) // sew mesh computed by BLSURF with pre-existing mesh
3015 SMESH_MeshEditor editor( &aMesh );
3016 SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
3017 TIDSortedElemSet segementsOnEdge;
3018 TIDSortedNodeSet nodesOnEdge;
3019 TSubMeshSet::iterator smIt;
3020 SMESHDS_SubMesh* smDS;
3021 typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_NodeIteratorPtr > TNodeIterator;
3024 // merge nodes on EDGE's with ones computed by BLSURF
3025 for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
3027 if (! (smDS = *smIt) ) continue;
3028 getNodeGroupsToMerge( smDS, meshDS->IndexToShape((*smIt)->GetID()), nodeGroupsToMerge );
3030 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
3031 while ( segIt->more() )
3032 segementsOnEdge.insert( segIt->next() );
3035 editor.MergeNodes( nodeGroupsToMerge );
3038 SMESH_MeshEditor::TListOfListOfElementsID equalSegments;
3039 editor.FindEqualElements( segementsOnEdge, equalSegments );
3040 editor.MergeElements( equalSegments );
3042 // remove excess segments created on the boundary of viscous layers
3043 const SMDS_TypeOfPosition onFace = SMDS_TOP_FACE;
3044 for ( int i = 1; i <= emap.Extent(); ++i )
3046 if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( emap( i )))
3048 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
3049 while ( segIt->more() )
3051 const SMDS_MeshElement* seg = segIt->next();
3052 if ( seg->GetNode(0)->GetPosition()->GetTypeOfPosition() == onFace ||
3053 seg->GetNode(1)->GetPosition()->GetTypeOfPosition() == onFace )
3054 meshDS->RemoveFreeElement( seg, smDS );
3060 // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
3061 TopLoc_Location loc; double f,l;
3062 for (int i = 1; i <= emap.Extent(); i++)
3063 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
3064 sm->SetIsAlwaysComputed( true );
3065 for (int i = 1; i <= pmap.Extent(); i++)
3066 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
3067 if ( !sm->IsMeshComputed() )
3068 sm->SetIsAlwaysComputed( true );
3070 // Set error to FACE's w/o elements
3071 SMESH_ComputeErrorName err = COMPERR_ALGO_FAILED;
3072 if ( _comment.empty() )
3074 err = COMPERR_WARNING;
3075 _comment = "No mesh elements assigned to a face";
3077 for ( int i = 1; i <= fmap.Extent(); ++i )
3079 SMESH_subMesh* sm = aMesh.GetSubMesh( fmap(i) );
3080 if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
3081 sm->GetComputeError().reset( new SMESH_ComputeError( err, _comment, this ));
3084 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
3086 if ( oldFEFlags > 0 )
3087 feenableexcept( oldFEFlags );
3088 feclearexcept( FE_ALL_EXCEPT );
3092 std::cout << "FacesWithSizeMap" << std::endl;
3093 FacesWithSizeMap.Statistics(std::cout);
3094 std::cout << "EdgesWithSizeMap" << std::endl;
3095 EdgesWithSizeMap.Statistics(std::cout);
3096 std::cout << "VerticesWithSizeMap" << std::endl;
3097 VerticesWithSizeMap.Statistics(std::cout);
3098 std::cout << "FacesWithEnforcedVertices" << std::endl;
3099 FacesWithEnforcedVertices.Statistics(std::cout);
3102 MESSAGE("END OF BLSURFPlugin_BLSURF::Compute()");
3103 return ( status == STATUS_OK && !quadraticSubMeshAndViscousLayer );
3106 //================================================================================
3108 * \brief Terminates computation
3110 //================================================================================
3112 void BLSURFPlugin_BLSURF::CancelCompute()
3114 _compute_canceled = true;
3117 //=============================================================================
3121 //=============================================================================
3123 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, const SMDS_MeshNode* node, const TopoDS_Shape& ed) {
3124 const TopoDS_Edge edge = TopoDS::Edge(ed);
3126 gp_Pnt pnt(node->X(), node->Y(), node->Z());
3128 Standard_Real p0 = 0.0;
3129 Standard_Real p1 = 1.0;
3130 TopLoc_Location loc;
3131 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
3133 if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
3134 GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
3137 if ( proj.NbPoints() > 0 )
3139 pa = (double)proj.LowerDistanceParameter();
3140 // Issue 0020656. Move node if it is too far from edge
3141 gp_Pnt curve_pnt = curve->Value( pa );
3142 double dist2 = pnt.SquareDistance( curve_pnt );
3143 double tol = BRep_Tool::Tolerance( edge );
3144 if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
3146 curve_pnt.Transform( loc );
3147 meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
3150 // GProp_GProps LProps;
3151 // BRepGProp::LinearProperties(ed, LProps);
3152 // double lg = (double)LProps.Mass();
3154 meshDS->SetNodeOnEdge(node, edge, pa);
3157 /* Curve definition function See cad_curv_t in file meshgems/cad.h for
3159 * NOTE : if when your CAD systems evaluates second
3160 * order derivatives it also computes first order derivatives and
3161 * function evaluation, you can optimize this example by making only
3162 * one CAD call and filling the necessary uv, dt, dtt arrays.
3164 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
3166 /* t is given. It contains the t (time) 1D parametric coordintaes
3167 of the point PreCAD/BLSurf is querying on the curve */
3169 /* user_data identifies the edge PreCAD/BLSurf is querying
3170 * (see cad_edge_new later in this example) */
3171 const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
3174 /* BLSurf is querying the function evaluation */
3177 uv[0]=P.X(); uv[1]=P.Y();
3181 /* query for the first order derivatives */
3184 dt[0]=V1.X(); dt[1]=V1.Y();
3188 /* query for the second order derivatives */
3191 dtt[0]=V2.X(); dtt[1]=V2.Y();
3197 /* Surface definition function.
3198 * See cad_surf_t in file meshgems/cad.h for more information.
3199 * NOTE : if when your CAD systems evaluates second order derivatives it also
3200 * computes first order derivatives and function evaluation, you can optimize
3201 * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
3204 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
3205 real *duu, real *duv, real *dvv, void *user_data)
3207 /* uv[2] is given. It contains the u,v coordinates of the point
3208 * PreCAD/BLSurf is querying on the surface */
3210 /* user_data identifies the face PreCAD/BLSurf is querying (see
3211 * cad_face_new later in this example)*/
3212 const Geom_Surface* geometry = (const Geom_Surface*) user_data;
3216 P=geometry->Value(uv[0],uv[1]); // S.D0(U,V,P);
3217 xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
3224 geometry->D1(uv[0],uv[1],P,D1U,D1V);
3225 du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
3226 dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
3229 if(duu && duv && dvv){
3233 gp_Vec D2U,D2V,D2UV;
3235 geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
3236 duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
3237 duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
3238 dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
3245 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
3247 //MESSAGE("size_on_surface")
3248 if (FaceId2PythonSmp.count(face_id) != 0){
3249 //MESSAGE("A size map is used to calculate size on face : "<<face_id)
3250 PyObject * pyresult = NULL;
3251 PyObject* new_stderr = NULL;
3252 assert(Py_IsInitialized());
3253 PyGILState_STATE gstate;
3254 gstate = PyGILState_Ensure();
3255 pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
3257 if ( pyresult != NULL) {
3258 result = PyFloat_AsDouble(pyresult);
3259 Py_DECREF(pyresult);
3264 string err_description="";
3265 new_stderr = newPyStdOut(err_description);
3266 PySys_SetObject((char*)"stderr", new_stderr);
3268 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
3269 Py_DECREF(new_stderr);
3270 MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
3271 result = *((real*)user_data);
3274 PyGILState_Release(gstate);
3276 else if (FaceIndex2ClassAttractor.count(face_id) !=0 && !FaceIndex2ClassAttractor[face_id]->Empty()){
3277 // MESSAGE("attractor used on face :"<<face_id)
3278 // MESSAGE("List of attractor is not empty")
3279 // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
3280 real result = FaceIndex2ClassAttractor[face_id]->GetSize(uv[0],uv[1]);
3284 // MESSAGE("List of attractor is empty !!!")
3285 *size = *((real*)user_data);
3287 // std::cout << "Size_on_surface sur la face " << face_id << " donne une size de: " << *size << std::endl;
3291 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
3293 if (EdgeId2PythonSmp.count(edge_id) != 0){
3294 PyObject * pyresult = NULL;
3295 PyObject* new_stderr = NULL;
3296 assert(Py_IsInitialized());
3297 PyGILState_STATE gstate;
3298 gstate = PyGILState_Ensure();
3299 pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
3301 if ( pyresult != NULL) {
3302 result = PyFloat_AsDouble(pyresult);
3303 Py_DECREF(pyresult);
3308 string err_description="";
3309 new_stderr = newPyStdOut(err_description);
3310 PySys_SetObject((char*)"stderr", new_stderr);
3312 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
3313 Py_DECREF(new_stderr);
3314 MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
3315 result = *((real*)user_data);
3318 PyGILState_Release(gstate);
3321 *size = *((real*)user_data);
3326 status_t size_on_vertex(integer point_id, real *size, void *user_data)
3328 if (VertexId2PythonSmp.count(point_id) != 0){
3329 PyObject * pyresult = NULL;
3330 PyObject* new_stderr = NULL;
3331 assert(Py_IsInitialized());
3332 PyGILState_STATE gstate;
3333 gstate = PyGILState_Ensure();
3334 pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
3336 if ( pyresult != NULL) {
3337 result = PyFloat_AsDouble(pyresult);
3338 Py_DECREF(pyresult);
3343 string err_description="";
3344 new_stderr = newPyStdOut(err_description);
3345 PySys_SetObject((char*)"stderr", new_stderr);
3347 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
3348 Py_DECREF(new_stderr);
3349 MESSAGE("Can't evaluate f()" << " error is " << err_description);
3350 result = *((real*)user_data);
3353 PyGILState_Release(gstate);
3356 *size = *((real*)user_data);
3362 * The following function will be called for PreCAD/BLSurf message
3363 * printing. See context_set_message_callback (later in this
3364 * template) for how to set user_data.
3366 status_t message_cb(message_t *msg, void *user_data)
3368 integer errnumber = 0;
3370 message_get_number(msg, &errnumber);
3371 message_get_description(msg, &desc);
3373 message_cb_user_data * mcud = (message_cb_user_data*)user_data;
3374 // Get all the error message and some warning messages related to license and periodicity
3375 if ( errnumber < 0 || err.find("license") != string::npos || err.find("periodicity") != string::npos ) {
3376 // remove ^A from the tail
3377 int len = strlen( desc );
3378 while (len > 0 && desc[len-1] != '\n')
3380 mcud->_error->append( desc, len );
3383 if ( errnumber == 3009001 )
3384 * mcud->_progress = atof( desc + 11 ) / 100.;
3385 if ( mcud->_verbosity > 0 )
3386 std::cout << desc << std::endl;
3391 /* This is the interrupt callback. PreCAD/BLSurf will call this
3392 * function regularily. See the file meshgems/interrupt.h
3394 status_t interrupt_cb(integer *interrupt_status, void *user_data)
3396 integer you_want_to_continue = 1;
3397 BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
3398 you_want_to_continue = !tmp->computeCanceled();
3400 if(you_want_to_continue)
3402 *interrupt_status = INTERRUPT_CONTINUE;
3405 else /* you want to stop BLSurf */
3407 *interrupt_status = INTERRUPT_STOP;
3408 return STATUS_ERROR;
3412 //=============================================================================
3416 //=============================================================================
3417 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh& aMesh,
3418 const TopoDS_Shape& aShape,
3419 MapShapeNbElems& aResMap)
3421 double diagonal = aMesh.GetShapeDiagonalSize();
3422 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
3423 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
3424 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
3425 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
3426 //int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
3427 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
3428 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
3430 _physicalMesh = (int) _hypothesis->GetPhysicalMesh();
3431 _phySizeRel = _hypothesis->IsPhySizeRel();
3432 if ( _hypothesis->GetPhySize() > 0)
3433 _phySize = _phySizeRel ? diagonal*_hypothesis->GetPhySize() : _hypothesis->GetPhySize();
3434 //_geometricMesh = (int) hyp->GetGeometricMesh();
3435 if (_hypothesis->GetAngleMesh() > 0)
3436 _angleMesh = _hypothesis->GetAngleMesh();
3437 _quadAllowed = _hypothesis->GetQuadAllowed();
3439 //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
3440 // GetDefaultPhySize() sometimes leads to computation failure
3441 _phySize = aMesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
3442 MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
3445 bool IsQuadratic = _quadraticMesh;
3450 TopTools_DataMapOfShapeInteger EdgesMap;
3451 double fullLen = 0.0;
3452 double fullNbSeg = 0;
3453 for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
3454 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3455 if( EdgesMap.IsBound(E) )
3457 SMESH_subMesh *sm = aMesh.GetSubMesh(E);
3458 double aLen = SMESH_Algo::EdgeLength(E);
3461 if(_physicalMesh==1) {
3462 nb1d = (int)( aLen/_phySize + 1 );
3467 Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
3468 double fullAng = 0.0;
3469 double dp = (l-f)/200;
3474 for(int j=2; j<=200; j++) {
3477 fullAng += fabs(V1.Angle(V2));
3481 nb1d = (int)( fullAng/_angleMesh + 1 );
3484 std::vector<int> aVec(SMDSEntity_Last);
3485 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3486 if( IsQuadratic > 0 ) {
3487 aVec[SMDSEntity_Node] = 2*nb1d - 1;
3488 aVec[SMDSEntity_Quad_Edge] = nb1d;
3491 aVec[SMDSEntity_Node] = nb1d - 1;
3492 aVec[SMDSEntity_Edge] = nb1d;
3494 aResMap.insert(std::make_pair(sm,aVec));
3495 EdgesMap.Bind(E,nb1d);
3497 double ELen = fullLen/fullNbSeg;
3501 // try to evaluate as in MEFISTO
3502 for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
3503 TopoDS_Face F = TopoDS::Face( exp.Current() );
3504 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
3506 BRepGProp::SurfaceProperties(F,G);
3507 double anArea = G.Mass();
3509 std::vector<int> nb1dVec;
3510 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
3511 int nbSeg = EdgesMap.Find(exp1.Current());
3513 nb1dVec.push_back( nbSeg );
3516 int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
3517 int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
3520 if ( nb1dVec.size() == 4 ) // quadrangle geom face
3522 int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
3524 nbNodes = (n1 + 1) * (n2 + 1);
3529 nbTria = nbQuad = nbTria / 3 + 1;
3532 std::vector<int> aVec(SMDSEntity_Last,0);
3534 int nb1d_in = (nbTria*3 - nb1d) / 2;
3535 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3536 aVec[SMDSEntity_Quad_Triangle] = nbTria;
3537 aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
3540 aVec[SMDSEntity_Node] = nbNodes;
3541 aVec[SMDSEntity_Triangle] = nbTria;
3542 aVec[SMDSEntity_Quadrangle] = nbQuad;
3544 aResMap.insert(std::make_pair(sm,aVec));
3551 BRepGProp::VolumeProperties(aShape,G);
3552 double aVolume = G.Mass();
3553 double tetrVol = 0.1179*ELen*ELen*ELen;
3554 int nbVols = int(aVolume/tetrVol);
3555 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3556 std::vector<int> aVec(SMDSEntity_Last);
3557 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3559 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3560 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3563 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3564 aVec[SMDSEntity_Tetra] = nbVols;
3566 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3567 aResMap.insert(std::make_pair(sm,aVec));