1 // Copyright (C) 2007-2016 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>
36 #include <structmember.h>
39 #include <Basics_Utils.hxx>
40 #include <Basics_OCCTVersion.hxx>
42 #include <SMDS_EdgePosition.hxx>
43 #include <SMESHDS_Group.hxx>
44 #include <SMESH_Gen.hxx>
45 #include <SMESH_Group.hxx>
46 #include <SMESH_Mesh.hxx>
47 #include <SMESH_MeshEditor.hxx>
48 #include <SMESH_MesherHelper.hxx>
49 #include <StdMeshers_FaceSide.hxx>
50 #include <StdMeshers_ViscousLayers2D.hxx>
51 #include <SMESH_File.hxx>
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>
100 /* ==================================
101 * =========== PYTHON ==============
102 * ==================================*/
113 PyStdOut_dealloc(PyStdOut *self)
119 PyStdOut_write(PyStdOut *self, PyObject *args)
123 if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
126 *(self->out)=*(self->out)+c;
132 static PyMethodDef PyStdOut_methods[] = {
133 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
134 PyDoc_STR("write(string) -> None")},
135 {NULL, NULL} /* sentinel */
138 static PyMemberDef PyStdOut_memberlist[] = {
139 {(char*)"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
140 (char*)"flag indicating that a space needs to be printed; used by print"},
141 {NULL} /* Sentinel */
144 static PyTypeObject PyStdOut_Type = {
145 /* The ob_type field must be initialized in the module init function
146 * to be portable to Windows without using C++. */
147 PyObject_HEAD_INIT(NULL)
150 sizeof(PyStdOut), /*tp_basicsize*/
153 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
160 0, /*tp_as_sequence*/
165 PyObject_GenericGetAttr, /*tp_getattro*/
166 /* softspace is writable: we must supply tp_setattro */
167 PyObject_GenericSetAttr, /* tp_setattro */
169 Py_TPFLAGS_DEFAULT, /*tp_flags*/
173 0, /*tp_richcompare*/
174 0, /*tp_weaklistoffset*/
177 PyStdOut_methods, /*tp_methods*/
178 PyStdOut_memberlist, /*tp_members*/
192 PyObject * newPyStdOut( std::string& out )
194 PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
199 return (PyObject*)self;
204 ////////////////////////END PYTHON///////////////////////////
206 //////////////////MY MAPS////////////////////////////////////////
208 TopTools_IndexedMapOfShape FacesWithSizeMap;
209 std::map<int,string> FaceId2SizeMap;
210 TopTools_IndexedMapOfShape EdgesWithSizeMap;
211 std::map<int,string> EdgeId2SizeMap;
212 TopTools_IndexedMapOfShape VerticesWithSizeMap;
213 std::map<int,string> VertexId2SizeMap;
215 std::map<int,PyObject*> FaceId2PythonSmp;
216 std::map<int,PyObject*> EdgeId2PythonSmp;
217 std::map<int,PyObject*> VertexId2PythonSmp;
219 typedef std::map<int, std::vector< BLSURFPlugin_Attractor* > > TId2ClsAttractorVec;
220 TId2ClsAttractorVec FaceId2ClassAttractor;
221 TId2ClsAttractorVec FaceIndex2ClassAttractor;
222 std::map<int,std::vector<double> > FaceId2AttractorCoords;
225 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
226 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
227 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
228 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
230 bool HasSizeMapOnFace=false;
231 bool HasSizeMapOnEdge=false;
232 bool HasSizeMapOnVertex=false;
233 //bool HasAttractorOnFace=false;
235 //=============================================================================
239 //=============================================================================
241 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int hypId, SMESH_Gen* gen)
242 : SMESH_2D_Algo(hypId, gen)
244 MESSAGE("BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF");
246 _name = "MG-CADSurf";//"BLSURF";
247 _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
248 _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType());
249 _compatibleHypothesis.push_back(StdMeshers_ViscousLayers2D::GetHypType());
250 _requireDiscreteBoundary = false;
251 _onlyUnaryInput = false;
253 _supportSubmeshes = true;
255 smeshGen_i = SMESH_Gen_i::GetSMESHGen();
256 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/Study");
257 myStudy = SALOMEDS::Study::_narrow(anObject);
258 if ( !myStudy->_is_nil() )
259 MESSAGE("myStudy not empty");
261 /* Initialize the Python interpreter */
262 assert(Py_IsInitialized());
263 PyGILState_STATE gstate;
264 gstate = PyGILState_Ensure();
267 main_mod = PyImport_AddModule("__main__");
270 main_dict = PyModule_GetDict(main_mod);
272 PyRun_SimpleString("from math import *");
273 PyGILState_Release(gstate);
275 FacesWithSizeMap.Clear();
276 FaceId2SizeMap.clear();
277 EdgesWithSizeMap.Clear();
278 EdgeId2SizeMap.clear();
279 VerticesWithSizeMap.Clear();
280 VertexId2SizeMap.clear();
281 FaceId2PythonSmp.clear();
282 EdgeId2PythonSmp.clear();
283 VertexId2PythonSmp.clear();
284 FaceId2AttractorCoords.clear();
285 FaceId2ClassAttractor.clear();
286 FaceIndex2ClassAttractor.clear();
287 FacesWithEnforcedVertices.Clear();
288 FaceId2EnforcedVertexCoords.clear();
289 EnfVertexCoords2ProjVertex.clear();
290 EnfVertexCoords2EnfVertexList.clear();
292 _compute_canceled = false;
295 //=============================================================================
299 //=============================================================================
301 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
303 MESSAGE("BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF");
307 //=============================================================================
311 //=============================================================================
313 bool BLSURFPlugin_BLSURF::CheckHypothesis
315 const TopoDS_Shape& aShape,
316 SMESH_Hypothesis::Hypothesis_Status& aStatus)
319 _haveViscousLayers = false;
321 list<const SMESHDS_Hypothesis*>::const_iterator itl;
322 const SMESHDS_Hypothesis* theHyp;
324 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape,
325 /*ignoreAuxiliary=*/false);
326 aStatus = SMESH_Hypothesis::HYP_OK;
329 return true; // can work with no hypothesis
332 for ( itl = hyps.begin(); itl != hyps.end() && ( aStatus == HYP_OK ); ++itl )
335 string hypName = theHyp->GetName();
336 if ( hypName == BLSURFPlugin_Hypothesis::GetHypType() )
338 _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
340 if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
341 _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
342 // hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
343 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
345 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
347 if ( !_haveViscousLayers )
349 if ( error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus )))
350 _haveViscousLayers = true;
355 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
358 return aStatus == SMESH_Hypothesis::HYP_OK;
361 //=============================================================================
363 * Pass parameters to MG-CADSurf
365 //=============================================================================
367 inline std::string val_to_string(double d)
369 std::ostringstream o;
374 inline std::string val_to_string_rel(double d)
376 std::ostringstream o;
382 inline std::string val_to_string(int i)
384 std::ostringstream o;
389 inline std::string val_to_string_rel(int i)
391 std::ostringstream o;
397 double _smp_phy_size;
398 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
399 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
400 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
406 /////////////////////////////////////////////////////////
407 projectionPoint getProjectionPoint(const TopoDS_Face& face, const gp_Pnt& point)
409 projectionPoint myPoint;
410 Handle(Geom_Surface) surface = BRep_Tool::Surface(face);
411 GeomAPI_ProjectPointOnSurf projector( point, surface );
412 if ( !projector.IsDone() || projector.NbPoints()==0 )
413 throw "getProjectionPoint: Can't project";
415 Quantity_Parameter u,v;
416 projector.LowerDistanceParameters(u,v);
417 myPoint.uv = gp_XY(u,v);
418 gp_Pnt aPnt = projector.NearestPoint();
419 myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
423 /////////////////////////////////////////////////////////
425 /////////////////////////////////////////////////////////
426 double getT(const TopoDS_Edge& edge, const gp_Pnt& point)
429 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, f,l);
430 GeomAPI_ProjectPointOnCurve projector( point, curve);
431 if ( projector.NbPoints() == 0 )
433 return projector.LowerDistanceParameter();
436 /////////////////////////////////////////////////////////
437 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
439 MESSAGE("BLSURFPlugin_BLSURF::entryToShape "<<entry );
440 GEOM::GEOM_Object_var aGeomObj;
441 TopoDS_Shape S = TopoDS_Shape();
442 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
443 if (!aSObj->_is_nil()) {
444 CORBA::Object_var obj = aSObj->GetObject();
445 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
448 if ( !aGeomObj->_is_nil() )
449 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
453 void _createEnforcedVertexOnFace(TopoDS_Face faceShape, gp_Pnt aPnt, BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex)
455 BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
460 // Get the (u,v) values of the enforced vertex on the face
461 projectionPoint myPoint = getProjectionPoint(faceShape,aPnt);
463 MESSAGE("Enforced Vertex: " << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z());
464 MESSAGE("Projected Vertex: " << myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z());
465 MESSAGE("Parametric coordinates: " << myPoint.uv.X() << ", " << myPoint.uv.Y() );
467 enf_coords.push_back(aPnt.X());
468 enf_coords.push_back(aPnt.Y());
469 enf_coords.push_back(aPnt.Z());
471 coords.push_back(myPoint.uv.X());
472 coords.push_back(myPoint.uv.Y());
473 coords.push_back(myPoint.xyz.X());
474 coords.push_back(myPoint.xyz.Y());
475 coords.push_back(myPoint.xyz.Z());
477 s_coords.push_back(myPoint.xyz.X());
478 s_coords.push_back(myPoint.xyz.Y());
479 s_coords.push_back(myPoint.xyz.Z());
481 // Save pair projected vertex / enf vertex
482 MESSAGE("Storing pair projected vertex / enf vertex:");
483 MESSAGE("("<< myPoint.xyz.X() << ", " << myPoint.xyz.Y() << ", " << myPoint.xyz.Z() <<") / (" << aPnt.X() << ", " << aPnt.Y() << ", " << aPnt.Z()<<")");
484 EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
485 MESSAGE("Group name is: \"" << enfVertex->grpName << "\"");
486 pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
487 BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
488 ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
489 if (ret.second == false) {
491 (*it)->grpName = enfVertex->grpName;
495 if (! FacesWithEnforcedVertices.Contains(faceShape)) {
496 key = FacesWithEnforcedVertices.Add(faceShape);
499 key = FacesWithEnforcedVertices.FindIndex(faceShape);
502 // If a node is already created by an attractor, do not create enforced vertex
503 int attractorKey = FacesWithSizeMap.FindIndex(faceShape);
504 bool sameAttractor = false;
505 if (attractorKey >= 0)
506 if (FaceId2AttractorCoords.count(attractorKey) > 0)
507 if (FaceId2AttractorCoords[attractorKey] == coords)
508 sameAttractor = true;
510 if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
511 MESSAGE("Map of enf. vertex has key " << key)
512 MESSAGE("Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
514 FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
516 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
517 MESSAGE("New Enf. vertex list size is: " << FaceId2EnforcedVertexCoords[key].size())
520 MESSAGE("Map of enf. vertex has not key " << key << ": creating it")
521 if (! sameAttractor) {
522 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
524 FaceId2EnforcedVertexCoords[key] = ens;
527 MESSAGE("An attractor node is already defined: I don't add the enforced vertex");
531 /////////////////////////////////////////////////////////
532 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
534 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex;
537 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfVertexListIt = enfVertexList.begin();
539 for( ; enfVertexListIt != enfVertexList.end() ; ++enfVertexListIt ) {
540 enfVertex = *enfVertexListIt;
541 // Case of manual coords
542 if (enfVertex->coords.size() != 0) {
543 aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
544 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
547 // Case of geom vertex coords
548 if (enfVertex->geomEntry != "") {
549 TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
550 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
551 if (GeomType == TopAbs_VERTEX){
552 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
553 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
556 if (GeomType == TopAbs_COMPOUND){
557 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
558 if (it.Value().ShapeType() == TopAbs_VERTEX){
559 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
560 _createEnforcedVertexOnFace( TopoDS::Face(faceShape), aPnt, enfVertex);
568 /////////////////////////////////////////////////////////
569 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction, double defaultSize)
571 MESSAGE("Attractor function: "<< AttractorFunction);
572 double xa, ya, za; // Coordinates of attractor point
573 double a, b; // Attractor parameter
575 bool createNode=false; // To create a node on attractor projection
577 const char *sep = ";";
578 // atIt->second has the following pattern:
579 // ATTRACTOR(xa;ya;za;a;b;True|False;d)
581 // xa;ya;za : coordinates of attractor
582 // a : desired size on attractor
583 // b : distance of influence of attractor
584 // d : distance until which the size remains constant
586 // We search the parameters in the string
588 pos1 = AttractorFunction.find(sep);
589 if (pos1!=string::npos)
590 xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
592 pos2 = AttractorFunction.find(sep, pos1+1);
593 if (pos2!=string::npos) {
594 ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
598 pos2 = AttractorFunction.find(sep, pos1+1);
599 if (pos2!=string::npos) {
600 za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
604 pos2 = AttractorFunction.find(sep, pos1+1);
605 if (pos2!=string::npos) {
606 a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
610 pos2 = AttractorFunction.find(sep, pos1+1);
611 if (pos2!=string::npos) {
612 b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
616 pos2 = AttractorFunction.find(sep, pos1+1);
617 if (pos2!=string::npos) {
618 string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
619 MESSAGE("createNode: " << createNodeStr);
620 createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
624 pos2 = AttractorFunction.find(")");
625 if (pos2!=string::npos) {
626 d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
629 // Get the (u,v) values of the attractor on the face
630 projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
631 gp_XY uvPoint = myPoint.uv;
632 gp_XYZ xyzPoint = myPoint.xyz;
633 Standard_Real u0 = uvPoint.X();
634 Standard_Real v0 = uvPoint.Y();
635 Standard_Real x0 = xyzPoint.X();
636 Standard_Real y0 = xyzPoint.Y();
637 Standard_Real z0 = xyzPoint.Z();
638 std::vector<double> coords;
639 coords.push_back(u0);
640 coords.push_back(v0);
641 coords.push_back(x0);
642 coords.push_back(y0);
643 coords.push_back(z0);
644 // We construct the python function
645 ostringstream attractorFunctionStream;
646 attractorFunctionStream << "def f(u,v): return ";
647 attractorFunctionStream << defaultSize << "-(" << defaultSize <<"-" << a << ")";
648 //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
649 // rnc: make possible to keep the size constant until
650 // a defined distance. Distance is expressed as the positiv part
651 // of r-d where r is the distance to (u0,v0)
652 attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
654 MESSAGE("Python function for attractor:" << std::endl << attractorFunctionStream.str());
657 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
658 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
661 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
663 FaceId2SizeMap[key] =attractorFunctionStream.str();
665 MESSAGE("Creating node on ("<<x0<<","<<y0<<","<<z0<<")");
666 FaceId2AttractorCoords[key] = coords;
668 // // Test for new attractors
669 // gp_Pnt myP(xyzPoint);
670 // TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
671 // BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
672 // myAttractor.SetParameters(a, defaultSize, b, d);
673 // myAttractor.SetType(1);
674 // FaceId2ClassAttractor[key] = myAttractor;
675 // if(FaceId2ClassAttractor[key].GetFace().IsNull()){
676 // MESSAGE("face nulle ");
679 // MESSAGE("face OK");
681 // if (FaceId2ClassAttractor[key].GetAttractorShape().IsNull()){
682 // MESSAGE("pas de point");
685 // MESSAGE("point OK");
688 // One sub-shape to get ids from
689 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(TopoDS_Shape theMainShape, TopoDS_Shape theSubShape,
690 TopAbs_ShapeEnum theShapeType)
692 BLSURFPlugin_BLSURF::TListOfIDs face_ids;
693 TopTools_IndexedMapOfShape anIndices;
695 TopExp::MapShapes(theMainShape, theShapeType, anIndices);
697 // Standard_Boolean result = BRepTools::Write(theMainShape,"main_shape.brep");
699 for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
701 int face_id = anIndices.FindIndex(face_iter.Current());
703 throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
704 face_ids.push_back(face_id);
705 // std::ostringstream o;
706 // o << "face_" << face_id << ".brep";
707 // std::string face_name = o.str();
708 // const TopoDS_Face& face = TopoDS::Face(face_iter.Current());
709 // Standard_Boolean result = BRepTools::Write(face,face_name.c_str());
715 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(SMESH_Mesh* theMesh,
716 TopoDS_Shape theSubShape,
717 TopAbs_ShapeEnum theShapeType)
719 BLSURFPlugin_BLSURF::TListOfIDs face_ids;
721 for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
723 int face_id = theMesh->GetMeshDS()->ShapeToIndex(face_iter.Current());
725 throw SALOME_Exception ( SMESH_Comment("Sub_shape not found in main_shape"));
726 face_ids.push_back(face_id);
732 void BLSURFPlugin_BLSURF::addCoordsFromVertices(const std::vector<std::string> &theVerticesEntries, std::vector<double> &theVerticesCoords)
734 for (std::vector<std::string>::const_iterator it = theVerticesEntries.begin(); it != theVerticesEntries.end(); it++)
736 BLSURFPlugin_Hypothesis::TEntry theVertexEntry = *it;
737 MESSAGE("Vertex entry " << theVertexEntry);
738 addCoordsFromVertex(theVertexEntry, theVerticesCoords);
743 void BLSURFPlugin_BLSURF::addCoordsFromVertex(BLSURFPlugin_Hypothesis::TEntry theVertexEntry, std::vector<double> &theVerticesCoords)
745 if (theVertexEntry!="")
747 TopoDS_Shape aShape = entryToShape(theVertexEntry);
749 gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex( aShape ) );
750 double theX, theY, theZ;
755 theVerticesCoords.push_back(theX);
756 theVerticesCoords.push_back(theY);
757 theVerticesCoords.push_back(theZ);
761 /////////////////////////////////////////////////////////
762 void BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
764 MESSAGE("BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity");
766 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
767 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
769 TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_FACE);
770 TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_FACE);
772 TPreCadPeriodicityIDs preCadFacesPeriodicityIDs;
773 preCadFacesPeriodicityIDs.shape1IDs = theFace1_ids;
774 preCadFacesPeriodicityIDs.shape2IDs = theFace2_ids;
776 MESSAGE("preCadPeriodicity.theSourceVerticesEntries.size(): " << preCadPeriodicity.theSourceVerticesEntries.size());
777 MESSAGE("preCadPeriodicity.theTargetVerticesEntries.size(): " << preCadPeriodicity.theTargetVerticesEntries.size());
779 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadFacesPeriodicityIDs.theSourceVerticesCoords);
780 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadFacesPeriodicityIDs.theTargetVerticesCoords);
782 MESSAGE("preCadFacesPeriodicityIDs.theSourceVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theSourceVerticesCoords.size());
783 MESSAGE("preCadFacesPeriodicityIDs.theTargetVerticesCoords.size(): " << preCadFacesPeriodicityIDs.theTargetVerticesCoords.size());
785 _preCadFacesIDsPeriodicityVector.push_back(preCadFacesPeriodicityIDs);
786 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
787 MESSAGE("BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity END");
791 /////////////////////////////////////////////////////////
792 void BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
794 MESSAGE("BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity");
796 TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
797 TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
799 TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_EDGE);
800 TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_EDGE);
802 TPreCadPeriodicityIDs preCadEdgesPeriodicityIDs;
803 preCadEdgesPeriodicityIDs.shape1IDs = theEdge1_ids;
804 preCadEdgesPeriodicityIDs.shape2IDs = theEdge2_ids;
806 addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadEdgesPeriodicityIDs.theSourceVerticesCoords);
807 addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadEdgesPeriodicityIDs.theTargetVerticesCoords);
809 _preCadEdgesIDsPeriodicityVector.push_back(preCadEdgesPeriodicityIDs);
810 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
811 MESSAGE("BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity END");
816 /////////////////////////////////////////////////////////
818 void BLSURFPlugin_BLSURF::SetParameters(const BLSURFPlugin_Hypothesis* hyp,
819 cadsurf_session_t * css,
820 const TopoDS_Shape& theGeomShape
824 // Clear map so that it is not stored in the algorithm with old enforced vertices in it
825 EnfVertexCoords2EnfVertexList.clear();
827 double diagonal = SMESH_Mesh::GetShapeDiagonalSize( theGeomShape );
828 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
829 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
830 int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
831 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
832 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
833 double _minSize = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
834 bool _minSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
835 double _maxSize = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
836 bool _maxSizeRel = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
837 double _use_gradation = BLSURFPlugin_Hypothesis::GetDefaultUseGradation();
838 double _gradation = BLSURFPlugin_Hypothesis::GetDefaultGradation();
839 double _use_volume_gradation = BLSURFPlugin_Hypothesis::GetDefaultUseVolumeGradation();
840 double _volume_gradation = BLSURFPlugin_Hypothesis::GetDefaultVolumeGradation();
841 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
842 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
843 double _chordalError = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
844 bool _anisotropic = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
845 double _anisotropicRatio = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
846 bool _removeTinyEdges = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
847 double _tinyEdgeLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
848 bool _optimiseTinyEdges = BLSURFPlugin_Hypothesis::GetDefaultOptimiseTinyEdges();
849 double _tinyEdgeOptimisLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeOptimisationLength(diagonal);
850 bool _correctSurfaceIntersec= BLSURFPlugin_Hypothesis::GetDefaultCorrectSurfaceIntersection();
851 double _corrSurfaceIntersCost = BLSURFPlugin_Hypothesis::GetDefaultCorrectSurfaceIntersectionMaxCost();
852 bool _badElementRemoval = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
853 double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
854 bool _optimizeMesh = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
855 bool _quadraticMesh = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
856 int _verb = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
857 //int _topology = BLSURFPlugin_Hypothesis::GetDefaultTopology();
860 //int _precadMergeEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
861 int _precadRemoveTinyUVEdges = BLSURFPlugin_Hypothesis::GetDefaultPreCADRemoveTinyUVEdges();
862 //int _precadRemoveDuplicateCADFaces = BLSURFPlugin_Hypothesis::GetDefaultPreCADRemoveDuplicateCADFaces();
863 //int _precadProcess3DTopology = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
864 //int _precadDiscardInput = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
868 MESSAGE("BLSURFPlugin_BLSURF::SetParameters");
869 _physicalMesh = (int) hyp->GetPhysicalMesh();
870 _geometricMesh = (int) hyp->GetGeometricMesh();
871 if (hyp->GetPhySize() > 0) {
872 _phySize = hyp->GetPhySize();
873 // if user size is not explicitly specified, "relative" flag is ignored
874 _phySizeRel = hyp->IsPhySizeRel();
876 if (hyp->GetMinSize() > 0) {
877 _minSize = hyp->GetMinSize();
878 // if min size is not explicitly specified, "relative" flag is ignored
879 _minSizeRel = hyp->IsMinSizeRel();
881 if (hyp->GetMaxSize() > 0) {
882 _maxSize = hyp->GetMaxSize();
883 // if max size is not explicitly specified, "relative" flag is ignored
884 _maxSizeRel = hyp->IsMaxSizeRel();
886 _use_gradation = hyp->GetUseGradation();
887 if (hyp->GetGradation() > 0 && _use_gradation)
888 _gradation = hyp->GetGradation();
889 _use_volume_gradation = hyp->GetUseVolumeGradation();
890 if (hyp->GetVolumeGradation() > 0 && _use_volume_gradation )
891 _volume_gradation = hyp->GetVolumeGradation();
892 _quadAllowed = hyp->GetQuadAllowed();
893 if (hyp->GetAngleMesh() > 0)
894 _angleMesh = hyp->GetAngleMesh();
895 if (hyp->GetChordalError() > 0)
896 _chordalError = hyp->GetChordalError();
897 _anisotropic = hyp->GetAnisotropic();
898 if (hyp->GetAnisotropicRatio() >= 0)
899 _anisotropicRatio = hyp->GetAnisotropicRatio();
900 _removeTinyEdges = hyp->GetRemoveTinyEdges();
901 if (hyp->GetTinyEdgeLength() > 0)
902 _tinyEdgeLength = hyp->GetTinyEdgeLength();
903 _optimiseTinyEdges = hyp->GetOptimiseTinyEdges();
904 if (hyp->GetTinyEdgeOptimisationLength() > 0)
905 _tinyEdgeOptimisLength = hyp->GetTinyEdgeOptimisationLength();
906 _correctSurfaceIntersec = hyp->GetCorrectSurfaceIntersection();
907 if (hyp->GetCorrectSurfaceIntersectionMaxCost() > 0)
908 _corrSurfaceIntersCost = hyp->GetCorrectSurfaceIntersectionMaxCost();
909 _badElementRemoval = hyp->GetBadElementRemoval();
910 if (hyp->GetBadElementAspectRatio() >= 0)
911 _badElementAspectRatio = hyp->GetBadElementAspectRatio();
912 _optimizeMesh = hyp->GetOptimizeMesh();
913 _quadraticMesh = hyp->GetQuadraticMesh();
914 _verb = hyp->GetVerbosity();
915 //_topology = (int) hyp->GetTopology();
917 //_precadMergeEdges = hyp->GetPreCADMergeEdges();
918 _precadRemoveTinyUVEdges = hyp->GetPreCADRemoveTinyUVEdges();
919 //_precadRemoveDuplicateCADFaces = hyp->GetPreCADRemoveDuplicateCADFaces();
920 //_precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
921 //_precadDiscardInput = hyp->GetPreCADDiscardInput();
923 const BLSURFPlugin_Hypothesis::TOptionValues& opts = hyp->GetOptionValues();
924 BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
925 for ( opIt = opts.begin(); opIt != opts.end(); ++opIt )
926 if ( !opIt->second.empty() ) {
927 MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
928 set_param(css, opIt->first.c_str(), opIt->second.c_str());
931 const BLSURFPlugin_Hypothesis::TOptionValues& custom_opts = hyp->GetCustomOptionValues();
932 for ( opIt = custom_opts.begin(); opIt != custom_opts.end(); ++opIt )
933 if ( !opIt->second.empty() ) {
934 MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
935 set_param(css, opIt->first.c_str(), opIt->second.c_str());
938 const BLSURFPlugin_Hypothesis::TOptionValues& preCADopts = hyp->GetPreCADOptionValues();
939 for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
940 if ( !opIt->second.empty() ) {
941 MESSAGE("cadsurf_set_param(): " << opIt->first << " = " << opIt->second);
942 set_param(css, opIt->first.c_str(), opIt->second.c_str());
946 if ( BLSURFPlugin_Hypothesis::HasPreCADOptions( hyp ))
948 cadsurf_set_param(css, "use_precad", "yes" ); // for old versions
950 // PreProcessor (formerly PreCAD) -- commented params are preCADoptions (since 0023307)
951 //set_param(css, "merge_edges", _precadMergeEdges ? "yes" : "no");
952 set_param(css, "remove_tiny_uv_edges", _precadRemoveTinyUVEdges ? "yes" : "no");
953 //set_param(css, "remove_duplicate_cad_faces", _precadRemoveDuplicateCADFaces ? "yes" : "no");
954 //set_param(css, "process_3d_topology", _precadProcess3DTopology ? "1" : "0");
955 //set_param(css, "discard_input_topology", _precadDiscardInput ? "1" : "0");
956 //set_param(css, "max_number_of_points_per_patch", "1000000");
958 bool useGradation = false;
959 switch (_physicalMesh)
961 case BLSURFPlugin_Hypothesis::PhysicalGlobalSize:
962 set_param(css, "physical_size_mode", "global");
963 set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
965 case BLSURFPlugin_Hypothesis::PhysicalLocalSize:
966 set_param(css, "physical_size_mode", "local");
967 set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
971 set_param(css, "physical_size_mode", "none");
974 switch (_geometricMesh)
976 case BLSURFPlugin_Hypothesis::GeometricalGlobalSize:
977 set_param(css, "geometric_size_mode", "global");
978 set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
979 set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
982 case BLSURFPlugin_Hypothesis::GeometricalLocalSize:
983 set_param(css, "geometric_size_mode", "local");
984 set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
985 set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
989 set_param(css, "geometric_size_mode", "none");
992 if ( hyp && hyp->GetPhySize() > 0 ) {
993 // user size is explicitly specified via hypothesis parameters
994 // min and max sizes should be compared with explicitly specified user size
995 // - compute absolute min size
996 double mins = _minSizeRel ? _minSize * diagonal : _minSize;
997 // - min size should not be greater than user size
998 if ( _phySize < mins )
999 set_param(css, "min_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1001 set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
1002 // - compute absolute max size
1003 double maxs = _maxSizeRel ? _maxSize * diagonal : _maxSize;
1004 // - max size should not be less than user size
1005 if ( _phySize > maxs )
1006 set_param(css, "max_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1008 set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
1011 // user size is not explicitly specified
1012 // - if minsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1013 set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
1014 // - if maxsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1015 set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
1017 // anisotropic and quadrangle mesh requires disabling gradation
1018 if ( _anisotropic && _quadAllowed )
1019 useGradation = false; // limitation of V1.3
1020 if ( useGradation && _use_gradation )
1021 set_param(css, "gradation", val_to_string(_gradation).c_str());
1022 if ( useGradation && _use_volume_gradation )
1023 set_param(css, "volume_gradation", val_to_string(_volume_gradation).c_str());
1024 set_param(css, "element_generation", _quadAllowed ? "quad_dominant" : "triangle");
1027 set_param(css, "metric", _anisotropic ? "anisotropic" : "isotropic");
1029 set_param(css, "anisotropic_ratio", val_to_string(_anisotropicRatio).c_str());
1030 set_param(css, "remove_tiny_edges", _removeTinyEdges ? "1" : "0");
1031 if ( _removeTinyEdges )
1032 set_param(css, "tiny_edge_length", val_to_string(_tinyEdgeLength).c_str());
1033 set_param(css, "optimise_tiny_edges", _optimiseTinyEdges ? "1" : "0");
1034 if ( _optimiseTinyEdges )
1035 set_param(css, "tiny_edge_optimisation_length", val_to_string(_tinyEdgeOptimisLength).c_str());
1036 set_param(css, "correct_surface_intersections", _correctSurfaceIntersec ? "1" : "0");
1037 if ( _correctSurfaceIntersec )
1038 set_param(css, "surface_intersections_processing_max_cost", val_to_string(_corrSurfaceIntersCost ).c_str());
1039 set_param(css, "force_bad_surface_element_removal", _badElementRemoval ? "1" : "0");
1040 if ( _badElementRemoval )
1041 set_param(css, "bad_surface_element_aspect_ratio", val_to_string(_badElementAspectRatio).c_str());
1042 set_param(css, "optimisation", _optimizeMesh ? "yes" : "no");
1043 set_param(css, "element_order", _quadraticMesh ? "quadratic" : "linear");
1044 set_param(css, "verbose", val_to_string(_verb).c_str());
1046 _smp_phy_size = _phySizeRel ? _phySize*diagonal : _phySize;
1048 std::cout << "_smp_phy_size = " << _smp_phy_size << std::endl;
1050 if (_physicalMesh == BLSURFPlugin_Hypothesis::PhysicalLocalSize){
1051 TopoDS_Shape GeomShape;
1052 TopoDS_Shape AttShape;
1053 TopAbs_ShapeEnum GeomType;
1055 // Standard Size Maps
1057 MESSAGE("Setting a Size Map");
1058 const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
1059 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
1060 for ( ; smIt != sizeMaps.end(); ++smIt ) {
1061 if ( !smIt->second.empty() ) {
1062 MESSAGE("cadsurf_set_sizeMap(): " << smIt->first << " = " << smIt->second);
1063 GeomShape = entryToShape(smIt->first);
1064 GeomType = GeomShape.ShapeType();
1065 MESSAGE("Geomtype is " << GeomType);
1068 if (GeomType == TopAbs_COMPOUND) {
1069 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1071 if (it.Value().ShapeType() == TopAbs_FACE){
1072 HasSizeMapOnFace = true;
1073 if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
1074 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
1077 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
1078 // MESSAGE("Face with key " << key << " already in map");
1080 FaceId2SizeMap[key] = smIt->second;
1083 if (it.Value().ShapeType() == TopAbs_EDGE){
1084 HasSizeMapOnEdge = true;
1085 HasSizeMapOnFace = true;
1086 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
1087 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
1090 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
1091 // MESSAGE("Edge with key " << key << " already in map");
1093 EdgeId2SizeMap[key] = smIt->second;
1095 // Group of vertices
1096 if (it.Value().ShapeType() == TopAbs_VERTEX){
1097 HasSizeMapOnVertex = true;
1098 HasSizeMapOnEdge = true;
1099 HasSizeMapOnFace = true;
1100 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
1101 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
1104 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
1105 MESSAGE("Group of vertices with key " << key << " already in map");
1107 MESSAGE("Group of vertices with key " << key << " has a size map: " << smIt->second);
1108 VertexId2SizeMap[key] = smIt->second;
1113 if (GeomType == TopAbs_FACE){
1114 HasSizeMapOnFace = true;
1115 if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
1116 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
1119 key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
1120 // MESSAGE("Face with key " << key << " already in map");
1122 FaceId2SizeMap[key] = smIt->second;
1125 if (GeomType == TopAbs_EDGE){
1126 HasSizeMapOnEdge = true;
1127 HasSizeMapOnFace = true;
1128 if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
1129 key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
1132 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
1133 // MESSAGE("Edge with key " << key << " already in map");
1135 EdgeId2SizeMap[key] = smIt->second;
1138 if (GeomType == TopAbs_VERTEX){
1139 HasSizeMapOnVertex = true;
1140 HasSizeMapOnEdge = true;
1141 HasSizeMapOnFace = true;
1142 if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
1143 key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
1146 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
1147 MESSAGE("Vertex with key " << key << " already in map");
1149 MESSAGE("Vertex with key " << key << " has a size map: " << smIt->second);
1150 VertexId2SizeMap[key] = smIt->second;
1158 // TODO appeler le constructeur des attracteurs directement ici
1159 MESSAGE("Setting Attractors");
1160 // if ( !_phySizeRel ) {
1161 const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
1162 BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
1163 for ( ; atIt != attractors.end(); ++atIt ) {
1164 if ( !atIt->second.empty() ) {
1165 MESSAGE("cadsurf_set_attractor(): " << atIt->first << " = " << atIt->second);
1166 GeomShape = entryToShape(atIt->first);
1167 GeomType = GeomShape.ShapeType();
1169 if (GeomType == TopAbs_COMPOUND){
1170 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1171 if (it.Value().ShapeType() == TopAbs_FACE){
1172 HasSizeMapOnFace = true;
1173 createAttractorOnFace(it.Value(), atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1178 if (GeomType == TopAbs_FACE){
1179 HasSizeMapOnFace = true;
1180 createAttractorOnFace(GeomShape, atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1183 if (GeomType == TopAbs_EDGE){
1184 HasSizeMapOnEdge = true;
1185 HasSizeMapOnFace = true;
1186 EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
1188 if (GeomType == TopAbs_VERTEX){
1189 HasSizeMapOnVertex = true;
1190 HasSizeMapOnEdge = true;
1191 HasSizeMapOnFace = true;
1192 VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
1199 // MESSAGE("Impossible to create the attractors when the physical size is relative");
1202 // temporary commented out for testing
1204 // - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
1205 // - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
1206 // - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
1208 // - Construct the attractors with an empty dist. map in the hypothesis
1209 // - 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()
1210 // -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap() OK
1212 theNbAttractors = 0;
1213 const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
1215 BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
1216 for ( ; AtIt != class_attractors.end(); ++AtIt ) {
1217 if ( !AtIt->second->Empty() ) {
1218 // MESSAGE("cadsurf_set_attractor(): " << AtIt->first << " = " << AtIt->second);
1219 GeomShape = entryToShape(AtIt->first);
1220 if ( !SMESH_MesherHelper::IsSubShape( GeomShape, theGeomShape ))
1222 AttShape = AtIt->second->GetAttractorShape();
1223 GeomType = GeomShape.ShapeType();
1225 // if (GeomType == TopAbs_COMPOUND){
1226 // for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1227 // if (it.Value().ShapeType() == TopAbs_FACE){
1228 // HasAttractorOnFace = true;
1229 // myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
1234 if (GeomType == TopAbs_FACE
1235 && (AttShape.ShapeType() == TopAbs_VERTEX
1236 || AttShape.ShapeType() == TopAbs_EDGE
1237 || AttShape.ShapeType() == TopAbs_WIRE
1238 || AttShape.ShapeType() == TopAbs_COMPOUND) ){
1239 HasSizeMapOnFace = true;
1241 key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
1243 FaceId2ClassAttractor[key].push_back( AtIt->second );
1247 MESSAGE("Wrong shape type !!")
1255 // Enforced Vertices
1257 MESSAGE("Setting Enforced Vertices");
1258 const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
1259 BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
1260 for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
1261 if ( !enfIt->second.empty() ) {
1262 GeomShape = entryToShape(enfIt->first);
1263 GeomType = GeomShape.ShapeType();
1265 if (GeomType == TopAbs_COMPOUND){
1266 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1267 if (it.Value().ShapeType() == TopAbs_FACE){
1268 HasSizeMapOnFace = true;
1269 createEnforcedVertexOnFace(it.Value(), enfIt->second);
1274 if (GeomType == TopAbs_FACE){
1275 HasSizeMapOnFace = true;
1276 createEnforcedVertexOnFace(GeomShape, enfIt->second);
1281 // Internal vertices
1282 bool useInternalVertexAllFaces = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFaces(hyp);
1283 if (useInternalVertexAllFaces) {
1284 std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
1285 MESSAGE("Setting Internal Enforced Vertices");
1287 TopExp_Explorer exp (theGeomShape, TopAbs_FACE);
1288 for (; exp.More(); exp.Next()){
1289 MESSAGE("Iterating shapes. Shape type is " << exp.Current().ShapeType());
1290 TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX, TopAbs_EDGE);
1291 for (; exp_face.More(); exp_face.Next())
1293 // Get coords of vertex
1294 // Check if current coords is already in enfVertexList
1295 // If coords not in enfVertexList, add new enfVertex
1296 aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1297 MESSAGE("Found vertex on face at " << aPnt.X() <<", "<<aPnt.Y()<<", "<<aPnt.Z());
1298 BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1299 enfVertex->coords.push_back(aPnt.X());
1300 enfVertex->coords.push_back(aPnt.Y());
1301 enfVertex->coords.push_back(aPnt.Z());
1302 enfVertex->name = "";
1303 enfVertex->faceEntries.clear();
1304 enfVertex->geomEntry = "";
1305 enfVertex->grpName = grpName;
1306 enfVertex->vertex = TopoDS::Vertex( exp_face.Current() );
1307 _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()), aPnt, enfVertex);
1308 HasSizeMapOnFace = true;
1313 MESSAGE("Setting Size Map on FACES ");
1314 cadsurf_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
1316 if (HasSizeMapOnEdge){
1317 MESSAGE("Setting Size Map on EDGES ");
1318 cadsurf_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
1320 if (HasSizeMapOnVertex){
1321 MESSAGE("Setting Size Map on VERTICES ");
1322 cadsurf_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
1329 _preCadFacesIDsPeriodicityVector.clear();
1330 _preCadEdgesIDsPeriodicityVector.clear();
1332 MESSAGE("SetParameters preCadFacesPeriodicityVector");
1333 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadFacesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadFacesPeriodicityVector(hyp);
1335 for (std::size_t i = 0; i<preCadFacesPeriodicityVector.size(); i++){
1336 MESSAGE("SetParameters preCadFacesPeriodicityVector[" << i << "]");
1337 createPreCadFacesPeriodicity(theGeomShape, preCadFacesPeriodicityVector[i]);
1339 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
1341 MESSAGE("SetParameters preCadEdgesPeriodicityVector");
1342 const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadEdgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadEdgesPeriodicityVector(hyp);
1344 for (std::size_t i = 0; i<preCadEdgesPeriodicityVector.size(); i++){
1345 MESSAGE("SetParameters preCadEdgesPeriodicityVector[" << i << "]");
1346 createPreCadEdgesPeriodicity(theGeomShape, preCadEdgesPeriodicityVector[i]);
1348 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
1352 //================================================================================
1354 * \brief Throws an exception if a parameter name is wrong
1356 //================================================================================
1358 void BLSURFPlugin_BLSURF::set_param(cadsurf_session_t *css,
1359 const char * option_name,
1360 const char * option_value)
1362 status_t status = cadsurf_set_param(css, option_name, option_value );
1364 if ( _hypothesis && _hypothesis->GetVerbosity() > _hypothesis->GetDefaultVerbosity() )
1365 cout << option_name << " = " << option_value << endl;
1367 if ( status != MESHGEMS_STATUS_OK )
1369 if ( status == MESHGEMS_STATUS_UNKNOWN_PARAMETER ) {
1370 throw SALOME_Exception
1371 ( SMESH_Comment("Invalid name of CADSURF parameter: ") << option_name );
1373 else if ( status == MESHGEMS_STATUS_NOLICENSE )
1374 throw SALOME_Exception
1375 ( "No valid license available" );
1377 throw SALOME_Exception
1378 ( SMESH_Comment("Either wrong name or unacceptable value of CADSURF parameter '")
1379 << option_name << "': " << option_value);
1385 // --------------------------------------------------------------------------
1387 * \brief Class correctly terminating usage of MG-CADSurf library at destruction
1389 class BLSURF_Cleaner
1392 cadsurf_session_t* _css;
1396 BLSURF_Cleaner(context_t * ctx,
1397 cadsurf_session_t* css,
1408 Clean( /*exceptContext=*/false );
1410 void Clean(const bool exceptContext)
1414 cadsurf_session_delete(_css); _css = 0;
1416 // #if BLSURF_VERSION_LONG >= "3.1.1"
1417 // // if(geo_sizemap_e)
1418 // // distene_sizemap_delete(geo_sizemap_e);
1419 // // if(geo_sizemap_f)
1420 // // distene_sizemap_delete(geo_sizemap_f);
1421 // if(iso_sizemap_p)
1422 // distene_sizemap_delete(iso_sizemap_p);
1423 // if(iso_sizemap_e)
1424 // distene_sizemap_delete(iso_sizemap_e);
1425 // if(iso_sizemap_f)
1426 // distene_sizemap_delete(iso_sizemap_f);
1428 // // if(clean_geo_sizemap_e)
1429 // // distene_sizemap_delete(clean_geo_sizemap_e);
1430 // // if(clean_geo_sizemap_f)
1431 // // distene_sizemap_delete(clean_geo_sizemap_f);
1432 // if(clean_iso_sizemap_p)
1433 // distene_sizemap_delete(clean_iso_sizemap_p);
1434 // if(clean_iso_sizemap_e)
1435 // distene_sizemap_delete(clean_iso_sizemap_e);
1436 // if(clean_iso_sizemap_f)
1437 // distene_sizemap_delete(clean_iso_sizemap_f);
1440 cad_delete(_cad); _cad = 0;
1441 dcad_delete(_dcad); _dcad = 0;
1442 if ( !exceptContext )
1444 context_delete(_ctx); _ctx = 0;
1450 // --------------------------------------------------------------------------
1451 // comparator to sort nodes and sub-meshes
1452 struct ShapeTypeCompare
1454 // sort nodes by position in the following order:
1455 // SMDS_TOP_FACE=2, SMDS_TOP_EDGE=1, SMDS_TOP_VERTEX=0, SMDS_TOP_3DSPACE=3
1456 bool operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
1458 // NEW ORDER: nodes earlier added to sub-mesh are considered "less"
1459 return n1->getIdInShape() < n2->getIdInShape();
1460 // SMDS_TypeOfPosition pos1 = n1->GetPosition()->GetTypeOfPosition();
1461 // SMDS_TypeOfPosition pos2 = n2->GetPosition()->GetTypeOfPosition();
1462 // if ( pos1 == pos2 ) return 0;
1463 // if ( pos1 < pos2 || pos1 == SMDS_TOP_3DSPACE ) return 1;
1466 // sort sub-meshes in order: EDGE, VERTEX
1467 bool operator()( const SMESHDS_SubMesh* s1, const SMESHDS_SubMesh* s2 ) const
1469 int isVertex1 = ( s1 && s1->NbElements() == 0 );
1470 int isVertex2 = ( s2 && s2->NbElements() == 0 );
1471 if ( isVertex1 == isVertex2 )
1473 return isVertex1 < isVertex2;
1477 //================================================================================
1479 * \brief Fills groups of nodes to be merged
1481 //================================================================================
1483 void getNodeGroupsToMerge( const SMESHDS_SubMesh* smDS,
1484 const TopoDS_Shape& shape,
1485 SMESH_MeshEditor::TListOfListOfNodes& nodeGroupsToMerge)
1487 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1488 switch ( shape.ShapeType() )
1490 case TopAbs_VERTEX: {
1491 std::list< const SMDS_MeshNode* > nodes;
1492 while ( nIt->more() )
1493 nodes.push_back( nIt->next() );
1494 if ( nodes.size() > 1 )
1495 nodeGroupsToMerge.push_back( nodes );
1499 std::multimap< double, const SMDS_MeshNode* > u2node;
1500 const SMDS_EdgePosition* ePos;
1501 while ( nIt->more() )
1503 const SMDS_MeshNode* n = nIt->next();
1504 if (( ePos = dynamic_cast< const SMDS_EdgePosition* >( n->GetPosition() )))
1505 u2node.insert( make_pair( ePos->GetUParameter(), n ));
1507 if ( u2node.size() < 2 ) return;
1509 //double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
1511 BRep_Tool::Range( TopoDS::Edge( shape ), f,l );
1512 double tol = (( l - f ) / 20.) / u2node.size();
1514 std::multimap< double, const SMDS_MeshNode* >::iterator un2, un1;
1515 for ( un2 = u2node.begin(), un1 = un2++; un2 != u2node.end(); un1 = un2++ )
1517 if (( un2->first - un1->first ) <= tol )
1519 std::list< const SMDS_MeshNode* > nodes;
1520 nodes.push_back( un1->second );
1521 while (( un2->first - un1->first ) <= tol )
1523 nodes.push_back( un2->second );
1524 if ( ++un2 == u2node.end()) {
1529 // make nodes created on the boundary of viscous layer replace nodes created
1530 // by MG-CADSurf as their SMDS_Position is more correct
1531 nodes.sort( ShapeTypeCompare() );
1532 nodeGroupsToMerge.push_back( nodes );
1539 // SMESH_MeshEditor::TListOfListOfNodes::const_iterator nll = nodeGroupsToMerge.begin();
1540 // for ( ; nll != nodeGroupsToMerge.end(); ++nll )
1542 // cout << "Merge ";
1543 // const std::list< const SMDS_MeshNode* >& nl = *nll;
1544 // std::list< const SMDS_MeshNode* >::const_iterator nIt = nl.begin();
1545 // for ( ; nIt != nl.end(); ++nIt )
1546 // cout << (*nIt) << " ";
1552 //================================================================================
1554 * \brief A temporary mesh used to compute mesh on a proxy FACE
1556 //================================================================================
1558 struct TmpMesh: public SMESH_Mesh
1560 typedef std::map<const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
1561 TN2NMap _tmp2origNN;
1562 TopoDS_Face _proxyFace;
1566 _myMeshDS = new SMESHDS_Mesh( _id, true );
1568 //--------------------------------------------------------------------------------
1570 * \brief Creates a FACE bound by viscous layers and mesh each its EDGE with 1 segment
1572 //--------------------------------------------------------------------------------
1574 const TopoDS_Face& makeProxyFace( SMESH_ProxyMesh::Ptr& viscousMesh,
1575 const TopoDS_Face& origFace)
1577 // get data of nodes on inner boundary of viscous layers
1578 SMESH_Mesh* origMesh = viscousMesh->GetMesh();
1580 TSideVector wireVec = StdMeshers_FaceSide::GetFaceWires(origFace, *origMesh,
1581 /*skipMediumNodes = */true,
1583 if ( err && err->IsKO() )
1584 throw *err.get(); // it should be caught at SMESH_subMesh
1586 // proxy nodes and corresponding tmp VERTEXes
1587 std::vector<const SMDS_MeshNode*> origNodes;
1588 std::vector<TopoDS_Vertex> tmpVertex;
1590 // create a proxy FACE
1591 TopoDS_Shape origFaceCopy = origFace.EmptyCopied();
1592 BRepBuilderAPI_MakeFace newFace( TopoDS::Face( origFaceCopy ));
1593 for ( size_t iW = 0; iW != wireVec.size(); ++iW )
1595 StdMeshers_FaceSidePtr& wireData = wireVec[iW];
1596 const UVPtStructVec& wirePoints = wireData->GetUVPtStruct();
1597 if ( wirePoints.size() < 3 )
1600 BRepBuilderAPI_MakePolygon wire;
1601 const size_t i0 = tmpVertex.size();
1602 for ( size_t iN = 0; iN < wirePoints.size(); ++iN )
1604 wire.Add( SMESH_TNodeXYZ( wirePoints[ iN ].node ));
1605 origNodes.push_back( wirePoints[ iN ].node );
1606 tmpVertex.push_back( wire.LastVertex() );
1608 tmpVertex[ i0 ] = wire.FirstVertex(); // wire.LastVertex()==NULL for 1 vertex in wire
1610 if ( !wire.IsDone() )
1611 throw SALOME_Exception("BLSURFPlugin_BLSURF: BRepBuilderAPI_MakePolygon failed");
1612 newFace.Add( wire );
1614 _proxyFace = newFace;
1616 // set a new shape to mesh
1617 TopoDS_Compound auxCompoundToMesh;
1618 BRep_Builder shapeBuilder;
1619 shapeBuilder.MakeCompound( auxCompoundToMesh );
1620 shapeBuilder.Add( auxCompoundToMesh, _proxyFace );
1621 shapeBuilder.Add( auxCompoundToMesh, origMesh->GetShapeToMesh() );
1623 ShapeToMesh( auxCompoundToMesh );
1625 //TopExp_Explorer fExp( auxCompoundToMesh, TopAbs_FACE );
1626 //_proxyFace = TopoDS::Face( fExp.Current() );
1629 // Make input mesh for MG-CADSurf: segments on EDGE's of newFace
1631 // make nodes and fill in _tmp2origNN
1633 SMESHDS_Mesh* tmpMeshDS = GetMeshDS();
1634 for ( size_t i = 0; i < origNodes.size(); ++i )
1636 GetSubMesh( tmpVertex[i] )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1637 if ( const SMDS_MeshNode* tmpN = SMESH_Algo::VertexNode( tmpVertex[i], tmpMeshDS ))
1638 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( tmpN, origNodes[i] ));
1640 throw SALOME_Exception("BLSURFPlugin_BLSURF: a proxy vertex not meshed");
1644 TopoDS_Vertex v1, v2;
1645 for ( TopExp_Explorer edge( _proxyFace, TopAbs_EDGE ); edge.More(); edge.Next() )
1647 const TopoDS_Edge& E = TopoDS::Edge( edge.Current() );
1648 TopExp::Vertices( E, v1, v2 );
1649 const SMDS_MeshNode* n1 = SMESH_Algo::VertexNode( v1, tmpMeshDS );
1650 const SMDS_MeshNode* n2 = SMESH_Algo::VertexNode( v2, tmpMeshDS );
1652 if ( SMDS_MeshElement* seg = tmpMeshDS->AddEdge( n1, n2 ))
1653 tmpMeshDS->SetMeshElementOnShape( seg, E );
1659 //--------------------------------------------------------------------------------
1661 * \brief Fill in the origMesh with faces computed by MG-CADSurf in this tmp mesh
1663 //--------------------------------------------------------------------------------
1665 void FillInOrigMesh( SMESH_Mesh& origMesh,
1666 const TopoDS_Face& origFace )
1668 SMESH_MesherHelper helper( origMesh );
1669 helper.SetSubShape( origFace );
1670 helper.SetElementsOnShape( true );
1672 SMESH_MesherHelper tmpHelper( *this );
1673 tmpHelper.SetSubShape( _proxyFace );
1675 // iterate over tmp faces and copy them in origMesh
1676 const SMDS_MeshNode* nodes[27];
1677 const SMDS_MeshNode* nullNode = 0;
1679 SMDS_FaceIteratorPtr fIt = GetMeshDS()->facesIterator(/*idInceasingOrder=*/true);
1680 while ( fIt->more() )
1682 const SMDS_MeshElement* f = fIt->next();
1683 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
1685 for ( ; nIt->more(); ++nbN )
1687 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
1688 TN2NMap::iterator n2nIt =
1689 _tmp2origNN.insert( _tmp2origNN.end(), make_pair( n, nullNode ));
1690 if ( !n2nIt->second ) {
1692 gp_XY uv = tmpHelper.GetNodeUV( _proxyFace, n );
1693 n2nIt->second = helper.AddNode( xyz[0], xyz[1], xyz[2], uv.X(), uv.Y() );
1695 nodes[ nbN ] = n2nIt->second;
1698 case 3: helper.AddFace( nodes[0], nodes[1], nodes[2] ); break;
1699 // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
1700 // nodes[3], nodes[4], nodes[5]); break;
1701 case 4: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
1702 // case 9: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1703 // nodes[4], nodes[5], nodes[6], nodes[7], nodes[8]); break;
1704 // case 8: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1705 // nodes[4], nodes[5], nodes[6], nodes[7]); break;
1712 * \brief A structure holding an error description and a verbisity level
1714 struct message_cb_user_data
1716 std::string * _error;
1723 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1724 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1725 real *duu, real *duv, real *dvv, void *user_data);
1726 status_t message_cb(message_t *msg, void *user_data);
1727 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1729 //=============================================================================
1733 //=============================================================================
1735 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape) {
1737 MESSAGE("BLSURFPlugin_BLSURF::Compute");
1739 // Fix problem with locales
1740 Kernel_Utils::Localizer aLocalizer;
1742 this->SMESH_Algo::_progress = 1e-3; // prevent progress advancment while computing attractors
1744 bool viscousLayersMade =
1745 ( aShape.ShapeType() == TopAbs_FACE &&
1746 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( aShape ), aMesh ));
1748 if ( !viscousLayersMade )
1749 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1752 if ( _haveViscousLayers || viscousLayersMade )
1754 // Compute viscous layers
1756 TopTools_MapOfShape map;
1757 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1759 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1760 if ( !map.Add( F )) continue;
1761 SMESH_ProxyMesh::Ptr viscousMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
1763 return false; // error in StdMeshers_ViscousLayers2D::Compute()
1765 // Compute MG-CADSurf mesh on viscous layers
1767 if ( viscousMesh->NbProxySubMeshes() > 0 )
1770 const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
1771 if ( !compute( tmpMesh, proxyFace, /*allowSubMeshClearing=*/false ))
1773 tmpMesh.FillInOrigMesh( aMesh, F );
1777 // Re-compute MG-CADSurf mesh on the rest faces if the mesh was cleared
1779 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1781 const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1782 SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
1783 if ( fSM->IsMeshComputed() ) continue;
1785 if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1793 //=============================================================================
1797 //=============================================================================
1799 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh& aMesh,
1800 const TopoDS_Shape& aShape,
1801 bool allowSubMeshClearing)
1803 /* create a distene context (generic object) */
1804 status_t status = STATUS_ERROR;
1807 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1808 SMESH_MesherHelper helper( aMesh );
1809 // do not call helper.IsQuadraticSubMesh() because sub-meshes
1810 // may be cleaned and helper.myTLinkNodeMap gets invalid in such a case
1811 bool haveQuadraticSubMesh = SMESH_MesherHelper( aMesh ).IsQuadraticSubMesh( aShape );
1812 bool quadraticSubMeshAndViscousLayer = false;
1813 bool needMerge = false;
1814 typedef set< SMESHDS_SubMesh*, ShapeTypeCompare > TSubMeshSet;
1815 TSubMeshSet edgeSubmeshes;
1816 TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
1818 TopTools_IndexedMapOfShape pmap, emap, fmap;
1820 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1822 feclearexcept( FE_ALL_EXCEPT );
1823 int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1826 context_t *ctx = context_new();
1828 /* Set the message callback in the working context */
1829 message_cb_user_data mcud;
1830 mcud._error = & this->SMESH_Algo::_comment;
1831 mcud._progress = & this->SMESH_Algo::_progress;
1833 _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
1834 context_set_message_callback(ctx, message_cb, &mcud);
1836 /* set the interruption callback */
1837 _compute_canceled = false;
1838 context_set_interrupt_callback(ctx, interrupt_cb, this);
1840 /* create the CAD object we will work on. It is associated to the context ctx. */
1841 cad_t *c = cad_new(ctx);
1842 dcad_t *dcad = dcad_new(c);
1844 FacesWithSizeMap.Clear();
1845 FaceId2SizeMap.clear();
1846 FaceId2ClassAttractor.clear();
1847 FaceIndex2ClassAttractor.clear();
1848 EdgesWithSizeMap.Clear();
1849 EdgeId2SizeMap.clear();
1850 VerticesWithSizeMap.Clear();
1851 VertexId2SizeMap.clear();
1853 /* Now fill the CAD object with data from your CAD
1854 * environement. This is the most complex part of a successfull
1860 cadsurf_session_t *css = cadsurf_session_new(ctx);
1862 // an object that correctly deletes all cadsurf objects at destruction
1863 BLSURF_Cleaner cleaner( ctx,css,c,dcad );
1865 MESSAGE("BEGIN SetParameters");
1866 SetParameters(_hypothesis, css, aShape);
1867 MESSAGE("END SetParameters");
1869 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
1871 haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis != NULL && _hypothesis->GetQuadraticMesh());
1872 helper.SetIsQuadratic( haveQuadraticSubMesh );
1874 // To remove as soon as quadratic mesh is allowed - BEGIN
1875 // GDD: Viscous layer is not allowed with quadratic mesh
1876 if (_haveViscousLayers && haveQuadraticSubMesh ) {
1877 quadraticSubMeshAndViscousLayer = true;
1878 _haveViscousLayers = !haveQuadraticSubMesh;
1879 _comment += "Warning: Viscous layer is not possible with a quadratic mesh, it is ignored.";
1880 error(COMPERR_WARNING, _comment);
1882 // To remove as soon as quadratic mesh is allowed - END
1884 // needed to prevent the opencascade memory managmement from freeing things
1885 vector<Handle(Geom2d_Curve)> curves;
1886 vector<Handle(Geom_Surface)> surfaces;
1890 FaceId2PythonSmp.clear();
1891 EdgeId2PythonSmp.clear();
1892 VertexId2PythonSmp.clear();
1894 /****************************************************************************************
1896 *****************************************************************************************/
1898 string bad_end = "return";
1900 TopTools_IndexedMapOfShape _map;
1901 TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
1902 int ienf = _map.Extent();
1904 assert(Py_IsInitialized());
1905 PyGILState_STATE gstate;
1907 string theSizeMapStr;
1909 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1911 TopoDS_Face f = TopoDS::Face(face_iter.Current());
1913 SMESH_subMesh* fSM = aMesh.GetSubMesh( f );
1914 if ( !fSM->IsEmpty() ) continue; // skip already meshed FACE with viscous layers
1916 // make INTERNAL face oriented FORWARD (issue 0020993)
1917 if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
1918 f.Orientation(TopAbs_FORWARD);
1920 iface = fmap.Add(f);
1921 // std::string aFileName = "fmap_face_";
1922 // aFileName.append(val_to_string(iface));
1923 // aFileName.append(".brep");
1924 // BRepTools::Write(f,aFileName.c_str());
1926 surfaces.push_back(BRep_Tool::Surface(f));
1928 /* create an object representing the face for cadsurf */
1929 /* where face_id is an integer identifying the face.
1930 * surf_function is the function that defines the surface
1931 * (For this face, it will be called by cadsurf with your_face_object_ptr
1932 * as last parameter.
1934 #if OCC_VERSION_MAJOR < 7
1935 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back());
1937 cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back().get());
1940 /* by default a face has no tag (color).
1941 The following call sets it to the same value as the Geom module ID : */
1942 const int faceTag = meshDS->ShapeToIndex(f);
1943 cad_face_set_tag(fce, faceTag);
1945 /* Set face orientation (optional if you want a well oriented output mesh)*/
1946 if(f.Orientation() != TopAbs_FORWARD)
1947 cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
1949 cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
1951 if (HasSizeMapOnFace /*&& !use_precad*/) //22903: use_precad seems not to interfere
1953 // -----------------
1955 // -----------------
1956 faceKey = FacesWithSizeMap.FindIndex(f);
1959 if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end()) {
1960 MESSAGE("A size map is defined on face :"<<faceKey);
1961 theSizeMapStr = FaceId2SizeMap[faceKey];
1962 // check if function ends with "return"
1963 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
1965 // Expr To Python function, verification is performed at validation in GUI
1966 gstate = PyGILState_Ensure();
1967 PyObject * obj = NULL;
1968 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
1970 PyObject * func = NULL;
1971 func = PyObject_GetAttrString(main_mod, "f");
1972 FaceId2PythonSmp[iface]=func;
1973 FaceId2SizeMap.erase(faceKey);
1974 PyGILState_Release(gstate);
1977 // Specific size map = Attractor
1978 std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
1980 for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
1981 if (attractor_iter->first == faceKey) {
1982 MESSAGE("Face indice: " << iface);
1983 MESSAGE("Adding attractor");
1985 double xyzCoords[3] = {attractor_iter->second[2],
1986 attractor_iter->second[3],
1987 attractor_iter->second[4]};
1989 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
1990 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
1991 BRepClass_FaceClassifier scl(f,P,1e-7);
1992 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
1993 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
1994 // OCC 6.5.2: scl.Perform() is not bugged anymore
1995 scl.Perform(f, P, 1e-7);
1996 TopAbs_State result = scl.State();
1997 MESSAGE("Position of point on face: "<<result);
1998 if ( result == TopAbs_OUT )
1999 MESSAGE("Point is out of face: node is not created");
2000 if ( result == TopAbs_UNKNOWN )
2001 MESSAGE("Point position on face is unknown: node is not created");
2002 if ( result == TopAbs_ON )
2003 MESSAGE("Point is on border of face: node is not created");
2004 if ( result == TopAbs_IN )
2006 // Point is inside face and not on border
2007 MESSAGE("Point is in face: node is created");
2008 double uvCoords[2] = {attractor_iter->second[0],attractor_iter->second[1]};
2010 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2011 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2012 cad_point_set_tag(point_p, ienf);
2014 FaceId2AttractorCoords.erase(faceKey);
2018 // -----------------
2020 // -----------------
2021 TId2ClsAttractorVec::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
2022 if (clAttractor_iter != FaceId2ClassAttractor.end()){
2023 MESSAGE("Face indice: " << iface);
2024 MESSAGE("Adding attractor");
2025 std::vector< BLSURFPlugin_Attractor* > & attVec = clAttractor_iter->second;
2026 for ( size_t i = 0; i < attVec.size(); ++i )
2027 if ( !attVec[i]->IsMapBuilt() ) {
2028 std::cout<<"Compute " << theNbAttractors-- << "-th attractor" <<std::endl;
2029 attVec[i]->BuildMap();
2031 FaceIndex2ClassAttractor[iface].swap( attVec );
2032 FaceId2ClassAttractor.erase(clAttractor_iter);
2034 } // if (HasSizeMapOnFace && !use_precad)
2036 // ------------------
2037 // Enforced Vertices
2038 // ------------------
2039 faceKey = FacesWithEnforcedVertices.FindIndex(f);
2040 std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
2041 if (evmIt != FaceId2EnforcedVertexCoords.end()) {
2042 MESSAGE("Some enforced vertices are defined");
2043 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl;
2044 MESSAGE("Face indice: " << iface);
2045 MESSAGE("Adding enforced vertices");
2046 evl = evmIt->second;
2047 MESSAGE("Number of vertices to add: "<< evl.size());
2048 BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
2049 for (; evlIt != evl.end(); ++evlIt) {
2050 BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
2051 xyzCoords.push_back(evlIt->at(2));
2052 xyzCoords.push_back(evlIt->at(3));
2053 xyzCoords.push_back(evlIt->at(4));
2054 MESSAGE("Check position of vertex =(" << xyzCoords[0] << "," << xyzCoords[1] << "," << xyzCoords[2] << ")");
2055 gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2056 BRepClass_FaceClassifier scl(f,P,1e-7);
2057 // OCC 6.3sp6 : scl.Perform() is bugged. The function was rewritten
2058 // BRepClass_FaceClassifierPerform(&scl,f,P,1e-7);
2059 // OCC 6.5.2: scl.Perform() is not bugged anymore
2060 scl.Perform(f, P, 1e-7);
2061 TopAbs_State result = scl.State();
2062 MESSAGE("Position of point on face: "<<result);
2063 if ( result == TopAbs_OUT ) {
2064 MESSAGE("Point is out of face: node is not created");
2065 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2066 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2067 // isssue 22783. Do not erase as this point can be IN other face of a group
2068 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2071 if ( result == TopAbs_UNKNOWN ) {
2072 MESSAGE("Point position on face is unknown: node is not created");
2073 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2074 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2075 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2078 if ( result == TopAbs_ON ) {
2079 MESSAGE("Point is on border of face: node is not created");
2080 if (EnfVertexCoords2ProjVertex.find(xyzCoords) != EnfVertexCoords2ProjVertex.end()) {
2081 EnfVertexCoords2ProjVertex.erase(xyzCoords);
2082 //EnfVertexCoords2EnfVertexList.erase(xyzCoords);
2085 if ( result == TopAbs_IN )
2087 // Point is inside face and not on border
2088 MESSAGE("Point is in face: node is created");
2089 double uvCoords[2] = {evlIt->at(0),evlIt->at(1)};
2091 MESSAGE("Add cad point on (u,v)=(" << uvCoords[0] << "," << uvCoords[1] << ") with id = " << ienf);
2092 cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2094 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(xyzCoords);
2095 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end() &&
2096 !enfCoordsIt->second.empty() )
2098 // to merge nodes of an INTERNAL vertex belonging to several faces
2099 TopoDS_Vertex v = (*enfCoordsIt->second.begin())->vertex;
2100 if ( v.IsNull() ) v = (*enfCoordsIt->second.rbegin())->vertex;
2101 if ( !v.IsNull() ) {
2102 tag = pmap.Add( v );
2103 SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
2104 vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2105 mergeSubmeshes.insert( vSM->GetSubMeshDS() );
2106 // //if ( tag != pmap.Extent() )
2107 // needMerge = true;
2110 if ( tag == 0 ) tag = ienf;
2111 cad_point_set_tag(point_p, tag);
2114 FaceId2EnforcedVertexCoords.erase(faceKey);
2118 /****************************************************************************************
2120 now create the edges associated to this face
2121 *****************************************************************************************/
2123 for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next())
2125 TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
2126 int ic = emap.FindIndex(e);
2130 // std::string aFileName = "fmap_edge_";
2131 // aFileName.append(val_to_string(ic));
2132 // aFileName.append(".brep");
2133 // BRepTools::Write(e,aFileName.c_str());
2136 curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
2138 if (HasSizeMapOnEdge){
2139 edgeKey = EdgesWithSizeMap.FindIndex(e);
2140 if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end()) {
2141 MESSAGE("Sizemap defined on edge with index " << edgeKey);
2142 theSizeMapStr = EdgeId2SizeMap[edgeKey];
2143 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2145 // Expr To Python function, verification is performed at validation in GUI
2146 gstate = PyGILState_Ensure();
2147 PyObject * obj = NULL;
2148 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2150 PyObject * func = NULL;
2151 func = PyObject_GetAttrString(main_mod, "f");
2152 EdgeId2PythonSmp[ic]=func;
2153 EdgeId2SizeMap.erase(edgeKey);
2154 PyGILState_Release(gstate);
2157 /* data of nodes existing on the edge */
2158 StdMeshers_FaceSidePtr nodeData;
2159 SMESH_subMesh* sm = aMesh.GetSubMesh( e );
2160 if ( !sm->IsEmpty() )
2162 // SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
2163 // /*complexFirst=*/false);
2164 // while ( subsmIt->more() )
2165 // edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
2166 edgeSubmeshes.insert( sm->GetSubMeshDS() );
2168 nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
2169 /*ignoreMedium=*/haveQuadraticSubMesh));
2170 if ( nodeData->MissVertexNode() )
2171 return error(COMPERR_BAD_INPUT_MESH,"No node on vertex");
2173 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2174 if ( !nodeDataVec.empty() )
2176 if ( Abs( nodeDataVec[0].param - tmin ) > Abs( nodeDataVec.back().param - tmin ))
2178 nodeData->Reverse();
2179 nodeData->GetUVPtStruct(); // nodeData recomputes nodeDataVec
2181 // tmin and tmax can change in case of viscous layer on an adjacent edge
2182 tmin = nodeDataVec.front().param;
2183 tmax = nodeDataVec.back().param;
2187 cout << "---------------- Invalid nodeData" << endl;
2192 /* attach the edge to the current cadsurf face */
2193 #if OCC_VERSION_MAJOR < 7
2194 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back());
2196 cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back().get());
2199 /* by default an edge has no tag (color).
2200 The following call sets it to the same value as the edge_id : */
2201 cad_edge_set_tag(edg, ic);
2203 /* by default, an edge does not necessalry appear in the resulting mesh,
2204 unless the following property is set :
2206 cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
2208 /* by default an edge is a boundary edge */
2209 if (e.Orientation() == TopAbs_INTERNAL)
2210 cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
2212 // pass existing nodes of sub-meshes to MG-CADSurf
2215 const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2216 const int nbNodes = nodeDataVec.size();
2218 dcad_edge_discretization_t *dedge;
2219 dcad_get_edge_discretization(dcad, edg, &dedge);
2220 dcad_edge_discretization_set_vertex_count( dedge, nbNodes );
2222 // cout << endl << " EDGE " << ic << endl;
2223 // cout << "tmin = "<<tmin << ", tmax = "<< tmax << endl;
2224 for ( int iN = 0; iN < nbNodes; ++iN )
2226 const UVPtStruct& nData = nodeDataVec[ iN ];
2227 double t = nData.param;
2228 real uv[2] = { nData.u, nData.v };
2229 SMESH_TNodeXYZ nXYZ( nData.node );
2230 // cout << "\tt = " << t
2231 // << "\t uv = ( " << uv[0] << ","<< uv[1] << " ) "
2232 // << "\t u = " << nData.param
2233 // << "\t ID = " << nData.node->GetID() << endl;
2234 dcad_edge_discretization_set_vertex_coordinates( dedge, iN+1, t, uv, nXYZ._xyz );
2236 dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2239 /****************************************************************************************
2241 *****************************************************************************************/
2245 gp_Pnt2d e0 = curves.back()->Value(tmin);
2246 gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
2247 Standard_Real d1=0,d2=0;
2250 for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
2251 TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
2255 d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2258 d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2260 *ip = pmap.FindIndex(v);
2263 // SMESH_subMesh* sm = aMesh.GetSubMesh(v);
2264 // if ( sm->IsMeshComputed() )
2265 // edgeSubmeshes.insert( sm->GetSubMeshDS() );
2268 // std::string aFileName = "fmap_vertex_";
2269 // aFileName.append(val_to_string(*ip));
2270 // aFileName.append(".brep");
2271 // BRepTools::Write(v,aFileName.c_str());
2273 if (HasSizeMapOnVertex){
2274 vertexKey = VerticesWithSizeMap.FindIndex(v);
2275 if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
2276 theSizeMapStr = VertexId2SizeMap[vertexKey];
2277 //MESSAGE("VertexId2SizeMap[faceKey]: " << VertexId2SizeMap[vertexKey]);
2278 if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2280 // Expr To Python function, verification is performed at validation in GUI
2281 gstate = PyGILState_Ensure();
2282 PyObject * obj = NULL;
2283 obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2285 PyObject * func = NULL;
2286 func = PyObject_GetAttrString(main_mod, "f");
2287 VertexId2PythonSmp[*ip]=func;
2288 VertexId2SizeMap.erase(vertexKey); // do not erase if using a vector
2289 PyGILState_Release(gstate);
2294 // should not happen
2295 MESSAGE("An edge does not have 2 extremities.");
2298 // This defines the curves extremity connectivity
2299 cad_edge_set_extremities(edg, ip1, ip2);
2300 /* set the tag (color) to the same value as the extremity id : */
2301 cad_edge_set_extremities_tag(edg, ip1, ip2);
2304 cad_edge_set_extremities(edg, ip2, ip1);
2305 cad_edge_set_extremities_tag(edg, ip2, ip1);
2311 // Clear mesh from already meshed edges if possible else
2312 // remember that merge is needed
2313 TSubMeshSet::iterator smIt = edgeSubmeshes.begin();
2314 for ( ; smIt != edgeSubmeshes.end(); ++smIt ) // loop on already meshed EDGEs
2316 SMESHDS_SubMesh* smDS = *smIt;
2317 if ( !smDS ) continue;
2318 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2321 const SMDS_MeshNode* n = nIt->next();
2322 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
2324 needMerge = true; // to correctly sew with viscous mesh
2325 // add existing medium nodes to helper
2326 if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
2328 SMDS_ElemIteratorPtr edgeIt = smDS->GetElements();
2329 while ( edgeIt->more() )
2330 helper.AddTLinks( static_cast<const SMDS_MeshEdge*>(edgeIt->next()));
2335 if ( allowSubMeshClearing )
2337 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2338 while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), 0 );
2339 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2340 while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), 0 );
2349 ///////////////////////
2351 ///////////////////////
2353 MESSAGE("BEFORE PERIODICITY");
2354 MESSAGE("_preCadFacesIDsPeriodicityVector.size() = " << _preCadFacesIDsPeriodicityVector.size());
2355 if (! _preCadFacesIDsPeriodicityVector.empty()) {
2356 MESSAGE("INTO PRECAD FACES PERIODICITY");
2357 for (std::size_t i=0; i < _preCadFacesIDsPeriodicityVector.size(); i++){
2358 std::vector<int> theFace1_ids = _preCadFacesIDsPeriodicityVector[i].shape1IDs;
2359 std::vector<int> theFace2_ids = _preCadFacesIDsPeriodicityVector[i].shape2IDs;
2360 int* theFace1_ids_c = &theFace1_ids[0];
2361 int* theFace2_ids_c = &theFace2_ids[0];
2362 std::ostringstream o;
2363 o << "_preCadFacesIDsPeriodicityVector[" << i << "] = [";
2364 for (std::size_t j=0; j < theFace1_ids.size(); j++)
2365 o << theFace1_ids[j] << ", ";
2367 for (std::size_t j=0; j < theFace2_ids.size(); j++)
2368 o << theFace2_ids[j] << ", ";
2371 MESSAGE("theFace1_ids.size(): " << theFace1_ids.size());
2372 MESSAGE("theFace2_ids.size(): " << theFace2_ids.size());
2373 if (_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2375 // If no source points, call peridoicity without transformation function
2376 MESSAGE("periodicity without transformation function");
2377 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2378 status = cad_add_face_multiple_periodicity_with_transformation_function(c, theFace1_ids_c, theFace1_ids.size(),
2379 theFace2_ids_c, theFace2_ids.size(), periodicity_transformation, NULL);
2380 if(status != STATUS_OK)
2381 cout << "cad_add_face_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2385 // get the transformation vertices
2386 MESSAGE("periodicity with transformation vertices");
2387 double* theSourceVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2388 double* theTargetVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2389 int nbSourceVertices = _preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2390 int nbTargetVertices = _preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2392 MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2394 status = cad_add_face_multiple_periodicity_with_transformation_function_by_points(c, theFace1_ids_c, theFace1_ids.size(),
2395 theFace2_ids_c, theFace2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2396 if(status != STATUS_OK)
2397 cout << "cad_add_face_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2401 MESSAGE("END PRECAD FACES PERIODICITY");
2404 MESSAGE("_preCadEdgesIDsPeriodicityVector.size() = " << _preCadEdgesIDsPeriodicityVector.size());
2405 if (! _preCadEdgesIDsPeriodicityVector.empty()) {
2406 MESSAGE("INTO PRECAD EDGES PERIODICITY");
2407 for (std::size_t i=0; i < _preCadEdgesIDsPeriodicityVector.size(); i++){
2408 std::vector<int> theEdge1_ids = _preCadEdgesIDsPeriodicityVector[i].shape1IDs;
2409 std::vector<int> theEdge2_ids = _preCadEdgesIDsPeriodicityVector[i].shape2IDs;
2410 // Use the address of the first element of the vector to initialise the array
2411 int* theEdge1_ids_c = &theEdge1_ids[0];
2412 int* theEdge2_ids_c = &theEdge2_ids[0];
2414 std::ostringstream o;
2415 o << "_preCadEdgesIDsPeriodicityVector[" << i << "] = [";
2416 for (std::size_t j=0; j < theEdge1_ids.size(); j++)
2417 o << theEdge1_ids[j] << ", ";
2419 for (std::size_t j=0; j < theEdge2_ids.size(); j++)
2420 o << theEdge2_ids[j] << ", ";
2423 MESSAGE("theEdge1_ids.size(): " << theEdge1_ids.size());
2424 MESSAGE("theEdge2_ids.size(): " << theEdge2_ids.size());
2426 if (_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2428 // If no source points, call peridoicity without transformation function
2429 MESSAGE("periodicity without transformation function");
2430 meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2431 status = cad_add_edge_multiple_periodicity_with_transformation_function(c, theEdge1_ids_c, theEdge1_ids.size(),
2432 theEdge2_ids_c, theEdge2_ids.size(), periodicity_transformation, NULL);
2433 if(status != STATUS_OK)
2434 cout << "cad_add_edge_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2438 // get the transformation vertices
2439 MESSAGE("periodicity with transformation vertices");
2440 double* theSourceVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2441 double* theTargetVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2442 int nbSourceVertices = _preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2443 int nbTargetVertices = _preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2445 MESSAGE("nbSourceVertices: " << nbSourceVertices << ", nbTargetVertices: " << nbTargetVertices);
2447 status = cad_add_edge_multiple_periodicity_with_transformation_function_by_points(c, theEdge1_ids_c, theEdge1_ids.size(),
2448 theEdge2_ids_c, theEdge2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2449 if(status != STATUS_OK)
2450 cout << "cad_add_edge_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2452 MESSAGE("cad_add_edge_multiple_periodicity_with_transformation_function_by_points succeeded.\n");
2456 MESSAGE("END PRECAD EDGES PERIODICITY");
2460 // TODO: be able to use a mesh in input.
2461 // See imsh usage in Products/templates/mg-cadsurf_template_common.cpp
2462 // => cadsurf_set_mesh
2464 // Use the original dcad
2465 cadsurf_set_dcad(css, dcad);
2467 // Use the original cad
2468 cadsurf_set_cad(css, c);
2470 std::cout << std::endl;
2471 std::cout << "Beginning of Surface Mesh generation" << std::endl;
2472 std::cout << std::endl;
2477 status = cadsurf_compute_mesh(css);
2480 catch ( std::exception& exc ) {
2481 _comment += exc.what();
2483 catch (Standard_Failure& ex) {
2484 _comment += ex.DynamicType()->Name();
2485 if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
2487 _comment += ex.GetMessageString();
2491 if ( _comment.empty() )
2492 _comment = "Exception in cadsurf_compute_mesh()";
2495 std::cout << std::endl;
2496 std::cout << "End of Surface Mesh generation" << std::endl;
2497 std::cout << std::endl;
2500 cadsurf_get_mesh(css, &msh);
2502 /* release the mesh object */
2503 cadsurf_regain_mesh(css, msh);
2504 return error(_comment);
2507 std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
2509 GMFFileName = _hypothesis->GetGMFFile();
2510 if (GMFFileName != "") {
2511 bool asciiFound = (GMFFileName.find(".mesh", GMFFileName.length()-5) != std::string::npos);
2512 bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
2513 if (!asciiFound && !binaryFound)
2514 GMFFileName.append(".mesh");
2515 mesh_write_mesh(msh, GMFFileName.c_str());
2518 /* retrieve mesh data (see meshgems/mesh.h) */
2519 integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
2520 integer *evedg, *evtri, *evquad, *tags_buff, type;
2523 mesh_get_vertex_count(msh, &nv);
2524 mesh_get_edge_count(msh, &ne);
2525 mesh_get_triangle_count(msh, &nt);
2526 mesh_get_quadrangle_count(msh, &nq);
2528 evedg = (integer *)mesh_calloc_generic_buffer(msh);
2529 evtri = (integer *)mesh_calloc_generic_buffer(msh);
2530 evquad = (integer *)mesh_calloc_generic_buffer(msh);
2531 tags_buff = (integer*)mesh_calloc_generic_buffer(msh);
2533 std::vector<const SMDS_MeshNode*> nodes(nv+1);
2534 std::vector<bool> tags(nv+1);
2536 /* enumerated vertices */
2537 for(int iv=1;iv<=nv;iv++) {
2538 mesh_get_vertex_coordinates(msh, iv, xyz);
2539 mesh_get_vertex_tag(msh, iv, &tag);
2540 // Issue 0020656. Use vertex coordinates
2542 if ( tag > 0 && tag <= pmap.Extent() ) {
2543 TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
2544 double tol = BRep_Tool::Tolerance( v );
2545 gp_Pnt p = BRep_Tool::Pnt( v );
2546 if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
2547 xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
2549 tag = 0; // enforced or attracted vertex
2550 nodes[iv] = SMESH_Algo::VertexNode( v, meshDS );
2553 nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
2555 // Create group of enforced vertices if requested
2556 BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
2558 projVertex.push_back((double)xyz[0]);
2559 projVertex.push_back((double)xyz[1]);
2560 projVertex.push_back((double)xyz[2]);
2561 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
2562 if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end()) {
2563 MESSAGE("Found enforced vertex @ " << xyz[0] << ", " << xyz[1] << ", " << xyz[2]);
2564 BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
2565 BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
2566 for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
2567 currentEnfVertex = (*enfListIt);
2568 if (currentEnfVertex->grpName != "") {
2569 bool groupDone = false;
2570 SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
2571 MESSAGE("currentEnfVertex->grpName: " << currentEnfVertex->grpName);
2572 MESSAGE("Parsing the groups of the mesh");
2573 while (grIt->more()) {
2574 SMESH_Group * group = grIt->next();
2575 if ( !group ) continue;
2576 MESSAGE("Group: " << group->GetName());
2577 SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2578 if ( !groupDS ) continue;
2579 MESSAGE("group->SMDSGroup().GetType(): " << (groupDS->GetType()));
2580 MESSAGE("group->SMDSGroup().GetType()==SMDSAbs_Node: " << (groupDS->GetType()==SMDSAbs_Node));
2581 MESSAGE("currentEnfVertex->grpName.compare(group->GetStoreName())==0: " << (currentEnfVertex->grpName.compare(group->GetName())==0));
2582 if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
2583 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
2584 aGroupDS->SMDSGroup().Add(nodes[iv]);
2585 MESSAGE("Node ID: " << nodes[iv]->GetID());
2586 // How can I inform the hypothesis ?
2587 // _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
2589 MESSAGE("Successfully added enforced vertex to existing group " << currentEnfVertex->grpName);
2596 SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
2597 aGroup->SetName( currentEnfVertex->grpName.c_str() );
2598 SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2599 aGroupDS->SMDSGroup().Add(nodes[iv]);
2600 MESSAGE("Successfully created enforced vertex group " << currentEnfVertex->grpName);
2604 throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
2607 MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
2611 // internal points are tagged to zero
2612 if(tag > 0 && tag <= pmap.Extent() ){
2613 meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
2620 /* enumerate edges */
2621 for(int it=1;it<=ne;it++) {
2623 mesh_get_edge_vertices(msh, it, vtx);
2624 mesh_get_edge_extra_vertices(msh, it, &type, evedg);
2625 mesh_get_edge_tag(msh, it, &tag);
2627 // If PreCAD performed some cleaning operations (remove tiny edges,
2628 // merge edges ...) an output tag can indeed represent several original tags.
2629 // Get the initial tags corresponding to the output tag and redefine the tag as
2630 // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
2631 mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
2633 tag=tags_buff[nb_tag-1];
2634 if ( tag < 1 || tag > emap.Extent() )
2636 std::cerr << "MG-CADSurf BUG:::: Edge tag " << tag
2637 << " does not point to a CAD edge (nb edges " << emap.Extent() << ")" << std::endl;
2641 Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
2642 tags[vtx[0]] = false;
2645 Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
2646 tags[vtx[1]] = false;
2648 if (type == MESHGEMS_MESH_ELEMENT_TYPE_EDGE3) {
2650 if (tags[evedg[0]]) {
2651 Set_NodeOnEdge(meshDS, nodes[evedg[0]], emap(tag));
2652 tags[evedg[0]] = false;
2654 edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]], nodes[evedg[0]]);
2657 edg = helper.AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
2659 meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
2662 /* enumerate triangles */
2663 for(int it=1;it<=nt;it++) {
2665 mesh_get_triangle_vertices(msh, it, vtx);
2666 mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
2667 mesh_get_triangle_tag(msh, it, &tag);
2669 meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2670 tags[vtx[0]] = false;
2673 meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2674 tags[vtx[1]] = false;
2677 meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
2678 tags[vtx[2]] = false;
2680 if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
2681 // QUADRATIC TRIANGLE
2682 if (tags[evtri[0]]) {
2683 meshDS->SetNodeOnFace(nodes[evtri[0]], tag);
2684 tags[evtri[0]] = false;
2686 if (tags[evtri[1]]) {
2687 meshDS->SetNodeOnFace(nodes[evtri[1]], tag);
2688 tags[evtri[1]] = false;
2690 if (tags[evtri[2]]) {
2691 meshDS->SetNodeOnFace(nodes[evtri[2]], tag);
2692 tags[evtri[2]] = false;
2694 tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
2695 nodes[evtri[0]], nodes[evtri[1]], nodes[evtri[2]]);
2698 tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
2700 meshDS->SetMeshElementOnShape(tri, tag);
2703 /* enumerate quadrangles */
2704 for(int it=1;it<=nq;it++) {
2705 SMDS_MeshFace* quad;
2706 mesh_get_quadrangle_vertices(msh, it, vtx);
2707 mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
2708 mesh_get_quadrangle_tag(msh, it, &tag);
2710 meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2711 tags[vtx[0]] = false;
2714 meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2715 tags[vtx[1]] = false;
2718 meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
2719 tags[vtx[2]] = false;
2722 meshDS->SetNodeOnFace(nodes[vtx[3]], tag);
2723 tags[vtx[3]] = false;
2725 if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
2726 // QUADRATIC QUADRANGLE
2727 std::cout << "This is a quadratic quadrangle" << std::endl;
2728 if (tags[evquad[0]]) {
2729 meshDS->SetNodeOnFace(nodes[evquad[0]], tag);
2730 tags[evquad[0]] = false;
2732 if (tags[evquad[1]]) {
2733 meshDS->SetNodeOnFace(nodes[evquad[1]], tag);
2734 tags[evquad[1]] = false;
2736 if (tags[evquad[2]]) {
2737 meshDS->SetNodeOnFace(nodes[evquad[2]], tag);
2738 tags[evquad[2]] = false;
2740 if (tags[evquad[3]]) {
2741 meshDS->SetNodeOnFace(nodes[evquad[3]], tag);
2742 tags[evquad[3]] = false;
2744 if (tags[evquad[4]]) {
2745 meshDS->SetNodeOnFace(nodes[evquad[4]], tag);
2746 tags[evquad[4]] = false;
2748 quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
2749 nodes[evquad[0]], nodes[evquad[1]], nodes[evquad[2]], nodes[evquad[3]],
2753 quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
2755 meshDS->SetMeshElementOnShape(quad, tag);
2758 /* release the mesh object, the rest is released by cleaner */
2759 cadsurf_regain_mesh(css, msh);
2762 // Remove free nodes that can appear e.g. if "remove tiny edges"(IPAL53235)
2763 for(int iv=1;iv<=nv;iv++)
2764 if ( nodes[iv] && nodes[iv]->NbInverseElements() == 0 )
2765 meshDS->RemoveFreeNode( nodes[iv], 0, /*fromGroups=*/false );
2768 if ( needMerge ) // sew mesh computed by MG-CADSurf with pre-existing mesh
2770 SMESH_MeshEditor editor( &aMesh );
2771 SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
2772 TIDSortedElemSet segementsOnEdge;
2773 TSubMeshSet::iterator smIt;
2774 SMESHDS_SubMesh* smDS;
2776 // merge nodes on EDGE's with ones computed by MG-CADSurf
2777 for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
2779 if (! (smDS = *smIt) ) continue;
2780 getNodeGroupsToMerge( smDS, meshDS->IndexToShape((*smIt)->GetID()), nodeGroupsToMerge );
2782 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2783 while ( segIt->more() )
2784 segementsOnEdge.insert( segIt->next() );
2787 editor.MergeNodes( nodeGroupsToMerge );
2790 SMESH_MeshEditor::TListOfListOfElementsID equalSegments;
2791 editor.FindEqualElements( segementsOnEdge, equalSegments );
2792 editor.MergeElements( equalSegments );
2794 // remove excess segments created on the boundary of viscous layers
2795 const SMDS_TypeOfPosition onFace = SMDS_TOP_FACE;
2796 for ( int i = 1; i <= emap.Extent(); ++i )
2798 if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( emap( i )))
2800 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2801 while ( segIt->more() )
2803 const SMDS_MeshElement* seg = segIt->next();
2804 if ( seg->GetNode(0)->GetPosition()->GetTypeOfPosition() == onFace ||
2805 seg->GetNode(1)->GetPosition()->GetTypeOfPosition() == onFace )
2806 meshDS->RemoveFreeElement( seg, smDS );
2813 // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
2814 for (int i = 1; i <= emap.Extent(); i++)
2815 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
2816 sm->SetIsAlwaysComputed( true );
2817 for (int i = 1; i <= pmap.Extent(); i++)
2818 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
2819 if ( !sm->IsMeshComputed() )
2820 sm->SetIsAlwaysComputed( true );
2822 // Set error to FACE's w/o elements
2823 SMESH_ComputeErrorName err = COMPERR_ALGO_FAILED;
2824 if ( _comment.empty() && status == STATUS_OK )
2826 err = COMPERR_WARNING;
2827 _comment = "No mesh elements assigned to a face";
2829 bool badFaceFound = false;
2830 for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
2832 TopoDS_Face f = TopoDS::Face(face_iter.Current());
2833 SMESH_subMesh* sm = aMesh.GetSubMesh( f );
2834 if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
2836 sm->GetComputeError().reset( new SMESH_ComputeError( err, _comment, this ));
2837 badFaceFound = true;
2840 if ( err == COMPERR_WARNING )
2844 if ( status != STATUS_OK && !badFaceFound ) {
2848 // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
2850 if ( oldFEFlags > 0 )
2851 feenableexcept( oldFEFlags );
2852 feclearexcept( FE_ALL_EXCEPT );
2856 std::cout << "FacesWithSizeMap" << std::endl;
2857 FacesWithSizeMap.Statistics(std::cout);
2858 std::cout << "EdgesWithSizeMap" << std::endl;
2859 EdgesWithSizeMap.Statistics(std::cout);
2860 std::cout << "VerticesWithSizeMap" << std::endl;
2861 VerticesWithSizeMap.Statistics(std::cout);
2862 std::cout << "FacesWithEnforcedVertices" << std::endl;
2863 FacesWithEnforcedVertices.Statistics(std::cout);
2866 MESSAGE("END OF BLSURFPlugin_BLSURF::Compute()");
2867 return ( status == STATUS_OK && !quadraticSubMeshAndViscousLayer );
2870 //================================================================================
2872 * \brief Terminates computation
2874 //================================================================================
2876 void BLSURFPlugin_BLSURF::CancelCompute()
2878 _compute_canceled = true;
2881 //=============================================================================
2885 //=============================================================================
2887 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh* meshDS, const SMDS_MeshNode* node, const TopoDS_Shape& ed) {
2888 const TopoDS_Edge edge = TopoDS::Edge(ed);
2890 gp_Pnt pnt(node->X(), node->Y(), node->Z());
2892 Standard_Real p0 = 0.0;
2893 Standard_Real p1 = 1.0;
2894 TopLoc_Location loc;
2895 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
2896 if ( curve.IsNull() )
2898 // issue 22499. Node at a sphere apex
2899 meshDS->SetNodeOnEdge(node, edge, p0);
2903 if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
2904 GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
2907 if ( proj.NbPoints() > 0 )
2909 pa = (double)proj.LowerDistanceParameter();
2910 // Issue 0020656. Move node if it is too far from edge
2911 gp_Pnt curve_pnt = curve->Value( pa );
2912 double dist2 = pnt.SquareDistance( curve_pnt );
2913 double tol = BRep_Tool::Tolerance( edge );
2914 if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
2916 curve_pnt.Transform( loc );
2917 meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
2921 meshDS->SetNodeOnEdge(node, edge, pa);
2924 /* Curve definition function See cad_curv_t in file meshgems/cad.h for
2926 * NOTE : if when your CAD systems evaluates second
2927 * order derivatives it also computes first order derivatives and
2928 * function evaluation, you can optimize this example by making only
2929 * one CAD call and filling the necessary uv, dt, dtt arrays.
2931 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
2933 /* t is given. It contains the t (time) 1D parametric coordintaes
2934 of the point PreCAD/MG-CADSurf is querying on the curve */
2936 /* user_data identifies the edge PreCAD/MG-CADSurf is querying
2937 * (see cad_edge_new later in this example) */
2938 const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
2941 /* MG-CADSurf is querying the function evaluation */
2944 uv[0]=P.X(); uv[1]=P.Y();
2948 /* query for the first order derivatives */
2951 dt[0]=V1.X(); dt[1]=V1.Y();
2955 /* query for the second order derivatives */
2958 dtt[0]=V2.X(); dtt[1]=V2.Y();
2964 /* Surface definition function.
2965 * See cad_surf_t in file meshgems/cad.h for more information.
2966 * NOTE : if when your CAD systems evaluates second order derivatives it also
2967 * computes first order derivatives and function evaluation, you can optimize
2968 * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
2971 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
2972 real *duu, real *duv, real *dvv, void *user_data)
2974 /* uv[2] is given. It contains the u,v coordinates of the point
2975 * PreCAD/MG-CADSurf is querying on the surface */
2977 /* user_data identifies the face PreCAD/MG-CADSurf is querying (see
2978 * cad_face_new later in this example)*/
2979 const Geom_Surface* geometry = (const Geom_Surface*) user_data;
2983 P=geometry->Value(uv[0],uv[1]); // S.D0(U,V,P);
2984 xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
2991 geometry->D1(uv[0],uv[1],P,D1U,D1V);
2992 du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
2993 dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
2996 if(duu && duv && dvv){
3000 gp_Vec D2U,D2V,D2UV;
3002 geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
3003 duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
3004 duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
3005 dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
3012 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
3014 TId2ClsAttractorVec::iterator f2attVec;
3015 if (FaceId2PythonSmp.count(face_id) != 0){
3016 assert(Py_IsInitialized());
3017 PyGILState_STATE gstate;
3018 gstate = PyGILState_Ensure();
3019 PyObject* pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
3021 if ( pyresult != NULL) {
3022 result = PyFloat_AsDouble(pyresult);
3023 Py_DECREF(pyresult);
3028 string err_description="";
3029 PyObject* new_stderr = newPyStdOut(err_description);
3030 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3031 Py_INCREF(old_stderr);
3032 PySys_SetObject((char*)"stderr", new_stderr);
3034 PySys_SetObject((char*)"stderr", old_stderr);
3035 Py_DECREF(new_stderr);
3036 MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
3037 result = *((real*)user_data);
3040 PyGILState_Release(gstate);
3042 else if (( f2attVec = FaceIndex2ClassAttractor.find(face_id)) != FaceIndex2ClassAttractor.end() && !f2attVec->second.empty()){
3043 // MESSAGE("attractor used on face :"<<face_id)
3044 // MESSAGE("List of attractor is not empty")
3045 // MESSAGE("Attractor empty : "<< FaceIndex2ClassAttractor[face_id]->Empty())
3048 std::vector< BLSURFPlugin_Attractor* > & attVec = f2attVec->second;
3049 for ( size_t i = 0; i < attVec.size(); ++i )
3051 //result += attVec[i]->GetSize(uv[0],uv[1]);
3052 result = Min( result, attVec[i]->GetSize(uv[0],uv[1]));
3054 //*size = result / attVec.size(); // mean of sizes defined by all attractors
3058 // MESSAGE("List of attractor is empty !!!")
3059 *size = *((real*)user_data);
3061 // std::cout << "Size_on_surface sur la face " << face_id << " donne une size de: " << *size << std::endl;
3065 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
3067 if (EdgeId2PythonSmp.count(edge_id) != 0){
3068 assert(Py_IsInitialized());
3069 PyGILState_STATE gstate;
3070 gstate = PyGILState_Ensure();
3071 PyObject* pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
3073 if ( pyresult != NULL) {
3074 result = PyFloat_AsDouble(pyresult);
3075 Py_DECREF(pyresult);
3080 string err_description="";
3081 PyObject* new_stderr = newPyStdOut(err_description);
3082 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3083 Py_INCREF(old_stderr);
3084 PySys_SetObject((char*)"stderr", new_stderr);
3086 PySys_SetObject((char*)"stderr", old_stderr);
3087 Py_DECREF(new_stderr);
3088 MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
3089 result = *((real*)user_data);
3092 PyGILState_Release(gstate);
3095 *size = *((real*)user_data);
3100 status_t size_on_vertex(integer point_id, real *size, void *user_data)
3102 if (VertexId2PythonSmp.count(point_id) != 0){
3103 assert(Py_IsInitialized());
3104 PyGILState_STATE gstate;
3105 gstate = PyGILState_Ensure();
3106 PyObject* pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
3108 if ( pyresult != NULL) {
3109 result = PyFloat_AsDouble(pyresult);
3110 Py_DECREF(pyresult);
3115 string err_description="";
3116 PyObject* new_stderr = newPyStdOut(err_description);
3117 PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3118 Py_INCREF(old_stderr);
3119 PySys_SetObject((char*)"stderr", new_stderr);
3121 PySys_SetObject((char*)"stderr", old_stderr);
3122 Py_DECREF(new_stderr);
3123 MESSAGE("Can't evaluate f()" << " error is " << err_description);
3124 result = *((real*)user_data);
3127 PyGILState_Release(gstate);
3130 *size = *((real*)user_data);
3136 * The following function will be called for PreCAD/MG-CADSurf message
3137 * printing. See context_set_message_callback (later in this
3138 * template) for how to set user_data.
3140 status_t message_cb(message_t *msg, void *user_data)
3142 integer errnumber = 0;
3144 message_get_number(msg, &errnumber);
3145 message_get_description(msg, &desc);
3147 message_cb_user_data * mcud = (message_cb_user_data*)user_data;
3148 // Get all the error message and some warning messages related to license and periodicity
3149 if ( errnumber < 0 ||
3150 err.find("license" ) != string::npos ||
3151 err.find("periodicity") != string::npos )
3153 // remove ^A from the tail
3154 int len = strlen( desc );
3155 while (len > 0 && desc[len-1] != '\n')
3157 mcud->_error->append( desc, len );
3160 if ( errnumber == 3009001 )
3161 * mcud->_progress = atof( desc + 11 ) / 100.;
3162 if ( mcud->_verbosity > 0 )
3163 std::cout << desc << std::endl;
3168 /* This is the interrupt callback. PreCAD/MG-CADSurf will call this
3169 * function regularily. See the file meshgems/interrupt.h
3171 status_t interrupt_cb(integer *interrupt_status, void *user_data)
3173 integer you_want_to_continue = 1;
3174 BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
3175 you_want_to_continue = !tmp->computeCanceled();
3177 if(you_want_to_continue)
3179 *interrupt_status = INTERRUPT_CONTINUE;
3182 else /* you want to stop MG-CADSurf */
3184 *interrupt_status = INTERRUPT_STOP;
3185 return STATUS_ERROR;
3189 //=============================================================================
3193 //=============================================================================
3194 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh& aMesh,
3195 const TopoDS_Shape& aShape,
3196 MapShapeNbElems& aResMap)
3198 double diagonal = aMesh.GetShapeDiagonalSize();
3199 double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
3200 int _physicalMesh = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
3201 double _phySize = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
3202 bool _phySizeRel = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
3203 //int _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
3204 double _angleMesh = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
3205 bool _quadAllowed = BLSURFPlugin_Hypothesis::GetDefaultQuadAllowed();
3207 _physicalMesh = (int) _hypothesis->GetPhysicalMesh();
3208 _phySizeRel = _hypothesis->IsPhySizeRel();
3209 if ( _hypothesis->GetPhySize() > 0)
3210 _phySize = _phySizeRel ? diagonal*_hypothesis->GetPhySize() : _hypothesis->GetPhySize();
3211 //_geometricMesh = (int) hyp->GetGeometricMesh();
3212 if (_hypothesis->GetAngleMesh() > 0)
3213 _angleMesh = _hypothesis->GetAngleMesh();
3214 _quadAllowed = _hypothesis->GetQuadAllowed();
3216 //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
3217 // GetDefaultPhySize() sometimes leads to computation failure
3218 _phySize = aMesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
3219 MESSAGE("BLSURFPlugin_BLSURF::SetParameters using defaults");
3222 bool IsQuadratic = _quadraticMesh;
3227 TopTools_DataMapOfShapeInteger EdgesMap;
3228 double fullLen = 0.0;
3229 double fullNbSeg = 0;
3230 for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
3231 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3232 if( EdgesMap.IsBound(E) )
3234 SMESH_subMesh *sm = aMesh.GetSubMesh(E);
3235 double aLen = SMESH_Algo::EdgeLength(E);
3238 if(_physicalMesh==1) {
3239 nb1d = (int)( aLen/_phySize + 1 );
3244 Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
3245 double fullAng = 0.0;
3246 double dp = (l-f)/200;
3251 for(int j=2; j<=200; j++) {
3254 fullAng += fabs(V1.Angle(V2));
3258 nb1d = (int)( fullAng/_angleMesh + 1 );
3261 std::vector<int> aVec(SMDSEntity_Last);
3262 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3263 if( IsQuadratic > 0 ) {
3264 aVec[SMDSEntity_Node] = 2*nb1d - 1;
3265 aVec[SMDSEntity_Quad_Edge] = nb1d;
3268 aVec[SMDSEntity_Node] = nb1d - 1;
3269 aVec[SMDSEntity_Edge] = nb1d;
3271 aResMap.insert(std::make_pair(sm,aVec));
3272 EdgesMap.Bind(E,nb1d);
3274 double ELen = fullLen/fullNbSeg;
3278 // try to evaluate as in MEFISTO
3279 for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
3280 TopoDS_Face F = TopoDS::Face( exp.Current() );
3281 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
3283 BRepGProp::SurfaceProperties(F,G);
3284 double anArea = G.Mass();
3286 std::vector<int> nb1dVec;
3287 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
3288 int nbSeg = EdgesMap.Find(exp1.Current());
3290 nb1dVec.push_back( nbSeg );
3293 int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
3294 int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
3297 if ( nb1dVec.size() == 4 ) // quadrangle geom face
3299 int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
3301 nbNodes = (n1 + 1) * (n2 + 1);
3306 nbTria = nbQuad = nbTria / 3 + 1;
3309 std::vector<int> aVec(SMDSEntity_Last,0);
3311 int nb1d_in = (nbTria*3 - nb1d) / 2;
3312 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3313 aVec[SMDSEntity_Quad_Triangle] = nbTria;
3314 aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
3317 aVec[SMDSEntity_Node] = nbNodes;
3318 aVec[SMDSEntity_Triangle] = nbTria;
3319 aVec[SMDSEntity_Quadrangle] = nbQuad;
3321 aResMap.insert(std::make_pair(sm,aVec));
3328 BRepGProp::VolumeProperties(aShape,G);
3329 double aVolume = G.Mass();
3330 double tetrVol = 0.1179*ELen*ELen*ELen;
3331 int nbVols = int(aVolume/tetrVol);
3332 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3333 std::vector<int> aVec(SMDSEntity_Last);
3334 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3336 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3337 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3340 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3341 aVec[SMDSEntity_Tetra] = nbVols;
3343 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3344 aResMap.insert(std::make_pair(sm,aVec));