]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
4457c08afba2465019076ba435ea31022ba005d4
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_AttributeSelection.cpp
4 // Created:     2 Oct 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include "Model_AttributeSelection.h"
8 #include "Model_Application.h"
9 #include "Model_Events.h"
10 #include "Model_Data.h"
11 #include "Model_Document.h"
12 #include "Model_SelectionNaming.h"
13 #include <ModelAPI_Feature.h>
14 #include <ModelAPI_ResultBody.h>
15 #include <ModelAPI_ResultConstruction.h>
16 #include <ModelAPI_ResultPart.h>
17 #include <ModelAPI_CompositeFeature.h>
18 #include <GeomAPI_Shape.h>
19 #include <GeomAPI_PlanarEdges.h>
20 #include <Events_Error.h>
21
22 #include <TNaming_Selector.hxx>
23 #include <TNaming_NamedShape.hxx>
24 #include <TNaming_Tool.hxx>
25 #include <TNaming_Builder.hxx>
26 #include <TNaming_Localizer.hxx>
27 #include <TopoDS_Shape.hxx>
28 #include <TopoDS_Compound.hxx>
29 #include <TDataStd_IntPackedMap.hxx>
30 #include <TDataStd_Integer.hxx>
31 #include <TDataStd_UAttribute.hxx>
32 #include <TDataStd_Name.hxx>
33 #include <TopTools_MapOfShape.hxx>
34 #include <TopTools_IndexedMapOfShape.hxx>
35 #include <TopTools_MapIteratorOfMapOfShape.hxx>
36 #include <TopTools_ListOfShape.hxx>
37 #include <NCollection_DataMap.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <TDF_LabelMap.hxx>
40 #include <BRep_Tool.hxx>
41 #include <BRep_Builder.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS.hxx>
44 #include <TopExp.hxx>
45 #include <TColStd_MapOfTransient.hxx>
46 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
47 #include <TopTools_ListIteratorOfListOfShape.hxx>
48 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
49 #include <gp_Pnt.hxx>
50 #include <Precision.hxx>
51 #include <TDF_ChildIterator.hxx>
52 #include <TDF_ChildIDIterator.hxx>
53 #include <TDataStd_Name.hxx>
54 #include <TopAbs_ShapeEnum.hxx>
55 #include <TopoDS_Iterator.hxx>
56 #include <TNaming_Iterator.hxx>
57 using namespace std;
58 //#define DEB_NAMING 1
59 #ifdef DEB_NAMING
60 #include <BRepTools.hxx>
61 #endif
62 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
63 /// (multiplied by the index of the edge)
64 static const int kSTART_VERTEX_DELTA = 1000000;
65 // identifier that there is simple reference: selection equals to context
66 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
67 // simple reference in the construction
68 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
69 // reference to Part sub-object
70 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
71
72 // on this label is stored:
73 // TNaming_NamedShape - selected shape
74 // TNaming_Naming - topological selection information (for the body)
75 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
76 // TDataStd_Integer - type of the selected shape (for construction)
77 // TDF_Reference - from ReferenceAttribute, the context
78 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
79   const std::shared_ptr<GeomAPI_Shape>& theSubShape)
80 {
81   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
82   bool isOldContext = theContext == myRef.value();
83   bool isOldShape = isOldContext &&
84     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
85   if (isOldShape) return; // shape is the same, so context is also unchanged
86   // update the referenced object if needed
87   if (!isOldContext)
88     myRef.setValue(theContext);
89
90   // do noth use naming if selected shape is result shape itself, but not sub-shape
91   TDF_Label aSelLab = selectionLabel();
92   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
93   aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
94
95   bool isDegeneratedEdge = false;
96   // do not use the degenerated edge as a shape, a null context and shape is used in the case
97   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
98     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
99     if (aSubShape.ShapeType() == TopAbs_EDGE)
100       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
101   }
102   if (!theContext.get() || isDegeneratedEdge) {
103     // to keep the reference attribute label
104     TDF_Label aRefLab = myRef.myRef->Label();
105     aSelLab.ForgetAllAttributes(true);
106     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
107     return;
108   }
109   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
110     // do not select the whole shape for body:it is already must be in the data framework
111     // equal and null selected objects mean the same: object is equal to context,
112     // TODO: synchronize with GUI later that it must be null always
113     if (theContext->shape().get() && 
114         (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
115       aSelLab.ForgetAllAttributes(true);
116       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
117     } else {
118       selectBody(theContext, theSubShape);
119     }
120   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
121     if (!theSubShape.get()) {
122       // to sub, so the whole result is selected
123       aSelLab.ForgetAllAttributes(true);
124       TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
125     } else {
126       selectConstruction(theContext, theSubShape);
127     }
128   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
129     aSelLab.ForgetAllAttributes(true);
130     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
131     selectPart(theContext, theSubShape);
132   }
133   //the attribute initialized state should be changed by sendAttributeUpdated only
134   //myIsInitialized = true;
135
136   owner()->data()->sendAttributeUpdated(this);
137
138   std::string aSelName = namingName();
139   if(!aSelName.empty())
140     TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
141 }
142
143 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
144 {
145   std::shared_ptr<GeomAPI_Shape> aResult;
146   if (myRef.isInitialized()) {
147     TDF_Label aSelLab = selectionLabel();
148     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
149       ResultPtr aContext = context();
150       if (!aContext.get()) 
151         return aResult; // empty result
152       return aContext->shape();
153     }
154     if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
155         return aResult; // empty result
156     }
157     if (aSelLab.IsAttribute(kPART_REF_ID)) {
158       /* TODO: implement used text here
159       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
160       if (!aPart.get() || !aPart->isActivated())
161         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
162       Handle(TDataStd_Integer) anIndex;
163       if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
164         return aPart->selectionValue(anIndex->Get());
165       }
166       Handle(TDataStd_Name) aName;
167       if (!selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
168         return std::shared_ptr<GeomAPI_Shape>(); // something is wrong
169       }
170       return aPart->shapeInPart(TCollection_AsciiString(aName).ToCString());
171       */
172     }
173
174     Handle(TNaming_NamedShape) aSelection;
175     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
176       TopoDS_Shape aSelShape = aSelection->Get();
177       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
178       aResult->setImpl(new TopoDS_Shape(aSelShape));
179     } else { // for simple construction element: just shape of this construction element
180       ResultConstructionPtr aConstr = 
181         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
182       if (aConstr) {
183         return aConstr->shape();
184       }
185     }
186   }
187   return aResult;
188 }
189
190 bool Model_AttributeSelection::isInitialized()
191 {
192   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checkings if it is initialized
193     std::shared_ptr<GeomAPI_Shape> aResult;
194     if (myRef.isInitialized()) {
195       TDF_Label aSelLab = selectionLabel();
196       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
197         ResultPtr aContext = context();
198         return aContext.get() != NULL;
199       }
200       if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
201           return true;
202       }
203
204       Handle(TNaming_NamedShape) aSelection;
205       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
206         return !aSelection->Get().IsNull();
207       } else { // for simple construction element: just shape of this construction element
208         ResultConstructionPtr aConstr = 
209           std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
210         if (aConstr.get()) {
211           return aConstr->shape().get() != NULL;
212         }
213       }
214     }
215   }
216   return false;
217 }
218
219 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
220   : myRef(theLabel)
221 {
222   myIsInitialized = myRef.isInitialized();
223 }
224
225 void Model_AttributeSelection::setID(const std::string theID)
226 {
227   myRef.setID(theID);
228   ModelAPI_AttributeSelection::setID(theID);
229 }
230
231 ResultPtr Model_AttributeSelection::context() {
232   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
233   // for parts there could be same-data result, so take the last enabled
234   if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
235     int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
236     for(int a = aSize - 1; a >= 0; a--) {
237       ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
238       if (aPart.get() && aPart->data() == aResult->data()) {
239         ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
240         FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
241         // check that this result is not this-feature result (it is forbidden t oselect itself)
242         if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
243           return aPartResult;
244         }
245       }
246     }
247   }
248   return aResult;
249 }
250
251
252 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
253 {
254   ModelAPI_AttributeSelection::setObject(theObject);
255   myRef.setObject(theObject);
256 }
257
258 TDF_LabelMap& Model_AttributeSelection::scope()
259 {
260   if (myScope.IsEmpty()) { // create a new scope if not yet done
261     // gets all featueres with named shapes that are bofore this feature label (before in history)
262     DocumentPtr aMyDoc = owner()->document();
263     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
264     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
265     for(; aFIter != allFeatures.end(); aFIter++) {
266       if (*aFIter == owner()) break; // the left features are created later
267       if (aFIter->get() && (*aFIter)->data()->isValid()) {
268         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
269           (*aFIter)->data())->label().Father();
270         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), 1);
271         for(; aNSIter.More(); aNSIter.Next()) {
272           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
273           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
274             myScope.Add(aNS->Label());
275           }
276         }
277       }
278     }
279   }
280   return myScope;
281 }
282
283 /// produces theEdge orientation relatively to theContext face
284 int edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
285 {
286   if (theContext.ShapeType() != TopAbs_FACE)
287     return 0;
288   TopoDS_Face aContext = TopoDS::Face(theContext);
289   if (theEdge.Orientation() == TopAbs_FORWARD) 
290     return 1;
291   if (theEdge.Orientation() == TopAbs_REVERSED) 
292     return -1;
293   return 0; // unknown
294 }
295
296 bool Model_AttributeSelection::update()
297 {
298   ResultPtr aContext = context();
299   if (!aContext.get()) return false;
300   TDF_Label aSelLab = selectionLabel();
301   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
302     return aContext->shape() && !aContext->shape()->isNull();
303   }
304   if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
305     return aContext->shape() && !aContext->shape()->isNull();
306   }
307
308   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
309     std::shared_ptr<GeomAPI_Shape> aNoSelection;
310     return selectPart(aContext, aNoSelection, true);
311   }
312
313   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
314     // body: just a named shape, use selection mechanism from OCCT
315     TNaming_Selector aSelector(aSelLab);
316     bool aResult = aSelector.Solve(scope()) == Standard_True;
317     owner()->data()->sendAttributeUpdated(this);
318     return aResult;
319   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
320     // construction: identification by the results indexes, recompute faces and
321     // take the face that more close by the indexes
322     ResultConstructionPtr aConstructionContext = 
323       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
324     FeaturePtr aContextFeature = aContext->document()->feature(aContext);
325     // sketch sub-element
326     if (aConstructionContext && 
327         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
328     {
329       TDF_Label aLab = myRef.myRef->Label();
330       // getting a type of selected shape
331       Handle(TDataStd_Integer) aTypeAttr;
332       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
333         return false;
334       }
335       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
336       // selected indexes will be needed in each "if"
337       Handle(TDataStd_IntPackedMap) aSubIds;
338       std::shared_ptr<GeomAPI_Shape> aNewSelected;
339       bool aNoIndexes = 
340         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
341       // for now working only with composite features
342       CompositeFeaturePtr aComposite = 
343         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
344       if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
345         return false;
346       }
347
348       if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
349         // If this is a wire with plane defined thin it is a sketch-like object
350         if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
351           return false;
352         // if there is no edges indexes, any face can be used: take the first
353         std::shared_ptr<GeomAPI_Shape> aNewSelected;
354         if (aNoIndexes) {
355           aNewSelected = aConstructionContext->face(0);
356         } else { // searching for most looks-like initial face by the indexes
357           // prepare edges of the current resut for the fast searching
358           NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
359           const int aSubNum = aComposite->numberOfSubs();
360           for(int a = 0; a < aSubNum; a++) {
361             int aSubID = aComposite->subFeatureId(a);
362             if (aSubIds->Contains(aSubID)) {
363               FeaturePtr aSub = aComposite->subFeature(a);
364               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
365               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
366               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
367                 ResultConstructionPtr aConstr = 
368                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
369                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
370                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
371                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
372                   if (!anEdge.IsNull()) {
373                     Standard_Real aFirst, aLast;
374                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
375                     // searching for orientation information
376                     int anOrient = 0;
377                     Handle(TDataStd_Integer) anInt;
378                     if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
379                       anOrient = anInt->Get();
380                     }
381                     allCurves.Bind(aCurve, anOrient);
382                   }
383                 }
384               }
385             }
386           }
387           double aBestFound = 0; // best percentage of found edges
388           int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
389           for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
390             int aFound = 0, aNotFound = 0, aSameOrientation = 0;
391             TopoDS_Face aFace = 
392               TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
393             TopExp_Explorer anEdgesExp(aFace, TopAbs_EDGE);
394             for(; anEdgesExp.More(); anEdgesExp.Next()) {
395               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
396               if (!anEdge.IsNull()) {
397                 Standard_Real aFirst, aLast;
398                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
399                 if (allCurves.IsBound(aCurve)) {
400                   aFound++;
401                   int anOrient = allCurves.Find(aCurve);
402                   if (anOrient != 0) {  // extra comparision score is orientation
403                     if (edgeOrientation(aFace, anEdge) == anOrient)
404                       aSameOrientation++;
405                   }
406                 } else {
407                   aNotFound++;
408                 }
409               }
410             }
411             if (aFound + aNotFound != 0) {
412               double aSum = aFound + aNotFound;
413                // aSameOrientation: if edges are same, take where orientation is better
414               double aPercentage = double(aFound) / double(aFound + aNotFound);
415               if (aPercentage > aBestFound || 
416                   (aPercentage == aBestFound && aSameOrientation > aBestOrient)) {
417                 aBestFound = aPercentage;
418                 aBestOrient = aSameOrientation;
419                 aNewSelected = aConstructionContext->face(aFaceIndex);
420               }
421             }
422           }
423         }
424         if (aNewSelected) { // store this new selection
425           selectConstruction(aContext, aNewSelected);
426           owner()->data()->sendAttributeUpdated(this);
427           return true;
428         }
429       } else if (aShapeType == TopAbs_EDGE) {
430         // just reselect the edge by the id
431         const int aSubNum = aComposite->numberOfSubs();
432         for(int a = 0; a < aSubNum; a++) {
433           // if aSubIds take any, the first appropriate
434           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
435             // found the appropriate feature
436             FeaturePtr aFeature = aComposite->subFeature(a);
437             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
438               aFeature->results().cbegin();
439             for(;aResIter != aFeature->results().cend(); aResIter++) {
440               ResultConstructionPtr aRes = 
441                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
442               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
443                 selectConstruction(aContext, aRes->shape());
444                 owner()->data()->sendAttributeUpdated(this);
445                 return true;
446               }
447             }
448           }
449         }
450       } else if (aShapeType == TopAbs_VERTEX) {
451         // just reselect the vertex by the id of edge
452         const int aSubNum = aComposite->numberOfSubs();
453         for(int a = 0; a < aSubNum; a++) {
454           // if aSubIds take any, the first appropriate
455           int aFeatureID = aComposite->subFeatureId(a);
456           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
457             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
458             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
459               // searching for deltas
460               int aVertexNum = 0;
461               if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
462               else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
463               // found the feature with appropriate edge
464               FeaturePtr aFeature = aComposite->subFeature(a);
465               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
466                 aFeature->results().cbegin();
467               for(;aResIter != aFeature->results().cend(); aResIter++) {
468                 ResultConstructionPtr aRes = 
469                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
470                 if (aRes && aRes->shape()) {
471                   if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
472                     selectConstruction(aContext, aRes->shape());
473                     owner()->data()->sendAttributeUpdated(this);
474                     return true;
475                   } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
476                     const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
477                     int aVIndex = 1;
478                     for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
479                       if (aVIndex == aVertexNum) { // found!
480                         std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
481                         aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
482                         selectConstruction(aContext, aVertex);
483                         owner()->data()->sendAttributeUpdated(this);
484                         return true;
485                       }
486                       aVIndex++;
487                     }
488                   }
489                 }
490               }
491           }
492         }
493       }
494     } else { // simple construction element: the selected is that needed
495       selectConstruction(aContext, aContext->shape());
496       owner()->data()->sendAttributeUpdated(this);
497       return true;
498     }
499   }
500   return false; // unknown case
501 }
502
503
504 void Model_AttributeSelection::selectBody(
505   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
506 {
507   // perform the selection
508   TNaming_Selector aSel(selectionLabel());
509   TopoDS_Shape aContext;
510
511   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
512   if (aBody) {
513     aContext = aBody->shape()->impl<TopoDS_Shape>();
514   } else {
515     ResultPtr aResult = 
516       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
517     if (aResult) {
518       aContext = aResult->shape()->impl<TopoDS_Shape>();
519     } else {
520       Events_Error::send("A result with shape is expected");
521       return;
522     }
523   }
524   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
525   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
526   /*
527   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
528   if (aFeatureOwner.get())
529     aFeatureOwner->eraseResults();
530     */
531   if (!aContext.IsNull()) {
532     aSel.Select(aNewShape, aContext); 
533   }
534 }
535
536 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
537 /// if theID is zero, 
538 /// theOrientation is additional information about the positioning of edge relatively to face
539 ///    it is stored in the integer attribute of the edge sub-label: 
540 ///    -1 is out, 1 is in, 0 is not needed
541 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
542   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
543   std::string theAdditionalName, std::map<int, int>& theOrientations,
544   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
545   const int theOrientation = 0)
546 {
547   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
548   if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
549     TDataStd_Integer::Set(aLab, theOrientation);
550   }
551   TNaming_Builder aBuilder(aLab);
552   aBuilder.Generated(theShape);
553   std::stringstream aName;
554   aName<<theContextFeature->name()<<"/";
555   if (!theAdditionalName.empty())
556     aName<<theAdditionalName<<"/";
557   if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
558   else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
559   else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
560
561   if (theRefs.IsNull()) {
562     aName<<theID;
563     if (theOrientation == 1)
564       aName<<"f";
565     else if (theOrientation == -1)
566       aName<<"r";
567   } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
568     TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
569     for(; aRef.More(); aRef.Next()) {
570       aName<<"-"<<aRef.Key();
571       if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
572         if (theOrientations[aRef.Key()] == 1)
573           aName<<"f";
574         else if (theOrientations[aRef.Key()] == -1)
575           aName<<"r";
576       }
577     }
578   }
579
580   theDoc->addNamingName(aLab, aName.str());
581   TDataStd_Name::Set(aLab, aName.str().c_str());
582 }
583
584 void Model_AttributeSelection::selectConstruction(
585   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
586 {
587   std::shared_ptr<Model_Document> aMyDoc = 
588     std::dynamic_pointer_cast<Model_Document>(owner()->document());
589   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
590   CompositeFeaturePtr aComposite = 
591     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
592   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
593   if (!aComposite || aComposite->numberOfSubs() == 0) {
594     // saving of context is enough: result construction contains exactly the needed shape
595     TNaming_Builder aBuilder(selectionLabel());
596     aBuilder.Generated(aSubShape);
597     aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
598     TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
599     return;
600   }
601   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
602   TDF_Label aLab = myRef.myRef->Label();
603   // identify the reuslts of sub-object of the composite by edges
604   // save type of the selected shape in integer attribute
605   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
606   TDataStd_Integer::Set(aLab, (int)aShapeType);
607   gp_Pnt aVertexPos;
608   TColStd_MapOfTransient allCurves;
609   if (aShapeType == TopAbs_VERTEX) { // compare positions
610     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
611   } else { 
612     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
613       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
614       Standard_Real aFirst, aLast;
615       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
616       allCurves.Add(aCurve);
617     }
618   }
619   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
620   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
621   std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
622   aRefs->Clear();
623   const int aSubNum = aComposite->numberOfSubs();
624   for(int a = 0; a < aSubNum; a++) {
625     FeaturePtr aSub = aComposite->subFeature(a);
626     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
627     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
628     // there may be many shapes (circle and center): register if at least one is in selection
629     for(; aRes != aResults.cend(); aRes++) {
630       ResultConstructionPtr aConstr = 
631         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
632       if (!aConstr->shape()) {
633         continue;
634       }
635       if (aShapeType == TopAbs_VERTEX) {
636         if (aConstr->shape()->isVertex()) { // compare vertices positions
637           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
638           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
639           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
640             aRefs->Add(aComposite->subFeatureId(a));
641           }
642         } else { // get first or last vertex of the edge: last is stored with negative sign
643           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
644           int aDelta = kSTART_VERTEX_DELTA;
645           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
646             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
647             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
648               aRefs->Add(aDelta + aComposite->subFeatureId(a));
649               break;
650             }
651             aDelta += kSTART_VERTEX_DELTA;
652           }
653         }
654       } else {
655         if (aConstr->shape()->isEdge()) {
656           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
657           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
658           if (!anEdge.IsNull()) {
659             Standard_Real aFirst, aLast;
660             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
661             if (allCurves.Contains(aCurve)) {
662               int anID = aComposite->subFeatureId(a);
663               aRefs->Add(anID);
664               if (aShapeType != TopAbs_EDGE) { // face nneds the sub-edges on sub-labels
665                 // add edges to sub-label to support naming for edges selection
666                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
667                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
668                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
669                   Standard_Real aFirst, aLast;
670                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
671                   if (aFaceCurve == aCurve) {
672                     int anOrient = edgeOrientation(aSubShape, anEdge);
673                     anOrientations[anID] = anOrient;
674                     registerSubShape(
675                       selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
676                       Handle(TDataStd_IntPackedMap)(), anOrient);
677                   }
678                 }
679               } else { // put vertices of the selected edge to sub-labels
680                 // add edges to sub-label to support naming for edges selection
681                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
682                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
683                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
684                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
685
686                   std::stringstream anAdditionalName; 
687                   registerSubShape(
688                     selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations);
689                 }
690               }
691             }
692           }
693         }
694       }
695     }
696   }
697   // store the selected as primitive
698   TNaming_Builder aBuilder(selectionLabel());
699   aBuilder.Generated(aSubShape);
700     registerSubShape(
701       selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aRefs); 
702 }
703
704 bool Model_AttributeSelection::selectPart(
705   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
706   const bool theUpdate)
707 {
708   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
709   if (!aPart.get() || !aPart->isActivated())
710     return true; // postponed naming
711   if (theUpdate) {
712     Handle(TDataStd_Integer) anIndex;
713     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
714       if (anIndex->Get() > 0) {
715         // update the selection by index
716         return aPart->updateInPart(anIndex->Get());
717       } else {
718         return true; // nothing to do, referencing just by name
719       }
720     }
721     return true; // nothing to do, referencing just by name
722   }
723   // store the shape (in case part is not loaded it should be usefull
724   TopoDS_Shape aShape;
725   std::string aName = theContext->data()->name();
726   if (theSubShape->isNull()) {// the whole part shape is selected
727     aShape = theContext->shape()->impl<TopoDS_Shape>();
728   } else {
729     aShape = theSubShape->impl<TopoDS_Shape>();
730     int anIndex;
731     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
732     TDataStd_Integer::Set(selectionLabel(), anIndex);
733   }
734   TNaming_Builder aBuilder(selectionLabel());
735   aBuilder.Select(aShape, aShape);
736   // identify by name in the part
737   TDataStd_Name::Set(selectionLabel(), aName.c_str());
738   return !aName.empty();
739 }
740
741 TDF_Label Model_AttributeSelection::selectionLabel()
742 {
743   return myRef.myRef->Label().FindChild(1);
744 }
745
746 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
747 {
748   std::string aName("");
749   if(!this->isInitialized())
750     return !theDefaultName.empty() ? theDefaultName : aName;
751   Handle(TDataStd_Name) anAtt;
752   if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
753     aName = TCollection_AsciiString(anAtt->Get()).ToCString();
754     return aName;
755   }
756
757   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
758   ResultPtr aCont = context();
759
760   Model_SelectionNaming aSelNaming(selectionLabel());
761   return aSelNaming.namingName(aCont, aSubSh, theDefaultName);
762 }
763
764 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
765 void Model_AttributeSelection::selectSubShape(
766   const std::string& theType, const std::string& theSubShapeName)
767 {
768   if(theSubShapeName.empty() || theType.empty()) return;
769
770   Model_SelectionNaming aSelNaming(selectionLabel());
771   std::shared_ptr<Model_Document> aDoc = 
772     std::dynamic_pointer_cast<Model_Document>(owner()->document());
773   std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
774   ResultPtr aCont;
775   if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
776     setValue(aCont, aShapeToBeSelected);
777   }
778 }
779
780 int Model_AttributeSelection::Id()
781 {
782   std::shared_ptr<GeomAPI_Shape> aSelection = value();
783   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
784   const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
785   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
786   int anID = 0;
787   if (aSelection && !aSelection->isNull() &&
788     aContext   && !aContext->isNull())
789   {
790     TopTools_IndexedMapOfShape aSubShapesMap;
791     TopExp::MapShapes(aMainShape, aSubShapesMap);
792     anID = aSubShapesMap.FindIndex(aSubShape);
793   }
794   return anID;
795 }