Salome HOME
Fix for the issue #2248 and issue #2251 : same curves sketch edges (splitted to make...
[modules/shaper.git] / src / Model / Model_SelectionNaming.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
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.
7 //
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.
12 //
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
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "Model_SelectionNaming.h"
22 #include "Model_Document.h"
23 #include "Model_Objects.h"
24 #include "Model_Data.h"
25 #include <ModelAPI_Feature.h>
26 #include <Events_InfoMessage.h>
27 #include <ModelAPI_Session.h>
28 #include <ModelAPI_ResultPart.h>
29 #include <ModelAPI_ResultConstruction.h>
30 #include <ModelAPI_CompositeFeature.h>
31 #include <ModelAPI_ResultBody.h>
32 #include <GeomAPI_Wire.h>
33
34 #include <TopoDS_Iterator.hxx>
35 #include <TopoDS.hxx>
36 #include <TopoDS_Compound.hxx>
37 #include <TopExp.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <TopTools_ListOfShape.hxx>
40 #include <TopTools_MapOfShape.hxx>
41 #include <TopTools_IndexedMapOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
43 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
44 #include <TopTools_MapIteratorOfMapOfShape.hxx>
45 #include <BRep_Builder.hxx>
46 #include <TNaming_Iterator.hxx>
47 #include <TNaming_Tool.hxx>
48 #include <TNaming_NamedShape.hxx>
49 #include <TNaming_Localizer.hxx>
50 #include <TDataStd_Name.hxx>
51 #include <TColStd_MapOfTransient.hxx>
52 #include <algorithm>
53 #include <stdexcept>
54
55 #ifdef DEB_NAMING
56 #include <BRepTools.hxx>
57 #endif
58
59 Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
60 {
61   myLab = theSelectionLab;
62 }
63
64 std::string Model_SelectionNaming::getShapeName(
65   std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
66   ResultPtr& theContext, const bool theAnotherDoc, const bool theWholeContext)
67 {
68   std::string aName;
69   // add the result name to the name of the shape
70   // (it was in BodyBuilder, but did not work on Result rename)
71   bool isNeedContextName = theContext->shape().get() != NULL;
72   // check if the subShape is already in DF
73   Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, myLab);
74   Handle(TDataStd_Name) anAttr;
75   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
76     if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
77       std::shared_ptr<Model_Data> aData =
78         std::dynamic_pointer_cast<Model_Data>(theContext->data());
79       if (isNeedContextName && aData && aData->label().IsEqual(aNS->Label())) {
80         // do nothing because this context name will be added later in this method
81       } else {
82         aName = TCollection_AsciiString(anAttr->Get()).ToCString();
83         // indexes are added to sub-shapes not primitives
84         // (primitives must not be located at the same label)
85         if(!aName.empty() && aNS->Evolution() != TNaming_PRIMITIVE && isNeedContextName) {
86           const TDF_Label& aLabel = aNS->Label();//theDoc->findNamingName(aName);
87           static const std::string aPostFix("_");
88           TNaming_Iterator anItL(aNS);
89           for(int i = 1; anItL.More(); anItL.Next(), i++) {
90             // in #1766 IsEqual produced no index of the face
91             if(anItL.NewShape().IsSame(theShape)) {
92               aName += aPostFix;
93               aName += TCollection_AsciiString (i).ToCString();
94               break;
95             }
96           }
97         }
98         // if a shape is under another context, use this name, not theContext
99         std::shared_ptr<Model_Data> aContextData =
100           std::dynamic_pointer_cast<Model_Data>(theContext->data());
101         // for constructions the naming is in arguments and has no evolution, so, apply this only
102         // for bodies
103         if (isNeedContextName && theContext->groupName() == ModelAPI_ResultBody::group() &&
104             !aNS->Label().IsDescendant(aContextData->label())) {
105           isNeedContextName = false;
106           TDF_Label aNSDataLab = aNS->Label();
107           while(aNSDataLab.Depth() != 7 && aNSDataLab.Depth() > 5)
108             aNSDataLab = aNSDataLab.Father();
109           ObjectPtr aNewContext = theDoc->objects()->object(aNSDataLab);
110           if (!aNewContext.get() && aNSDataLab.Depth() == 7) {
111             aNSDataLab = aNSDataLab.Father().Father();
112             aNewContext = theDoc->objects()->object(aNSDataLab);
113           }
114           if (aNewContext.get()) {
115             aName = aNewContext->data()->name() + "/" + aName;
116           }
117         }
118       }
119     }
120   }
121
122   // Name is empty and this is full context, it just add the whole context name that must be added
123   bool isEmptyName = aName.empty();
124   if (isNeedContextName && (!isEmptyName || theWholeContext)) {
125     aName = theContext->data()->name() + (isEmptyName ? "" : ("/" + aName));
126     if (theAnotherDoc)
127       aName = theContext->document()->kind() + "/" + aName; // PartSet
128   }
129   return aName;
130 }
131
132 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
133 {
134   // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
135   TopoDS_Compound aCmp;
136   BRep_Builder BB;
137   BB.MakeCompound(aCmp);
138   TopTools_ListIteratorOfListOfShape it(theAncestors);
139   for(;it.More();it.Next()) {
140     if (theSMap.Contains(it.Value()))
141       continue;
142     BB.Add(aCmp, it.Value());
143     theSMap.Add(it.Value());
144   }
145   int aNumber(0);
146   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
147   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
148   for (int i = 1; i <= aMap2.Extent(); i++) {
149     const TopoDS_Shape& aKey = aMap2.FindKey(i);
150     const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
151     if(anAncestors.Extent() > 1) aNumber++;
152   }
153   if(aNumber > 1) return false;
154   return true;
155 }
156
157 const TopoDS_Shape findCommonShape(
158   const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
159 {
160   if(theList.Extent() < 1) {
161     return TopoDS_Shape();
162   } else if (theList.Extent() == 1) { // check that sub-shape is bounded by this alone shape
163     TopTools_MapOfShape aSubsInShape;
164     TopExp_Explorer anExp(theList.First(), theType);
165     for(; anExp.More(); anExp.Next()) {
166       if (aSubsInShape.Contains(anExp.Current())) { // found duplicate
167         return anExp.Current();
168       }
169       aSubsInShape.Add(anExp.Current());
170     }
171   }
172
173   // Store in maps sub-shapes from each face.
174   std::vector<TopTools_MapOfShape> aVec;
175   for(TopTools_ListIteratorOfListOfShape anIt(theList); anIt.More(); anIt.Next()) {
176     const TopoDS_Shape aFace = anIt.Value();
177     TopTools_MapOfShape aMap;
178     for(TopExp_Explorer anExp(aFace, theType); anExp.More(); anExp.Next()) {
179       const TopoDS_Shape& aSubShape = anExp.Current();
180       aMap.Add(anExp.Current());
181     }
182     aVec.push_back(aMap);
183   }
184
185   // Find sub-shape shared between all faces.
186   TopoDS_Shape aSharedShape;
187   for(TopTools_MapIteratorOfMapOfShape anIt(aVec[0]); anIt.More(); anIt.Next()) {
188     const TopoDS_Shape& aSubShape = anIt.Value();
189     int aSharedNb = 1;
190     for(int anIndex = 1; anIndex < aVec.size(); ++anIndex) {
191       if(aVec[anIndex].Contains(aSubShape)) {
192         ++aSharedNb;
193       }
194     }
195     if(aSharedNb == theList.Extent()) {
196       if(aSharedShape.IsNull()) {
197         aSharedShape = aSubShape;
198       } else {
199         // More than one shape shared between all faces, return null shape in this case.
200         return TopoDS_Shape();
201       }
202     }
203   }
204
205   return aSharedShape;
206 }
207
208 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
209   std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
210   const bool theAnotherDoc)
211 {
212   std::string aName("Undefined name");
213   if(!theContext.get()
214       || !theContext->shape().get()
215       || theContext->shape()->isNull()) {
216     return !theDefaultName.empty() ? theDefaultName : aName;
217   }
218
219   // if it is in result of another part
220   std::shared_ptr<Model_Document> aDoc =
221     std::dynamic_pointer_cast<Model_Document>(theContext->document());
222   if (theContext->groupName() == ModelAPI_ResultPart::group()) {
223     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
224     int anIndex;
225     if (theSubSh.get())
226       return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
227     else
228       return aPart->data()->name();
229   }
230
231   if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
232     // but if it is in another Part, add this part name
233     std::string aPartName;
234     if (theAnotherDoc)
235       aPartName = theContext->document()->kind() + "/"; // PartSet
236     return aPartName + theContext->data()->name();
237   }
238   TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
239   TopoDS_Shape aContext  = theContext->shape()->impl<TopoDS_Shape>();
240 #ifdef DEB_NAMING
241   if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
242     BRepTools::Write(aSubShape, "Selection.brep");
243     BRepTools::Write(aContext, "Context.brep");
244   }
245 #endif
246   aName = getShapeName(aDoc, aSubShape, theContext, theAnotherDoc,
247     theContext->shape()->isEqual(theSubSh));
248
249   if(aName.empty() ) { // not in the document!
250     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
251     switch (aType) {
252     case TopAbs_FACE:
253       // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
254       break;
255     case TopAbs_EDGE:
256       {
257         // name structure: F1 & F2 [& F3 & F4],
258         // where F1 & F2 the faces which gives the Edge in trivial case
259         // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
260         if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
261           aName = "Degenerated_Edge";
262           break;
263         }
264         TopTools_IndexedDataMapOfShapeListOfShape aMap;
265         TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
266         TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
267         bool isTrivialCase(true);
268         if(aMap.Contains(aSubShape)) {
269           const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
270           // check that it is not a trivial case (F1 & F2: aNumber = 1)
271           isTrivialCase = isTrivial(anAncestors, aSMap);
272           if (!isTrivialCase) { // another try: check that getting of common shape can be done simply
273             isTrivialCase = !findCommonShape(TopAbs_EDGE, anAncestors).IsNull();
274           }
275         } else
276           break;
277         TopTools_ListOfShape aListOfNbs;
278         if(!isTrivialCase) { // find Neighbors
279           TNaming_Localizer aLocalizer;
280           TopTools_MapOfShape aMap3;
281           aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
282           //int n = aMap3.Extent();
283           TopTools_MapIteratorOfMapOfShape it(aMap3);
284           for(;it.More();it.Next()) {
285             const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
286             //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
287             const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
288             TopTools_ListIteratorOfListOfShape it2(aList);
289             for(;it2.More();it2.Next()) {
290               if(aSMap.Contains(it2.Value())) continue; // skip this Face
291               aListOfNbs.Append(it2.Value());
292             }
293           }
294         }  // else a trivial case
295
296         // build name of the sub-shape Edge
297         for(int i=1; i <= aSMap.Extent(); i++) {
298           const TopoDS_Shape& aFace = aSMap.FindKey(i);
299           std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
300           if(i == 1)
301             aName = aFaceName;
302           else
303             aName += "&" + aFaceName;
304         }
305         TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
306         for (;itl.More();itl.Next()) {
307           std::string aFaceName = getShapeName(aDoc, itl.Value(), theContext, theAnotherDoc, false);
308           aName += "&" + aFaceName;
309         }
310       }
311       break;
312
313     case TopAbs_VERTEX:
314       // name structure (Monifold Topology):
315       // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
316       // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition,
317       //                               but it should be kept as is to obtain safe recomputation
318       // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
319       //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
320       // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
321       //                   or compound of 2 open faces.
322       // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of
323       //                   two independent edges (wire or compound)
324       // implemented 2 first cases
325       {
326         TopTools_IndexedDataMapOfShapeListOfShape aMap;
327         TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
328         TopTools_ListOfShape aList;
329         TopTools_MapOfShape aFMap;
330         // simetimes when group is moved in history, naming may be badly updated, so
331         // avoid crash in FindFromKey (issue 1842)
332         if (aMap.Contains(aSubShape)) {
333           const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
334           // fix is below
335           TopTools_ListIteratorOfListOfShape itl2(aList2);
336           for (int i = 1;itl2.More();itl2.Next(),i++) {
337             if(aFMap.Add(itl2.Value()))
338               aList.Append(itl2.Value());
339           }
340         } else
341           break;
342         int n = aList.Extent();
343         bool isByFaces = n >= 3;
344         if(!isByFaces) { // open topology case or Compound case => via edges
345           TopTools_IndexedDataMapOfShapeListOfShape aMap;
346           TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
347           const TopTools_ListOfShape& aList22  = aMap.FindFromKey(aSubShape);
348           if(aList22.Extent() >= 2)  { // regular solution
349
350             // bug! duplication; fix is below
351             aFMap.Clear();
352             TopTools_ListOfShape aListE;
353             TopTools_ListIteratorOfListOfShape itl2(aList22);
354             for (int i = 1;itl2.More();itl2.Next(),i++) {
355               if(aFMap.Add(itl2.Value()))
356                 aListE.Append(itl2.Value());
357             }
358             n = aListE.Extent();
359             TopTools_ListIteratorOfListOfShape itl(aListE);
360             for (int i = 1;itl.More();itl.Next(),i++) {
361               const TopoDS_Shape& anEdge = itl.Value();
362               std::string anEdgeName = getShapeName(aDoc, anEdge, theContext, theAnotherDoc, false);
363               if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
364                 isByFaces = true;
365                 aName.clear();
366                 break;
367               }
368               if(i == 1)
369                 aName = anEdgeName;
370               else
371                 aName += "&" + anEdgeName;
372             }
373           }//reg
374           else { // dangle vertex: if(aList22.Extent() == 1)
375             //it should be already in DF
376           }
377         }
378         if (isByFaces) {
379           TopTools_ListIteratorOfListOfShape itl(aList);
380           for (int i = 1;itl.More();itl.Next(),i++) {
381             const TopoDS_Shape& aFace = itl.Value();
382             std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
383             if(i == 1)
384               aName = aFaceName;
385             else
386               aName += "&" + aFaceName;
387           }
388         }
389       }
390       break;
391     }
392   }
393
394   return aName;
395 }
396
397 TopAbs_ShapeEnum translateType (const std::string& theType)
398 {
399   // map from the textual shape types to OCCT enumeration
400   static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
401
402   if(aShapeTypes.size() == 0) {
403     aShapeTypes["compound"]   = TopAbs_COMPOUND;
404     aShapeTypes["compounds"]  = TopAbs_COMPOUND;
405     aShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
406     aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
407     aShapeTypes["solid"]      = TopAbs_SOLID;
408     aShapeTypes["solids"]     = TopAbs_SOLID;
409     aShapeTypes["shell"]      = TopAbs_SHELL;
410     aShapeTypes["shells"]     = TopAbs_SHELL;
411     aShapeTypes["face"]       = TopAbs_FACE;
412     aShapeTypes["faces"]      = TopAbs_FACE;
413     aShapeTypes["wire"]       = TopAbs_WIRE;
414     aShapeTypes["wires"]      = TopAbs_WIRE;
415     aShapeTypes["edge"]       = TopAbs_EDGE;
416     aShapeTypes["edges"]      = TopAbs_EDGE;
417     aShapeTypes["vertex"]     = TopAbs_VERTEX;
418     aShapeTypes["vertices"]   = TopAbs_VERTEX;
419     aShapeTypes["COMPOUND"]   = TopAbs_COMPOUND;
420     aShapeTypes["COMPOUNDS"]  = TopAbs_COMPOUND;
421     aShapeTypes["COMPSOLID"]  = TopAbs_COMPSOLID;
422     aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
423     aShapeTypes["SOLID"]      = TopAbs_SOLID;
424     aShapeTypes["SOLIDS"]     = TopAbs_SOLID;
425     aShapeTypes["SHELL"]      = TopAbs_SHELL;
426     aShapeTypes["SHELLS"]     = TopAbs_SHELL;
427     aShapeTypes["FACE"]       = TopAbs_FACE;
428     aShapeTypes["FACES"]      = TopAbs_FACE;
429     aShapeTypes["WIRE"]       = TopAbs_WIRE;
430     aShapeTypes["WIRES"]      = TopAbs_WIRE;
431     aShapeTypes["EDGE"]       = TopAbs_EDGE;
432     aShapeTypes["EDGES"]      = TopAbs_EDGE;
433     aShapeTypes["VERTEX"]     = TopAbs_VERTEX;
434     aShapeTypes["VERTICES"]   = TopAbs_VERTEX;
435   }
436   if (aShapeTypes.find(theType) != aShapeTypes.end())
437     return aShapeTypes[theType];
438   Events_InfoMessage("Model_SelectionNaming",
439     "Shape type defined in XML is not implemented!").send();
440   return TopAbs_SHAPE;
441 }
442
443 const TopoDS_Shape getShapeFromNS(
444   const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
445 {
446   TopoDS_Shape aSelection;
447   std::string::size_type n = theSubShapeName.rfind('/');
448   if (n == std::string::npos) n = -1;
449   std::string aSubString = theSubShapeName.substr(n + 1);
450   n = aSubString.rfind('_');
451   int indx = 1;
452   if (n != std::string::npos) {// for primitives this is a first
453     // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
454     Handle(TDataStd_Name) aName;
455     if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
456         aName->Get() != aSubString.c_str()) {
457       aSubString = aSubString.substr(n+1);
458       indx = atoi(aSubString.c_str());
459     }
460   }
461
462   TNaming_Iterator anItL(theNS);
463   for(int i = 1; anItL.More(); anItL.Next(), i++) {
464     if (i == indx) {
465       return anItL.NewShape();
466     }
467   }
468   return aSelection;
469 }
470
471 const TopoDS_Shape findFaceByName(
472   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
473 {
474   TopoDS_Shape aFace;
475   //std::string::size_type n, nb = theSubShapeName.rfind('/');
476   //if (nb == std::string::npos) nb = 0;
477   //std::string aSubString = theSubShapeName.substr(nb + 1);
478   std::string aSubString = theSubShapeName;
479
480   TDF_Label aLabel = theDoc->findNamingName(aSubString);
481   if (aLabel.IsNull()) { // try to remove additional artificial suffix
482     std::string::size_type n = aSubString.rfind('_');
483     if (n != std::string::npos) {
484       aSubString = aSubString.substr(0, n);
485        aLabel = theDoc->findNamingName(aSubString);
486     }
487   }
488   if(aLabel.IsNull()) return aFace;
489   Handle(TNaming_NamedShape) aNS;
490   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
491     aFace = getShapeFromNS(theSubShapeName, aNS);
492   }
493   return aFace;
494 }
495
496 size_t ParseName(const std::string& theSubShapeName,   std::list<std::string>& theList)
497 {
498   std::string aName = theSubShapeName;
499   std::string aLastName = aName;
500   size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
501   while ((n2 = aName.find('&', n1)) != std::string::npos) {
502     const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
503     theList.push_back(aName1);
504     n1 = n2 + 1;
505     aLastName = aName.substr(n1);
506   }
507   if(!aLastName.empty())
508     theList.push_back(aLastName);
509   return theList.size();
510 }
511
512 std::string getContextName(const std::string& theSubShapeName)
513 {
514   std::string aName;
515   std::string::size_type n = theSubShapeName.find('/');
516   if (n == std::string::npos) return theSubShapeName;
517   aName = theSubShapeName.substr(0, n);
518   return aName;
519 }
520
521 /// Parses naming name of sketch sub-elements: takes indices and orientation
522 /// (if theOriented = true) from this name. Map theIDs constains indices ->
523 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
524 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
525   const std::string& theName, const char* theShapeType,
526   std::map<int, int>& theIDs, const bool theOriented = false)
527 {
528   // collect all IDs in the name
529   std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
530   const int aSubNum = theComp->numberOfSubs();
531   for(int a = 0; a < aSubNum; a++) {
532     FeaturePtr aSub = theComp->subFeature(a);
533     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
534     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
535     // there may be many shapes (circle and center)
536     for(; aRes != aResults.cend(); aRes++) {
537       ResultConstructionPtr aConstr =
538         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
539       if (aConstr.get()) {
540         aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
541       }
542     }
543   }
544
545   size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
546   bool isShape = false; // anyway the first world must be 'Vertex'
547   do {
548     aLastNamePos = theName.find('-', aPrevPos);
549     std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
550     if (!isShape) {
551       if (anID != theShapeType)
552         return false;
553       isShape = true;
554     } else {
555       int anOrientation = 1; // default
556       if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
557         std::string::iterator aSymbol = anID.end() - 1;
558         if (*aSymbol == 'r') anOrientation = -1;
559         anID.erase(aSymbol); // remove last symbol
560       }
561       // check start/end symbols
562       std::string::iterator aBack = anID.end() - 1;
563       if (*aBack == 's') {
564         anOrientation *= 2;
565         anID.erase(aBack); // remove last symbol
566       } else if (*aBack == 'e') {
567         anOrientation *= 3;
568         anID.erase(aBack); // remove last symbol
569       }
570
571       if (aNames.find(anID) != aNames.end()) {
572         theIDs[aNames[anID]] = anOrientation;
573       }
574     }
575     aPrevPos = aLastNamePos + 1;
576   } while (aLastNamePos != std::string::npos);
577   return true;
578 }
579
580 /// produces theEdge orientation relatively to theContext face
581 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
582 {
583   if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
584     return 0;
585   if (theEdge.Orientation() == TopAbs_FORWARD)
586     return 1;
587   if (theEdge.Orientation() == TopAbs_REVERSED)
588     return -1;
589   return 0; // unknown
590 }
591
592 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
593   std::shared_ptr<ModelAPI_Result>& theConstr,
594   NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
595 {
596   int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
597   int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
598   std::shared_ptr<GeomAPI_Shape> aResult;
599   ResultConstructionPtr aConstructionContext =
600       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
601   if (!aConstructionContext.get())
602     return aResult;
603   for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
604     int aFound = 0, aNotFound = 0, aSameOrientation = 0;
605     TopoDS_Face aFace =
606       TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
607     std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
608     if (theIsWire) {
609       for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
610         aFacesWires.push_back(aWires.Current());
611       }
612     } else {
613       aFacesWires.push_back(aFace);
614     }
615     std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
616     for(; aFW != aFacesWires.end(); aFW++) {
617       TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
618       TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
619       for(; anEdgesExp.More(); anEdgesExp.Next()) {
620         TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
621         if (!anEdge.IsNull()) {
622           Standard_Real aFirst, aLast;
623           Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
624           if (alreadyProcessed.Contains(aCurve))
625             continue;
626           alreadyProcessed.Add(aCurve);
627           if (theCurves.IsBound(aCurve)) {
628             aFound++;
629             int anOrient = theCurves.Find(aCurve);
630             if (anOrient != 0) {  // extra comparision score is orientation
631               if (edgeOrientation(aFace, anEdge) == anOrient)
632                 aSameOrientation++;
633             }
634           } else {
635             aNotFound++;
636           }
637         }
638       }
639       if (aFound + aNotFound != 0) {
640         if (aFound > aBestFound ||
641           (aFound == aBestFound && aSameOrientation > aBestOrient)) {
642             aBestFound = aFound;
643             aBestOrient = aSameOrientation;
644             if (theIsWire) {
645               std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
646               aWire->setImpl(new TopoDS_Shape(*aFW));
647               aResult = aWire;
648             } else {
649               aResult = aConstructionContext->face(aFaceIndex);
650             }
651         }
652       }
653     }
654   }
655   return aResult;
656 }
657
658 std::string Model_SelectionNaming::shortName(
659   std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
660 {
661   std::string aName = theConstr->data()->name();
662   // remove "-", "/" and "&" command-symbols
663   aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
664   aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
665   aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
666   // remove the last 's', 'e', 'f' and 'r' symbols:
667   // they are used as markers of start/end/forward/rewersed indicators
668   static const std::string aSyms("sefr");
669   std::string::iterator aSuffix = aName.end() - 1;
670   while(aSyms.find(*aSuffix) != std::string::npos) {
671     --aSuffix;
672   }
673   aName.erase(aSuffix + 1, aName.end());
674
675   if (theEdgeVertexPos == 1) {
676     aName += "s"; // start
677   } else if (theEdgeVertexPos == 2) {
678     aName += "e"; // end
679   }
680   return aName;
681 }
682
683 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
684 bool Model_SelectionNaming::selectSubShape(const std::string& theType,
685   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
686   std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
687 {
688   if(theSubShapeName.empty() || theType.empty()) return false;
689   TopAbs_ShapeEnum aType = translateType(theType);
690
691   // check that it was selected in another document
692   size_t aSlash = theSubShapeName.find("/");
693   std::string aSubShapeName = theSubShapeName;
694   std::shared_ptr<Model_Document> aDoc = theDoc;
695   if (aSlash != std::string::npos) {
696     std::string aDocName = theSubShapeName.substr(0, aSlash);
697     ResultPartPtr aFoundPart;
698     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
699     if (aDocName == aRootDoc->kind()) {
700       aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
701     } else {
702       for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
703         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
704             aRootDoc->object(ModelAPI_ResultPart::group(), a));
705         if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
706           aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
707           aFoundPart = aPart;
708           break;
709         }
710       }
711     }
712     if (aDoc != theDoc) {
713       // so, the first word is the document name => reduce the string for the next manips
714       aSubShapeName = theSubShapeName.substr(aSlash + 1);
715       if (aSubShapeName.empty() && aFoundPart.get()) { // the whole Part result
716         theCont = aFoundPart;
717         return true;
718       }
719     }
720   }
721
722   std::string aContName = getContextName(aSubShapeName);
723   if(aContName.empty()) return false;
724   ResultPtr aCont = aDoc->findByName(aContName);
725    // possible this is body where postfix is added to distinguish several shapes on the same label
726   int aSubShapeId = -1; // -1 means sub shape not found
727   // for result body the name wihtout "_" has higher priority than with it: it is always added
728   if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) &&
729        aContName == aSubShapeName) {
730     size_t aPostIndex = aContName.rfind('_');
731     if (aPostIndex != std::string::npos) {
732       std::string aSubContName = aContName.substr(0, aPostIndex);
733       ResultPtr aSubCont = aDoc->findByName(aSubContName);
734       if (aSubCont.get()) {
735         try {
736           std::string aNum = aContName.substr(aPostIndex + 1);
737           aSubShapeId = std::stoi(aNum);
738         } catch (std::invalid_argument&) {
739           aSubShapeId = -1;
740         }
741         if (aSubShapeId > 0) {
742           aContName = aSubContName;
743           aCont = aSubCont;
744         }
745       }
746     }
747   }
748
749
750   TopoDS_Shape aSelection;
751   switch (aType)
752   {
753   case TopAbs_FACE:
754   case TopAbs_WIRE:
755     {
756       aSelection = findFaceByName(aSubShapeName, aDoc);
757     }
758     break;
759   case TopAbs_EDGE:
760     {
761       const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
762       if(!aLabel.IsNull()) {
763         Handle(TNaming_NamedShape) aNS;
764         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
765           aSelection = getShapeFromNS(aSubShapeName, aNS);
766         }
767       }
768     }
769     break;
770   case TopAbs_VERTEX:
771     {
772       const TDF_Label& aLabel = aDoc->findNamingName(aSubShapeName);
773       if(!aLabel.IsNull()) {
774         Handle(TNaming_NamedShape) aNS;
775         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
776           aSelection = getShapeFromNS(aSubShapeName, aNS);
777         }
778       }
779     }
780     break;
781   case TopAbs_COMPOUND:
782   case TopAbs_COMPSOLID:
783   case TopAbs_SOLID:
784   case TopAbs_SHELL:
785   default: {//TopAbs_SHAPE
786     /// case when the whole sketch is selected, so,
787     /// selection type is compound, but there is no value
788     if (aCont.get() && aCont->shape().get()) {
789       if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
790         theCont = aCont;
791         return true;
792       } else if (aSubShapeId > 0) { // try to find sub-shape by the index
793         TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
794         for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
795           anExp.Next();
796         }
797         if (anExp.More()) {
798           std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
799           aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
800           theShapeToBeSelected = aShapeToBeSelected;
801           theCont = aCont;
802           return true;
803         }
804       }
805     }
806     return false;
807     }
808   }
809   if (!aSelection.IsNull() &&
810       aSelection.ShapeType() != aType && aSelection.ShapeType() != TopAbs_COMPOUND)
811       aSelection.Nullify(); // to avoid selection of face instead of edge that is described by face
812   // another try to find edge or vertex by faces
813   std::list<std::string> aListofNames;
814   size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
815   if ((aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) ||
816       (!aSelection.IsNull() && aSelection.ShapeType() != aType)) { // edge by one face as example
817     if(aN >= 1) {
818       TopTools_ListOfShape aList;
819       std::list<std::string>::iterator it = aListofNames.begin();
820       for(; it != aListofNames.end(); it++){
821         const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
822         if(!aFace.IsNull())
823           aList.Append(aFace);
824       }
825       aSelection = findCommonShape(aType, aList);
826     }
827   }
828   // in case of construction, there is no registered names for all sub-elements,
829   // even for the main element; so, trying to find them by name (without "&" intersections)
830   if (aN < 2) {
831     size_t aConstrNamePos = aSubShapeName.find("/");
832     bool isFullName = aConstrNamePos == std::string::npos;
833     std::string aContrName = aContName;
834     ResultPtr aConstr = aDoc->findByName(aContrName);
835     if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
836       theCont = aConstr;
837       if (isFullName) {
838         // For the full construction selection shape must be empty.
839         //theShapeToBeSelected = aConstr->shape();
840         return true;
841       }
842       // for sketch sub-elements selected
843       CompositeFeaturePtr aComposite =
844         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
845       if (aComposite.get()) {
846         if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
847           // collect all IDs in the name
848           std::map<int, int> anIDs;
849           if (!parseSubIndices(aComposite, aSubShapeName,
850               aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs))
851             return false;
852
853           const int aSubNum = aComposite->numberOfSubs();
854           for(int a = 0; a < aSubNum; a++) {
855             int aCompID = aComposite->subFeatureId(a);
856             if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
857               FeaturePtr aSub = aComposite->subFeature(a);
858               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
859               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
860               // there may be many shapes (circle and center)
861               for(; aRIt != aResults.cend(); aRIt++) {
862                 ResultConstructionPtr aRes =
863                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
864                 if (aRes) {
865                   int anOrientation = abs(anIDs[aCompID]);
866                   TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
867                   if (anOrientation == 1) {
868                     if (aType == aShape.ShapeType()) {
869                       theShapeToBeSelected = aRes->shape();
870                       return true;
871                     }
872                   } else { // take first or second vertex of the edge
873                     TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
874                     if (aShape.ShapeType() == TopAbs_VERTEX) continue;
875                     TopExp_Explorer anExp(aShape, aType);
876                     for(; anExp.More() && anOrientation != 2; anOrientation--)
877                       anExp.Next();
878                     if (anExp.More()) {
879                       std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
880                       aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
881                       theShapeToBeSelected = aShapeToBeSelected;
882                       return true;
883                     }
884                   }
885                 }
886               }
887             }
888           }
889           // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
890         } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
891           std::map<int, int> anIDs;
892           if (!parseSubIndices(aComposite, aSubShapeName,
893               aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
894             return false;
895
896           // curves and orientations of edges
897           NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
898           const int aSubNum = aComposite->numberOfSubs();
899           for(int a = 0; a < aSubNum; a++) {
900             int aSubID = aComposite->subFeatureId(a);
901             if (anIDs.find(aSubID) != anIDs.end()) {
902               FeaturePtr aSub = aComposite->subFeature(a);
903               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
904               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
905               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
906                 ResultConstructionPtr aConstr =
907                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
908                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
909                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
910                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
911                   if (!anEdge.IsNull()) {
912                     Standard_Real aFirst, aLast;
913                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
914                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
915                   }
916                 }
917               }
918             }
919           }
920           std::shared_ptr<GeomAPI_Shape> aFoundFW =
921             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
922           if (aFoundFW.get()) {
923             theShapeToBeSelected = aFoundFW;
924             return true;
925           }
926         } else if (aType == TopAbs_WIRE) {
927           // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
928           std::map<int, int> anIDs;
929           if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
930             return false;
931
932            // curves and orientations of edges
933           NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
934           const int aSubNum = aComposite->numberOfSubs();
935           for(int a = 0; a < aSubNum; a++) {
936             int aSubID = aComposite->subFeatureId(a);
937             if (anIDs.find(aSubID) != anIDs.end()) {
938               FeaturePtr aSub = aComposite->subFeature(a);
939               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
940               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
941               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
942                 ResultConstructionPtr aConstr =
943                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
944                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
945                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
946                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
947                   if (!anEdge.IsNull()) {
948                     Standard_Real aFirst, aLast;
949                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
950                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
951                   }
952                 }
953               }
954             }
955           }
956           std::shared_ptr<GeomAPI_Shape> aFoundFW =
957             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
958           if (aFoundFW.get()) {
959             theShapeToBeSelected = aFoundFW;
960             return true;
961           }
962         }
963       }
964     }
965   }
966   if (!aSelection.IsNull()) {
967     // Select it (must be after N=0 checking,
968     // since for simple constructions the shape must be null)
969     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
970     aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
971     theShapeToBeSelected = aShapeToBeSelected;
972     theCont = aCont;
973     return true;
974   }
975
976   return false;
977 }