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