1 // Copyright (C) 2007-2011 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : BLSURFPlugin_BLSURF.cxx
21 // Authors : Francis KLOSS (OCC) & Patrick LAUG (INRIA) & Lioka RAZAFINDRAZAKA (CEA)
22 // & Aurelien ALLEAUME (DISTENE)
23 // Size maps developement: Nicolas GEIMER (OCC) & Gilles DAVID (EURIWARE)
26 #include "BLSURFPlugin_BLSURF.hxx"
27 #include "BLSURFPlugin_Hypothesis.hxx"
28 #include "BLSURFPlugin_Attractor.hxx"
31 #include <distene/api.h>
32 #include <distene/blsurf.h>
33 #include <distene/precad.h>
36 #include <structmember.h>
39 #include <Basics_Utils.hxx>
40 #include <Basics_OCCTVersion.hxx>
42 #include <SMESH_Gen.hxx>
43 #include <SMESH_Mesh.hxx>
44 #include <SMESH_ControlsDef.hxx>
45 #include <SMDSAbs_ElementType.hxx>
46 #include "SMESHDS_Group.hxx"
47 #include "SMESH_Group.hxx"
49 #include <utilities.h>
57 // OPENCASCADE includes
58 #include <BRep_Tool.hxx>
60 #include <TopExp_Explorer.hxx>
62 #include <NCollection_Map.hxx>
64 #include <Geom_Surface.hxx>
65 #include <Handle_Geom_Surface.hxx>
66 #include <Geom2d_Curve.hxx>
67 #include <Handle_Geom2d_Curve.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Handle_Geom_Curve.hxx>
70 #include <Handle_AIS_InteractiveObject.hxx>
71 #include <TopoDS_Vertex.hxx>
72 #include <TopoDS_Edge.hxx>
73 #include <TopoDS_Wire.hxx>
74 #include <TopoDS_Face.hxx>
76 #include <gp_Pnt2d.hxx>
78 #include <TopTools_IndexedMapOfShape.hxx>
79 #include <TopoDS_Shape.hxx>
80 #include <BRep_Builder.hxx>
81 #include <BRepBuilderAPI_MakeVertex.hxx>
82 #include <BRepTools.hxx>
84 #include <TopTools_DataMapOfShapeInteger.hxx>
85 #include <GProp_GProps.hxx>
86 #include <BRepGProp.hxx>
92 #include <Standard_ErrorHandler.hxx>
93 #include <GeomAPI_ProjectPointOnCurve.hxx>
94 #include <GeomAPI_ProjectPointOnSurf.hxx>
97 // #include <BRepClass_FaceClassifier.hxx>
98 #include <TopTools_MapOfShape.hxx>
100 /* ==================================
101 * =========== PYTHON ==============
102 * ==================================*/
111 PyStdOut_dealloc(PyStdOut *self)
117 PyStdOut_write(PyStdOut *self, PyObject *args)
121 if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
125 *(self->out)=*(self->out)+c;
131 static PyMethodDef PyStdOut_methods[] = {
132 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
133 PyDoc_STR("write(string) -> None")},
134 {NULL, NULL} /* sentinel */
137 static PyMemberDef PyStdOut_memberlist[] = {
138 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
139 (char*)"flag indicating that a space needs to be printed; used by print"},
140 {NULL} /* Sentinel */
143 static PyTypeObject PyStdOut_Type = {
144 /* The ob_type field must be initialized in the module init function
145 * to be portable to Windows without using C++. */
146 PyObject_HEAD_INIT(NULL)
149 sizeof(PyStdOut), /*tp_basicsize*/
152 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
159 0, /*tp_as_sequence*/
164 PyObject_GenericGetAttr, /*tp_getattro*/
165 /* softspace is writable: we must supply tp_setattro */
166 PyObject_GenericSetAttr, /* tp_setattro */
168 Py_TPFLAGS_DEFAULT, /*tp_flags*/
172 0, /*tp_richcompare*/
173 0, /*tp_weaklistoffset*/
176 PyStdOut_methods, /*tp_methods*/
177 PyStdOut_memberlist, /*tp_members*/
191 PyObject * newPyStdOut( std::string& out )
194 self = PyObject_New(PyStdOut, &PyStdOut_Type);
199 return (PyObject*)self;
203 ////////////////////////END PYTHON///////////////////////////
205 //////////////////MY MAPS////////////////////////////////////////
206 TopTools_IndexedMapOfShape FacesWithSizeMap;
207 std::map<int,string> FaceId2SizeMap;
208 TopTools_IndexedMapOfShape EdgesWithSizeMap;
209 std::map<int,string> EdgeId2SizeMap;
210 TopTools_IndexedMapOfShape VerticesWithSizeMap;
211 std::map<int,string> VertexId2SizeMap;
213 std::map<int,PyObject*> FaceId2PythonSmp;
214 std::map<int,PyObject*> EdgeId2PythonSmp;
215 std::map<int,PyObject*> VertexId2PythonSmp;
217 std::map<int,std::vector<double> > FaceId2AttractorCoords;
218 std::map<int,BLSURFPlugin_Attractor*> FaceId2ClassAttractor;
219 std::map<int,BLSURFPlugin_Attractor*> FaceIndex2ClassAttractor;
221 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
222 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
223 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
224 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
226 bool HasSizeMapOnFace=false;
227 bool HasSizeMapOnEdge=false;
228 bool HasSizeMapOnVertex=false;
229 //bool HasAttractorOnFace=false;
231 //=============================================================================
235 //=============================================================================
237 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, int studyId,
239 : SMESH_2D_Algo(hypId, studyId, gen)
241 MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
244 _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
245 _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType());
246 _requireDiscreteBoundary = false;
247 _onlyUnaryInput = false;
249 _supportSubmeshes = true;
251 smeshGen_i = SMESH_Gen_i::GetSMESHGen();
252 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
253 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
255 MESSAGE("studyid = " << _studyId);
258 myStudy = aStudyMgr->GetStudyByID(_studyId);
260 MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
262 /* Initialize the Python interpreter */
263 assert(Py_IsInitialized());
264 PyGILState_STATE gstate;
265 gstate = PyGILState_Ensure();
268 main_mod = PyImport_AddModule("__main__");
271 main_dict = PyModule_GetDict(main_mod);
273 PyRun_SimpleString("from math import *");
274 PyGILState_Release(gstate);
276 FacesWithSizeMap.Clear();
277 FaceId2SizeMap.clear();
278 EdgesWithSizeMap.Clear();
279 EdgeId2SizeMap.clear();
280 VerticesWithSizeMap.Clear();
281 VertexId2SizeMap.clear();
282 FaceId2PythonSmp.clear();
283 EdgeId2PythonSmp.clear();
284 VertexId2PythonSmp.clear();
285 FaceId2AttractorCoords.clear();
286 FaceId2ClassAttractor.clear();
287 FaceIndex2ClassAttractor.clear();
288 FacesWithEnforcedVertices.Clear();
289 FaceId2EnforcedVertexCoords.clear();
290 EnfVertexCoords2ProjVertex.clear();
291 EnfVertexCoords2EnfVertexList.clear();
293 #ifdef WITH_SMESH_CANCEL_COMPUTE
294 _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)
323 list<const SMESHDS_Hypothesis*>::const_iterator itl;
324 const SMESHDS_Hypothesis* theHyp;
326 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
327 int nbHyp = hyps.size();
330 aStatus = SMESH_Hypothesis::HYP_OK;
331 return true; // can work with no hypothesis
335 theHyp = (*itl); // use only the first hypothesis
337 string hypName = theHyp->GetName();
339 if (hypName == "BLSURF_Parameters")
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 aStatus = SMESH_Hypothesis::HYP_OK;
351 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
353 return aStatus == SMESH_Hypothesis::HYP_OK;
356 //=============================================================================
358 * Pass parameters to BLSURF
360 //=============================================================================
362 inline std::string to_string(double d)
364 std::ostringstream o;
369 inline std::string to_string(int i)
371 std::ostringstream o;
376 double _smp_phy_size;
377 // #if BLSURF_VERSION_LONG >= "3.1.1"
378 // // sizemap_t *geo_sizemap_e, *geo_sizemap_f;
379 // sizemap_t *iso_sizemap_p, *iso_sizemap_e, *iso_sizemap_f;
380 // // sizemap_t *clean_geo_sizemap_e, *clean_geo_sizemap_f;
381 // sizemap_t *clean_iso_sizemap_p, *clean_iso_sizemap_e, *clean_iso_sizemap_f;
383 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
384 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
385 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
387 double my_u_min=1e6,my_v_min=1e6,my_u_max=-1e6,my_v_max=-1e6;
393 /////////////////////////////////////////////////////////
394 projectionPoint getProjectionPoint(const TopoDS_Face& face, const gp_Pnt& point)
396 projectionPoint myPoint;
397 Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
398 GeomAPI_ProjectPointOnSurf projector( point, surface );
399 if ( !projector.IsDone() || projector.NbPoints()==0 )
400 throw "getProjectionPoint: Can't project";
402 Quantity_Parameter u,v;
403 projector.LowerDistanceParameters(u,v);
404 myPoint.uv = gp_XY(u,v);
405 gp_Pnt aPnt = projector.NearestPoint();
406 myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
410 /////////////////////////////////////////////////////////
412 /////////////////////////////////////////////////////////
413 double getT(const TopoDS_Edge& edge, const gp_Pnt& point)
416 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
417 GeomAPI_ProjectPointOnCurve projector( point, curve);
418 if ( projector.NbPoints() == 0 )
420 return projector.LowerDistanceParameter();
423 /////////////////////////////////////////////////////////
424 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
426 MESSAGE("BLSURFPlugin_BLSURF::entryToShape "<<entry );
427 GEOM::GEOM_Object_var aGeomObj;
428 TopoDS_Shape S = TopoDS_Shape();
429 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
430 SALOMEDS::GenericAttribute_var anAttr;
432 if (!aSObj->_is_nil() && aSObj->FindAttribute(anAttr, "AttributeIOR")) {
433 SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
434 CORBA::String_var aVal = anIOR->Value();
435 CORBA::Object_var obj = myStudy->ConvertIORToObject(aVal);
436 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
438 if ( !aGeomObj->_is_nil() )
439 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
443 void _createEnforcedVertexOnFace(TopoDS_Face faceShape, gp_Pnt aPnt, BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex)
445 BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
450 // Get the (u,v) values of the enforced vertex on the face
451 projectionPoint myPoint = getProjectionPoint(faceShape,aPnt);
453 MESSAGE("Enforced Vertex: " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z());
454 MESSAGE("Projected Vertex: " << myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z());
455 MESSAGE("Parametric coordinates: " << myPoint.uv.X() << ", " << myPoint.uv.Y() );
457 enf_coords.push_back(aPnt.X());
458 enf_coords.push_back(aPnt.Y());
459 enf_coords.push_back(aPnt.Z());
461 coords.push_back(myPoint.uv.X());
462 coords.push_back(myPoint.uv.Y());
463 coords.push_back(myPoint.xyz.X());
464 coords.push_back(myPoint.xyz.Y());
465 coords.push_back(myPoint.xyz.Z());
467 s_coords.push_back(myPoint.xyz.X());
468 s_coords.push_back(myPoint.xyz.Y());
469 s_coords.push_back(myPoint.xyz.Z());
471 // Save pair projected vertex / enf vertex
472 MESSAGE("Storing pair projected vertex / enf vertex:");
473 MESSAGE("("<< myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z() <<") / (" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z()<<")");
474 EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
475 MESSAGE("Group name is: \"" << enfVertex->grpName << "\"");
476 pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
477 BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
478 ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
479 if (ret.second == false) {
481 (*it)->grpName = enfVertex->grpName;
485 if (! FacesWithEnforcedVertices.Contains(faceShape)) {
486 key = FacesWithEnforcedVertices.Add(faceShape);
489 key = FacesWithEnforcedVertices.FindIndex(faceShape);
492 // If a node is already created by an attractor, do not create enforced vertex
493 int attractorKey = FacesWithSizeMap.FindIndex(faceShape);
494 bool sameAttractor = false;
495 if (attractorKey >= 0)
496 if (FaceId2AttractorCoords.count(attractorKey) > 0)
497 if (FaceId2AttractorCoords[attractorKey] == coords)
498 sameAttractor = true;
500 if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
501 MESSAGE("Map of enf. vertex has key " << key)
502 MESSAGE("Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
504 FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
506 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
507 MESSAGE("New Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
510 MESSAGE("Map of enf. vertex has not key " << key << ": creating it")
511 if (! sameAttractor) {
512 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
514 FaceId2EnforcedVertexCoords[key] = ens;
517 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
521 /////////////////////////////////////////////////////////
522 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
524 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex;
527 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfVertexListIt = enfVertexList.begin();
529 for( ; enfVertexListIt != enfVertexList.end() ; ++enfVertexListIt ) {
530 enfVertex = *enfVertexListIt;
531 // Case of manual coords
532 if (enfVertex->coords.size() != 0) {
533 aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
534 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
537 // Case of geom vertex coords
538 if (enfVertex->geomEntry != "") {
539 TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
540 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
541 if (GeomType == TopAbs_VERTEX){
542 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
543 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
546 if (GeomType == TopAbs_COMPOUND){
547 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
548 if (it.Value().ShapeType() == TopAbs_VERTEX){
549 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
550 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
558 /////////////////////////////////////////////////////////
559 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction)
561 MESSAGE("Attractor function: "<< AttractorFunction);
562 double xa, ya, za; // Coordinates of attractor point
563 double a, b; // Attractor parameter
565 bool createNode=false; // To create a node on attractor projection
567 const char *sep = ";";
568 // atIt->second has the following pattern:
569 // ATTRACTOR(xa;ya;za;a;b;True|False;d)
571 // xa;ya;za : coordinates of attractor
572 // a : desired size on attractor
573 // b : distance of influence of attractor
574 // d : distance until which the size remains constant
576 // We search the parameters in the string
578 pos1 = AttractorFunction.find(sep);
579 if (pos1!=string::npos)
580 xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
582 pos2 = AttractorFunction.find(sep, pos1+1);
583 if (pos2!=string::npos) {
584 ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
588 pos2 = AttractorFunction.find(sep, pos1+1);
589 if (pos2!=string::npos) {
590 za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
594 pos2 = AttractorFunction.find(sep, pos1+1);
595 if (pos2!=string::npos) {
596 a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
600 pos2 = AttractorFunction.find(sep, pos1+1);
601 if (pos2!=string::npos) {
602 b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
606 pos2 = AttractorFunction.find(sep, pos1+1);
607 if (pos2!=string::npos) {
608 string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
609 MESSAGE("createNode: " << createNodeStr);
610 createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
614 pos2 = AttractorFunction.find(")");
615 if (pos2!=string::npos) {
616 d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
619 // Get the (u,v) values of the attractor on the face
620 projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
621 gp_XY uvPoint = myPoint.uv;
622 gp_XYZ xyzPoint = myPoint.xyz;
623 Standard_Real u0 = uvPoint.X();
624 Standard_Real v0 = uvPoint.Y();
625 Standard_Real x0 = xyzPoint.X();
626 Standard_Real y0 = xyzPoint.Y();
627 Standard_Real z0 = xyzPoint.Z();
628 std::vector<double> coords;
629 coords.push_back(u0);
630 coords.push_back(v0);
631 coords.push_back(x0);
632 coords.push_back(y0);
633 coords.push_back(z0);
634 // We construct the python function
635 ostringstream attractorFunctionStream;
636 attractorFunctionStream << "def f(u,v): return ";
637 attractorFunctionStream << _smp_phy_size << "-(" << _smp_phy_size <<"-" << a << ")";
638 //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
639 // rnc: make possible to keep the size constant until
640 // a defined distance. Distance is expressed as the positiv part
641 // of r-d where r is the distance to (u0,v0)
642 attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
644 MESSAGE("Python function for attractor:" << std::endl << attractorFunctionStream.str());
647 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
648 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
651 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
653 FaceId2SizeMap[key] =attractorFunctionStream.str();
655 MESSAGE("Creating node on ("<<x0<<","<<y0<<","<<z0<<")");
656 FaceId2AttractorCoords[key] = coords;
658 // // Test for new attractors
659 // gp_Pnt myP(xyzPoint);
660 // TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
661 // BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
662 // myAttractor.SetParameters(a, _smp_phy_size, b, d);
663 // myAttractor.SetType(1);
664 // FaceId2ClassAttractor[key] = myAttractor;
665 // if(FaceId2ClassAttractor[key].GetFace().IsNull()){
666 // MESSAGE("face nulle ");
669 // MESSAGE("face OK");
671 // if (FaceId2ClassAttractor[key].GetAttractorShape().IsNull()){
672 // MESSAGE("pas de point");
675 // MESSAGE("point OK");
678 /////////////////////////////////////////////////////////
680 void BLSURFPlugin_BLSURF::SetParameters(
681 // #if BLSURF_VERSION_LONG >= "3.1.1"
684 const BLSURFPlugin_Hypothesis* hyp,
685 blsurf_session_t * bls,
686 precad_session_t * pcs,
691 int _topology = BLSURFPlugin_Hypothesis::GetDefaultTopology();
692 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
693 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize();
694 int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
695 double _angleMeshS = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshS();
696 double _angleMeshC = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshC();
697 double _gradation = BLSURFPlugin_Hypothesis::GetDefaultGradation();
698 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
699 bool _decimesh = BLSURFPlugin_Hypothesis::GetDefaultDecimesh();
700 int _verb = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
703 int _precadMergeEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
704 int _precadRemoveNanoEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADRemoveNanoEdges();
705 int _precadDiscardInput = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
706 double _precadEpsNano = BLSURFPlugin_Hypothesis::GetDefaultPreCADEpsNano();
710 MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
711 _topology = (int) hyp->GetTopology();
712 _physicalMesh = (int) hyp->GetPhysicalMesh();
713 _phySize = hyp->GetPhySize();
714 _geometricMesh = (int) hyp->GetGeometricMesh();
715 _angleMeshS = hyp->GetAngleMeshS();
716 _angleMeshC = hyp->GetAngleMeshC();
717 _gradation = hyp->GetGradation();
718 _quadAllowed = hyp->GetQuadAllowed();
719 _decimesh = hyp->GetDecimesh();
720 _verb = hyp->GetVerbosity();
721 if ( hyp->GetPhyMin() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
722 blsurf_set_param(bls, "hphymin", to_string(hyp->GetPhyMin()).c_str());
723 if ( hyp->GetPhyMax() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
724 blsurf_set_param(bls, "hphymax", to_string(hyp->GetPhyMax()).c_str());
725 if ( hyp->GetGeoMin() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
726 blsurf_set_param(bls, "hgeomin", to_string(hyp->GetGeoMin()).c_str());
727 if ( hyp->GetGeoMax() != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
728 blsurf_set_param(bls, "hgeomax", to_string(hyp->GetGeoMax()).c_str());
730 const BLSURFPlugin_Hypothesis::TOptionValues & opts = hyp->GetOptionValues();
731 BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
732 for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
733 if ( !opIt->second.empty() ) {
734 MESSAGE("blsurf_set_param(): " << opIt->first << " = " << opIt->second);
735 blsurf_set_param(bls, opIt->first.c_str(), opIt->second.c_str());
738 const BLSURFPlugin_Hypothesis::TOptionValues & preCADopts = hyp->GetPreCADOptionValues();
739 for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
740 if ( !opIt->second.empty() ) {
741 if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
742 MESSAGE("precad_set_param(): " << opIt->first << " = " << opIt->second);
743 blsurf_set_param(bls, opIt->first.c_str(), opIt->second.c_str());
748 _precadMergeEdges = hyp->GetPreCADMergeEdges();
749 _precadRemoveNanoEdges = hyp->GetPreCADRemoveNanoEdges();
750 _precadDiscardInput = hyp->GetPreCADDiscardInput();
751 _precadEpsNano = hyp->GetPreCADEpsNano();
754 //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
755 // GetDefaultPhySize() sometimes leads to computation failure
756 _phySize = mesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
757 MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
761 if (_topology == BLSURFPlugin_Hypothesis::PreCAD) {
763 precad_set_param(pcs, "verbose", to_string(_verb).c_str());
764 precad_set_param(pcs, "merge_edges", _precadMergeEdges ? "1" : "0");
765 precad_set_param(pcs, "remove_nano_edges", _precadRemoveNanoEdges ? "1" : "0");
766 precad_set_param(pcs, "discard_input_topology", _precadDiscardInput ? "1" : "0");
767 if ( _precadEpsNano != ::BLSURFPlugin_Hypothesis::undefinedDouble() )
768 precad_set_param(pcs, "eps_nano", to_string(_precadEpsNano).c_str());
771 _smp_phy_size = _phySize;
772 blsurf_set_param(bls, "topo_points", _topology == BLSURFPlugin_Hypothesis::Process || _topology == BLSURFPlugin_Hypothesis::Process2 ? "1" : "0");
773 blsurf_set_param(bls, "topo_curves", _topology == BLSURFPlugin_Hypothesis::Process || _topology == BLSURFPlugin_Hypothesis::Process2 ? "1" : "0");
774 blsurf_set_param(bls, "topo_project", _topology == BLSURFPlugin_Hypothesis::Process || _topology == BLSURFPlugin_Hypothesis::Process2 ? "1" : "0");
775 blsurf_set_param(bls, "clean_boundary", _topology == BLSURFPlugin_Hypothesis::Process2 ? "1" : "0");
776 blsurf_set_param(bls, "close_boundary", _topology == BLSURFPlugin_Hypothesis::Process2 ? "1" : "0");
777 blsurf_set_param(bls, "hphy_flag", to_string(_physicalMesh).c_str());
778 blsurf_set_param(bls, "hphydef", to_string(_phySize).c_str());
779 blsurf_set_param(bls, "hgeo_flag", to_string(_geometricMesh).c_str());
780 blsurf_set_param(bls, "relax_size", _decimesh ? "0": to_string(_geometricMesh).c_str());
781 blsurf_set_param(bls, "angle_meshs", to_string(_angleMeshS).c_str());
782 blsurf_set_param(bls, "angle_meshc", to_string(_angleMeshC).c_str());
783 blsurf_set_param(bls, "gradation", to_string(_gradation).c_str());
784 blsurf_set_param(bls, "patch_independent", _decimesh ? "1" : "0");
785 blsurf_set_param(bls, "element", _quadAllowed ? "q1.0" : "p1");
786 blsurf_set_param(bls, "verb", to_string(_verb).c_str());
788 if (_physicalMesh == BLSURFPlugin_Hypothesis::SizeMap){
789 TopoDS_Shape GeomShape;
790 TopoDS_Shape AttShape;
791 TopAbs_ShapeEnum GeomType;
793 // Standard Size Maps
795 MESSAGE("Setting a Size Map");
796 const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
797 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
798 for ( ; smIt != sizeMaps.end(); ++smIt ) {
799 if ( !smIt->second.empty() ) {
800 MESSAGE("blsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
801 GeomShape = entryToShape(smIt->first);
802 GeomType = GeomShape.ShapeType();
803 MESSAGE("Geomtype is " << GeomType);
806 if (GeomType == TopAbs_COMPOUND){
807 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
809 if (it.Value().ShapeType() == TopAbs_FACE){
810 HasSizeMapOnFace = true;
811 if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
812 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
815 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
816 // MESSAGE("Face with key " << key << " already in map");
818 FaceId2SizeMap[key] = smIt->second;
821 if (it.Value().ShapeType() == TopAbs_EDGE){
822 HasSizeMapOnEdge = true;
823 HasSizeMapOnFace = true;
824 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
825 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
828 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
829 // MESSAGE("Edge with key " << key << " already in map");
831 EdgeId2SizeMap[key] = smIt->second;
834 if (it.Value().ShapeType() == TopAbs_VERTEX){
835 HasSizeMapOnVertex = true;
836 HasSizeMapOnEdge = true;
837 HasSizeMapOnFace = true;
838 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
839 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
842 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
843 MESSAGE("Group of vertices with key " << key << " already in map");
845 MESSAGE("Group of vertices with key " << key << " has a size map: " << smIt->second);
846 VertexId2SizeMap[key] = smIt->second;
851 if (GeomType == TopAbs_FACE){
852 HasSizeMapOnFace = true;
853 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
854 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
857 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
858 // MESSAGE("Face with key " << key << " already in map");
860 FaceId2SizeMap[key] = smIt->second;
863 if (GeomType == TopAbs_EDGE){
864 HasSizeMapOnEdge = true;
865 HasSizeMapOnFace = true;
866 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
867 key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
870 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
871 // MESSAGE("Edge with key " << key << " already in map");
873 EdgeId2SizeMap[key] = smIt->second;
876 if (GeomType == TopAbs_VERTEX){
877 HasSizeMapOnVertex = true;
878 HasSizeMapOnEdge = true;
879 HasSizeMapOnFace = true;
880 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
881 key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
884 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
885 MESSAGE("Vertex with key " << key << " already in map");
887 MESSAGE("Vertex with key " << key << " has a size map: " << smIt->second);
888 VertexId2SizeMap[key] = smIt->second;
896 // TODO appeler le constructeur des attracteurs directement ici
897 MESSAGE("Setting Attractors");
898 const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
899 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
900 for ( ; atIt != attractors.end(); ++atIt ) {
901 if ( !atIt->second.empty() ) {
902 MESSAGE("blsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
903 GeomShape = entryToShape(atIt->first);
904 GeomType = GeomShape.ShapeType();
906 if (GeomType == TopAbs_COMPOUND){
907 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
908 if (it.Value().ShapeType() == TopAbs_FACE){
909 HasSizeMapOnFace = true;
910 createAttractorOnFace(it.Value(), atIt->second);
915 if (GeomType == TopAbs_FACE){
916 HasSizeMapOnFace = true;
917 createAttractorOnFace(GeomShape, atIt->second);
920 if (GeomType == TopAbs_EDGE){
921 HasSizeMapOnEdge = true;
922 HasSizeMapOnFace = true;
923 EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
925 if (GeomType == TopAbs_VERTEX){
926 HasSizeMapOnVertex = true;
927 HasSizeMapOnEdge = true;
928 HasSizeMapOnFace = true;
929 VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
936 // temporary commented out for testing
938 // - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
939 // - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
940 // - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
942 // - Construct the attractors with an empty dist. map in the hypothesis
943 // - 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()
944 // -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap() OK
946 const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
948 BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
949 for ( ; AtIt != class_attractors.end(); ++AtIt ) {
950 if ( !AtIt->second->Empty() ) {
951 // MESSAGE("blsurf_set_attractor(): " << AtIt->first << " = " << AtIt->second);
952 GeomShape = entryToShape(AtIt->first);
953 AttShape = AtIt->second->GetAttractorShape();
954 GeomType = GeomShape.ShapeType();
956 // if (GeomType == TopAbs_COMPOUND){
957 // for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
958 // if (it.Value().ShapeType() == TopAbs_FACE){
959 // HasAttractorOnFace = true;
960 // myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
965 if (GeomType == TopAbs_FACE
966 && (AttShape.ShapeType() == TopAbs_VERTEX
967 || AttShape.ShapeType() == TopAbs_EDGE
968 || AttShape.ShapeType() == TopAbs_WIRE
969 || AttShape.ShapeType() == TopAbs_COMPOUND) ){
970 HasSizeMapOnFace = true;
972 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape)) ) {
973 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
976 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
977 // MESSAGE("Face with key " << key << " already in map");
980 FaceId2ClassAttractor[key] = AtIt->second;
983 MESSAGE("Wrong shape type !!")
993 MESSAGE("Setting Enforced Vertices");
994 const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
995 BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
996 for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
997 if ( !enfIt->second.empty() ) {
998 GeomShape = entryToShape(enfIt->first);
999 GeomType = GeomShape.ShapeType();
1001 if (GeomType == TopAbs_COMPOUND){
1002 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1003 if (it.Value().ShapeType() == TopAbs_FACE){
1004 HasSizeMapOnFace = true;
1005 createEnforcedVertexOnFace(it.Value(), enfIt->second);
1010 if (GeomType == TopAbs_FACE){
1011 HasSizeMapOnFace = true;
1012 createEnforcedVertexOnFace(GeomShape, enfIt->second);
1017 // Internal vertices
1018 bool useInternalVertexAllFaces = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFaces(hyp);
1019 if (useInternalVertexAllFaces) {
1020 std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
1021 MESSAGE("Setting Internal Enforced Vertices");
1022 GeomShape = mesh.GetShapeToMesh();
1024 TopExp_Explorer exp (GeomShape, TopAbs_FACE);
1025 for (; exp.More(); exp.Next()){
1026 MESSAGE("Iterating shapes. Shape type is " << exp.Current().ShapeType());
1027 TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX);
1028 for (; exp_face.More(); exp_face.Next())
1030 // Get coords of vertex
1031 // Check if current coords is already in enfVertexList
1032 // If coords not in enfVertexList, add new enfVertex
1033 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1034 MESSAGE("Found vertex on face at " << aPnt.X() <<", "<<aPnt.Y()<<", "<<aPnt.Z());
1035 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1036 enfVertex->coords.push_back(aPnt.X());
1037 enfVertex->coords.push_back(aPnt.Y());
1038 enfVertex->coords.push_back(aPnt.Z());
1039 enfVertex->name = "";
1040 enfVertex->faceEntries.clear();
1041 enfVertex->geomEntry = "";
1042 enfVertex->grpName = grpName;
1043 _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()), aPnt, enfVertex);
1044 HasSizeMapOnFace = true;
1049 MESSAGE("Setting Size Map on FACES ");
1050 // #if BLSURF_VERSION_LONG < "3.1.1"
1051 blsurf_data_set_sizemap_iso_cad_face(bls, size_on_surface, &_smp_phy_size);
1054 // iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1056 // clean_iso_sizemap_f = sizemap_new(c, distene_sizemap_type_iso_cad_face, (void *)size_on_surface, NULL);
1059 if (HasSizeMapOnEdge){
1060 MESSAGE("Setting Size Map on EDGES ");
1061 // #if BLSURF_VERSION_LONG < "3.1.1"
1062 blsurf_data_set_sizemap_iso_cad_edge(bls, size_on_edge, &_smp_phy_size);
1065 // iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1067 // clean_iso_sizemap_e = sizemap_new(c, distene_sizemap_type_iso_cad_edge, (void *)size_on_edge, NULL);
1070 if (HasSizeMapOnVertex){
1071 MESSAGE("Setting Size Map on VERTICES ");
1072 // #if BLSURF_VERSION_LONG < "3.1.1"
1073 blsurf_data_set_sizemap_iso_cad_point(bls, size_on_vertex, &_smp_phy_size);
1076 // iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1078 // clean_iso_sizemap_p = sizemap_new(c, distene_sizemap_type_iso_cad_point, (void *)size_on_vertex, NULL);
1084 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1085 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1086 real *duu, real *duv, real *dvv, void *user_data);
1087 status_t message_cb(message_t *msg, void *user_data);
1088 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1090 //=============================================================================
1094 //=============================================================================
1096 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
1098 MESSAGE("BLSURFPlugin_BLSURF::Compute");
1100 // Fix problem with locales
1101 Kernel_Utils::Localizer aLocalizer;
1103 /* create a distene context (generic object) */
1104 status_t status = STATUS_ERROR;
1106 context_t *ctx = context_new();
1108 /* Set the message callback in the working context */
1109 context_set_message_callback(ctx, message_cb, &_comment);
1110 #ifdef WITH_SMESH_CANCEL_COMPUTE
1111 _compute_canceled = false;
1112 context_set_interrupt_callback(ctx, interrupt_cb, this);
1114 context_set_interrupt_callback(ctx, interrupt_cb, NULL);
1117 /* create the CAD object we will work on. It is associated to the context ctx. */
1118 cad_t *c = cad_new(ctx);
1120 FacesWithSizeMap.Clear();
1121 FaceId2SizeMap.clear();
1122 FaceId2ClassAttractor.clear();
1123 FaceIndex2ClassAttractor.clear();
1124 EdgesWithSizeMap.Clear();
1125 EdgeId2SizeMap.clear();
1126 VerticesWithSizeMap.Clear();
1127 VertexId2SizeMap.clear();
1130 /* Now fill the CAD object with data from your CAD
1131 * environement. This is the most complex part of a successfull
1136 // If user requests it, send the CAD through Distene preprocessor : PreCAD
1137 cad_t *cleanc = NULL;
1138 precad_session_t *pcs = precad_session_new(ctx);
1139 precad_data_set_cad(pcs, c);
1141 blsurf_session_t *bls = blsurf_session_new(ctx);
1143 MESSAGE("BEGIN SetParameters");
1144 bool use_precad = false;
1146 // #if BLSURF_VERSION_LONG >= "3.1.1"
1149 _hypothesis, bls, pcs, aMesh, &use_precad);
1150 MESSAGE("END SetParameters");
1152 // needed to prevent the opencascade memory managmement from freeing things
1153 vector<Handle(Geom2d_Curve)> curves;
1154 vector<Handle(Geom_Surface)> surfaces;
1159 TopTools_IndexedMapOfShape fmap;
1160 TopTools_IndexedMapOfShape emap;
1161 TopTools_IndexedMapOfShape pmap;
1164 FaceId2PythonSmp.clear();
1166 EdgeId2PythonSmp.clear();
1168 VertexId2PythonSmp.clear();
1170 assert(Py_IsInitialized());
1171 PyGILState_STATE gstate;
1172 gstate = PyGILState_Ensure();
1174 string theSizeMapStr;
1176 /****************************************************************************************
1178 *****************************************************************************************/
1180 string bad_end = "return";
1182 TopTools_IndexedMapOfShape _map;
1183 TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
1184 int ienf = _map.Extent();
1186 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next()) {
1187 TopoDS_Face f=TopoDS::Face(face_iter.Current());
1189 // make INTERNAL face oriented FORWARD (issue 0020993)
1190 if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
1191 f.Orientation(TopAbs_FORWARD);
1193 if (fmap.FindIndex(f) > 0)
1198 surfaces.push_back(BRep_Tool::Surface(f));
1200 /* create an object representing the face for blsurf */
1201 /* where face_id is an integer identifying the face.
1202 * surf_function is the function that defines the surface
1203 * (For this face, it will be called by blsurf with your_face_object_ptr
1204 * as last parameter.
1206 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
1208 /* by default a face has no tag (color). The following call sets it to the same value as the face_id : */
1209 cad_face_set_tag(fce, iface);
1211 /* Set face orientation (optional if you want a well oriented output mesh)*/
1212 if(f.Orientation() != TopAbs_FORWARD){
1213 cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
1215 cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
1218 if (HasSizeMapOnFace && !use_precad){
1219 // MESSAGE("A size map is defined on a face")
1220 // std::cout << "A size map is defined on a face" << std::endl;
1222 faceKey = FacesWithSizeMap.FindIndex(f);
1225 if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()){
1226 MESSAGE("A size map is defined on face :"<<faceKey)
1227 theSizeMapStr = FaceId2SizeMap[faceKey];
1228 // check if function ends with "return"
1229 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1231 // Expr To Python function, verification is performed at validation in GUI
1232 PyObject * obj = NULL;
1233 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1235 PyObject * func = NULL;
1236 func = PyObject_GetAttrString(main_mod, "f");
1237 FaceId2PythonSmp[iface]=func;
1238 FaceId2SizeMap.erase(faceKey);
1241 // Specific size map = Attractor
1242 std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
1244 for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
1245 if (attractor_iter->first == faceKey) {
1246 MESSAGE("Face indice: " << iface);
1247 MESSAGE("Adding attractor");
1249 double xyzCoords[3] = {attractor_iter->second[2],
1250 attractor_iter->second[3],
1251 attractor_iter->second[4]};
1253 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
1254 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
1255 BRepClass_FaceClassifier scl(f,P,1e-7);
1256 // scl.Perform() is bugged. The function was rewritten
1258 BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
1259 TopAbs_State result = scl.State();
1260 MESSAGE("Position of point on face: "<<result);
1261 if ( result == TopAbs_OUT )
1262 MESSAGE("Point is out of face: node is not created");
1263 if ( result == TopAbs_UNKNOWN )
1264 MESSAGE("Point position on face is unknown: node is not created");
1265 if ( result == TopAbs_ON )
1266 MESSAGE("Point is on border of face: node is not created");
1267 if ( result == TopAbs_IN )
1269 // Point is inside face and not on border
1270 MESSAGE("Point is in face: node is created");
1271 double uvCoords[2] = {attractor_iter->second[0],attractor_iter->second[1]};
1273 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
1274 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
1275 cad_point_set_tag(point_p, ienf);
1277 FaceId2AttractorCoords.erase(faceKey);
1282 std::map<int,BLSURFPlugin_Attractor* >::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
1283 if (clAttractor_iter != FaceId2ClassAttractor.end()){
1284 MESSAGE("Face indice: " << iface);
1285 MESSAGE("Adding attractor");
1286 FaceIndex2ClassAttractor[iface]=clAttractor_iter->second;
1287 FaceId2ClassAttractor.erase(clAttractor_iter);
1291 // Enforced Vertices
1292 faceKey = FacesWithEnforcedVertices.FindIndex(f);
1293 std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
1294 if (evmIt != FaceId2EnforcedVertexCoords.end()) {
1295 MESSAGE("Some enforced vertices are defined");
1296 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl;
1297 MESSAGE("Face indice: " << iface);
1298 MESSAGE("Adding enforced vertices");
1299 evl = evmIt->second;
1300 MESSAGE("Number of vertices to add: "<< evl.size());
1301 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
1302 for (; evlIt != evl.end(); ++evlIt) {
1303 BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
1304 xyzCoords.push_back(evlIt->at(2));
1305 xyzCoords.push_back(evlIt->at(3));
1306 xyzCoords.push_back(evlIt->at(4));
1307 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
1308 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
1309 BRepClass_FaceClassifier scl(f,P,1e-7);
1310 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
1311 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
1312 // OCC 6.5.2: scl.Perform() is not bugged anymore
1313 scl.Perform(f, P, 1e-7);
1314 TopAbs_State result = scl.State();
1315 MESSAGE("Position of point on face: "<<result);
1316 if ( result == TopAbs_OUT ) {
1317 MESSAGE("Point is out of face: node is not created");
1318 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1319 EnfVertexCoords2ProjVertex.erase(xyzCoords);
1320 EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1323 if ( result == TopAbs_UNKNOWN ) {
1324 MESSAGE("Point position on face is unknown: node is not created");
1325 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1326 EnfVertexCoords2ProjVertex.erase(xyzCoords);
1327 EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1330 if ( result == TopAbs_ON ) {
1331 MESSAGE("Point is on border of face: node is not created");
1332 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
1333 EnfVertexCoords2ProjVertex.erase(xyzCoords);
1334 EnfVertexCoords2EnfVertexList.erase(xyzCoords);
1337 if ( result == TopAbs_IN )
1339 // Point is inside face and not on border
1340 MESSAGE("Point is in face: node is created");
1341 double uvCoords[2] = {evlIt->at(0),evlIt->at(1)};
1343 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
1344 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
1345 cad_point_set_tag(point_p, ienf);
1348 FaceId2EnforcedVertexCoords.erase(faceKey);
1351 // std::cout << "No enforced vertex defined" << std::endl;
1355 /****************************************************************************************
1357 now create the edges associated to this face
1358 *****************************************************************************************/
1360 for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next()) {
1361 TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
1362 int ic = emap.FindIndex(e);
1367 curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
1369 if (HasSizeMapOnEdge){
1370 edgeKey = EdgesWithSizeMap.FindIndex(e);
1371 if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
1372 MESSAGE("Sizemap defined on edge with index " << edgeKey);
1373 theSizeMapStr = EdgeId2SizeMap[edgeKey];
1374 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1376 // Expr To Python function, verification is performed at validation in GUI
1377 PyObject * obj = NULL;
1378 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1380 PyObject * func = NULL;
1381 func = PyObject_GetAttrString(main_mod, "f");
1382 EdgeId2PythonSmp[ic]=func;
1383 EdgeId2SizeMap.erase(edgeKey);
1387 /* attach the edge to the current blsurf face */
1388 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
1390 /* by default an edge has no tag (color). The following call sets it to the same value as the edge_id : */
1391 cad_edge_set_tag(edg, ic);
1393 /* by default, an edge does not necessalry appear in the resulting mesh,
1394 unless the following property is set :
1396 cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
1398 /* by default an edge is a boundary edge */
1399 if (e.Orientation() == TopAbs_INTERNAL)
1400 cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
1404 gp_Pnt2d e0 = curves.back()->Value(tmin);
1405 gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
1406 Standard_Real d1=0,d2=0;
1409 /****************************************************************************************
1411 *****************************************************************************************/
1413 for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
1414 TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
1418 d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
1421 d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
1423 *ip = pmap.FindIndex(v);
1427 if (HasSizeMapOnVertex){
1428 vertexKey = VerticesWithSizeMap.FindIndex(v);
1429 if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
1430 theSizeMapStr = VertexId2SizeMap[vertexKey];
1431 //MESSAGE("VertexId2SizeMap[faceKey]: " << VertexId2SizeMap[vertexKey]);
1432 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1434 // Expr To Python function, verification is performed at validation in GUI
1435 PyObject * obj = NULL;
1436 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1438 PyObject * func = NULL;
1439 func = PyObject_GetAttrString(main_mod, "f");
1440 VertexId2PythonSmp[*ip]=func;
1441 VertexId2SizeMap.erase(vertexKey); // do not erase if using a vector
1446 // should not happen
1447 MESSAGE("An edge does not have 2 extremities.");
1450 // This defines the curves extremity connectivity
1451 cad_edge_set_extremities(edg, ip1, ip2);
1452 /* set the tag (color) to the same value as the extremity id : */
1453 cad_edge_set_extremities_tag(edg, ip1, ip2);
1456 cad_edge_set_extremities(edg, ip2, ip1);
1457 cad_edge_set_extremities_tag(edg, ip2, ip1);
1464 PyGILState_Release(gstate);
1467 /* Now launch the PreCAD process */
1468 status = precad_process(pcs);
1469 if(status != STATUS_OK){
1470 cout << "PreCAD processing failed with error code " << status << "\n";
1471 // Now we can delete the PreCAD session
1472 precad_session_delete(pcs);
1475 // retrieve the pre-processed CAD object
1476 cleanc = precad_new_cad(pcs);
1478 cout << "Unable to retrieve PreCAD result \n";
1480 cout << "PreCAD processing successfull \n";
1482 // #if BLSURF_VERSION_LONG >= "3.1.1"
1483 // /* We can now get the updated sizemaps (if any) */
1484 // // if(geo_sizemap_e)
1485 // // clean_geo_sizemap_e = precad_new_sizemap(pcs, geo_sizemap_e);
1487 // // if(geo_sizemap_f)
1488 // // clean_geo_sizemap_f = precad_new_sizemap(pcs, geo_sizemap_f);
1490 // if(iso_sizemap_p)
1491 // clean_iso_sizemap_p = precad_new_sizemap(pcs, iso_sizemap_p);
1493 // if(iso_sizemap_e)
1494 // clean_iso_sizemap_e = precad_new_sizemap(pcs, iso_sizemap_e);
1496 // if(iso_sizemap_f)
1497 // clean_iso_sizemap_f = precad_new_sizemap(pcs, iso_sizemap_f);
1500 // Now we can delete the PreCAD session
1501 precad_session_delete(pcs);
1506 // Give the pre-processed CAD object to the current BLSurf session
1507 blsurf_data_set_cad(bls, cleanc);
1510 // Use the original one
1511 blsurf_data_set_cad(bls, c);
1514 // #if BLSURF_VERSION_LONG >= "3.1.1"
1515 // blsurf_data_set_sizemap(bls, clean_iso_sizemap_p);
1516 // blsurf_data_set_sizemap(bls, clean_iso_sizemap_e);
1517 // blsurf_data_set_sizemap(bls, clean_iso_sizemap_f);
1520 std::cout << std::endl;
1521 std::cout << "Beginning of Surface Mesh generation" << std::endl;
1522 std::cout << std::endl;
1524 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1526 feclearexcept( FE_ALL_EXCEPT );
1527 int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1533 status = blsurf_compute_mesh(bls);
1536 catch ( std::exception& exc ) {
1537 _comment += exc.what();
1539 catch (Standard_Failure& ex) {
1540 _comment += ex.DynamicType()->Name();
1541 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
1543 _comment += ex.GetMessageString();
1547 if ( _comment.empty() )
1548 _comment = "Exception in blsurf_compute_mesh()";
1550 if ( status != STATUS_OK) {
1551 // There was an error while meshing
1552 blsurf_session_delete(bls);
1554 // #if BLSURF_VERSION_LONG >= "3.1.1"
1555 // // if(geo_sizemap_e)
1556 // // distene_sizemap_delete(geo_sizemap_e);
1557 // // if(geo_sizemap_f)
1558 // // distene_sizemap_delete(geo_sizemap_f);
1559 // if(iso_sizemap_p)
1560 // distene_sizemap_delete(iso_sizemap_p);
1561 // if(iso_sizemap_e)
1562 // distene_sizemap_delete(iso_sizemap_e);
1563 // if(iso_sizemap_f)
1564 // distene_sizemap_delete(iso_sizemap_f);
1566 // // if(clean_geo_sizemap_e)
1567 // // distene_sizemap_delete(clean_geo_sizemap_e);
1568 // // if(clean_geo_sizemap_f)
1569 // // distene_sizemap_delete(clean_geo_sizemap_f);
1570 // if(clean_iso_sizemap_p)
1571 // distene_sizemap_delete(clean_iso_sizemap_p);
1572 // if(clean_iso_sizemap_e)
1573 // distene_sizemap_delete(clean_iso_sizemap_e);
1574 // if(clean_iso_sizemap_f)
1575 // distene_sizemap_delete(clean_iso_sizemap_f);
1579 context_delete(ctx);
1581 return error(_comment);
1584 std::cout << std::endl;
1585 std::cout << "End of Surface Mesh generation" << std::endl;
1586 std::cout << std::endl;
1589 blsurf_data_get_mesh(bls, &msh);
1591 /* release the mesh object */
1592 blsurf_data_regain_mesh(bls, msh);
1593 /* clean up everything */
1594 blsurf_session_delete(bls);
1596 // #if BLSURF_VERSION_LONG >= "3.1.1"
1597 // // if(geo_sizemap_e)
1598 // // distene_sizemap_delete(geo_sizemap_e);
1599 // // if(geo_sizemap_f)
1600 // // distene_sizemap_delete(geo_sizemap_f);
1601 // if(iso_sizemap_p)
1602 // distene_sizemap_delete(iso_sizemap_p);
1603 // if(iso_sizemap_e)
1604 // distene_sizemap_delete(iso_sizemap_e);
1605 // if(iso_sizemap_f)
1606 // distene_sizemap_delete(iso_sizemap_f);
1608 // // if(clean_geo_sizemap_e)
1609 // // distene_sizemap_delete(clean_geo_sizemap_e);
1610 // // if(clean_geo_sizemap_f)
1611 // // distene_sizemap_delete(clean_geo_sizemap_f);
1612 // if(clean_iso_sizemap_p)
1613 // distene_sizemap_delete(clean_iso_sizemap_p);
1614 // if(clean_iso_sizemap_e)
1615 // distene_sizemap_delete(clean_iso_sizemap_e);
1616 // if(clean_iso_sizemap_f)
1617 // distene_sizemap_delete(clean_iso_sizemap_f);
1621 context_delete(ctx);
1623 return error(_comment);
1627 std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
1629 GMFFileName = _hypothesis->GetGMFFile();
1630 if (GMFFileName != "") {
1631 // bool GMFFileMode = _hypothesis->GetGMFFileMode();
1632 bool asciiFound = (GMFFileName.find(".mesh",GMFFileName.length()-5) != std::string::npos);
1633 bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
1634 if (!asciiFound && !binaryFound)
1635 GMFFileName.append(".mesh");
1640 GMFFileName.append("b");
1642 GMFFileName.append(".meshb");
1647 GMFFileName.append(".mesh");
1650 mesh_write_mesh(msh, GMFFileName.c_str());
1653 /* retrieve mesh data (see distene/mesh.h) */
1654 integer nv, ne, nt, nq, vtx[4], tag;
1657 mesh_get_vertex_count(msh, &nv);
1658 mesh_get_edge_count(msh, &ne);
1659 mesh_get_triangle_count(msh, &nt);
1660 mesh_get_quadrangle_count(msh, &nq);
1663 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1664 SMDS_MeshNode** nodes = new SMDS_MeshNode*[nv+1];
1665 bool* tags = new bool[nv+1];
1667 /* enumerated vertices */
1668 for(int iv=1;iv<=nv;iv++) {
1669 mesh_get_vertex_coordinates(msh, iv, xyz);
1670 mesh_get_vertex_tag(msh, iv, &tag);
1671 // Issue 0020656. Use vertex coordinates
1672 if ( tag > 0 && tag <= pmap.Extent() ) {
1673 TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
1674 double tol = BRep_Tool::Tolerance( v );
1675 gp_Pnt p = BRep_Tool::Pnt( v );
1676 if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
1677 xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
1679 tag = 0; // enforced or attracted vertex
1681 nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
1683 // Create group of enforced vertices if requested
1684 BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
1686 projVertex.push_back((double)xyz[0]);
1687 projVertex.push_back((double)xyz[1]);
1688 projVertex.push_back((double)xyz[2]);
1689 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
1690 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end()) {
1691 MESSAGE("Found enforced vertex @ " << xyz[0] << ", " << xyz[1] << ", " << xyz[2]);
1692 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
1693 BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
1694 for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
1695 currentEnfVertex = (*enfListIt);
1696 if (currentEnfVertex->grpName != "") {
1697 bool groupDone = false;
1698 SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
1699 MESSAGE("currentEnfVertex->grpName: " << currentEnfVertex->grpName);
1700 MESSAGE("Parsing the groups of the mesh");
1701 while (grIt->more()) {
1702 SMESH_Group * group = grIt->next();
1703 if ( !group ) continue;
1704 MESSAGE("Group: " << group->GetName());
1705 SMESHDS_GroupBase* groupDS = group->GetGroupDS();
1706 if ( !groupDS ) continue;
1707 MESSAGE("group->SMDSGroup().GetType(): " << (groupDS->GetType()));
1708 MESSAGE("group->SMDSGroup().GetType()==SMDSAbs_Node: " << (groupDS->GetType()==SMDSAbs_Node));
1709 MESSAGE("currentEnfVertex->grpName.compare(group->GetStoreName())==0: " << (currentEnfVertex->grpName.compare(group->GetName())==0));
1710 if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
1711 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
1712 aGroupDS->SMDSGroup().Add(nodes[iv]);
1713 MESSAGE("Node ID: " << nodes[iv]->GetID());
1714 // How can I inform the hypothesis ?
1715 // _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
1717 MESSAGE("Successfully added enforced vertex to existing group " << currentEnfVertex->grpName);
1724 SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
1725 aGroup->SetName( currentEnfVertex->grpName.c_str() );
1726 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
1727 aGroupDS->SMDSGroup().Add(nodes[iv]);
1728 MESSAGE("Successfully created enforced vertex group " << currentEnfVertex->grpName);
1732 throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
1735 MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
1740 // internal point are tagged to zero
1741 if(tag > 0 && tag <= pmap.Extent() ){
1742 meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
1749 /* enumerate edges */
1750 for(int it=1;it<=ne;it++) {
1751 mesh_get_edge_vertices(msh, it, vtx);
1752 SMDS_MeshEdge* edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
1753 mesh_get_edge_tag(msh, it, &tag);
1756 Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
1757 tags[vtx[0]] = false;
1760 Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
1761 tags[vtx[1]] = false;
1763 meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
1767 /* enumerate triangles */
1768 for(int it=1;it<=nt;it++) {
1769 mesh_get_triangle_vertices(msh, it, vtx);
1770 SMDS_MeshFace* tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
1771 mesh_get_triangle_tag(msh, it, &tag);
1772 meshDS->SetMeshElementOnShape(tri, TopoDS::Face(fmap(tag)));
1774 meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
1775 tags[vtx[0]] = false;
1778 meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
1779 tags[vtx[1]] = false;
1782 meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
1783 tags[vtx[2]] = false;
1787 /* enumerate quadrangles */
1788 for(int it=1;it<=nq;it++) {
1789 mesh_get_quadrangle_vertices(msh, it, vtx);
1790 SMDS_MeshFace* quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
1791 mesh_get_quadrangle_tag(msh, it, &tag);
1792 meshDS->SetMeshElementOnShape(quad, TopoDS::Face(fmap(tag)));
1794 meshDS->SetNodeOnFace(nodes[vtx[0]], TopoDS::Face(fmap(tag)));
1795 tags[vtx[0]] = false;
1798 meshDS->SetNodeOnFace(nodes[vtx[1]], TopoDS::Face(fmap(tag)));
1799 tags[vtx[1]] = false;
1802 meshDS->SetNodeOnFace(nodes[vtx[2]], TopoDS::Face(fmap(tag)));
1803 tags[vtx[2]] = false;
1806 meshDS->SetNodeOnFace(nodes[vtx[3]], TopoDS::Face(fmap(tag)));
1807 tags[vtx[3]] = false;
1811 // SetIsAlwaysComputed( true ) to sub-meshes of degenerated EDGEs
1812 TopLoc_Location loc; double f,l;
1813 for (int i = 1; i <= emap.Extent(); i++)
1814 if ( BRep_Tool::Curve(TopoDS::Edge( emap( i )), loc, f,l).IsNull() )
1815 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
1816 sm->SetIsAlwaysComputed( true );
1817 for (int i = 1; i <= pmap.Extent(); i++)
1818 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
1819 if ( !sm->IsMeshComputed() )
1820 sm->SetIsAlwaysComputed( true );
1824 /* release the mesh object */
1825 blsurf_data_regain_mesh(bls, msh);
1827 /* clean up everything */
1828 blsurf_session_delete(bls);
1830 // #if BLSURF_VERSION_LONG >= "3.1.1"
1831 // // if(geo_sizemap_e)
1832 // // distene_sizemap_delete(geo_sizemap_e);
1833 // // if(geo_sizemap_f)
1834 // // distene_sizemap_delete(geo_sizemap_f);
1835 // if(iso_sizemap_p)
1836 // distene_sizemap_delete(iso_sizemap_p);
1837 // if(iso_sizemap_e)
1838 // distene_sizemap_delete(iso_sizemap_e);
1839 // if(iso_sizemap_f)
1840 // distene_sizemap_delete(iso_sizemap_f);
1842 // // if(clean_geo_sizemap_e)
1843 // // distene_sizemap_delete(clean_geo_sizemap_e);
1844 // // if(clean_geo_sizemap_f)
1845 // // distene_sizemap_delete(clean_geo_sizemap_f);
1846 // if(clean_iso_sizemap_p)
1847 // distene_sizemap_delete(clean_iso_sizemap_p);
1848 // if(clean_iso_sizemap_e)
1849 // distene_sizemap_delete(clean_iso_sizemap_e);
1850 // if(clean_iso_sizemap_f)
1851 // distene_sizemap_delete(clean_iso_sizemap_f);
1856 context_delete(ctx);
1858 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1860 if ( oldFEFlags > 0 )
1861 feenableexcept( oldFEFlags );
1862 feclearexcept( FE_ALL_EXCEPT );
1866 std::cout << "FacesWithSizeMap" << std::endl;
1867 FacesWithSizeMap.Statistics(std::cout);
1868 std::cout << "EdgesWithSizeMap" << std::endl;
1869 EdgesWithSizeMap.Statistics(std::cout);
1870 std::cout << "VerticesWithSizeMap" << std::endl;
1871 VerticesWithSizeMap.Statistics(std::cout);
1872 std::cout << "FacesWithEnforcedVertices" << std::endl;
1873 FacesWithEnforcedVertices.Statistics(std::cout);
1876 MESSAGE("END OF BLSURFPlugin_BLSURF::Compute()");
1880 #ifdef WITH_SMESH_CANCEL_COMPUTE
1881 void BLSURFPlugin_BLSURF::CancelCompute()
1883 _compute_canceled = true;
1887 //=============================================================================
1891 //=============================================================================
1893 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, SMDS_MeshNode* node, const TopoDS_Shape& ed) {
1894 const TopoDS_Edge edge = TopoDS::Edge(ed);
1896 gp_Pnt pnt(node->X(), node->Y(), node->Z());
1898 Standard_Real p0 = 0.0;
1899 Standard_Real p1 = 1.0;
1900 TopLoc_Location loc;
1901 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
1903 if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
1904 GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
1907 if ( proj.NbPoints() > 0 )
1909 pa = (double)proj.LowerDistanceParameter();
1910 // Issue 0020656. Move node if it is too far from edge
1911 gp_Pnt curve_pnt = curve->Value( pa );
1912 double dist2 = pnt.SquareDistance( curve_pnt );
1913 double tol = BRep_Tool::Tolerance( edge );
1914 if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
1916 curve_pnt.Transform( loc );
1917 meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
1920 // GProp_GProps LProps;
1921 // BRepGProp::LinearProperties(ed, LProps);
1922 // double lg = (double)LProps.Mass();
1924 meshDS->SetNodeOnEdge(node, edge, pa);
1927 //=============================================================================
1931 //=============================================================================
1933 ostream & BLSURFPlugin_BLSURF::SaveTo(ostream & save)
1938 //=============================================================================
1942 //=============================================================================
1944 istream & BLSURFPlugin_BLSURF::LoadFrom(istream & load)
1949 //=============================================================================
1953 //=============================================================================
1955 ostream & operator << (ostream & save, BLSURFPlugin_BLSURF & hyp)
1957 return hyp.SaveTo( save );
1960 //=============================================================================
1964 //=============================================================================
1966 istream & operator >> (istream & load, BLSURFPlugin_BLSURF & hyp)
1968 return hyp.LoadFrom( load );
1971 /* Curve definition function See cad_curv_t in file distene/cad.h for
1973 * NOTE : if when your CAD systems evaluates second
1974 * order derivatives it also computes first order derivatives and
1975 * function evaluation, you can optimize this example by making only
1976 * one CAD call and filling the necessary uv, dt, dtt arrays.
1978 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
1980 /* t is given. It contains the t (time) 1D parametric coordintaes
1981 of the point PreCAD/BLSurf is querying on the curve */
1983 /* user_data identifies the edge PreCAD/BLSurf is querying
1984 * (see cad_edge_new later in this example) */
1985 const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
1988 /* BLSurf is querying the function evaluation */
1991 uv[0]=P.X(); uv[1]=P.Y();
1995 /* query for the first order derivatives */
1998 dt[0]=V1.X(); dt[1]=V1.Y();
2002 /* query for the second order derivatives */
2005 dtt[0]=V2.X(); dtt[1]=V2.Y();
2011 /* Surface definition function.
2012 * See cad_surf_t in file distene/cad.h for more information.
2013 * NOTE : if when your CAD systems evaluates second order derivatives it also
2014 * computes first order derivatives and function evaluation, you can optimize
2015 * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
2018 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
2019 real *duu, real *duv, real *dvv, void *user_data)
2021 /* uv[2] is given. It contains the u,v coordinates of the point
2022 * PreCAD/BLSurf is querying on the surface */
2024 /* user_data identifies the face PreCAD/BLSurf is querying (see
2025 * cad_face_new later in this example)*/
2026 const Geom_Surface* geometry = (const Geom_Surface*) user_data;
2030 P=geometry->Value(uv[0],uv[1]); // S.D0(U,V,P);
2031 xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
2038 geometry->D1(uv[0],uv[1],P,D1U,D1V);
2039 du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
2040 dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
2043 if(duu && duv && dvv){
2047 gp_Vec D2U,D2V,D2UV;
2049 geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
2050 duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
2051 duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
2052 dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
2059 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
2062 if (my_u_min > uv[0]) {
2065 if (my_v_min > uv[1]) {
2068 if (my_u_max < uv[0]) {
2071 if (my_v_max < uv[1]) {
2075 //MESSAGE("size_on_surface")
2076 if (FaceId2PythonSmp.count(face_id) != 0){
2077 //MESSAGE("A size map is used to calculate size on face : "<<face_id)
2078 PyObject * pyresult = NULL;
2079 PyObject* new_stderr = NULL;
2080 assert(Py_IsInitialized());
2081 PyGILState_STATE gstate;
2082 gstate = PyGILState_Ensure();
2083 pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
2085 if ( pyresult == NULL){
2087 string err_description="";
2088 new_stderr = newPyStdOut(err_description);
2089 PySys_SetObject((char*)"stderr", new_stderr);
2091 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2092 Py_DECREF(new_stderr);
2093 MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
2094 result = *((double*)user_data);
2097 result = PyFloat_AsDouble(pyresult);
2098 Py_DECREF(pyresult);
2100 // MESSAGE("f(" << uv[0] << "," << uv[1] << ")" << " = " << result);
2102 PyGILState_Release(gstate);
2104 else if (FaceIndex2ClassAttractor.count(face_id) !=0 && !FaceIndex2ClassAttractor[face_id]->Empty()){
2105 // MESSAGE("attractor used on face :"<<face_id)
2106 // MESSAGE("List of attractor is not empty")
2107 // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
2108 double result = FaceIndex2ClassAttractor[face_id]->GetSize(uv[0],uv[1]);
2110 // MESSAGE("f(" << uv[0] << "," << uv[1] << ")" << " = " << result);
2113 // MESSAGE("List of attractor is empty !!!")
2114 *size = *((double*)user_data);
2119 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
2121 if (EdgeId2PythonSmp.count(edge_id) != 0){
2122 PyObject * pyresult = NULL;
2123 PyObject* new_stderr = NULL;
2124 assert(Py_IsInitialized());
2125 PyGILState_STATE gstate;
2126 gstate = PyGILState_Ensure();
2127 pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
2129 if ( pyresult == NULL){
2131 string err_description="";
2132 new_stderr = newPyStdOut(err_description);
2133 PySys_SetObject((char*)"stderr", new_stderr);
2135 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2136 Py_DECREF(new_stderr);
2137 MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
2138 result = *((double*)user_data);
2141 result = PyFloat_AsDouble(pyresult);
2142 Py_DECREF(pyresult);
2145 PyGILState_Release(gstate);
2148 *size = *((double*)user_data);
2153 status_t size_on_vertex(integer point_id, real *size, void *user_data)
2155 if (VertexId2PythonSmp.count(point_id) != 0){
2156 PyObject * pyresult = NULL;
2157 PyObject* new_stderr = NULL;
2158 assert(Py_IsInitialized());
2159 PyGILState_STATE gstate;
2160 gstate = PyGILState_Ensure();
2161 pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
2163 if ( pyresult == NULL){
2165 string err_description="";
2166 new_stderr = newPyStdOut(err_description);
2167 PySys_SetObject((char*)"stderr", new_stderr);
2169 PySys_SetObject((char*)"stderr", PySys_GetObject((char*)"__stderr__"));
2170 Py_DECREF(new_stderr);
2171 MESSAGE("Can't evaluate f()" << " error is " << err_description);
2172 result = *((double*)user_data);
2175 result = PyFloat_AsDouble(pyresult);
2176 Py_DECREF(pyresult);
2179 PyGILState_Release(gstate);
2182 *size = *((double*)user_data);
2188 * The following function will be called for PreCAD/BLSurf message
2189 * printing. See context_set_message_callback (later in this
2190 * template) for how to set user_data.
2192 status_t message_cb(message_t *msg, void *user_data)
2194 integer errnumber = 0;
2196 message_get_number(msg, &errnumber);
2197 message_get_description(msg, &desc);
2199 if ( errnumber < 0 || err.find("license") != string::npos ) {
2200 string * error = (string*)user_data;
2201 // if ( !error->empty() )
2203 // remove ^A from the tail
2204 int len = strlen( desc );
2205 while (len > 0 && desc[len-1] != '\n')
2207 error->append( desc, len );
2210 std::cout << desc << std::endl;
2215 /* This is the interrupt callback. PreCAD/BLSurf will call this
2216 * function regularily. See the file distene/interrupt.h
2218 status_t interrupt_cb(integer *interrupt_status, void *user_data)
2220 integer you_want_to_continue = 1;
2221 #ifdef WITH_SMESH_CANCEL_COMPUTE
2222 BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
2223 you_want_to_continue = !tmp->computeCanceled();
2226 if(you_want_to_continue)
2228 *interrupt_status = INTERRUPT_CONTINUE;
2231 else /* you want to stop BLSurf */
2233 *interrupt_status = INTERRUPT_STOP;
2234 return STATUS_ERROR;
2238 //=============================================================================
2242 //=============================================================================
2243 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh& aMesh,
2244 const TopoDS_Shape& aShape,
2245 MapShapeNbElems& aResMap)
2247 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
2248 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize();
2249 //int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
2250 //double _angleMeshS = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshS();
2251 double _angleMeshC = BLSURFPlugin_Hypothesis::GetDefaultAngleMeshC();
2252 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
2254 _physicalMesh = (int) _hypothesis->GetPhysicalMesh();
2255 _phySize = _hypothesis->GetPhySize();
2256 //_geometricMesh = (int) hyp->GetGeometricMesh();
2257 //_angleMeshS = hyp->GetAngleMeshS();
2258 _angleMeshC = _hypothesis->GetAngleMeshC();
2259 _quadAllowed = _hypothesis->GetQuadAllowed();
2262 bool IsQuadratic = false;
2267 TopTools_DataMapOfShapeInteger EdgesMap;
2268 double fullLen = 0.0;
2269 double fullNbSeg = 0;
2270 for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
2271 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
2272 if( EdgesMap.IsBound(E) )
2274 SMESH_subMesh *sm = aMesh.GetSubMesh(E);
2275 double aLen = SMESH_Algo::EdgeLength(E);
2278 if(_physicalMesh==1) {
2279 nb1d = (int)( aLen/_phySize + 1 );
2284 Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
2285 double fullAng = 0.0;
2286 double dp = (l-f)/200;
2291 for(int j=2; j<=200; j++) {
2294 fullAng += fabs(V1.Angle(V2));
2298 nb1d = (int)( fullAng/_angleMeshC + 1 );
2301 std::vector<int> aVec(SMDSEntity_Last);
2302 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2303 if( IsQuadratic > 0 ) {
2304 aVec[SMDSEntity_Node] = 2*nb1d - 1;
2305 aVec[SMDSEntity_Quad_Edge] = nb1d;
2308 aVec[SMDSEntity_Node] = nb1d - 1;
2309 aVec[SMDSEntity_Edge] = nb1d;
2311 aResMap.insert(std::make_pair(sm,aVec));
2312 EdgesMap.Bind(E,nb1d);
2314 double ELen = fullLen/fullNbSeg;
2318 // try to evaluate as in MEFISTO
2319 for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
2320 TopoDS_Face F = TopoDS::Face( exp.Current() );
2321 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
2323 BRepGProp::SurfaceProperties(F,G);
2324 double anArea = G.Mass();
2326 std::vector<int> nb1dVec;
2327 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
2328 int nbSeg = EdgesMap.Find(exp1.Current());
2330 nb1dVec.push_back( nbSeg );
2333 int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
2334 int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
2337 if ( nb1dVec.size() == 4 ) // quadrangle geom face
2339 int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
2341 nbNodes = (n1 + 1) * (n2 + 1);
2346 nbTria = nbQuad = nbTria / 3 + 1;
2349 std::vector<int> aVec(SMDSEntity_Last,0);
2351 int nb1d_in = (nbTria*3 - nb1d) / 2;
2352 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
2353 aVec[SMDSEntity_Quad_Triangle] = nbTria;
2354 aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
2357 aVec[SMDSEntity_Node] = nbNodes;
2358 aVec[SMDSEntity_Triangle] = nbTria;
2359 aVec[SMDSEntity_Quadrangle] = nbQuad;
2361 aResMap.insert(std::make_pair(sm,aVec));
2368 BRepGProp::VolumeProperties(aShape,G);
2369 double aVolume = G.Mass();
2370 double tetrVol = 0.1179*ELen*ELen*ELen;
2371 int nbVols = int(aVolume/tetrVol);
2372 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
2373 std::vector<int> aVec(SMDSEntity_Last);
2374 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2376 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
2377 aVec[SMDSEntity_Quad_Tetra] = nbVols;
2380 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
2381 aVec[SMDSEntity_Tetra] = nbVols;
2383 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
2384 aResMap.insert(std::make_pair(sm,aVec));
2389 //=============================================================================
2391 * Rewritting of the BRepClass_FaceClassifier::Perform function which is bugged (CAS 6.3sp6)
2392 * Following line was added:
2393 * myExtrem.Perform(P);
2395 //=============================================================================
2396 void BLSURFPlugin_BLSURF::BRepClass_FaceClassifierPerform(BRepClass_FaceClassifier* fc,
2397 const TopoDS_Face& face,
2399 const Standard_Real Tol)
2401 //-- Voir BRepExtrema_ExtPF.cxx
2402 BRepAdaptor_Surface Surf(face);
2403 Standard_Real U1, U2, V1, V2;
2404 BRepTools::UVBounds(face, U1, U2, V1, V2);
2405 Extrema_ExtPS myExtrem;
2406 myExtrem.Initialize(Surf, U1, U2, V1, V2, Tol, Tol);
2407 myExtrem.Perform(P);
2408 //----------------------------------------------------------
2409 //-- On cherche le point le plus proche , PUIS
2410 //-- On le classifie.
2411 Standard_Integer nbv = 0; // xpu
2412 Standard_Real MaxDist = RealLast();
2413 Standard_Integer indice = 0;
2414 if (myExtrem.IsDone()) {
2415 nbv = myExtrem.NbExt();
2416 for (Standard_Integer i = 1; i <= nbv; i++) {
2417 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
2418 Standard_Real d = myExtrem.SquareDistance(i);
2420 Standard_Real d = myExtrem.Value(i);
2431 Standard_Real U1,U2;
2432 myExtrem.Point(indice).Parameter(U1, U2);
2433 Puv.SetCoord(U1, U2);
2434 fc->Perform(face, Puv, Tol);
2437 fc->Perform(face, gp_Pnt2d(U1-1.0,V1 - 1.0), Tol); //-- NYI etc BUG PAS BEAU En attendant l acces a rejected
2438 //-- le resultat est TopAbs_OUT;