1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_SelectionNaming.cpp
4 // Created: 11 Aug 2015
5 // Author: Mikhail PONIKAROV
7 #include "Model_SelectionNaming.h"
8 #include "Model_Document.h"
9 #include "Model_Objects.h"
10 #include "Model_Data.h"
11 #include <ModelAPI_Feature.h>
12 #include <Events_InfoMessage.h>
13 #include <ModelAPI_Session.h>
14 #include <ModelAPI_ResultPart.h>
15 #include <ModelAPI_ResultConstruction.h>
16 #include <ModelAPI_CompositeFeature.h>
17 #include <ModelAPI_ResultBody.h>
18 #include <GeomAPI_Wire.h>
20 #include <TopoDS_Iterator.hxx>
22 #include <TopoDS_Compound.hxx>
24 #include <TopExp_Explorer.hxx>
25 #include <TopTools_ListOfShape.hxx>
26 #include <TopTools_MapOfShape.hxx>
27 #include <TopTools_IndexedMapOfShape.hxx>
28 #include <TopTools_ListIteratorOfListOfShape.hxx>
29 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
30 #include <TopTools_MapIteratorOfMapOfShape.hxx>
31 #include <BRep_Builder.hxx>
32 #include <TNaming_Iterator.hxx>
33 #include <TNaming_Tool.hxx>
34 #include <TNaming_NamedShape.hxx>
35 #include <TNaming_Localizer.hxx>
36 #include <TDataStd_Name.hxx>
37 #include <TColStd_MapOfTransient.hxx>
42 #include <BRepTools.hxx>
45 Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
47 myLab = theSelectionLab;
50 std::string Model_SelectionNaming::getShapeName(
51 std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
52 ResultPtr& theContext, const bool theAnotherDoc, const bool theWholeContext)
55 // add the result name to the name of the shape
56 // (it was in BodyBuilder, but did not work on Result rename)
57 bool isNeedContextName = theContext->shape().get() != NULL;
58 // && !theContext->shape()->isEqual(theSubSh);
59 // check if the subShape is already in DF
60 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, myLab);
61 Handle(TDataStd_Name) anAttr;
62 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
63 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
64 std::shared_ptr<Model_Data> aData =
65 std::dynamic_pointer_cast<Model_Data>(theContext->data());
66 if (isNeedContextName && aData && aData->label().IsEqual(aNS->Label())) {
67 // do nothing because this context name will be added later in this method
69 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
70 // indexes are added to sub-shapes not primitives
71 // (primitives must not be located at the same label)
72 if(!aName.empty() && aNS->Evolution() != TNaming_PRIMITIVE && isNeedContextName) {
73 const TDF_Label& aLabel = aNS->Label();//theDoc->findNamingName(aName);
74 static const std::string aPostFix("_");
75 TNaming_Iterator anItL(aNS);
76 for(int i = 1; anItL.More(); anItL.Next(), i++) {
77 if(anItL.NewShape().IsSame(theShape)) { // in #1766 IsEqual produced no index of the face
79 aName += TCollection_AsciiString (i).ToCString();
84 // if a shape is under another context, use this name, not theContext
85 std::shared_ptr<Model_Data> aContextData =
86 std::dynamic_pointer_cast<Model_Data>(theContext->data());
87 // for constructions the naming is in arguments and has no evolution, so, apply this only
89 if (isNeedContextName && theContext->groupName() == ModelAPI_ResultBody::group() &&
90 !aNS->Label().IsDescendant(aContextData->label())) {
91 isNeedContextName = false;
92 TDF_Label aNSDataLab = aNS->Label();
93 while(aNSDataLab.Depth() != 7 && aNSDataLab.Depth() > 5)
94 aNSDataLab = aNSDataLab.Father();
95 ObjectPtr aNewContext = theDoc->objects()->object(aNSDataLab);
96 if (!aNewContext.get() && aNSDataLab.Depth() == 7) {
97 aNSDataLab = aNSDataLab.Father().Father();
98 aNewContext = theDoc->objects()->object(aNSDataLab);
100 if (aNewContext.get()) {
101 aName = aNewContext->data()->name() + "/" + aName;
108 // Name is empty and this is full context, it just add the whole context name that must be added
109 bool isEmptyName = aName.empty();
110 if (isNeedContextName && (!isEmptyName || theWholeContext)) {
111 aName = theContext->data()->name() + (isEmptyName ? "" : ("/" + aName));
113 aName = theContext->document()->kind() + "/" + aName; // PartSet
118 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
120 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
121 TopoDS_Compound aCmp;
123 BB.MakeCompound(aCmp);
124 TopTools_ListIteratorOfListOfShape it(theAncestors);
125 for(;it.More();it.Next()) {
126 BB.Add(aCmp, it.Value());
127 theSMap.Add(it.Value());
130 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
131 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
132 for (int i = 1; i <= aMap2.Extent(); i++) {
133 const TopoDS_Shape& aKey = aMap2.FindKey(i);
134 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
135 if(anAncestors.Extent() > 1) aNumber++;
137 if(aNumber > 1) return false;
141 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
142 std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
143 const bool theAnotherDoc)
145 std::string aName("Undefined name");
146 if(!theContext.get() || theContext->shape()->isNull())
147 return !theDefaultName.empty() ? theDefaultName : aName;
149 // if it is in result of another part
150 std::shared_ptr<Model_Document> aDoc =
151 std::dynamic_pointer_cast<Model_Document>(theContext->document());
152 if (theContext->groupName() == ModelAPI_ResultPart::group()) {
153 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
156 return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
158 return aPart->data()->name();
161 if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
162 // but if it is in another Part, add this part name
163 std::string aPartName;
165 aPartName = theContext->document()->kind() + "/"; // PartSet
166 return aPartName + theContext->data()->name();
168 TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
169 TopoDS_Shape aContext = theContext->shape()->impl<TopoDS_Shape>();
171 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
172 BRepTools::Write(aSubShape, "Selection.brep");
173 BRepTools::Write(aContext, "Context.brep");
176 aName = getShapeName(aDoc, aSubShape, theContext, theAnotherDoc,
177 theContext->shape()->isEqual(theSubSh));
179 if(aName.empty() ) { // not in the document!
180 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
183 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
187 // name structure: F1 & F2 [& F3 & F4],
188 // where F1 & F2 the faces which gives the Edge in trivial case
189 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
190 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
191 aName = "Degenerated_Edge";
194 TopTools_IndexedDataMapOfShapeListOfShape aMap;
195 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
196 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
197 bool isTrivialCase(true);
198 if(aMap.Contains(aSubShape)) {
199 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
200 // check that it is not a trivial case (F1 & F2: aNumber = 1)
201 isTrivialCase = isTrivial(anAncestors, aSMap);
204 TopTools_ListOfShape aListOfNbs;
205 if(!isTrivialCase) { // find Neighbors
206 TNaming_Localizer aLocalizer;
207 TopTools_MapOfShape aMap3;
208 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
209 //int n = aMap3.Extent();
210 TopTools_MapIteratorOfMapOfShape it(aMap3);
211 for(;it.More();it.Next()) {
212 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
213 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
214 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
215 TopTools_ListIteratorOfListOfShape it2(aList);
216 for(;it2.More();it2.Next()) {
217 if(aSMap.Contains(it2.Value())) continue; // skip this Face
218 aListOfNbs.Append(it2.Value());
221 } // else a trivial case
223 // build name of the sub-shape Edge
224 for(int i=1; i <= aSMap.Extent(); i++) {
225 const TopoDS_Shape& aFace = aSMap.FindKey(i);
226 std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
230 aName += "&" + aFaceName;
232 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
233 for (;itl.More();itl.Next()) {
234 std::string aFaceName = getShapeName(aDoc, itl.Value(), theContext, theAnotherDoc, false);
235 aName += "&" + aFaceName;
241 // name structure (Monifold Topology):
242 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
243 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition,
244 // but it should be kept as is to obtain safe recomputation
245 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
246 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
247 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
248 // or compound of 2 open faces.
249 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
250 // two independent edges (wire or compound)
251 // implemented 2 first cases
253 TopTools_IndexedDataMapOfShapeListOfShape aMap;
254 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
255 TopTools_ListOfShape aList;
256 TopTools_MapOfShape aFMap;
257 // simetimes when group is moved in history, naming may be badly updated, so
258 // avoid crash in FindFromKey (issue 1842)
259 if (aMap.Contains(aSubShape)) {
260 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
262 TopTools_ListIteratorOfListOfShape itl2(aList2);
263 for (int i = 1;itl2.More();itl2.Next(),i++) {
264 if(aFMap.Add(itl2.Value()))
265 aList.Append(itl2.Value());
269 int n = aList.Extent();
270 bool isByFaces = n >= 3;
271 if(!isByFaces) { // open topology case or Compound case => via edges
272 TopTools_IndexedDataMapOfShapeListOfShape aMap;
273 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
274 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
275 if(aList22.Extent() >= 2) { // regular solution
277 // bug! duplication; fix is below
279 TopTools_ListOfShape aListE;
280 TopTools_ListIteratorOfListOfShape itl2(aList22);
281 for (int i = 1;itl2.More();itl2.Next(),i++) {
282 if(aFMap.Add(itl2.Value()))
283 aListE.Append(itl2.Value());
286 TopTools_ListIteratorOfListOfShape itl(aListE);
287 for (int i = 1;itl.More();itl.Next(),i++) {
288 const TopoDS_Shape& anEdge = itl.Value();
289 std::string anEdgeName = getShapeName(aDoc, anEdge, theContext, theAnotherDoc, false);
290 if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
298 aName += "&" + anEdgeName;
301 else { // dangle vertex: if(aList22.Extent() == 1)
302 //it should be already in DF
306 TopTools_ListIteratorOfListOfShape itl(aList);
307 for (int i = 1;itl.More();itl.Next(),i++) {
308 const TopoDS_Shape& aFace = itl.Value();
309 std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
313 aName += "&" + aFaceName;
324 TopAbs_ShapeEnum translateType (const std::string& theType)
326 // map from the textual shape types to OCCT enumeration
327 static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
329 if(aShapeTypes.size() == 0) {
330 aShapeTypes["compound"] = TopAbs_COMPOUND;
331 aShapeTypes["compounds"] = TopAbs_COMPOUND;
332 aShapeTypes["compsolid"] = TopAbs_COMPSOLID;
333 aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
334 aShapeTypes["solid"] = TopAbs_SOLID;
335 aShapeTypes["solids"] = TopAbs_SOLID;
336 aShapeTypes["shell"] = TopAbs_SHELL;
337 aShapeTypes["shells"] = TopAbs_SHELL;
338 aShapeTypes["face"] = TopAbs_FACE;
339 aShapeTypes["faces"] = TopAbs_FACE;
340 aShapeTypes["wire"] = TopAbs_WIRE;
341 aShapeTypes["wires"] = TopAbs_WIRE;
342 aShapeTypes["edge"] = TopAbs_EDGE;
343 aShapeTypes["edges"] = TopAbs_EDGE;
344 aShapeTypes["vertex"] = TopAbs_VERTEX;
345 aShapeTypes["vertices"] = TopAbs_VERTEX;
346 aShapeTypes["COMPOUND"] = TopAbs_COMPOUND;
347 aShapeTypes["COMPOUNDS"] = TopAbs_COMPOUND;
348 aShapeTypes["COMPSOLID"] = TopAbs_COMPSOLID;
349 aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
350 aShapeTypes["SOLID"] = TopAbs_SOLID;
351 aShapeTypes["SOLIDS"] = TopAbs_SOLID;
352 aShapeTypes["SHELL"] = TopAbs_SHELL;
353 aShapeTypes["SHELLS"] = TopAbs_SHELL;
354 aShapeTypes["FACE"] = TopAbs_FACE;
355 aShapeTypes["FACES"] = TopAbs_FACE;
356 aShapeTypes["WIRE"] = TopAbs_WIRE;
357 aShapeTypes["WIRES"] = TopAbs_WIRE;
358 aShapeTypes["EDGE"] = TopAbs_EDGE;
359 aShapeTypes["EDGES"] = TopAbs_EDGE;
360 aShapeTypes["VERTEX"] = TopAbs_VERTEX;
361 aShapeTypes["VERTICES"] = TopAbs_VERTEX;
363 if (aShapeTypes.find(theType) != aShapeTypes.end())
364 return aShapeTypes[theType];
365 Events_InfoMessage("Model_SelectionNaming",
366 "Shape type defined in XML is not implemented!").send();
370 const TopoDS_Shape getShapeFromNS(
371 const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
373 TopoDS_Shape aSelection;
374 std::string::size_type n = theSubShapeName.rfind('/');
375 if (n == std::string::npos) n = -1;
376 std::string aSubString = theSubShapeName.substr(n + 1);
377 n = aSubString.rfind('_');
379 if (n != std::string::npos) {// for primitives this is a first
380 // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
381 Handle(TDataStd_Name) aName;
382 if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
383 aName->Get() != theSubShapeName.c_str()) {
384 aSubString = aSubString.substr(n+1);
385 indx = atoi(aSubString.c_str());
389 TNaming_Iterator anItL(theNS);
390 for(int i = 1; anItL.More(); anItL.Next(), i++) {
392 return anItL.NewShape();
398 const TopoDS_Shape findFaceByName(
399 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
402 //std::string::size_type n, nb = theSubShapeName.rfind('/');
403 //if (nb == std::string::npos) nb = 0;
404 //std::string aSubString = theSubShapeName.substr(nb + 1);
405 std::string aSubString = theSubShapeName;
407 TDF_Label aLabel = theDoc->findNamingName(aSubString);
408 if (aLabel.IsNull()) { // try to remove additional artificial suffix
409 std::string::size_type n = aSubString.rfind('_');
410 if (n != std::string::npos) {
411 aSubString = aSubString.substr(0, n);
412 aLabel = theDoc->findNamingName(aSubString);
415 if(aLabel.IsNull()) return aFace;
416 Handle(TNaming_NamedShape) aNS;
417 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
418 aFace = getShapeFromNS(theSubShapeName, aNS);
423 size_t ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
425 std::string aName = theSubShapeName;
426 std::string aLastName;
427 size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
428 while ((n2 = aName.find('&', n1)) != std::string::npos) {
429 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
430 theList.push_back(aName1);
432 aLastName = aName.substr(n1);
434 if(!aLastName.empty())
435 theList.push_back(aLastName);
436 return theList.size();
439 const TopoDS_Shape findCommonShape(
440 const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
442 if(theList.IsEmpty() || theList.Extent() == 1) {
443 return TopoDS_Shape();
447 std::vector<TopTools_MapOfShape> aVec;
448 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
449 if(theList.Extent() > 1) {
450 aVec.push_back(aMap1);
451 aVec.push_back(aMap2);
453 if(theList.Extent() > 2)
454 aVec.push_back(aMap3);
455 if(theList.Extent() == 4)
456 aVec.push_back(aMap4);
459 TopTools_ListIteratorOfListOfShape it(theList);
460 for(int i = 0;it.More();it.Next(),i++) {
461 const TopoDS_Shape& aFace = it.Value();
463 TopExp_Explorer anExp (aFace, theType);
464 for(;anExp.More();anExp.Next()) {
465 const TopoDS_Shape& anEdge = anExp.Current();
466 if (!anEdge.IsNull())
467 aVec[i].Add(anExp.Current());
470 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
471 for(;anExp.More();anExp.Next()) {
472 const TopoDS_Shape& aVertex = anExp.Current();
473 if (!aVertex.IsNull())
474 aVec[i].Add(anExp.Current());
478 //trivial case: 2 faces
479 TopTools_ListOfShape aList;
480 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
481 for(;it2.More();it2.Next()) {
482 if(aVec[1].Contains(it2.Key())) {
484 if(theList.Extent() == 2)
487 aList.Append(it2.Key());
490 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
491 if(aVec[2].Extent() && aVec[3].Extent()) {
492 TopTools_ListIteratorOfListOfShape it(aList);
493 for(;it.More();it.Next()) {
494 const TopoDS_Shape& aCand = it.Value();
495 // not yet completelly implemented, to be rechecked
496 TopoDS_Vertex aV1, aV2;
497 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
499 if(aVec[2].Contains(aV1)) aNum++;
500 else if(aVec[2].Contains(aV2)) aNum++;
501 if(aVec[3].Contains(aV1)) aNum++;
502 else if(aVec[3].Contains(aV2)) aNum++;
511 if(aList.Extent() && aVec.size() == 3) {
513 TopTools_ListIteratorOfListOfShape it(aList);
514 for(;it.More();it.Next()) {
515 const TopoDS_Shape& aCand = it.Value();
516 if(aVec[2].Contains(aCand)) {
525 std::string getContextName(const std::string& theSubShapeName)
528 std::string::size_type n = theSubShapeName.find('/');
529 if (n == std::string::npos) return theSubShapeName;
530 aName = theSubShapeName.substr(0, n);
534 /// Parses naming name of sketch sub-elements: takes indices and orientation
535 /// (if theOriented = true) from this name. Map theIDs constains indices ->
536 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
537 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
538 const std::string& theName, const char* theShapeType,
539 std::map<int, int>& theIDs, const bool theOriented = false)
541 // collect all IDs in the name
542 std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
543 const int aSubNum = theComp->numberOfSubs();
544 for(int a = 0; a < aSubNum; a++) {
545 FeaturePtr aSub = theComp->subFeature(a);
546 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
547 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
548 // there may be many shapes (circle and center)
549 for(; aRes != aResults.cend(); aRes++) {
550 ResultConstructionPtr aConstr =
551 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
553 aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
558 size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
559 bool isShape = false; // anyway the first world must be 'Vertex'
561 aLastNamePos = theName.find('-', aPrevPos);
562 std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
564 if (anID != theShapeType)
568 int anOrientation = 1; // default
569 if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
570 std::string::iterator aSymbol = anID.end() - 1;
571 if (*aSymbol == 'r') anOrientation = -1;
572 anID.erase(aSymbol); // remove last symbol
574 // check start/end symbols
575 std::string::iterator aBack = anID.end() - 1;
578 anID.erase(aBack); // remove last symbol
579 } else if (*aBack == 'e') {
581 anID.erase(aBack); // remove last symbol
584 if (aNames.find(anID) != aNames.end()) {
585 theIDs[aNames[anID]] = anOrientation;
588 aPrevPos = aLastNamePos + 1;
589 } while (aLastNamePos != std::string::npos);
593 /// produces theEdge orientation relatively to theContext face
594 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
596 if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
598 if (theEdge.Orientation() == TopAbs_FORWARD)
600 if (theEdge.Orientation() == TopAbs_REVERSED)
605 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
606 std::shared_ptr<ModelAPI_Result>& theConstr,
607 NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
609 int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
610 int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
611 std::shared_ptr<GeomAPI_Shape> aResult;
612 ResultConstructionPtr aConstructionContext =
613 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
614 if (!aConstructionContext.get())
616 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
617 int aFound = 0, aNotFound = 0, aSameOrientation = 0;
619 TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
620 std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
622 for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
623 aFacesWires.push_back(aWires.Current());
626 aFacesWires.push_back(aFace);
628 std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
629 for(; aFW != aFacesWires.end(); aFW++) {
630 TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
631 TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
632 for(; anEdgesExp.More(); anEdgesExp.Next()) {
633 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
634 if (!anEdge.IsNull()) {
635 Standard_Real aFirst, aLast;
636 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
637 if (alreadyProcessed.Contains(aCurve))
639 alreadyProcessed.Add(aCurve);
640 if (theCurves.IsBound(aCurve)) {
642 int anOrient = theCurves.Find(aCurve);
643 if (anOrient != 0) { // extra comparision score is orientation
644 if (edgeOrientation(aFace, anEdge) == anOrient)
652 if (aFound + aNotFound != 0) {
653 if (aFound > aBestFound ||
654 (aFound == aBestFound && aSameOrientation > aBestOrient)) {
656 aBestOrient = aSameOrientation;
658 std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
659 aWire->setImpl(new TopoDS_Shape(*aFW));
662 aResult = aConstructionContext->face(aFaceIndex);
671 std::string Model_SelectionNaming::shortName(
672 std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
674 std::string aName = theConstr->data()->name();
675 // remove "-", "/" and "&" command-symbols
676 aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
677 aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
678 aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
679 // remove the last 's', 'e', 'f' and 'r' symbols:
680 // they are used as markers of start/end/forward/rewersed indicators
681 static const std::string aSyms("sefr");
682 std::string::iterator aSuffix = aName.end() - 1;
683 while(aSyms.find(*aSuffix) != std::string::npos) {
686 aName.erase(aSuffix + 1, aName.end());
688 if (theEdgeVertexPos == 1) {
689 aName += "s"; // start
690 } else if (theEdgeVertexPos == 2) {
696 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
697 bool Model_SelectionNaming::selectSubShape(const std::string& theType,
698 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
699 std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
701 if(theSubShapeName.empty() || theType.empty()) return false;
702 TopAbs_ShapeEnum aType = translateType(theType);
704 // check that it was selected in another document
705 size_t aSlash = theSubShapeName.find("/");
706 std::string aSubShapeName = theSubShapeName;
707 std::shared_ptr<Model_Document> aDoc = theDoc;
708 if (aSlash != std::string::npos) {
709 std::string aDocName = theSubShapeName.substr(0, aSlash);
710 ResultPartPtr aFoundPart;
711 DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
712 if (aDocName == aRootDoc->kind()) {
713 aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
715 for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
716 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
717 aRootDoc->object(ModelAPI_ResultPart::group(), a));
718 if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
719 aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
725 if (aDoc != theDoc) {
726 // so, the first word is the document name => reduce the string for the next manips
727 aSubShapeName = theSubShapeName.substr(aSlash + 1);
728 if (aSubShapeName.empty() && aFoundPart.get()) { // the whole Part result
729 theCont = aFoundPart;
735 std::string aContName = getContextName(aSubShapeName);
736 if(aContName.empty()) return false;
737 ResultPtr aCont = aDoc->findByName(aContName);
738 // possible this is body where postfix is added to distinguish several shapes on the same label
739 int aSubShapeId = -1; // -1 means sub shape not found
740 // for result body the name wihtout "_" has higher priority than with it: it is always added
741 if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) &&
742 aContName == aSubShapeName) {
743 size_t aPostIndex = aContName.rfind('_');
744 if (aPostIndex != std::string::npos) {
745 std::string aSubContName = aContName.substr(0, aPostIndex);
746 ResultPtr aSubCont = aDoc->findByName(aSubContName);
747 if (aSubCont.get()) {
749 std::string aNum = aContName.substr(aPostIndex + 1);
750 aSubShapeId = std::stoi(aNum);
751 } catch (std::invalid_argument&) {
754 if (aSubShapeId > 0) {
755 aContName = aSubContName;
763 TopoDS_Shape aSelection;
769 aSelection = findFaceByName(aSubShapeName, aDoc);
774 const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
775 if(!aLabel.IsNull()) {
776 Handle(TNaming_NamedShape) aNS;
777 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
778 aSelection = getShapeFromNS(aSubShapeName, aNS);
785 const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
786 if(!aLabel.IsNull()) {
787 Handle(TNaming_NamedShape) aNS;
788 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
789 aSelection = getShapeFromNS(aSubShapeName, aNS);
794 case TopAbs_COMPOUND:
795 case TopAbs_COMPSOLID:
798 default: {//TopAbs_SHAPE
799 /// case when the whole sketch is selected, so,
800 /// selection type is compound, but there is no value
801 if (aCont.get() && aCont->shape().get()) {
802 if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
805 } else if (aSubShapeId > 0) { // try to find sub-shape by the index
806 TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
807 for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
811 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
812 aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
813 theShapeToBeSelected = aShapeToBeSelected;
822 // another try to find edge or vertex by faces
823 std::list<std::string> aListofNames;
824 size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
825 if (aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) {
826 if(aN > 1 && (aN < 4 || (aType == TopAbs_EDGE && aN < 5))) { // 2 || 3 or 4 for EDGE
827 TopTools_ListOfShape aList;
828 std::list<std::string>::iterator it = aListofNames.begin();
829 for(; it != aListofNames.end(); it++){
830 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
834 aSelection = findCommonShape(aType, aList);
837 // in case of construction, there is no registered names for all sub-elements,
838 // even for the main element; so, trying to find them by name (without "&" intersections)
840 size_t aConstrNamePos = aSubShapeName.find("/");
841 bool isFullName = aConstrNamePos == std::string::npos;
842 std::string aContrName = aContName;
843 ResultPtr aConstr = aDoc->findByName(aContrName);
844 if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
847 // For the full construction selection shape must be empty.
848 //theShapeToBeSelected = aConstr->shape();
851 // for sketch sub-elements selected
852 CompositeFeaturePtr aComposite =
853 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
854 if (aComposite.get()) {
855 if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
856 // collect all IDs in the name
857 std::map<int, int> anIDs;
858 if (!parseSubIndices(aComposite, aSubShapeName,
859 aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs))
862 const int aSubNum = aComposite->numberOfSubs();
863 for(int a = 0; a < aSubNum; a++) {
864 int aCompID = aComposite->subFeatureId(a);
865 if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
866 FeaturePtr aSub = aComposite->subFeature(a);
867 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
868 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
869 // there may be many shapes (circle and center)
870 for(; aRIt != aResults.cend(); aRIt++) {
871 ResultConstructionPtr aRes =
872 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
874 int anOrientation = abs(anIDs[aCompID]);
875 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
876 if (anOrientation == 1) {
877 if (aType == aShape.ShapeType()) {
878 theShapeToBeSelected = aRes->shape();
881 } else { // take first or second vertex of the edge
882 TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
883 TopExp_Explorer anExp(aShape, aType);
884 for(; anExp.More() && anOrientation != 2; anOrientation--)
887 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
888 aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
889 theShapeToBeSelected = aShapeToBeSelected;
897 // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
898 } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
899 std::map<int, int> anIDs;
900 if (!parseSubIndices(aComposite, aSubShapeName,
901 aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
904 // curves and orientations of edges
905 NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
906 const int aSubNum = aComposite->numberOfSubs();
907 for(int a = 0; a < aSubNum; a++) {
908 int aSubID = aComposite->subFeatureId(a);
909 if (anIDs.find(aSubID) != anIDs.end()) {
910 FeaturePtr aSub = aComposite->subFeature(a);
911 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
912 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
913 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
914 ResultConstructionPtr aConstr =
915 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
916 if (aConstr->shape() && aConstr->shape()->isEdge()) {
917 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
918 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
919 if (!anEdge.IsNull()) {
920 Standard_Real aFirst, aLast;
921 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
922 allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
928 std::shared_ptr<GeomAPI_Shape> aFoundFW =
929 findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
930 if (aFoundFW.get()) {
931 theShapeToBeSelected = aFoundFW;
934 } else if (aType == TopAbs_WIRE) {
935 // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
936 std::map<int, int> anIDs;
937 if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
940 // curves and orientations of edges
941 NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
942 const int aSubNum = aComposite->numberOfSubs();
943 for(int a = 0; a < aSubNum; a++) {
944 int aSubID = aComposite->subFeatureId(a);
945 if (anIDs.find(aSubID) != anIDs.end()) {
946 FeaturePtr aSub = aComposite->subFeature(a);
947 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
948 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
949 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
950 ResultConstructionPtr aConstr =
951 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
952 if (aConstr->shape() && aConstr->shape()->isEdge()) {
953 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
954 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
955 if (!anEdge.IsNull()) {
956 Standard_Real aFirst, aLast;
957 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
958 allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
964 std::shared_ptr<GeomAPI_Shape> aFoundFW =
965 findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
966 if (aFoundFW.get()) {
967 theShapeToBeSelected = aFoundFW;
974 if (!aSelection.IsNull()) {
975 // Select it (must be after N=0 checking,
976 // since for simple constructions the shape must be null)
977 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
978 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
979 theShapeToBeSelected = aShapeToBeSelected;