1 // Copyright (C) 2007-2015 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, or (at your option) any later version.
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////////////////////////////////////////
205 TopTools_IndexedMapOfShape FacesWithSizeMap;
206 std::map<int,string> FaceId2SizeMap;
207 TopTools_IndexedMapOfShape EdgesWithSizeMap;
208 std::map<int,string> EdgeId2SizeMap;
209 TopTools_IndexedMapOfShape VerticesWithSizeMap;
210 std::map<int,string> VertexId2SizeMap;
212 std::map<int,PyObject*> FaceId2PythonSmp;
213 std::map<int,PyObject*> EdgeId2PythonSmp;
214 std::map<int,PyObject*> VertexId2PythonSmp;
216 typedef std::map<int, std::vector< BLSURFPlugin_Attractor* > > TId2ClsAttractorVec;
217 TId2ClsAttractorVec FaceId2ClassAttractor;
218 TId2ClsAttractorVec FaceIndex2ClassAttractor;
219 std::map<int,std::vector<double> > FaceId2AttractorCoords;
222 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
223 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
224 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
225 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
227 bool HasSizeMapOnFace=false;
228 bool HasSizeMapOnEdge=false;
229 bool HasSizeMapOnVertex=false;
230 //bool HasAttractorOnFace=false;
232 //=============================================================================
236 //=============================================================================
238 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
240 : SMESH_2D_Algo(hypId, studyId, gen)
242 MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
244 _name = "MG-CADSurf";//"BLSURF";
245 _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
246 _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType());
247 _compatibleHypothesis.push_back(StdMeshers_ViscousLayers2D::GetHypType());
248 _requireDiscreteBoundary = false;
249 _onlyUnaryInput = false;
251 _supportSubmeshes = true;
253 smeshGen_i = SMESH_Gen_i::GetSMESHGen();
254 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
255 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
257 MESSAGE("studyid = " << _studyId);
260 myStudy = aStudyMgr->GetStudyByID(_studyId);
261 if ( !myStudy->_is_nil() )
262 MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
264 /* Initialize the Python interpreter */
265 assert(Py_IsInitialized());
266 PyGILState_STATE gstate;
267 gstate = PyGILState_Ensure();
270 main_mod = PyImport_AddModule("__main__");
273 main_dict = PyModule_GetDict(main_mod);
275 PyRun_SimpleString("from math import *");
276 PyGILState_Release(gstate);
278 FacesWithSizeMap.Clear();
279 FaceId2SizeMap.clear();
280 EdgesWithSizeMap.Clear();
281 EdgeId2SizeMap.clear();
282 VerticesWithSizeMap.Clear();
283 VertexId2SizeMap.clear();
284 FaceId2PythonSmp.clear();
285 EdgeId2PythonSmp.clear();
286 VertexId2PythonSmp.clear();
287 FaceId2AttractorCoords.clear();
288 FaceId2ClassAttractor.clear();
289 FaceIndex2ClassAttractor.clear();
290 FacesWithEnforcedVertices.Clear();
291 FaceId2EnforcedVertexCoords.clear();
292 EnfVertexCoords2ProjVertex.clear();
293 EnfVertexCoords2EnfVertexList.clear();
295 _compute_canceled = false;
298 //=============================================================================
302 //=============================================================================
304 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
306 MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
310 //=============================================================================
314 //=============================================================================
316 bool BLSURFPlugin_BLSURF::CheckHypothesis
318 const TopoDS_Shape& aShape,
319 SMESH_Hypothesis::Hypothesis_Status& aStatus)
322 _haveViscousLayers = false;
324 list<const SMESHDS_Hypothesis*>::const_iterator itl;
325 const SMESHDS_Hypothesis* theHyp;
327 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape,
328 /*ignoreAuxiliary=*/false);
329 aStatus = SMESH_Hypothesis::HYP_OK;
332 return true; // can work with no hypothesis
335 for ( itl = hyps.begin(); itl != hyps.end() && ( aStatus == HYP_OK ); ++itl )
338 string hypName = theHyp->GetName();
339 if ( hypName == BLSURFPlugin_Hypothesis::GetHypType() )
341 _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
343 if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
344 _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
345 // hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
346 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
348 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
350 if ( !_haveViscousLayers )
352 if ( error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus )))
353 _haveViscousLayers = true;
358 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
361 return aStatus == SMESH_Hypothesis::HYP_OK;
364 //=============================================================================
366 * Pass parameters to MG-CADSurf
368 //=============================================================================
370 inline std::string to_string(double d)
372 std::ostringstream o;
377 inline std::string to_string_rel(double d)
379 std::ostringstream o;
385 inline std::string to_string(int i)
387 std::ostringstream o;
392 inline std::string to_string_rel(int i)
394 std::ostringstream o;
400 double _smp_phy_size;
401 // #if BLSURF_VERSION_LONG >= "3.1.1"
402 // // sizemap_t *geo_sizemap_e, *geo_sizemap_f;
403 // sizemap_t *iso_sizemap_p, *iso_sizemap_e, *iso_sizemap_f;
404 // // sizemap_t *clean_geo_sizemap_e, *clean_geo_sizemap_f;
405 // sizemap_t *clean_iso_sizemap_p, *clean_iso_sizemap_e, *clean_iso_sizemap_f;
407 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
408 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
409 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
415 /////////////////////////////////////////////////////////
416 projectionPoint getProjectionPoint(const TopoDS_Face& face, const gp_Pnt& point)
418 projectionPoint myPoint;
419 Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
420 GeomAPI_ProjectPointOnSurf projector( point, surface );
421 if ( !projector.IsDone() || projector.NbPoints()==0 )
422 throw "getProjectionPoint: Can't project";
424 Quantity_Parameter u,v;
425 projector.LowerDistanceParameters(u,v);
426 myPoint.uv = gp_XY(u,v);
427 gp_Pnt aPnt = projector.NearestPoint();
428 myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
432 /////////////////////////////////////////////////////////
434 /////////////////////////////////////////////////////////
435 double getT(const TopoDS_Edge& edge, const gp_Pnt& point)
438 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
439 GeomAPI_ProjectPointOnCurve projector( point, curve);
440 if ( projector.NbPoints() == 0 )
442 return projector.LowerDistanceParameter();
445 /////////////////////////////////////////////////////////
446 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
448 MESSAGE("BLSURFPlugin_BLSURF::entryToShape "<<entry );
449 GEOM::GEOM_Object_var aGeomObj;
450 TopoDS_Shape S = TopoDS_Shape();
451 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
452 if (!aSObj->_is_nil()) {
453 CORBA::Object_var obj = aSObj->GetObject();
454 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
457 if ( !aGeomObj->_is_nil() )
458 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
462 void _createEnforcedVertexOnFace(TopoDS_Face faceShape, gp_Pnt aPnt, BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex)
464 BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
469 // Get the (u,v) values of the enforced vertex on the face
470 projectionPoint myPoint = getProjectionPoint(faceShape,aPnt);
472 MESSAGE("Enforced Vertex: " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z());
473 MESSAGE("Projected Vertex: " << myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z());
474 MESSAGE("Parametric coordinates: " << myPoint.uv.X() << ", " << myPoint.uv.Y() );
476 enf_coords.push_back(aPnt.X());
477 enf_coords.push_back(aPnt.Y());
478 enf_coords.push_back(aPnt.Z());
480 coords.push_back(myPoint.uv.X());
481 coords.push_back(myPoint.uv.Y());
482 coords.push_back(myPoint.xyz.X());
483 coords.push_back(myPoint.xyz.Y());
484 coords.push_back(myPoint.xyz.Z());
486 s_coords.push_back(myPoint.xyz.X());
487 s_coords.push_back(myPoint.xyz.Y());
488 s_coords.push_back(myPoint.xyz.Z());
490 // Save pair projected vertex / enf vertex
491 MESSAGE("Storing pair projected vertex / enf vertex:");
492 MESSAGE("("<< myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z() <<") / (" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z()<<")");
493 EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
494 MESSAGE("Group name is: \"" << enfVertex->grpName << "\"");
495 pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
496 BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
497 ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
498 if (ret.second == false) {
500 (*it)->grpName = enfVertex->grpName;
504 if (! FacesWithEnforcedVertices.Contains(faceShape)) {
505 key = FacesWithEnforcedVertices.Add(faceShape);
508 key = FacesWithEnforcedVertices.FindIndex(faceShape);
511 // If a node is already created by an attractor, do not create enforced vertex
512 int attractorKey = FacesWithSizeMap.FindIndex(faceShape);
513 bool sameAttractor = false;
514 if (attractorKey >= 0)
515 if (FaceId2AttractorCoords.count(attractorKey) > 0)
516 if (FaceId2AttractorCoords[attractorKey] == coords)
517 sameAttractor = true;
519 if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
520 MESSAGE("Map of enf. vertex has key " << key)
521 MESSAGE("Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
523 FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
525 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
526 MESSAGE("New Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
529 MESSAGE("Map of enf. vertex has not key " << key << ": creating it")
530 if (! sameAttractor) {
531 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
533 FaceId2EnforcedVertexCoords[key] = ens;
536 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
540 /////////////////////////////////////////////////////////
541 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
543 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex;
546 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfVertexListIt = enfVertexList.begin();
548 for( ; enfVertexListIt != enfVertexList.end() ; ++enfVertexListIt ) {
549 enfVertex = *enfVertexListIt;
550 // Case of manual coords
551 if (enfVertex->coords.size() != 0) {
552 aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
553 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
556 // Case of geom vertex coords
557 if (enfVertex->geomEntry != "") {
558 TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
559 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
560 if (GeomType == TopAbs_VERTEX){
561 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
562 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
565 if (GeomType == TopAbs_COMPOUND){
566 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
567 if (it.Value().ShapeType() == TopAbs_VERTEX){
568 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
569 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
577 /////////////////////////////////////////////////////////
578 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction, double defaultSize)
580 MESSAGE("Attractor function: "<< AttractorFunction);
581 double xa, ya, za; // Coordinates of attractor point
582 double a, b; // Attractor parameter
584 bool createNode=false; // To create a node on attractor projection
586 const char *sep = ";";
587 // atIt->second has the following pattern:
588 // ATTRACTOR(xa;ya;za;a;b;True|False;d)
590 // xa;ya;za : coordinates of attractor
591 // a : desired size on attractor
592 // b : distance of influence of attractor
593 // d : distance until which the size remains constant
595 // We search the parameters in the string
597 pos1 = AttractorFunction.find(sep);
598 if (pos1!=string::npos)
599 xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
601 pos2 = AttractorFunction.find(sep, pos1+1);
602 if (pos2!=string::npos) {
603 ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
607 pos2 = AttractorFunction.find(sep, pos1+1);
608 if (pos2!=string::npos) {
609 za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
613 pos2 = AttractorFunction.find(sep, pos1+1);
614 if (pos2!=string::npos) {
615 a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
619 pos2 = AttractorFunction.find(sep, pos1+1);
620 if (pos2!=string::npos) {
621 b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
625 pos2 = AttractorFunction.find(sep, pos1+1);
626 if (pos2!=string::npos) {
627 string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
628 MESSAGE("createNode: " << createNodeStr);
629 createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
633 pos2 = AttractorFunction.find(")");
634 if (pos2!=string::npos) {
635 d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
638 // Get the (u,v) values of the attractor on the face
639 projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
640 gp_XY uvPoint = myPoint.uv;
641 gp_XYZ xyzPoint = myPoint.xyz;
642 Standard_Real u0 = uvPoint.X();
643 Standard_Real v0 = uvPoint.Y();
644 Standard_Real x0 = xyzPoint.X();
645 Standard_Real y0 = xyzPoint.Y();
646 Standard_Real z0 = xyzPoint.Z();
647 std::vector<double> coords;
648 coords.push_back(u0);
649 coords.push_back(v0);
650 coords.push_back(x0);
651 coords.push_back(y0);
652 coords.push_back(z0);
653 // We construct the python function
654 ostringstream attractorFunctionStream;
655 attractorFunctionStream << "def f(u,v): return ";
656 attractorFunctionStream << defaultSize << "-(" << defaultSize <<"-" << a << ")";
657 //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
658 // rnc: make possible to keep the size constant until
659 // a defined distance. Distance is expressed as the positiv part
660 // of r-d where r is the distance to (u0,v0)
661 attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
663 MESSAGE("Python function for attractor:" << std::endl << attractorFunctionStream.str());
666 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
667 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
670 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
672 FaceId2SizeMap[key] =attractorFunctionStream.str();
674 MESSAGE("Creating node on ("<<x0<<","<<y0<<","<<z0<<")");
675 FaceId2AttractorCoords[key] = coords;
677 // // Test for new attractors
678 // gp_Pnt myP(xyzPoint);
679 // TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
680 // BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
681 // myAttractor.SetParameters(a, defaultSize, b, d);
682 // myAttractor.SetType(1);
683 // FaceId2ClassAttractor[key] = myAttractor;
684 // if(FaceId2ClassAttractor[key].GetFace().IsNull()){
685 // MESSAGE("face nulle ");
688 // MESSAGE("face OK");
690 // if (FaceId2ClassAttractor[key].GetAttractorShape().IsNull()){
691 // MESSAGE("pas de point");
694 // MESSAGE("point OK");
697 // One sub-shape to get ids from
698 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(TopoDS_Shape theMainShape, TopoDS_Shape theSubShape,
699 TopAbs_ShapeEnum theShapeType)
701 BLSURFPlugin_BLSURF::TListOfIDs face_ids;
702 TopTools_IndexedMapOfShape anIndices;
704 TopExp::MapShapes(theMainShape, theShapeType, anIndices);
706 // Standard_Boolean result = BRepTools::Write(theMainShape,"main_shape.brep");
708 for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
710 int face_id = anIndices.FindIndex(face_iter.Current());
712 throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
713 face_ids.push_back(face_id);
714 // std::ostringstream o;
715 // o << "face_" << face_id << ".brep";
716 // std::string face_name = o.str();
717 // const TopoDS_Face& face = TopoDS::Face(face_iter.Current());
718 // Standard_Boolean result = BRepTools::Write(face,face_name.c_str());
724 void BLSURFPlugin_BLSURF::addCoordsFromVertices(const std::vector<std::string> &theVerticesEntries, std::vector<double> &theVerticesCoords)
726 for (std::vector<std::string>::const_iterator it = theVerticesEntries.begin(); it != theVerticesEntries.end(); it++)
728 BLSURFPlugin_Hypothesis::TEntry theVertexEntry = *it;
729 MESSAGE("Vertex entry " << theVertexEntry);
730 addCoordsFromVertex(theVertexEntry, theVerticesCoords);
735 void BLSURFPlugin_BLSURF::addCoordsFromVertex(BLSURFPlugin_Hypothesis::TEntry theVertexEntry, std::vector<double> &theVerticesCoords)
737 if (theVertexEntry!="")
739 TopoDS_Shape aShape = entryToShape(theVertexEntry);
741 gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex( aShape ) );
742 double theX, theY, theZ;
747 theVerticesCoords.push_back(theX);
748 theVerticesCoords.push_back(theY);
749 theVerticesCoords.push_back(theZ);
753 /////////////////////////////////////////////////////////
754 void BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
756 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity");
758 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
759 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
761 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_FACE);
762 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_FACE);
764 TPreCadPeriodicityIDs preCadFacesPeriodicityIDs;
765 preCadFacesPeriodicityIDs.shape1IDs = theFace1_ids;
766 preCadFacesPeriodicityIDs.shape2IDs = theFace2_ids;
768 MESSAGE("preCadPeriodicity.theSourceVerticesEntries.size(): " << preCadPeriodicity.theSourceVerticesEntries.size());
769 MESSAGE("preCadPeriodicity.theTargetVerticesEntries.size(): " << preCadPeriodicity.theTargetVerticesEntries.size());
771 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadFacesPeriodicityIDs.theSourceVerticesCoords);
772 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadFacesPeriodicityIDs.theTargetVerticesCoords);
774 MESSAGE("preCadFacesPeriodicityIDs.theSourceVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theSourceVerticesCoords.size());
775 MESSAGE("preCadFacesPeriodicityIDs.theTargetVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theTargetVerticesCoords.size());
777 _preCadFacesIDsPeriodicityVector.push_back(preCadFacesPeriodicityIDs);
778 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
779 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity END");
783 /////////////////////////////////////////////////////////
784 void BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
786 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity");
788 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
789 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
791 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_EDGE);
792 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_EDGE);
794 TPreCadPeriodicityIDs preCadEdgesPeriodicityIDs;
795 preCadEdgesPeriodicityIDs.shape1IDs = theEdge1_ids;
796 preCadEdgesPeriodicityIDs.shape2IDs = theEdge2_ids;
798 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadEdgesPeriodicityIDs.theSourceVerticesCoords);
799 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadEdgesPeriodicityIDs.theTargetVerticesCoords);
801 _preCadEdgesIDsPeriodicityVector.push_back(preCadEdgesPeriodicityIDs);
802 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
803 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity END");
807 /////////////////////////////////////////////////////////
808 void BLSURFPlugin_BLSURF::createFacesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theFace1, BLSURFPlugin_Hypothesis::TEntry theFace2)
810 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity");
812 TopoDS_Shape GeomShape1 = entryToShape(theFace1);
813 TopoDS_Shape GeomShape2 = entryToShape(theFace2);
815 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomShape1, TopAbs_FACE);
816 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomShape2, TopAbs_FACE);
818 // Only one face id, since only a face can be selected
819 int theFace1_id = theFace1_ids[0];
820 int theFace2_id = theFace2_ids[0];
822 std::pair<int, int> pairOfFacesID = std::make_pair(theFace1_id, theFace2_id);
824 _facesIDsPeriodicityVector.push_back(pairOfFacesID);
825 MESSAGE("_facesIDsPeriodicityVector.size() = " << _facesIDsPeriodicityVector.size());
826 MESSAGE("BLSURFPlugin_BLSURF::createFacesPeriodicity END");
831 /////////////////////////////////////////////////////////
832 void BLSURFPlugin_BLSURF::createEdgesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theFace1, BLSURFPlugin_Hypothesis::TEntry theEdge1,
833 BLSURFPlugin_Hypothesis::TEntry theFace2, BLSURFPlugin_Hypothesis::TEntry theEdge2, int edge_orientation)
835 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity");
837 TEdgePeriodicityIDs edgePeriodicityIDs;
841 TopoDS_Shape GeomFace1 = entryToShape(theFace1);
842 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomFace1, TopAbs_FACE);
843 // Only one face id, since only a face can be selected
844 edgePeriodicityIDs.theFace1ID = theFace1_ids[0];
847 edgePeriodicityIDs.theFace1ID = 0;
850 TopoDS_Shape GeomFace2 = entryToShape(theFace2);
851 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomFace2, TopAbs_FACE);
852 edgePeriodicityIDs.theFace2ID = theFace2_ids[0];
855 edgePeriodicityIDs.theFace2ID = 0;
857 TopoDS_Shape GeomEdge1 = entryToShape(theEdge1);
858 TopoDS_Shape GeomEdge2 = entryToShape(theEdge2);
860 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge1, TopAbs_EDGE);
861 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge2, TopAbs_EDGE);
863 if (edge_orientation == 0 && GeomEdge1.Closed())
865 // if edge is closed, we have to set its orientation
866 MESSAGE("GeomEdge1.Orientation() = " << GeomEdge1.Orientation());
867 MESSAGE("GeomEdge2.Orientation() = " << GeomEdge2.Orientation());
868 if(GeomEdge1.Orientation() == TopAbs_FORWARD)
869 edge_orientation = CAD_ORIENTATION_REVERSED;
871 edge_orientation = CAD_ORIENTATION_FORWARD;
874 // Only one edge id, since only a edge can be selected
875 edgePeriodicityIDs.theEdge1ID = theEdge1_ids[0];
876 edgePeriodicityIDs.theEdge2ID = theEdge2_ids[0];
877 edgePeriodicityIDs.edge_orientation = edge_orientation;
879 _edgesIDsPeriodicityVector.push_back(edgePeriodicityIDs);
880 MESSAGE("_edgesIDsPeriodicityVector.size() = " << _edgesIDsPeriodicityVector.size());
881 MESSAGE("BLSURFPlugin_BLSURF::createEdgesPeriodicity END");
886 /////////////////////////////////////////////////////////
887 void BLSURFPlugin_BLSURF::createVerticesPeriodicity(TopoDS_Shape theGeomShape, BLSURFPlugin_Hypothesis::TEntry theEdge1, BLSURFPlugin_Hypothesis::TEntry theVertex1,
888 BLSURFPlugin_Hypothesis::TEntry theEdge2, BLSURFPlugin_Hypothesis::TEntry theVertex2)
890 MESSAGE("BLSURFPlugin_BLSURF::createVerticesPeriodicity");
892 TopoDS_Shape GeomEdge1 = entryToShape(theEdge1);
893 TopoDS_Shape GeomVertex1 = entryToShape(theVertex1);
894 TopoDS_Shape GeomEdge2 = entryToShape(theEdge2);
895 TopoDS_Shape GeomVertex2 = entryToShape(theVertex2);
897 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge1, TopAbs_EDGE);
898 TListOfIDs vertices1_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomVertex1, TopAbs_VERTEX);
899 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomEdge2, TopAbs_EDGE);
900 TListOfIDs vertices2_ids = _getSubShapeIDsInMainShape(theGeomShape, GeomVertex2, TopAbs_VERTEX);
902 // Only one vertex id, since only a vertex can be selected
903 TVertexPeriodicityIDs vertexPeriodicityIDs;
904 vertexPeriodicityIDs.theEdge1ID = theEdge1_ids[0];
905 vertexPeriodicityIDs.theVertex1ID = vertices1_ids[0];
906 vertexPeriodicityIDs.theEdge2ID = theEdge2_ids[0];
907 vertexPeriodicityIDs.theVertex2ID = vertices2_ids[0];
909 _verticesIDsPeriodicityVector.push_back(vertexPeriodicityIDs);
910 MESSAGE("_verticesIDsPeriodicityVector.size() = " << _verticesIDsPeriodicityVector.size());
911 MESSAGE("BLSURFPlugin_BLSURF::createVerticesPeriodicity END");
915 /////////////////////////////////////////////////////////
917 void BLSURFPlugin_BLSURF::SetParameters(
918 // #if BLSURF_VERSION_LONG >= "3.1.1"
921 const BLSURFPlugin_Hypothesis* hyp,
922 cadsurf_session_t * css,
923 precad_session_t * pcs,
924 const TopoDS_Shape& theGeomShape,
929 // Clear map so that it is not stored in the algorithm with old enforced vertices in it
930 EnfVertexCoords2EnfVertexList.clear();
932 double diagonal = SMESH_Mesh::GetShapeDiagonalSize( theGeomShape );
933 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
934 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
935 int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
936 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
937 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
938 double _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
939 bool _minSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
940 double _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
941 bool _maxSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
942 double _gradation = BLSURFPlugin_Hypothesis::GetDefaultGradation();
943 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
944 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
945 double _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
946 bool _anisotropic = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
947 double _anisotropicRatio = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
948 bool _removeTinyEdges = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
949 double _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
950 bool _badElementRemoval = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
951 double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
952 bool _optimizeMesh = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
953 bool _quadraticMesh = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
954 int _verb = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
955 int _topology = BLSURFPlugin_Hypothesis::GetDefaultTopology();
958 int _precadMergeEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
959 int _precadProcess3DTopology = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
960 int _precadDiscardInput = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
964 MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
965 _physicalMesh = (int) hyp->GetPhysicalMesh();
966 _geometricMesh = (int) hyp->GetGeometricMesh();
967 if (hyp->GetPhySize() > 0) {
968 _phySize = hyp->GetPhySize();
969 // if user size is not explicitly specified, "relative" flag is ignored
970 _phySizeRel = hyp->IsPhySizeRel();
972 if (hyp->GetMinSize() > 0) {
973 _minSize = hyp->GetMinSize();
974 // if min size is not explicitly specified, "relative" flag is ignored
975 _minSizeRel = hyp->IsMinSizeRel();
977 if (hyp->GetMaxSize() > 0) {
978 _maxSize = hyp->GetMaxSize();
979 // if max size is not explicitly specified, "relative" flag is ignored
980 _maxSizeRel = hyp->IsMaxSizeRel();
982 if (hyp->GetGradation() > 0)
983 _gradation = hyp->GetGradation();
984 _quadAllowed = hyp->GetQuadAllowed();
985 if (hyp->GetAngleMesh() > 0)
986 _angleMesh = hyp->GetAngleMesh();
987 if (hyp->GetChordalError() > 0)
988 _chordalError = hyp->GetChordalError();
989 _anisotropic = hyp->GetAnisotropic();
990 if (hyp->GetAnisotropicRatio() >= 0)
991 _anisotropicRatio = hyp->GetAnisotropicRatio();
992 _removeTinyEdges = hyp->GetRemoveTinyEdges();
993 if (hyp->GetTinyEdgeLength() > 0)
994 _tinyEdgeLength = hyp->GetTinyEdgeLength();
995 _badElementRemoval = hyp->GetBadElementRemoval();
996 if (hyp->GetBadElementAspectRatio() >= 0)
997 _badElementAspectRatio = hyp->GetBadElementAspectRatio();
998 _optimizeMesh = hyp->GetOptimizeMesh();
999 _quadraticMesh = hyp->GetQuadraticMesh();
1000 _verb = hyp->GetVerbosity();
1001 _topology = (int) hyp->GetTopology();
1003 _precadMergeEdges = hyp->GetPreCADMergeEdges();
1004 _precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
1005 _precadDiscardInput = hyp->GetPreCADDiscardInput();
1007 const BLSURFPlugin_Hypothesis::TOptionValues & opts = hyp->GetOptionValues();
1008 BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
1009 for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
1010 if ( !opIt->second.empty() ) {
1011 MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
1012 set_param(css, opIt->first.c_str(), opIt->second.c_str());
1015 const BLSURFPlugin_Hypothesis::TOptionValues & preCADopts = hyp->GetPreCADOptionValues();
1016 for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
1017 if ( !opIt->second.empty() ) {
1019 MESSAGE("precad_set_param(): " << opIt->first << " = " << opIt->second);
1020 precad_set_param(pcs, opIt->first.c_str(), opIt->second.c_str());
1024 // //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
1025 // // GetDefaultPhySize() sometimes leads to computation failure
1026 // // GDD 26/07/2012 From Distene documentation, global physical size default value = diag/100
1027 // _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal);
1028 // _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
1029 // _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
1030 // _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
1031 // _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
1032 // MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
1036 if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
1038 precad_set_param(pcs, "verbose", to_string(_verb).c_str());
1039 precad_set_param(pcs, "merge_edges", _precadMergeEdges ? "1" : "0");
1040 precad_set_param(pcs, "process_3d_topology", _precadProcess3DTopology ? "1" : "0");
1041 precad_set_param(pcs, "discard_input_topology", _precadDiscardInput ? "1" : "0");
1043 // unlimit mesh size (issue 0022266)
1044 set_param(css, "max_number_of_points_per_patch", "1000000");
1046 bool useGradation = false;
1047 switch (_physicalMesh)
1049 case BLSURFPlugin_Hypothesis::PhysicalGlobalSize:
1050 set_param(css, "physical_size_mode", "global");
1051 set_param(css, "global_physical_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1053 case BLSURFPlugin_Hypothesis::PhysicalLocalSize:
1054 set_param(css, "physical_size_mode", "local");
1055 set_param(css, "global_physical_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1056 useGradation = true;
1059 set_param(css, "physical_size_mode", "none");
1062 switch (_geometricMesh)
1064 case BLSURFPlugin_Hypothesis::GeometricalGlobalSize:
1065 set_param(css, "geometric_size_mode", "global");
1066 set_param(css, "geometric_approximation", to_string(_angleMesh).c_str());
1067 set_param(css, "chordal_error", to_string(_chordalError).c_str());
1068 useGradation = true;
1070 case BLSURFPlugin_Hypothesis::GeometricalLocalSize:
1071 set_param(css, "geometric_size_mode", "local");
1072 set_param(css, "geometric_approximation", to_string(_angleMesh).c_str());
1073 set_param(css, "chordal_error", to_string(_chordalError).c_str());
1074 useGradation = true;
1077 set_param(css, "geometric_size_mode", "none");
1080 if ( hyp && hyp->GetPhySize() > 0 ) {
1081 // user size is explicitly specified via hypothesis parameters
1082 // min and max sizes should be compared with explicitly specified user size
1083 // - compute absolute min size
1084 double mins = _minSizeRel ? _minSize * diagonal : _minSize;
1085 // - min size should not be greater than user size
1086 if ( _phySize < mins )
1087 set_param(css, "min_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1089 set_param(css, "min_size", _minSizeRel ? to_string_rel(_minSize).c_str() : to_string(_minSize).c_str());
1090 // - compute absolute max size
1091 double maxs = _maxSizeRel ? _maxSize * diagonal : _maxSize;
1092 // - max size should not be less than user size
1093 if ( _phySize > maxs )
1094 set_param(css, "max_size", _phySizeRel ? to_string_rel(_phySize).c_str() : to_string(_phySize).c_str());
1096 set_param(css, "max_size", _maxSizeRel ? to_string_rel(_maxSize).c_str() : to_string(_maxSize).c_str());
1099 // user size is not explicitly specified
1100 // - if minsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1101 set_param(css, "min_size", _minSizeRel ? to_string_rel(_minSize).c_str() : to_string(_minSize).c_str());
1102 // - if maxsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1103 set_param(css, "max_size", _maxSizeRel ? to_string_rel(_maxSize).c_str() : to_string(_maxSize).c_str());
1105 // anisotropic and quadrangle mesh requires disabling gradation
1106 if ( _anisotropic && _quadAllowed )
1107 useGradation = false; // limitation of V1.3
1109 set_param(css, "gradation", to_string(_gradation).c_str());
1110 set_param(css, "element_generation", _quadAllowed ? "quad_dominant" : "triangle");
1113 set_param(css, "metric", _anisotropic ? "anisotropic" : "isotropic");
1115 set_param(css, "anisotropic_ratio", to_string(_anisotropicRatio).c_str());
1116 set_param(css, "remove_tiny_edges", _removeTinyEdges ? "1" : "0");
1117 if ( _removeTinyEdges )
1118 set_param(css, "tiny_edge_length", to_string(_tinyEdgeLength).c_str());
1119 set_param(css, "force_bad_surface_element_removal", _badElementRemoval ? "1" : "0");
1120 if ( _badElementRemoval )
1121 set_param(css, "bad_surface_element_aspect_ratio", to_string(_badElementAspectRatio).c_str());
1122 set_param(css, "optimisation", _optimizeMesh ? "yes" : "no");
1123 set_param(css, "element_order", _quadraticMesh ? "quadratic" : "linear");
1124 set_param(css, "verbose", to_string(_verb).c_str());
1126 _smp_phy_size = _phySizeRel ? _phySize*diagonal : _phySize;
1128 std::cout << "_smp_phy_size = " << _smp_phy_size << std::endl;
1130 if (_physicalMesh == BLSURFPlugin_Hypothesis::PhysicalLocalSize){
1131 TopoDS_Shape GeomShape;
1132 TopoDS_Shape AttShape;
1133 TopAbs_ShapeEnum GeomType;
1135 // Standard Size Maps
1137 MESSAGE("Setting a Size Map");
1138 const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
1139 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
1140 for ( ; smIt != sizeMaps.end(); ++smIt ) {
1141 if ( !smIt->second.empty() ) {
1142 MESSAGE("cadsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
1143 GeomShape = entryToShape(smIt->first);
1144 GeomType = GeomShape.ShapeType();
1145 MESSAGE("Geomtype is " << GeomType);
1148 if (GeomType == TopAbs_COMPOUND){
1149 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1151 if (it.Value().ShapeType() == TopAbs_FACE){
1152 HasSizeMapOnFace = true;
1153 if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
1154 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
1157 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
1158 // MESSAGE("Face with key " << key << " already in map");
1160 FaceId2SizeMap[key] = smIt->second;
1163 if (it.Value().ShapeType() == TopAbs_EDGE){
1164 HasSizeMapOnEdge = true;
1165 HasSizeMapOnFace = true;
1166 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
1167 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
1170 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
1171 // MESSAGE("Edge with key " << key << " already in map");
1173 EdgeId2SizeMap[key] = smIt->second;
1175 // Group of vertices
1176 if (it.Value().ShapeType() == TopAbs_VERTEX){
1177 HasSizeMapOnVertex = true;
1178 HasSizeMapOnEdge = true;
1179 HasSizeMapOnFace = true;
1180 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
1181 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
1184 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
1185 MESSAGE("Group of vertices with key " << key << " already in map");
1187 MESSAGE("Group of vertices with key " << key << " has a size map: " << smIt->second);
1188 VertexId2SizeMap[key] = smIt->second;
1193 if (GeomType == TopAbs_FACE){
1194 HasSizeMapOnFace = true;
1195 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
1196 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
1199 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
1200 // MESSAGE("Face with key " << key << " already in map");
1202 FaceId2SizeMap[key] = smIt->second;
1205 if (GeomType == TopAbs_EDGE){
1206 HasSizeMapOnEdge = true;
1207 HasSizeMapOnFace = true;
1208 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
1209 key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
1212 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
1213 // MESSAGE("Edge with key " << key << " already in map");
1215 EdgeId2SizeMap[key] = smIt->second;
1218 if (GeomType == TopAbs_VERTEX){
1219 HasSizeMapOnVertex = true;
1220 HasSizeMapOnEdge = true;
1221 HasSizeMapOnFace = true;
1222 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
1223 key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
1226 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
1227 MESSAGE("Vertex with key " << key << " already in map");
1229 MESSAGE("Vertex with key " << key << " has a size map: " << smIt->second);
1230 VertexId2SizeMap[key] = smIt->second;
1238 // TODO appeler le constructeur des attracteurs directement ici
1239 MESSAGE("Setting Attractors");
1240 // if ( !_phySizeRel ) {
1241 const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
1242 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
1243 for ( ; atIt != attractors.end(); ++atIt ) {
1244 if ( !atIt->second.empty() ) {
1245 MESSAGE("cadsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
1246 GeomShape = entryToShape(atIt->first);
1247 GeomType = GeomShape.ShapeType();
1249 if (GeomType == TopAbs_COMPOUND){
1250 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1251 if (it.Value().ShapeType() == TopAbs_FACE){
1252 HasSizeMapOnFace = true;
1253 createAttractorOnFace(it.Value(), atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1258 if (GeomType == TopAbs_FACE){
1259 HasSizeMapOnFace = true;
1260 createAttractorOnFace(GeomShape, atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1263 if (GeomType == TopAbs_EDGE){
1264 HasSizeMapOnEdge = true;
1265 HasSizeMapOnFace = true;
1266 EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
1268 if (GeomType == TopAbs_VERTEX){
1269 HasSizeMapOnVertex = true;
1270 HasSizeMapOnEdge = true;
1271 HasSizeMapOnFace = true;
1272 VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
1279 // MESSAGE("Impossible to create the attractors when the physical size is relative");
1282 // temporary commented out for testing
1284 // - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
1285 // - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
1286 // - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
1288 // - Construct the attractors with an empty dist. map in the hypothesis
1289 // - 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()
1290 // -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap() OK
1292 theNbAttractors = 0;
1293 const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
1295 BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
1296 for ( ; AtIt != class_attractors.end(); ++AtIt ) {
1297 if ( !AtIt->second->Empty() ) {
1298 // MESSAGE("cadsurf_set_attractor(): " << AtIt->first << " = " << AtIt->second);
1299 GeomShape = entryToShape(AtIt->first);
1300 if ( !SMESH_MesherHelper::IsSubShape( GeomShape, theGeomShape ))
1302 AttShape = AtIt->second->GetAttractorShape();
1303 GeomType = GeomShape.ShapeType();
1305 // if (GeomType == TopAbs_COMPOUND){
1306 // for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1307 // if (it.Value().ShapeType() == TopAbs_FACE){
1308 // HasAttractorOnFace = true;
1309 // myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
1314 if (GeomType == TopAbs_FACE
1315 && (AttShape.ShapeType() == TopAbs_VERTEX
1316 || AttShape.ShapeType() == TopAbs_EDGE
1317 || AttShape.ShapeType() == TopAbs_WIRE
1318 || AttShape.ShapeType() == TopAbs_COMPOUND) ){
1319 HasSizeMapOnFace = true;
1321 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
1323 FaceId2ClassAttractor[key].push_back( AtIt->second );
1327 MESSAGE("Wrong shape type !!")
1335 // Enforced Vertices
1337 MESSAGE("Setting Enforced Vertices");
1338 const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
1339 BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
1340 for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
1341 if ( !enfIt->second.empty() ) {
1342 GeomShape = entryToShape(enfIt->first);
1343 GeomType = GeomShape.ShapeType();
1345 if (GeomType == TopAbs_COMPOUND){
1346 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1347 if (it.Value().ShapeType() == TopAbs_FACE){
1348 HasSizeMapOnFace = true;
1349 createEnforcedVertexOnFace(it.Value(), enfIt->second);
1354 if (GeomType == TopAbs_FACE){
1355 HasSizeMapOnFace = true;
1356 createEnforcedVertexOnFace(GeomShape, enfIt->second);
1361 // Internal vertices
1362 bool useInternalVertexAllFaces = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFaces(hyp);
1363 if (useInternalVertexAllFaces) {
1364 std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
1365 MESSAGE("Setting Internal Enforced Vertices");
1367 TopExp_Explorer exp (theGeomShape, TopAbs_FACE);
1368 for (; exp.More(); exp.Next()){
1369 MESSAGE("Iterating shapes. Shape type is " << exp.Current().ShapeType());
1370 TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX, TopAbs_EDGE);
1371 for (; exp_face.More(); exp_face.Next())
1373 // Get coords of vertex
1374 // Check if current coords is already in enfVertexList
1375 // If coords not in enfVertexList, add new enfVertex
1376 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1377 MESSAGE("Found vertex on face at " << aPnt.X() <<", "<<aPnt.Y()<<", "<<aPnt.Z());
1378 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1379 enfVertex->coords.push_back(aPnt.X());
1380 enfVertex->coords.push_back(aPnt.Y());
1381 enfVertex->coords.push_back(aPnt.Z());
1382 enfVertex->name = "";
1383 enfVertex->faceEntries.clear();
1384 enfVertex->geomEntry = "";
1385 enfVertex->grpName = grpName;
1386 enfVertex->vertex = TopoDS::Vertex( exp_face.Current() );
1387 _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()), aPnt, enfVertex);
1388 HasSizeMapOnFace = true;
1393 MESSAGE("Setting Size Map on FACES ");
1394 // #if BLSURF_VERSION_LONG < "3.1.1"
1395 cadsurf_data_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
1398 // iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1400 // clean_iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1403 if (HasSizeMapOnEdge){
1404 MESSAGE("Setting Size Map on EDGES ");
1405 // #if BLSURF_VERSION_LONG < "3.1.1"
1406 cadsurf_data_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
1409 // iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1411 // clean_iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1414 if (HasSizeMapOnVertex){
1415 MESSAGE("Setting Size Map on VERTICES ");
1416 // #if BLSURF_VERSION_LONG < "3.1.1"
1417 cadsurf_data_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
1420 // iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1422 // clean_iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1430 _preCadFacesIDsPeriodicityVector.clear();
1431 _preCadEdgesIDsPeriodicityVector.clear();
1432 _facesIDsPeriodicityVector.clear();
1433 _edgesIDsPeriodicityVector.clear();
1434 _verticesIDsPeriodicityVector.clear();
1436 MESSAGE("SetParameters preCadFacesPeriodicityVector");
1437 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadFacesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadFacesPeriodicityVector(hyp);
1439 for (std::size_t i = 0; i<preCadFacesPeriodicityVector.size(); i++){
1440 MESSAGE("SetParameters preCadFacesPeriodicityVector[" << i << "]");
1441 createPreCadFacesPeriodicity(theGeomShape, preCadFacesPeriodicityVector[i]);
1443 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
1445 MESSAGE("SetParameters preCadEdgesPeriodicityVector");
1446 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadEdgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadEdgesPeriodicityVector(hyp);
1448 for (std::size_t i = 0; i<preCadEdgesPeriodicityVector.size(); i++){
1449 MESSAGE("SetParameters preCadEdgesPeriodicityVector[" << i << "]");
1450 createPreCadEdgesPeriodicity(theGeomShape, preCadEdgesPeriodicityVector[i]);
1452 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
1454 if ( _preCadFacesIDsPeriodicityVector.size() > 0 || _preCadEdgesIDsPeriodicityVector.size() > 0 )
1456 MESSAGE("USING PRECAD FOR PERIODICITY")
1458 precad_set_param(pcs, "verbose", to_string(_verb).c_str());
1461 MESSAGE("SetParameters facesPeriodicityVector");
1462 const BLSURFPlugin_Hypothesis::TFacesPeriodicityVector facesPeriodicityVector = BLSURFPlugin_Hypothesis::GetFacesPeriodicityVector(hyp);
1464 for (std::size_t i = 0; i<facesPeriodicityVector.size(); i++){
1465 MESSAGE("SetParameters facesPeriodicityVector[" << i << "]");
1466 createFacesPeriodicity(theGeomShape, facesPeriodicityVector[i].first, facesPeriodicityVector[i].second);
1468 MESSAGE("_facesIDsPeriodicityVector.size() = " << _facesIDsPeriodicityVector.size());
1471 MESSAGE("SetParameters edgesPeriodicityVector");
1472 const BLSURFPlugin_Hypothesis::TEdgesPeriodicityVector edgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetEdgesPeriodicityVector(hyp);
1474 for (std::size_t i = 0; i<edgesPeriodicityVector.size(); i++){
1475 MESSAGE("SetParameters edgesPeriodicityVector[" << i << "]");
1476 // TODO: passer directement en paramètre edgesPeriodicityVector[i] plutôt que tous ces attributs
1477 createEdgesPeriodicity(theGeomShape, edgesPeriodicityVector[i].theFace1Entry, edgesPeriodicityVector[i].theEdge1Entry,
1478 edgesPeriodicityVector[i].theFace2Entry, edgesPeriodicityVector[i].theEdge2Entry, edgesPeriodicityVector[i].edge_orientation);
1480 MESSAGE("_edgesIDsPeriodicityVector.size() = " << _edgesIDsPeriodicityVector.size());
1482 MESSAGE("SetParameters verticesPeriodicityVector");
1483 const BLSURFPlugin_Hypothesis::TVerticesPeriodicityVector verticesPeriodicityVector = BLSURFPlugin_Hypothesis::GetVerticesPeriodicityVector(hyp);
1485 for (std::size_t i = 0; i<verticesPeriodicityVector.size(); i++){
1486 MESSAGE("SetParameters verticesPeriodicityVector[" << i << "]");
1487 // TODO: passer directement en paramètre verticesPeriodicityVector[i] plutôt que tous ces attributs
1488 createVerticesPeriodicity(theGeomShape, verticesPeriodicityVector[i].theEdge1Entry, verticesPeriodicityVector[i].theVertex1Entry,
1489 verticesPeriodicityVector[i].theEdge2Entry, verticesPeriodicityVector[i].theVertex2Entry);
1491 MESSAGE("_verticesIDsPeriodicityVector.size() = " << _verticesIDsPeriodicityVector.size());
1494 //================================================================================
1496 * \brief Throws an exception if a parameter name is wrong
1498 //================================================================================
1500 void BLSURFPlugin_BLSURF::set_param(cadsurf_session_t *css,
1501 const char * option_name,
1502 const char * option_value)
1504 status_t status = cadsurf_set_param(css, option_name, option_value );
1505 if ( status != MESHGEMS_STATUS_OK )
1507 if ( status == MESHGEMS_STATUS_UNKNOWN_PARAMETER ) {
1508 throw SALOME_Exception
1509 ( SMESH_Comment("Invalid name of CADSURF parameter: ") << option_name );
1511 else if ( status == MESHGEMS_STATUS_NOLICENSE )
1512 throw SALOME_Exception
1513 ( "No valid license available" );
1515 throw SALOME_Exception
1516 ( SMESH_Comment("Unacceptable value of CADSURF parameter '")
1517 << option_name << "': " << option_value);
1523 // --------------------------------------------------------------------------
1525 * \brief Class correctly terminating usage of MG-CADSurf library at destruction
1527 class BLSURF_Cleaner
1530 cadsurf_session_t* _css;
1536 BLSURF_Cleaner(context_t * ctx,
1537 cadsurf_session_t* css,
1552 Clean( /*exceptContext=*/false );
1554 void Clean(const bool exceptContext)
1558 cadsurf_session_delete(_css); _css = 0;
1560 // #if BLSURF_VERSION_LONG >= "3.1.1"
1561 // // if(geo_sizemap_e)
1562 // // distene_sizemap_delete(geo_sizemap_e);
1563 // // if(geo_sizemap_f)
1564 // // distene_sizemap_delete(geo_sizemap_f);
1565 // if(iso_sizemap_p)
1566 // distene_sizemap_delete(iso_sizemap_p);
1567 // if(iso_sizemap_e)
1568 // distene_sizemap_delete(iso_sizemap_e);
1569 // if(iso_sizemap_f)
1570 // distene_sizemap_delete(iso_sizemap_f);
1572 // // if(clean_geo_sizemap_e)
1573 // // distene_sizemap_delete(clean_geo_sizemap_e);
1574 // // if(clean_geo_sizemap_f)
1575 // // distene_sizemap_delete(clean_geo_sizemap_f);
1576 // if(clean_iso_sizemap_p)
1577 // distene_sizemap_delete(clean_iso_sizemap_p);
1578 // if(clean_iso_sizemap_e)
1579 // distene_sizemap_delete(clean_iso_sizemap_e);
1580 // if(clean_iso_sizemap_f)
1581 // distene_sizemap_delete(clean_iso_sizemap_f);
1584 cad_delete(_cad); _cad = 0;
1585 dcad_delete(_dcad); _dcad = 0;
1586 cad_delete(_cleanc); _cleanc = 0;
1587 dcad_delete(_cleandc); _cleandc = 0;
1588 if ( !exceptContext )
1590 context_delete(_ctx); _ctx = 0;
1596 // --------------------------------------------------------------------------
1597 // comparator to sort nodes and sub-meshes
1598 struct ShapeTypeCompare
1600 // sort nodes by position in the following order:
1601 // SMDS_TOP_FACE=2, SMDS_TOP_EDGE=1, SMDS_TOP_VERTEX=0, SMDS_TOP_3DSPACE=3
1602 bool operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
1604 // NEW ORDER: nodes earlier added to sub-mesh are considered "less"
1605 return n1->getIdInShape() < n2->getIdInShape();
1606 // SMDS_TypeOfPosition pos1 = n1->GetPosition()->GetTypeOfPosition();
1607 // SMDS_TypeOfPosition pos2 = n2->GetPosition()->GetTypeOfPosition();
1608 // if ( pos1 == pos2 ) return 0;
1609 // if ( pos1 < pos2 || pos1 == SMDS_TOP_3DSPACE ) return 1;
1612 // sort sub-meshes in order: EDGE, VERTEX
1613 bool operator()( const SMESHDS_SubMesh* s1, const SMESHDS_SubMesh* s2 ) const
1615 int isVertex1 = ( s1 && s1->NbElements() == 0 );
1616 int isVertex2 = ( s2 && s2->NbElements() == 0 );
1617 if ( isVertex1 == isVertex2 )
1619 return isVertex1 < isVertex2;
1623 //================================================================================
1625 * \brief Fills groups of nodes to be merged
1627 //================================================================================
1629 void getNodeGroupsToMerge( const SMESHDS_SubMesh* smDS,
1630 const TopoDS_Shape& shape,
1631 SMESH_MeshEditor::TListOfListOfNodes& nodeGroupsToMerge)
1633 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1634 switch ( shape.ShapeType() )
1636 case TopAbs_VERTEX: {
1637 std::list< const SMDS_MeshNode* > nodes;
1638 while ( nIt->more() )
1639 nodes.push_back( nIt->next() );
1640 if ( nodes.size() > 1 )
1641 nodeGroupsToMerge.push_back( nodes );
1645 std::multimap< double, const SMDS_MeshNode* > u2node;
1646 const SMDS_EdgePosition* ePos;
1647 while ( nIt->more() )
1649 const SMDS_MeshNode* n = nIt->next();
1650 if (( ePos = dynamic_cast< const SMDS_EdgePosition* >( n->GetPosition() )))
1651 u2node.insert( make_pair( ePos->GetUParameter(), n ));
1653 if ( u2node.size() < 2 ) return;
1655 //double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
1657 BRep_Tool::Range( TopoDS::Edge( shape ), f,l );
1658 double tol = (( l - f ) / 20.) / u2node.size();
1660 std::multimap< double, const SMDS_MeshNode* >::iterator un2, un1;
1661 for ( un2 = u2node.begin(), un1 = un2++; un2 != u2node.end(); un1 = un2++ )
1663 if (( un2->first - un1->first ) <= tol )
1665 std::list< const SMDS_MeshNode* > nodes;
1666 nodes.push_back( un1->second );
1667 while (( un2->first - un1->first ) <= tol )
1669 nodes.push_back( un2->second );
1670 if ( ++un2 == u2node.end()) {
1675 // make nodes created on the boundary of viscous layer replace nodes created
1676 // by MG-CADSurf as their SMDS_Position is more correct
1677 nodes.sort( ShapeTypeCompare() );
1678 nodeGroupsToMerge.push_back( nodes );
1685 // SMESH_MeshEditor::TListOfListOfNodes::const_iterator nll = nodeGroupsToMerge.begin();
1686 // for ( ; nll != nodeGroupsToMerge.end(); ++nll )
1688 // cout << "Merge ";
1689 // const std::list< const SMDS_MeshNode* >& nl = *nll;
1690 // std::list< const SMDS_MeshNode* >::const_iterator nIt = nl.begin();
1691 // for ( ; nIt != nl.end(); ++nIt )
1692 // cout << (*nIt) << " ";
1698 //================================================================================
1700 * \brief A temporary mesh used to compute mesh on a proxy FACE
1702 //================================================================================
1704 struct TmpMesh: public SMESH_Mesh
1706 typedef std::map<const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
1707 TN2NMap _tmp2origNN;
1708 TopoDS_Face _proxyFace;
1712 _myMeshDS = new SMESHDS_Mesh( _id, true );
1714 //--------------------------------------------------------------------------------
1716 * \brief Creates a FACE bound by viscous layers and mesh each its EDGE with 1 segment
1718 //--------------------------------------------------------------------------------
1720 const TopoDS_Face& makeProxyFace( SMESH_ProxyMesh::Ptr& viscousMesh,
1721 const TopoDS_Face& origFace)
1723 // get data of nodes on inner boundary of viscous layers
1724 SMESH_Mesh* origMesh = viscousMesh->GetMesh();
1726 TSideVector wireVec = StdMeshers_FaceSide::GetFaceWires(origFace, *origMesh,
1727 /*skipMediumNodes = */true,
1729 if ( err && err->IsKO() )
1730 throw *err.get(); // it should be caught at SMESH_subMesh
1732 // proxy nodes and corresponding tmp VERTEXes
1733 std::vector<const SMDS_MeshNode*> origNodes;
1734 std::vector<TopoDS_Vertex> tmpVertex;
1736 // create a proxy FACE
1737 TopoDS_Shape origFaceCopy = origFace.EmptyCopied();
1738 BRepBuilderAPI_MakeFace newFace( TopoDS::Face( origFaceCopy ));
1739 for ( size_t iW = 0; iW != wireVec.size(); ++iW )
1741 StdMeshers_FaceSidePtr& wireData = wireVec[iW];
1742 const UVPtStructVec& wirePoints = wireData->GetUVPtStruct();
1743 if ( wirePoints.size() < 3 )
1746 BRepBuilderAPI_MakePolygon wire;
1747 const size_t i0 = tmpVertex.size();
1748 for ( size_t iN = 1; iN < wirePoints.size(); ++iN )
1750 wire.Add( SMESH_TNodeXYZ( wirePoints[ iN ].node ));
1751 origNodes.push_back( wirePoints[ iN ].node );
1752 tmpVertex.push_back( wire.LastVertex() );
1754 tmpVertex[ i0 ] = wire.FirstVertex(); // wire.LastVertex()==NULL for 1 vertex in wire
1756 if ( !wire.IsDone() )
1757 throw SALOME_Exception("BLSURFPlugin_BLSURF: BRepBuilderAPI_MakePolygon failed");
1758 newFace.Add( wire );
1760 _proxyFace = newFace;
1762 // set a new shape to mesh
1763 TopoDS_Compound auxCompoundToMesh;
1764 BRep_Builder shapeBuilder;
1765 shapeBuilder.MakeCompound( auxCompoundToMesh );
1766 shapeBuilder.Add( auxCompoundToMesh, _proxyFace );
1767 shapeBuilder.Add( auxCompoundToMesh, origMesh->GetShapeToMesh() );
1769 ShapeToMesh( auxCompoundToMesh );
1771 //TopExp_Explorer fExp( auxCompoundToMesh, TopAbs_FACE );
1772 //_proxyFace = TopoDS::Face( fExp.Current() );
1775 // Make input mesh for MG-CADSurf: segments on EDGE's of newFace
1777 // make nodes and fill in _tmp2origNN
1779 SMESHDS_Mesh* tmpMeshDS = GetMeshDS();
1780 for ( size_t i = 0; i < origNodes.size(); ++i )
1782 GetSubMesh( tmpVertex[i] )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1783 if ( const SMDS_MeshNode* tmpN = SMESH_Algo::VertexNode( tmpVertex[i], tmpMeshDS ))
1784 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( tmpN, origNodes[i] ));
1786 throw SALOME_Exception("BLSURFPlugin_BLSURF: a proxy vertex not meshed");
1790 TopoDS_Vertex v1, v2;
1791 for ( TopExp_Explorer edge( _proxyFace, TopAbs_EDGE ); edge.More(); edge.Next() )
1793 const TopoDS_Edge& E = TopoDS::Edge( edge.Current() );
1794 TopExp::Vertices( E, v1, v2 );
1795 const SMDS_MeshNode* n1 = SMESH_Algo::VertexNode( v1, tmpMeshDS );
1796 const SMDS_MeshNode* n2 = SMESH_Algo::VertexNode( v2, tmpMeshDS );
1798 if ( SMDS_MeshElement* seg = tmpMeshDS->AddEdge( n1, n2 ))
1799 tmpMeshDS->SetMeshElementOnShape( seg, E );
1805 //--------------------------------------------------------------------------------
1807 * \brief Fill in the origMesh with faces computed by MG-CADSurf in this tmp mesh
1809 //--------------------------------------------------------------------------------
1811 void FillInOrigMesh( SMESH_Mesh& origMesh,
1812 const TopoDS_Face& origFace )
1814 SMESH_MesherHelper helper( origMesh );
1815 helper.SetSubShape( origFace );
1816 helper.SetElementsOnShape( true );
1818 SMESH_MesherHelper tmpHelper( *this );
1819 tmpHelper.SetSubShape( _proxyFace );
1821 // iterate over tmp faces and copy them in origMesh
1822 const SMDS_MeshNode* nodes[27];
1823 const SMDS_MeshNode* nullNode = 0;
1825 SMDS_FaceIteratorPtr fIt = GetMeshDS()->facesIterator(/*idInceasingOrder=*/true);
1826 while ( fIt->more() )
1828 const SMDS_MeshElement* f = fIt->next();
1829 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
1831 for ( ; nIt->more(); ++nbN )
1833 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
1834 TN2NMap::iterator n2nIt =
1835 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( n, nullNode ));
1836 if ( !n2nIt->second ) {
1838 gp_XY uv = tmpHelper.GetNodeUV( _proxyFace, n );
1839 n2nIt->second = helper.AddNode( xyz[0], xyz[1], xyz[2], uv.X(), uv.Y() );
1841 nodes[ nbN ] = n2nIt->second;
1844 case 3: helper.AddFace( nodes[0], nodes[1], nodes[2] ); break;
1845 // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
1846 // nodes[3], nodes[4], nodes[5]); break;
1847 case 4: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
1848 // case 9: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1849 // nodes[4], nodes[5], nodes[6], nodes[7], nodes[8]); break;
1850 // case 8: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1851 // nodes[4], nodes[5], nodes[6], nodes[7]); break;
1858 * \brief A structure holding an error description and a verbisity level
1860 struct message_cb_user_data
1862 std::string * _error;
1870 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1871 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1872 real *duu, real *duv, real *dvv, void *user_data);
1873 status_t message_cb(message_t *msg, void *user_data);
1874 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1876 //=============================================================================
1880 //=============================================================================
1882 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
1884 MESSAGE("BLSURFPlugin_BLSURF::Compute");
1886 // Fix problem with locales
1887 Kernel_Utils::Localizer aLocalizer;
1889 this->SMESH_Algo::_progress = 1e-3; // prevent progress advancment while computing attractors
1891 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1894 if ( _haveViscousLayers )
1896 // Compute viscous layers
1898 TopTools_MapOfShape map;
1899 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1901 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1902 if ( !map.Add( F )) continue;
1903 SMESH_ProxyMesh::Ptr viscousMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
1905 return false; // error in StdMeshers_ViscousLayers2D::Compute()
1907 // Compute MG-CADSurf mesh on viscous layers
1909 if ( viscousMesh->NbProxySubMeshes() > 0 )
1912 const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
1913 if ( !compute( tmpMesh, proxyFace, /*allowSubMeshClearing=*/false ))
1915 tmpMesh.FillInOrigMesh( aMesh, F );
1919 // Re-compute MG-CADSurf mesh on the rest faces if the mesh was cleared
1921 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1923 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1924 SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
1925 if ( fSM->IsMeshComputed() ) continue;
1927 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1935 //=============================================================================
1939 //=============================================================================
1941 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh& aMesh,
1942 const TopoDS_Shape& aShape,
1943 bool allowSubMeshClearing)
1945 /* create a distene context (generic object) */
1946 status_t status = STATUS_ERROR;
1948 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1949 SMESH_MesherHelper helper( aMesh );
1950 // do not call helper.IsQuadraticSubMesh() because sub-meshes
1951 // may be cleaned and helper.myTLinkNodeMap gets invalid in such a case
1952 bool haveQuadraticSubMesh = SMESH_MesherHelper( aMesh ).IsQuadraticSubMesh( aShape );
1953 bool quadraticSubMeshAndViscousLayer = false;
1954 bool needMerge = false;
1955 typedef set< SMESHDS_SubMesh*, ShapeTypeCompare > TSubMeshSet;
1956 TSubMeshSet edgeSubmeshes;
1957 TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
1959 TopTools_IndexedMapOfShape fmap;
1960 TopTools_IndexedMapOfShape emap;
1961 TopTools_IndexedMapOfShape pmap;
1963 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1965 feclearexcept( FE_ALL_EXCEPT );
1966 int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1969 context_t *ctx = context_new();
1971 /* Set the message callback in the working context */
1972 message_cb_user_data mcud;
1973 mcud._error = & this->SMESH_Algo::_comment;
1974 mcud._progress = & this->SMESH_Algo::_progress;
1976 _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
1977 context_set_message_callback(ctx, message_cb, &mcud);
1979 /* set the interruption callback */
1980 _compute_canceled = false;
1981 context_set_interrupt_callback(ctx, interrupt_cb, this);
1983 /* create the CAD object we will work on. It is associated to the context ctx. */
1984 cad_t *c = cad_new(ctx);
1985 dcad_t *dcad = dcad_new(c);
1987 FacesWithSizeMap.Clear();
1988 FaceId2SizeMap.clear();
1989 FaceId2ClassAttractor.clear();
1990 FaceIndex2ClassAttractor.clear();
1991 EdgesWithSizeMap.Clear();
1992 EdgeId2SizeMap.clear();
1993 VerticesWithSizeMap.Clear();
1994 VertexId2SizeMap.clear();
1996 /* Now fill the CAD object with data from your CAD
1997 * environement. This is the most complex part of a successfull
2002 // If user requests it, send the CAD through Distene preprocessor : PreCAD
2003 cad_t *cleanc = NULL; // preprocessed cad
2004 dcad_t *cleandc = NULL; // preprocessed dcad
2005 precad_session_t *pcs = precad_session_new(ctx);
2006 // Give both dcad and cad to precad
2007 precad_data_set_dcad(pcs, dcad);
2008 precad_data_set_cad(pcs, c);
2010 cadsurf_session_t *css = cadsurf_session_new(ctx);
2012 // an object that correctly deletes all cadsurf objects at destruction
2013 BLSURF_Cleaner cleaner( ctx,css,c,dcad,cleanc,cleandc );
2015 MESSAGE("BEGIN SetParameters");
2016 bool use_precad = false;
2018 // #if BLSURF_VERSION_LONG >= "3.1.1"
2021 _hypothesis, css, pcs, aShape, &use_precad);
2022 MESSAGE("END SetParameters");
2024 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
2026 haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis != NULL && _hypothesis->GetQuadraticMesh());
2027 helper.SetIsQuadratic( haveQuadraticSubMesh );
2029 // To remove as soon as quadratic mesh is allowed - BEGIN
2030 // GDD: Viscous layer is not allowed with quadratic mesh
2031 if (_haveViscousLayers && haveQuadraticSubMesh ) {
2032 quadraticSubMeshAndViscousLayer = true;
2033 _haveViscousLayers = !haveQuadraticSubMesh;
2034 _comment += "Warning: Viscous layer is not possible with a quadratic mesh, it is ignored.";
2035 error(COMPERR_WARNING, _comment);
2037 // To remove as soon as quadratic mesh is allowed - END
2039 // needed to prevent the opencascade memory managmement from freeing things
2040 vector<Handle(Geom2d_Curve)> curves;
2041 vector<Handle(Geom_Surface)> surfaces;
2046 FaceId2PythonSmp.clear();
2047 EdgeId2PythonSmp.clear();
2048 VertexId2PythonSmp.clear();
2050 /****************************************************************************************
2052 *****************************************************************************************/
2054 string bad_end = "return";
2056 TopTools_IndexedMapOfShape _map;
2057 TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
2058 int ienf = _map.Extent();
2060 assert(Py_IsInitialized());
2061 PyGILState_STATE gstate;
2063 string theSizeMapStr;
2065 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
2067 TopoDS_Face f = TopoDS::Face(face_iter.Current());
2069 SMESH_subMesh* fSM = aMesh.GetSubMesh( f );
2070 if ( !fSM->IsEmpty() ) continue; // skip already meshed FACE with viscous layers
2072 // make INTERNAL face oriented FORWARD (issue 0020993)
2073 if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
2074 f.Orientation(TopAbs_FORWARD);
2076 if (fmap.FindIndex(f) > 0)
2078 iface = fmap.Add(f);
2079 // std::string aFileName = "fmap_face_";
2080 // aFileName.append(to_string(iface));
2081 // aFileName.append(".brep");
2082 // BRepTools::Write(f,aFileName.c_str());
2084 surfaces.push_back(BRep_Tool::Surface(f));
2086 /* create an object representing the face for cadsurf */
2087 /* where face_id is an integer identifying the face.
2088 * surf_function is the function that defines the surface
2089 * (For this face, it will be called by cadsurf with your_face_object_ptr
2090 * as last parameter.
2092 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
2094 /* by default a face has no tag (color).
2095 The following call sets it to the same value as the face_id : */
2096 cad_face_set_tag(fce, iface);
2098 /* Set face orientation (optional if you want a well oriented output mesh)*/
2099 if(f.Orientation() != TopAbs_FORWARD)
2100 cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
2102 cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
2104 if (HasSizeMapOnFace /*&& !use_precad*/) //22903: use_precad seems not to interfere
2106 // -----------------
2108 // -----------------
2109 faceKey = FacesWithSizeMap.FindIndex(f);
2112 if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()) {
2113 MESSAGE("A size map is defined on face :"<<faceKey)
2114 theSizeMapStr = FaceId2SizeMap[faceKey];
2115 // check if function ends with "return"
2116 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2118 // Expr To Python function, verification is performed at validation in GUI
2119 gstate = PyGILState_Ensure();
2120 PyObject * obj = NULL;
2121 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2123 PyObject * func = NULL;
2124 func = PyObject_GetAttrString(main_mod, "f");
2125 FaceId2PythonSmp[iface]=func;
2126 FaceId2SizeMap.erase(faceKey);
2127 PyGILState_Release(gstate);
2130 // Specific size map = Attractor
2131 std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
2133 for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
2134 if (attractor_iter->first == faceKey) {
2135 MESSAGE("Face indice: " << iface);
2136 MESSAGE("Adding attractor");
2138 double xyzCoords[3] = {attractor_iter->second[2],
2139 attractor_iter->second[3],
2140 attractor_iter->second[4]};
2142 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
2143 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2144 BRepClass_FaceClassifier scl(f,P,1e-7);
2145 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
2146 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
2147 // OCC 6.5.2: scl.Perform() is not bugged anymore
2148 scl.Perform(f, P, 1e-7);
2149 TopAbs_State result = scl.State();
2150 MESSAGE("Position of point on face: "<<result);
2151 if ( result == TopAbs_OUT )
2152 MESSAGE("Point is out of face: node is not created");
2153 if ( result == TopAbs_UNKNOWN )
2154 MESSAGE("Point position on face is unknown: node is not created");
2155 if ( result == TopAbs_ON )
2156 MESSAGE("Point is on border of face: node is not created");
2157 if ( result == TopAbs_IN )
2159 // Point is inside face and not on border
2160 MESSAGE("Point is in face: node is created");
2161 double uvCoords[2] = {attractor_iter->second[0],attractor_iter->second[1]};
2163 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2164 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2165 cad_point_set_tag(point_p, ienf);
2167 FaceId2AttractorCoords.erase(faceKey);
2171 // -----------------
2173 // -----------------
2174 TId2ClsAttractorVec::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
2175 if (clAttractor_iter != FaceId2ClassAttractor.end()){
2176 MESSAGE("Face indice: " << iface);
2177 MESSAGE("Adding attractor");
2178 std::vector< BLSURFPlugin_Attractor* > & attVec = clAttractor_iter->second;
2179 for ( size_t i = 0; i < attVec.size(); ++i )
2180 if ( !attVec[i]->IsMapBuilt() ) {
2181 std::cout<<"Compute " << theNbAttractors-- << "-th attractor" <<std::endl;
2182 attVec[i]->BuildMap();
2184 FaceIndex2ClassAttractor[iface].swap( attVec );
2185 FaceId2ClassAttractor.erase(clAttractor_iter);
2187 } // if (HasSizeMapOnFace && !use_precad)
2189 // ------------------
2190 // Enforced Vertices
2191 // ------------------
2192 faceKey = FacesWithEnforcedVertices.FindIndex(f);
2193 std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
2194 if (evmIt != FaceId2EnforcedVertexCoords.end()) {
2195 MESSAGE("Some enforced vertices are defined");
2196 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl;
2197 MESSAGE("Face indice: " << iface);
2198 MESSAGE("Adding enforced vertices");
2199 evl = evmIt->second;
2200 MESSAGE("Number of vertices to add: "<< evl.size());
2201 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
2202 for (; evlIt != evl.end(); ++evlIt) {
2203 BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
2204 xyzCoords.push_back(evlIt->at(2));
2205 xyzCoords.push_back(evlIt->at(3));
2206 xyzCoords.push_back(evlIt->at(4));
2207 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
2208 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2209 BRepClass_FaceClassifier scl(f,P,1e-7);
2210 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
2211 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
2212 // OCC 6.5.2: scl.Perform() is not bugged anymore
2213 scl.Perform(f, P, 1e-7);
2214 TopAbs_State result = scl.State();
2215 MESSAGE("Position of point on face: "<<result);
2216 if ( result == TopAbs_OUT ) {
2217 MESSAGE("Point is out of face: node is not created");
2218 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2219 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2220 // isssue 22783. Do not erase as this point can be IN other face of a group
2221 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2224 if ( result == TopAbs_UNKNOWN ) {
2225 MESSAGE("Point position on face is unknown: node is not created");
2226 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2227 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2228 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2231 if ( result == TopAbs_ON ) {
2232 MESSAGE("Point is on border of face: node is not created");
2233 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2234 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2235 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2238 if ( result == TopAbs_IN )
2240 // Point is inside face and not on border
2241 MESSAGE("Point is in face: node is created");
2242 double uvCoords[2] = {evlIt->at(0),evlIt->at(1)};
2244 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2245 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2247 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(xyzCoords);
2248 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end() &&
2249 !enfCoordsIt->second.empty() )
2251 // to merge nodes of an INTERNAL vertex belonging to several faces
2252 TopoDS_Vertex v = (*enfCoordsIt->second.begin())->vertex;
2253 if ( v.IsNull() ) v = (*enfCoordsIt->second.rbegin())->vertex;
2254 if ( !v.IsNull() ) {
2255 tag = pmap.Add( v );
2256 SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
2257 vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2258 mergeSubmeshes.insert( vSM->GetSubMeshDS() );
2259 // //if ( tag != pmap.Extent() )
2260 // needMerge = true;
2263 if ( tag == 0 ) tag = ienf;
2264 cad_point_set_tag(point_p, tag);
2267 FaceId2EnforcedVertexCoords.erase(faceKey);
2271 /****************************************************************************************
2273 now create the edges associated to this face
2274 *****************************************************************************************/
2276 for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next())
2278 TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
2279 int ic = emap.FindIndex(e);
2283 // std::string aFileName = "fmap_edge_";
2284 // aFileName.append(to_string(ic));
2285 // aFileName.append(".brep");
2286 // BRepTools::Write(e,aFileName.c_str());
2289 curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
2291 if (HasSizeMapOnEdge){
2292 edgeKey = EdgesWithSizeMap.FindIndex(e);
2293 if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
2294 MESSAGE("Sizemap defined on edge with index " << edgeKey);
2295 theSizeMapStr = EdgeId2SizeMap[edgeKey];
2296 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2298 // Expr To Python function, verification is performed at validation in GUI
2299 gstate = PyGILState_Ensure();
2300 PyObject * obj = NULL;
2301 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2303 PyObject * func = NULL;
2304 func = PyObject_GetAttrString(main_mod, "f");
2305 EdgeId2PythonSmp[ic]=func;
2306 EdgeId2SizeMap.erase(edgeKey);
2307 PyGILState_Release(gstate);
2310 /* data of nodes existing on the edge */
2311 StdMeshers_FaceSidePtr nodeData;
2312 SMESH_subMesh* sm = aMesh.GetSubMesh( e );
2313 if ( !sm->IsEmpty() )
2315 // SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
2316 // /*complexFirst=*/false);
2317 // while ( subsmIt->more() )
2318 // edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
2319 edgeSubmeshes.insert( sm->GetSubMeshDS() );
2321 nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
2322 /*ignoreMedium=*/haveQuadraticSubMesh));
2323 if ( nodeData->MissVertexNode() )
2324 return error(COMPERR_BAD_INPUT_MESH,"No node on vertex");
2326 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2327 if ( !nodeDataVec.empty() )
2329 if ( Abs( nodeDataVec[0].param - tmin ) > Abs( nodeDataVec.back().param - tmin ))
2331 nodeData->Reverse();
2332 nodeData->GetUVPtStruct(); // nodeData recomputes nodeDataVec
2334 // tmin and tmax can change in case of viscous layer on an adjacent edge
2335 tmin = nodeDataVec.front().param;
2336 tmax = nodeDataVec.back().param;
2340 cout << "---------------- Invalid nodeData" << endl;
2345 /* attach the edge to the current cadsurf face */
2346 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
2348 /* by default an edge has no tag (color).
2349 The following call sets it to the same value as the edge_id : */
2350 cad_edge_set_tag(edg, ic);
2352 /* by default, an edge does not necessalry appear in the resulting mesh,
2353 unless the following property is set :
2355 cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
2357 /* by default an edge is a boundary edge */
2358 if (e.Orientation() == TopAbs_INTERNAL)
2359 cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
2361 // pass existing nodes of sub-meshes to MG-CADSurf
2364 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2365 const int nbNodes = nodeDataVec.size();
2367 dcad_edge_discretization_t *dedge;
2368 dcad_get_edge_discretization(dcad, edg, &dedge);
2369 dcad_edge_discretization_set_vertex_count( dedge, nbNodes );
2371 // cout << endl << " EDGE " << ic << endl;
2372 // cout << "tmin = "<<tmin << ", tmax = "<< tmax << endl;
2373 for ( int iN = 0; iN < nbNodes; ++iN )
2375 const UVPtStruct& nData = nodeDataVec[ iN ];
2376 double t = nData.param;
2377 real uv[2] = { nData.u, nData.v };
2378 SMESH_TNodeXYZ nXYZ( nData.node );
2379 // cout << "\tt = " << t
2380 // << "\t uv = ( " << uv[0] << ","<< uv[1] << " ) "
2381 // << "\t u = " << nData.param
2382 // << "\t ID = " << nData.node->GetID() << endl;
2383 dcad_edge_discretization_set_vertex_coordinates( dedge, iN+1, t, uv, nXYZ._xyz );
2385 dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2388 /****************************************************************************************
2390 *****************************************************************************************/
2394 gp_Pnt2d e0 = curves.back()->Value(tmin);
2395 gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
2396 Standard_Real d1=0,d2=0;
2399 for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
2400 TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
2404 d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2407 d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2409 *ip = pmap.FindIndex(v);
2412 // SMESH_subMesh* sm = aMesh.GetSubMesh(v);
2413 // if ( sm->IsMeshComputed() )
2414 // edgeSubmeshes.insert( sm->GetSubMeshDS() );
2417 // std::string aFileName = "fmap_vertex_";
2418 // aFileName.append(to_string(*ip));
2419 // aFileName.append(".brep");
2420 // BRepTools::Write(v,aFileName.c_str());
2422 if (HasSizeMapOnVertex){
2423 vertexKey = VerticesWithSizeMap.FindIndex(v);
2424 if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
2425 theSizeMapStr = VertexId2SizeMap[vertexKey];
2426 //MESSAGE("VertexId2SizeMap[faceKey]: " << VertexId2SizeMap[vertexKey]);
2427 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2429 // Expr To Python function, verification is performed at validation in GUI
2430 gstate = PyGILState_Ensure();
2431 PyObject * obj = NULL;
2432 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2434 PyObject * func = NULL;
2435 func = PyObject_GetAttrString(main_mod, "f");
2436 VertexId2PythonSmp[*ip]=func;
2437 VertexId2SizeMap.erase(vertexKey); // do not erase if using a vector
2438 PyGILState_Release(gstate);
2443 // should not happen
2444 MESSAGE("An edge does not have 2 extremities.");
2447 // This defines the curves extremity connectivity
2448 cad_edge_set_extremities(edg, ip1, ip2);
2449 /* set the tag (color) to the same value as the extremity id : */
2450 cad_edge_set_extremities_tag(edg, ip1, ip2);
2453 cad_edge_set_extremities(edg, ip2, ip1);
2454 cad_edge_set_extremities_tag(edg, ip2, ip1);
2460 // Clear mesh from already meshed edges if possible else
2461 // remember that merge is needed
2462 TSubMeshSet::iterator smIt = edgeSubmeshes.begin();
2463 for ( ; smIt != edgeSubmeshes.end(); ++smIt ) // loop on already meshed EDGEs
2465 SMESHDS_SubMesh* smDS = *smIt;
2466 if ( !smDS ) continue;
2467 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2470 const SMDS_MeshNode* n = nIt->next();
2471 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
2473 needMerge = true; // to correctly sew with viscous mesh
2474 // add existing medium nodes to helper
2475 if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
2477 SMDS_ElemIteratorPtr edgeIt = smDS->GetElements();
2478 while ( edgeIt->more() )
2479 helper.AddTLinks( static_cast<const SMDS_MeshEdge*>(edgeIt->next()));
2484 if ( allowSubMeshClearing )
2486 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2487 while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), 0 );
2488 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2489 while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), 0 );
2498 ///////////////////////
2500 ///////////////////////
2502 MESSAGE("BEFORE PERIODICITY");
2503 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
2504 if (! _preCadFacesIDsPeriodicityVector.empty()) {
2505 MESSAGE("INTO PRECAD FACES PERIODICITY");
2506 for (std::size_t i=0; i < _preCadFacesIDsPeriodicityVector.size(); i++){
2507 std::vector<int> theFace1_ids = _preCadFacesIDsPeriodicityVector[i].shape1IDs;
2508 std::vector<int> theFace2_ids = _preCadFacesIDsPeriodicityVector[i].shape2IDs;
2509 int* theFace1_ids_c = &theFace1_ids[0];
2510 int* theFace2_ids_c = &theFace2_ids[0];
2511 std::ostringstream o;
2512 o << "_preCadFacesIDsPeriodicityVector[" << i << "] = [";
2513 for (std::size_t j=0; j < theFace1_ids.size(); j++)
2514 o << theFace1_ids[j] << ", ";
2516 for (std::size_t j=0; j < theFace2_ids.size(); j++)
2517 o << theFace2_ids[j] << ", ";
2520 MESSAGE("theFace1_ids.size(): " << theFace1_ids.size());
2521 MESSAGE("theFace2_ids.size(): " << theFace2_ids.size());
2522 if (_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2524 // If no source points, call peridoicity without transformation function
2525 MESSAGE("periodicity without transformation function");
2526 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2527 status = cad_add_face_multiple_periodicity_with_transformation_function(c, theFace1_ids_c, theFace1_ids.size(),
2528 theFace2_ids_c, theFace2_ids.size(), periodicity_transformation, NULL);
2529 if(status != STATUS_OK)
2530 cout << "cad_add_face_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2534 // get the transformation vertices
2535 MESSAGE("periodicity with transformation vertices");
2536 double* theSourceVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2537 double* theTargetVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2538 int nbSourceVertices = _preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2539 int nbTargetVertices = _preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2541 MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2543 status = cad_add_face_multiple_periodicity_with_transformation_function_by_points(c, theFace1_ids_c, theFace1_ids.size(),
2544 theFace2_ids_c, theFace2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2545 if(status != STATUS_OK)
2546 cout << "cad_add_face_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2550 MESSAGE("END PRECAD FACES PERIODICITY");
2553 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
2554 if (! _preCadEdgesIDsPeriodicityVector.empty()) {
2555 MESSAGE("INTO PRECAD EDGES PERIODICITY");
2556 for (std::size_t i=0; i < _preCadEdgesIDsPeriodicityVector.size(); i++){
2557 std::vector<int> theEdge1_ids = _preCadEdgesIDsPeriodicityVector[i].shape1IDs;
2558 std::vector<int> theEdge2_ids = _preCadEdgesIDsPeriodicityVector[i].shape2IDs;
2559 // Use the address of the first element of the vector to initialise the array
2560 int* theEdge1_ids_c = &theEdge1_ids[0];
2561 int* theEdge2_ids_c = &theEdge2_ids[0];
2563 std::ostringstream o;
2564 o << "_preCadEdgesIDsPeriodicityVector[" << i << "] = [";
2565 for (std::size_t j=0; j < theEdge1_ids.size(); j++)
2566 o << theEdge1_ids[j] << ", ";
2568 for (std::size_t j=0; j < theEdge2_ids.size(); j++)
2569 o << theEdge2_ids[j] << ", ";
2572 MESSAGE("theEdge1_ids.size(): " << theEdge1_ids.size());
2573 MESSAGE("theEdge2_ids.size(): " << theEdge2_ids.size());
2575 if (_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2577 // If no source points, call peridoicity without transformation function
2578 MESSAGE("periodicity without transformation function");
2579 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2580 status = cad_add_edge_multiple_periodicity_with_transformation_function(c, theEdge1_ids_c, theEdge1_ids.size(),
2581 theEdge2_ids_c, theEdge2_ids.size(), periodicity_transformation, NULL);
2582 if(status != STATUS_OK)
2583 cout << "cad_add_edge_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2587 // get the transformation vertices
2588 MESSAGE("periodicity with transformation vertices");
2589 double* theSourceVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2590 double* theTargetVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2591 int nbSourceVertices = _preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2592 int nbTargetVertices = _preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2594 MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2596 status = cad_add_edge_multiple_periodicity_with_transformation_function_by_points(c, theEdge1_ids_c, theEdge1_ids.size(),
2597 theEdge2_ids_c, theEdge2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2598 if(status != STATUS_OK)
2599 cout << "cad_add_edge_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2601 MESSAGE("cad_add_edge_multiple_periodicity_with_transformation_function_by_points succeeded.\n");
2605 MESSAGE("END PRECAD EDGES PERIODICITY");
2608 if (! _facesIDsPeriodicityVector.empty()){
2609 MESSAGE("INTO FACE PERIODICITY");
2610 for (std::size_t i=0; i < _facesIDsPeriodicityVector.size(); i++){
2611 int theFace1 = _facesIDsPeriodicityVector[i].first;
2612 int theFace2 = _facesIDsPeriodicityVector[i].second;
2613 MESSAGE("_facesIDsPeriodicityVector[" << i << "] = (" << theFace1 << ", " << theFace2 << ")");
2614 status = cad_add_face_periodicity(c, theFace1, theFace2);
2615 if(status != STATUS_OK){
2616 cout << "cad_add_face_periodicity failed with error code " << status << "\n";
2619 MESSAGE("END FACE PERIODICITY");
2623 if (! _edgesIDsPeriodicityVector.empty()){
2624 MESSAGE("INTO EDGE PERIODICITY");
2625 for (std::size_t i=0; i < _edgesIDsPeriodicityVector.size(); i++){
2626 int theFace1 = _edgesIDsPeriodicityVector[i].theFace1ID;
2627 int theEdge1 = _edgesIDsPeriodicityVector[i].theEdge1ID;
2628 int theFace2 = _edgesIDsPeriodicityVector[i].theFace2ID;
2629 int theEdge2 = _edgesIDsPeriodicityVector[i].theEdge2ID;
2630 int edge_orientation = _edgesIDsPeriodicityVector[i].edge_orientation;
2631 MESSAGE("_edgesIDsPeriodicityVector[" << i << "] = (" << theFace1 << ", " << theEdge1 << ", " << theFace2 << ", " << theEdge2 << ", " << edge_orientation << ")");
2632 status = cad_add_edge_periodicity(c, theFace1, theEdge1, theFace2, theEdge2, edge_orientation);
2633 if(status != STATUS_OK){
2634 cout << "cad_add_edge_periodicity failed with error code " << status << "\n";
2637 MESSAGE("END EDGE PERIODICITY");
2640 if (! _verticesIDsPeriodicityVector.empty()){
2641 MESSAGE("INTO VERTEX PERIODICITY");
2642 for (std::size_t i=0; i < _verticesIDsPeriodicityVector.size(); i++){
2643 int theEdge1 = _verticesIDsPeriodicityVector[i].theEdge1ID;
2644 int theVertex1 = _verticesIDsPeriodicityVector[i].theVertex1ID;
2645 int theEdge2 = _verticesIDsPeriodicityVector[i].theEdge2ID;
2646 int theVertex2 = _verticesIDsPeriodicityVector[i].theVertex2ID;
2647 MESSAGE("_verticesIDsPeriodicityVector[" << i << "] = (" << theEdge1 << ", " << theVertex1 << ", " << theEdge2 << ", " << theVertex2 << ")");
2648 status = cad_add_point_periodicity(c, theEdge1, theVertex1, theEdge2, theVertex2);
2649 if(status != STATUS_OK){
2650 cout << "cad_add_vertex_periodicity failed with error code " << status << "\n";
2653 MESSAGE("END VERTEX PERIODICITY");
2659 MESSAGE("use_precad");
2660 /* Now launch the PreCAD process */
2661 status = precad_process(pcs);
2662 if(status != STATUS_OK){
2663 // TODO: raise an error if status < 0.
2664 cout << "================ WARNING =================== \n";
2666 msg << "PreCAD processing failed with error code " << status << "\n";
2667 msg << *mcud._error;
2669 cout << "============================================ \n";
2670 // the text of _comment is set in message_cb by mcud->_error
2671 // => No need to append msg to _comment
2674 // TODO: fix the SIGSEGV of COMPERR_WARNING with 2 launches
2675 error(COMPERR_WARNING, _comment);
2683 // retrieve the pre-processed CAD object
2686 cleandc = precad_new_dcad(pcs);
2688 cout << "Unable to retrieve PreCAD result on dcad \n";
2691 cout << "PreCAD processing successfull on dcad \n";
2694 cleanc = precad_new_cad(pcs);
2696 cout << "Unable to retrieve PreCAD result on cad \n";
2699 cout << "PreCAD processing successfull on cad \n";
2701 // #if BLSURF_VERSION_LONG >= "3.1.1"
2702 // /* We can now get the updated sizemaps (if any) */
2703 // // if(geo_sizemap_e)
2704 // // clean_geo_sizemap_e = precad_new_sizemap(pcs, geo_sizemap_e);
2706 // // if(geo_sizemap_f)
2707 // // clean_geo_sizemap_f = precad_new_sizemap(pcs, geo_sizemap_f);
2709 // if(iso_sizemap_p)
2710 // clean_iso_sizemap_p = precad_new_sizemap(pcs, iso_sizemap_p);
2712 // if(iso_sizemap_e)
2713 // clean_iso_sizemap_e = precad_new_sizemap(pcs, iso_sizemap_e);
2715 // if(iso_sizemap_f)
2716 // clean_iso_sizemap_f = precad_new_sizemap(pcs, iso_sizemap_f);
2719 // Now we can delete the PreCAD session
2720 precad_session_delete(pcs);
2724 cout << "Give the pre-processed dcad object to the current MG-CADSurf session \n";
2725 cadsurf_data_set_dcad(css, cleandc);
2728 // Use the original one
2729 cadsurf_data_set_dcad(css, dcad);
2733 // Give the pre-processed CAD object to the current MG-CADSurf session
2734 cout << "Give the pre-processed CAD object to the current MG-CADSurf session \n";
2735 cadsurf_data_set_cad(css, cleanc);
2738 // Use the original one
2739 cadsurf_data_set_cad(css, c);
2742 std::cout << std::endl;
2743 std::cout << "Beginning of Surface Mesh generation" << std::endl;
2744 std::cout << std::endl;
2749 status = cadsurf_compute_mesh(css);
2752 catch ( std::exception& exc ) {
2753 _comment += exc.what();
2755 catch (Standard_Failure& ex) {
2756 _comment += ex.DynamicType()->Name();
2757 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
2759 _comment += ex.GetMessageString();
2763 if ( _comment.empty() )
2764 _comment = "Exception in cadsurf_compute_mesh()";
2767 std::cout << std::endl;
2768 std::cout << "End of Surface Mesh generation" << std::endl;
2769 std::cout << std::endl;
2772 cadsurf_data_get_mesh(css, &msh);
2774 /* release the mesh object */
2775 cadsurf_data_regain_mesh(css, msh);
2776 return error(_comment);
2779 std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
2781 GMFFileName = _hypothesis->GetGMFFile();
2782 if (GMFFileName != "") {
2783 // bool GMFFileMode = _hypothesis->GetGMFFileMode();
2784 bool asciiFound = (GMFFileName.find(".mesh",GMFFileName.length()-5) != std::string::npos);
2785 bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
2786 if (!asciiFound && !binaryFound)
2787 GMFFileName.append(".mesh");
2788 mesh_write_mesh(msh, GMFFileName.c_str());
2791 /* retrieve mesh data (see meshgems/mesh.h) */
2792 integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
2793 integer *evedg, *evtri, *evquad, *tags_buff, type;
2796 mesh_get_vertex_count(msh, &nv);
2797 mesh_get_edge_count(msh, &ne);
2798 mesh_get_triangle_count(msh, &nt);
2799 mesh_get_quadrangle_count(msh, &nq);
2801 evedg = (integer *)mesh_calloc_generic_buffer(msh);
2802 evtri = (integer *)mesh_calloc_generic_buffer(msh);
2803 evquad = (integer *)mesh_calloc_generic_buffer(msh);
2804 tags_buff = (integer*)mesh_calloc_generic_buffer(msh);
2806 std::vector<const SMDS_MeshNode*> nodes(nv+1);
2807 std::vector<bool> tags(nv+1);
2809 /* enumerated vertices */
2810 for(int iv=1;iv<=nv;iv++) {
2811 mesh_get_vertex_coordinates(msh, iv, xyz);
2812 mesh_get_vertex_tag(msh, iv, &tag);
2813 // Issue 0020656. Use vertex coordinates
2815 if ( tag > 0 && tag <= pmap.Extent() ) {
2816 TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
2817 double tol = BRep_Tool::Tolerance( v );
2818 gp_Pnt p = BRep_Tool::Pnt( v );
2819 if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
2820 xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
2822 tag = 0; // enforced or attracted vertex
2823 nodes[iv] = SMESH_Algo::VertexNode( v, meshDS );
2826 nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
2828 // Create group of enforced vertices if requested
2829 BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
2831 projVertex.push_back((double)xyz[0]);
2832 projVertex.push_back((double)xyz[1]);
2833 projVertex.push_back((double)xyz[2]);
2834 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
2835 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end()) {
2836 MESSAGE("Found enforced vertex @ " << xyz[0] << ", " << xyz[1] << ", " << xyz[2]);
2837 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
2838 BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
2839 for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
2840 currentEnfVertex = (*enfListIt);
2841 if (currentEnfVertex->grpName != "") {
2842 bool groupDone = false;
2843 SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
2844 MESSAGE("currentEnfVertex->grpName: " << currentEnfVertex->grpName);
2845 MESSAGE("Parsing the groups of the mesh");
2846 while (grIt->more()) {
2847 SMESH_Group * group = grIt->next();
2848 if ( !group ) continue;
2849 MESSAGE("Group: " << group->GetName());
2850 SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2851 if ( !groupDS ) continue;
2852 MESSAGE("group->SMDSGroup().GetType(): " << (groupDS->GetType()));
2853 MESSAGE("group->SMDSGroup().GetType()==SMDSAbs_Node: " << (groupDS->GetType()==SMDSAbs_Node));
2854 MESSAGE("currentEnfVertex->grpName.compare(group->GetStoreName())==0: " << (currentEnfVertex->grpName.compare(group->GetName())==0));
2855 if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
2856 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
2857 aGroupDS->SMDSGroup().Add(nodes[iv]);
2858 MESSAGE("Node ID: " << nodes[iv]->GetID());
2859 // How can I inform the hypothesis ?
2860 // _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
2862 MESSAGE("Successfully added enforced vertex to existing group " << currentEnfVertex->grpName);
2869 SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
2870 aGroup->SetName( currentEnfVertex->grpName.c_str() );
2871 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2872 aGroupDS->SMDSGroup().Add(nodes[iv]);
2873 MESSAGE("Successfully created enforced vertex group " << currentEnfVertex->grpName);
2877 throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
2880 MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
2884 // internal points are tagged to zero
2885 if(tag > 0 && tag <= pmap.Extent() ){
2886 meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
2893 /* enumerate edges */
2894 for(int it=1;it<=ne;it++) {
2896 mesh_get_edge_vertices(msh, it, vtx);
2897 mesh_get_edge_extra_vertices(msh, it, &type, evedg);
2898 mesh_get_edge_tag(msh, it, &tag);
2900 // If PreCAD performed some cleaning operations (remove tiny edges,
2901 // merge edges ...) an output tag can indeed represent several original tags.
2902 // Get the initial tags corresponding to the output tag and redefine the tag as
2903 // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
2904 mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
2906 tag=tags_buff[nb_tag-1];
2907 if ( tag > emap.Extent() )
2909 std::cerr << "MG-CADSurf BUG:::: Edge tag " << tag
2910 << " more than nb CAD egdes (" << emap.Extent() << ")" << std::endl;
2914 Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
2915 tags[vtx[0]] = false;
2918 Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
2919 tags[vtx[1]] = false;
2921 if (type == MESHGEMS_MESH_ELEMENT_TYPE_EDGE3) {
2923 if (tags[evedg[0]]) {
2924 Set_NodeOnEdge(meshDS, nodes[evedg[0]], emap(tag));
2925 tags[evedg[0]] = false;
2927 edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]], nodes[evedg[0]]);
2930 edg = helper.AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
2932 meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
2935 /* enumerate triangles */
2936 for(int it=1;it<=nt;it++) {
2938 mesh_get_triangle_vertices(msh, it, vtx);
2939 mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
2940 mesh_get_triangle_tag(msh, it, &tag);
2942 meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
2943 tags[vtx[0]] = false;
2946 meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
2947 tags[vtx[1]] = false;
2950 meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
2951 tags[vtx[2]] = false;
2953 if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
2954 // QUADRATIC TRIANGLE
2955 if (tags[evtri[0]]) {
2956 meshDS->SetNodeOnFace(nodes[evtri[0]], TopoDS::Face(fmap(tag)));
2957 tags[evtri[0]] = false;
2959 if (tags[evtri[1]]) {
2960 meshDS->SetNodeOnFace(nodes[evtri[1]], TopoDS::Face(fmap(tag)));
2961 tags[evtri[1]] = false;
2963 if (tags[evtri[2]]) {
2964 meshDS->SetNodeOnFace(nodes[evtri[2]], TopoDS::Face(fmap(tag)));
2965 tags[evtri[2]] = false;
2967 tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
2968 nodes[evtri[0]], nodes[evtri[1]], nodes[evtri[2]]);
2971 tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
2973 meshDS->SetMeshElementOnShape(tri, TopoDS::Face(fmap(tag)));
2976 /* enumerate quadrangles */
2977 for(int it=1;it<=nq;it++) {
2978 SMDS_MeshFace* quad;
2979 mesh_get_quadrangle_vertices(msh, it, vtx);
2980 mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
2981 mesh_get_quadrangle_tag(msh, it, &tag);
2983 meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
2984 tags[vtx[0]] = false;
2987 meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
2988 tags[vtx[1]] = false;
2991 meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
2992 tags[vtx[2]] = false;
2995 meshDS->SetNodeOnFace(nodes[vtx[3]], TopoDS::Face(fmap(tag)));
2996 tags[vtx[3]] = false;
2998 if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
2999 // QUADRATIC QUADRANGLE
3000 std::cout << "This is a quadratic quadrangle" << std::endl;
3001 if (tags[evquad[0]]) {
3002 meshDS->SetNodeOnFace(nodes[evquad[0]], TopoDS::Face(fmap(tag)));
3003 tags[evquad[0]] = false;
3005 if (tags[evquad[1]]) {
3006 meshDS->SetNodeOnFace(nodes[evquad[1]], TopoDS::Face(fmap(tag)));
3007 tags[evquad[1]] = false;
3009 if (tags[evquad[2]]) {
3010 meshDS->SetNodeOnFace(nodes[evquad[2]], TopoDS::Face(fmap(tag)));
3011 tags[evquad[2]] = false;
3013 if (tags[evquad[3]]) {
3014 meshDS->SetNodeOnFace(nodes[evquad[3]], TopoDS::Face(fmap(tag)));
3015 tags[evquad[3]] = false;
3017 if (tags[evquad[4]]) {
3018 meshDS->SetNodeOnFace(nodes[evquad[4]], TopoDS::Face(fmap(tag)));
3019 tags[evquad[4]] = false;
3021 quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
3022 nodes[evquad[0]], nodes[evquad[1]], nodes[evquad[2]], nodes[evquad[3]],
3026 quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
3028 meshDS->SetMeshElementOnShape(quad, TopoDS::Face(fmap(tag)));
3031 /* release the mesh object, the rest is released by cleaner */
3032 cadsurf_data_regain_mesh(css, msh);
3034 if ( needMerge ) // sew mesh computed by MG-CADSurf with pre-existing mesh
3036 SMESH_MeshEditor editor( &aMesh );
3037 SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
3038 TIDSortedElemSet segementsOnEdge;
3039 TSubMeshSet::iterator smIt;
3040 SMESHDS_SubMesh* smDS;
3042 // merge nodes on EDGE's with ones computed by MG-CADSurf
3043 for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
3045 if (! (smDS = *smIt) ) continue;
3046 getNodeGroupsToMerge( smDS, meshDS->IndexToShape((*smIt)->GetID()), nodeGroupsToMerge );
3048 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
3049 while ( segIt->more() )
3050 segementsOnEdge.insert( segIt->next() );
3053 editor.MergeNodes( nodeGroupsToMerge );
3056 SMESH_MeshEditor::TListOfListOfElementsID equalSegments;
3057 editor.FindEqualElements( segementsOnEdge, equalSegments );
3058 editor.MergeElements( equalSegments );
3060 // remove excess segments created on the boundary of viscous layers
3061 const SMDS_TypeOfPosition onFace = SMDS_TOP_FACE;
3062 for ( int i = 1; i <= emap.Extent(); ++i )
3064 if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( emap( i )))
3066 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
3067 while ( segIt->more() )
3069 const SMDS_MeshElement* seg = segIt->next();
3070 if ( seg->GetNode(0)->GetPosition()->GetTypeOfPosition() == onFace ||
3071 seg->GetNode(1)->GetPosition()->GetTypeOfPosition() == onFace )
3072 meshDS->RemoveFreeElement( seg, smDS );
3078 // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
3079 TopLoc_Location loc; double f,l;
3080 for (int i = 1; i <= emap.Extent(); i++)
3081 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
3082 sm->SetIsAlwaysComputed( true );
3083 for (int i = 1; i <= pmap.Extent(); i++)
3084 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
3085 if ( !sm->IsMeshComputed() )
3086 sm->SetIsAlwaysComputed( true );
3088 // Set error to FACE's w/o elements
3089 SMESH_ComputeErrorName err = COMPERR_ALGO_FAILED;
3090 if ( _comment.empty() && status == STATUS_OK )
3092 err = COMPERR_WARNING;
3093 _comment = "No mesh elements assigned to a face";
3095 bool badFaceFound = false;
3096 for ( int i = 1; i <= fmap.Extent(); ++i )
3098 SMESH_subMesh* sm = aMesh.GetSubMesh( fmap(i) );
3099 if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
3101 sm->GetComputeError().reset( new SMESH_ComputeError( err, _comment, this ));
3102 badFaceFound = true;
3105 if ( err == COMPERR_WARNING )
3109 if ( status != STATUS_OK && !badFaceFound ) {
3113 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
3115 if ( oldFEFlags > 0 )
3116 feenableexcept( oldFEFlags );
3117 feclearexcept( FE_ALL_EXCEPT );
3121 std::cout << "FacesWithSizeMap" << std::endl;
3122 FacesWithSizeMap.Statistics(std::cout);
3123 std::cout << "EdgesWithSizeMap" << std::endl;
3124 EdgesWithSizeMap.Statistics(std::cout);
3125 std::cout << "VerticesWithSizeMap" << std::endl;
3126 VerticesWithSizeMap.Statistics(std::cout);
3127 std::cout << "FacesWithEnforcedVertices" << std::endl;
3128 FacesWithEnforcedVertices.Statistics(std::cout);
3131 MESSAGE("END OF BLSURFPlugin_BLSURF::Compute()");
3132 return ( status == STATUS_OK && !quadraticSubMeshAndViscousLayer );
3135 //================================================================================
3137 * \brief Terminates computation
3139 //================================================================================
3141 void BLSURFPlugin_BLSURF::CancelCompute()
3143 _compute_canceled = true;
3146 //=============================================================================
3150 //=============================================================================
3152 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, const SMDS_MeshNode* node, const TopoDS_Shape& ed) {
3153 const TopoDS_Edge edge = TopoDS::Edge(ed);
3155 gp_Pnt pnt(node->X(), node->Y(), node->Z());
3157 Standard_Real p0 = 0.0;
3158 Standard_Real p1 = 1.0;
3159 TopLoc_Location loc;
3160 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
3161 if ( curve.IsNull() )
3163 // issue 22499. Node at a sphere apex
3164 meshDS->SetNodeOnEdge(node, edge, p0);
3168 if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
3169 GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
3172 if ( proj.NbPoints() > 0 )
3174 pa = (double)proj.LowerDistanceParameter();
3175 // Issue 0020656. Move node if it is too far from edge
3176 gp_Pnt curve_pnt = curve->Value( pa );
3177 double dist2 = pnt.SquareDistance( curve_pnt );
3178 double tol = BRep_Tool::Tolerance( edge );
3179 if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
3181 curve_pnt.Transform( loc );
3182 meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
3186 meshDS->SetNodeOnEdge(node, edge, pa);
3189 /* Curve definition function See cad_curv_t in file meshgems/cad.h for
3191 * NOTE : if when your CAD systems evaluates second
3192 * order derivatives it also computes first order derivatives and
3193 * function evaluation, you can optimize this example by making only
3194 * one CAD call and filling the necessary uv, dt, dtt arrays.
3196 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
3198 /* t is given. It contains the t (time) 1D parametric coordintaes
3199 of the point PreCAD/MG-CADSurf is querying on the curve */
3201 /* user_data identifies the edge PreCAD/MG-CADSurf is querying
3202 * (see cad_edge_new later in this example) */
3203 const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
3206 /* MG-CADSurf is querying the function evaluation */
3209 uv[0]=P.X(); uv[1]=P.Y();
3213 /* query for the first order derivatives */
3216 dt[0]=V1.X(); dt[1]=V1.Y();
3220 /* query for the second order derivatives */
3223 dtt[0]=V2.X(); dtt[1]=V2.Y();
3229 /* Surface definition function.
3230 * See cad_surf_t in file meshgems/cad.h for more information.
3231 * NOTE : if when your CAD systems evaluates second order derivatives it also
3232 * computes first order derivatives and function evaluation, you can optimize
3233 * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
3236 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
3237 real *duu, real *duv, real *dvv, void *user_data)
3239 /* uv[2] is given. It contains the u,v coordinates of the point
3240 * PreCAD/MG-CADSurf is querying on the surface */
3242 /* user_data identifies the face PreCAD/MG-CADSurf is querying (see
3243 * cad_face_new later in this example)*/
3244 const Geom_Surface* geometry = (const Geom_Surface*) user_data;
3248 P=geometry->Value(uv[0],uv[1]); // S.D0(U,V,P);
3249 xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
3256 geometry->D1(uv[0],uv[1],P,D1U,D1V);
3257 du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
3258 dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
3261 if(duu && duv && dvv){
3265 gp_Vec D2U,D2V,D2UV;
3267 geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
3268 duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
3269 duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
3270 dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
3277 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
3279 //MESSAGE("size_on_surface")
3280 TId2ClsAttractorVec::iterator f2attVec;
3281 if (FaceId2PythonSmp.count(face_id) != 0){
3282 //MESSAGE("A size map is used to calculate size on face : "<<face_id)
3283 PyObject * pyresult = NULL;
3284 PyObject* new_stderr = NULL;
3285 assert(Py_IsInitialized());
3286 PyGILState_STATE gstate;
3287 gstate = PyGILState_Ensure();
3288 pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
3290 if ( pyresult != NULL) {
3291 result = PyFloat_AsDouble(pyresult);
3292 Py_DECREF(pyresult);
3297 string err_description="";
3298 new_stderr = newPyStdOut(err_description);
3299 PySys_SetObject((char*)"stderr", new_stderr);
3301 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
3302 Py_DECREF(new_stderr);
3303 MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
3304 result = *((real*)user_data);
3307 PyGILState_Release(gstate);
3309 else if (( f2attVec = FaceIndex2ClassAttractor.find(face_id)) != FaceIndex2ClassAttractor.end() && !f2attVec->second.empty()){
3310 // MESSAGE("attractor used on face :"<<face_id)
3311 // MESSAGE("List of attractor is not empty")
3312 // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
3315 std::vector< BLSURFPlugin_Attractor* > & attVec = f2attVec->second;
3316 for ( size_t i = 0; i < attVec.size(); ++i )
3318 //result += attVec[i]->GetSize(uv[0],uv[1]);
3319 result = Min( result, attVec[i]->GetSize(uv[0],uv[1]));
3321 //*size = result / attVec.size(); // mean of sizes defined by all attractors
3325 // MESSAGE("List of attractor is empty !!!")
3326 *size = *((real*)user_data);
3328 // std::cout << "Size_on_surface sur la face " << face_id << " donne une size de: " << *size << std::endl;
3332 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
3334 if (EdgeId2PythonSmp.count(edge_id) != 0){
3335 PyObject * pyresult = NULL;
3336 PyObject* new_stderr = NULL;
3337 assert(Py_IsInitialized());
3338 PyGILState_STATE gstate;
3339 gstate = PyGILState_Ensure();
3340 pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
3342 if ( pyresult != NULL) {
3343 result = PyFloat_AsDouble(pyresult);
3344 Py_DECREF(pyresult);
3349 string err_description="";
3350 new_stderr = newPyStdOut(err_description);
3351 PySys_SetObject((char*)"stderr", new_stderr);
3353 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
3354 Py_DECREF(new_stderr);
3355 MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
3356 result = *((real*)user_data);
3359 PyGILState_Release(gstate);
3362 *size = *((real*)user_data);
3367 status_t size_on_vertex(integer point_id, real *size, void *user_data)
3369 if (VertexId2PythonSmp.count(point_id) != 0){
3370 PyObject * pyresult = NULL;
3371 PyObject* new_stderr = NULL;
3372 assert(Py_IsInitialized());
3373 PyGILState_STATE gstate;
3374 gstate = PyGILState_Ensure();
3375 pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
3377 if ( pyresult != NULL) {
3378 result = PyFloat_AsDouble(pyresult);
3379 Py_DECREF(pyresult);
3384 string err_description="";
3385 new_stderr = newPyStdOut(err_description);
3386 PySys_SetObject((char*)"stderr", new_stderr);
3388 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
3389 Py_DECREF(new_stderr);
3390 MESSAGE("Can't evaluate f()" << " error is " << err_description);
3391 result = *((real*)user_data);
3394 PyGILState_Release(gstate);
3397 *size = *((real*)user_data);
3403 * The following function will be called for PreCAD/MG-CADSurf message
3404 * printing. See context_set_message_callback (later in this
3405 * template) for how to set user_data.
3407 status_t message_cb(message_t *msg, void *user_data)
3409 integer errnumber = 0;
3411 message_get_number(msg, &errnumber);
3412 message_get_description(msg, &desc);
3414 message_cb_user_data * mcud = (message_cb_user_data*)user_data;
3415 // Get all the error message and some warning messages related to license and periodicity
3416 if ( errnumber < 0 ||
3417 err.find("license" ) != string::npos ||
3418 err.find("periodicity") != string::npos )
3420 // remove ^A from the tail
3421 int len = strlen( desc );
3422 while (len > 0 && desc[len-1] != '\n')
3424 mcud->_error->append( desc, len );
3427 if ( errnumber == 3009001 )
3428 * mcud->_progress = atof( desc + 11 ) / 100.;
3429 if ( mcud->_verbosity > 0 )
3430 std::cout << desc << std::endl;
3435 /* This is the interrupt callback. PreCAD/MG-CADSurf will call this
3436 * function regularily. See the file meshgems/interrupt.h
3438 status_t interrupt_cb(integer *interrupt_status, void *user_data)
3440 integer you_want_to_continue = 1;
3441 BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
3442 you_want_to_continue = !tmp->computeCanceled();
3444 if(you_want_to_continue)
3446 *interrupt_status = INTERRUPT_CONTINUE;
3449 else /* you want to stop MG-CADSurf */
3451 *interrupt_status = INTERRUPT_STOP;
3452 return STATUS_ERROR;
3456 //=============================================================================
3460 //=============================================================================
3461 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh& aMesh,
3462 const TopoDS_Shape& aShape,
3463 MapShapeNbElems& aResMap)
3465 double diagonal = aMesh.GetShapeDiagonalSize();
3466 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
3467 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
3468 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
3469 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
3470 //int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
3471 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
3472 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
3474 _physicalMesh = (int) _hypothesis->GetPhysicalMesh();
3475 _phySizeRel = _hypothesis->IsPhySizeRel();
3476 if ( _hypothesis->GetPhySize() > 0)
3477 _phySize = _phySizeRel ? diagonal*_hypothesis->GetPhySize() : _hypothesis->GetPhySize();
3478 //_geometricMesh = (int) hyp->GetGeometricMesh();
3479 if (_hypothesis->GetAngleMesh() > 0)
3480 _angleMesh = _hypothesis->GetAngleMesh();
3481 _quadAllowed = _hypothesis->GetQuadAllowed();
3483 //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
3484 // GetDefaultPhySize() sometimes leads to computation failure
3485 _phySize = aMesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
3486 MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
3489 bool IsQuadratic = _quadraticMesh;
3494 TopTools_DataMapOfShapeInteger EdgesMap;
3495 double fullLen = 0.0;
3496 double fullNbSeg = 0;
3497 for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
3498 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3499 if( EdgesMap.IsBound(E) )
3501 SMESH_subMesh *sm = aMesh.GetSubMesh(E);
3502 double aLen = SMESH_Algo::EdgeLength(E);
3505 if(_physicalMesh==1) {
3506 nb1d = (int)( aLen/_phySize + 1 );
3511 Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
3512 double fullAng = 0.0;
3513 double dp = (l-f)/200;
3518 for(int j=2; j<=200; j++) {
3521 fullAng += fabs(V1.Angle(V2));
3525 nb1d = (int)( fullAng/_angleMesh + 1 );
3528 std::vector<int> aVec(SMDSEntity_Last);
3529 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3530 if( IsQuadratic > 0 ) {
3531 aVec[SMDSEntity_Node] = 2*nb1d - 1;
3532 aVec[SMDSEntity_Quad_Edge] = nb1d;
3535 aVec[SMDSEntity_Node] = nb1d - 1;
3536 aVec[SMDSEntity_Edge] = nb1d;
3538 aResMap.insert(std::make_pair(sm,aVec));
3539 EdgesMap.Bind(E,nb1d);
3541 double ELen = fullLen/fullNbSeg;
3545 // try to evaluate as in MEFISTO
3546 for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
3547 TopoDS_Face F = TopoDS::Face( exp.Current() );
3548 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
3550 BRepGProp::SurfaceProperties(F,G);
3551 double anArea = G.Mass();
3553 std::vector<int> nb1dVec;
3554 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
3555 int nbSeg = EdgesMap.Find(exp1.Current());
3557 nb1dVec.push_back( nbSeg );
3560 int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
3561 int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
3564 if ( nb1dVec.size() == 4 ) // quadrangle geom face
3566 int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
3568 nbNodes = (n1 + 1) * (n2 + 1);
3573 nbTria = nbQuad = nbTria / 3 + 1;
3576 std::vector<int> aVec(SMDSEntity_Last,0);
3578 int nb1d_in = (nbTria*3 - nb1d) / 2;
3579 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3580 aVec[SMDSEntity_Quad_Triangle] = nbTria;
3581 aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
3584 aVec[SMDSEntity_Node] = nbNodes;
3585 aVec[SMDSEntity_Triangle] = nbTria;
3586 aVec[SMDSEntity_Quadrangle] = nbQuad;
3588 aResMap.insert(std::make_pair(sm,aVec));
3595 BRepGProp::VolumeProperties(aShape,G);
3596 double aVolume = G.Mass();
3597 double tetrVol = 0.1179*ELen*ELen*ELen;
3598 int nbVols = int(aVolume/tetrVol);
3599 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3600 std::vector<int> aVec(SMDSEntity_Last);
3601 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3603 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3604 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3607 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3608 aVec[SMDSEntity_Tetra] = nbVols;
3610 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3611 aResMap.insert(std::make_pair(sm,aVec));