Salome HOME
Merge branch 'Dev_0.6.1' of newgeom:newgeom into Dev_0.6.1
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_AttributeSelection.h
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 <ModelAPI_Feature.h>
13 #include <ModelAPI_ResultBody.h>
14 #include <ModelAPI_ResultConstruction.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <GeomAPI_Shape.h>
17 #include <GeomAPI_PlanarEdges.h>
18 #include <GeomAlgoAPI_SketchBuilder.h>
19 #include <Events_Error.h>
20
21 #include <TNaming_Selector.hxx>
22 #include <TNaming_NamedShape.hxx>
23 #include <TNaming_Tool.hxx>
24 #include <TNaming_Builder.hxx>
25 #include <TNaming_Localizer.hxx>
26 #include <TopoDS_Shape.hxx>
27 #include <TopoDS_Compound.hxx>
28 #include <TDataStd_IntPackedMap.hxx>
29 #include <TDataStd_Integer.hxx>
30 #include <TDataStd_UAttribute.hxx>
31 #include <TDataStd_Name.hxx>
32 #include <TopTools_MapOfShape.hxx>
33 #include <TopTools_IndexedMapOfShape.hxx>
34 #include <TopTools_MapIteratorOfMapOfShape.hxx>
35 #include <TopTools_ListOfShape.hxx>
36 #include <TopExp_Explorer.hxx>
37 #include <TDF_LabelMap.hxx>
38 #include <BRep_Tool.hxx>
39 #include <BRep_Builder.hxx>
40 #include <TopoDS_Edge.hxx>
41 #include <TopoDS.hxx>
42 #include <TopExp.hxx>
43 #include <TColStd_MapOfTransient.hxx>
44 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_ListIteratorOfListOfShape.hxx>
46 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
47 #include <gp_Pnt.hxx>
48 #include <Precision.hxx>
49 #include <TDF_ChildIterator.hxx>
50 #include <TDF_ChildIDIterator.hxx>
51 #include <TDataStd_Name.hxx>
52 #include <TopAbs_ShapeEnum.hxx>
53 #include <TopoDS_Iterator.hxx>
54 using namespace std;
55 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
56 /// (multiplied by the index of the edge)
57 static const int kSTART_VERTEX_DELTA = 1000000;
58 // identifier that there is simple reference: selection equals to context
59 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
60
61 // on this label is stored:
62 // TNaming_NamedShape - selected shape
63 // TNaming_Naming - topological selection information (for the body)
64 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
65 // TDataStd_Integer - type of the selected shape (for construction)
66 // TDF_Reference - from ReferenceAttribute, the context
67 #define DDDD 1
68 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
69   const std::shared_ptr<GeomAPI_Shape>& theSubShape)
70 {
71   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
72   bool isOldShape = 
73     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
74   if (isOldShape) return; // shape is the same, so context is also unchanged
75   // update the referenced object if needed
76   bool isOldContext = theContext == myRef.value();
77
78
79   if (!isOldContext)
80     myRef.setValue(theContext);
81
82   // do noth use naming if selected shape is result shape itself, but not sub-shape
83   TDF_Label aSelLab = selectionLabel();
84   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
85   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
86     // do not select the whole shape for body:it is already must be in the data framework
87     if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
88       aSelLab.ForgetAllAttributes(true);
89       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
90     } else {
91       selectBody(theContext, theSubShape);
92     }
93   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
94     selectConstruction(theContext, theSubShape);
95   }
96   myIsInitialized = true;
97
98   std::string aSelName = namingName();
99   if(!aSelName.empty())
100           TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
101 #ifdef DDDD
102   //####
103   //selectSubShape("FACE",  "Extrusion_1/LateralFace_3");
104   //selectSubShape("FACE",  "Extrusion_1/TopFace");
105   //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
106   //selectSubShape("EDGE", "Sketch_1/Edge_6");
107 #endif
108   owner()->data()->sendAttributeUpdated(this);
109 }
110
111 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
112 {
113   std::shared_ptr<GeomAPI_Shape> aResult;
114   if (myIsInitialized) {
115     TDF_Label aSelLab = selectionLabel();
116     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
117       ResultPtr aContext = context();
118       if (!aContext.get()) 
119         return aResult; // empty result
120       return aContext->shape();
121     }
122
123     Handle(TNaming_NamedShape) aSelection;
124     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
125       TopoDS_Shape aSelShape = aSelection->Get();
126       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
127       aResult->setImpl(new TopoDS_Shape(aSelShape));
128     } else { // for simple construction element: just shape of this construction element
129       ResultConstructionPtr aConstr = 
130         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
131       if (aConstr) {
132         return aConstr->shape();
133       }
134     }
135   }
136   return aResult;
137 }
138
139 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
140   : myRef(theLabel)
141 {
142   myIsInitialized = myRef.isInitialized();
143 }
144
145 ResultPtr Model_AttributeSelection::context() {
146   return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
147 }
148
149
150 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
151 {
152   ModelAPI_AttributeSelection::setObject(theObject);
153   myRef.setObject(theObject);
154 }
155
156 TDF_LabelMap& Model_AttributeSelection::scope()
157 {
158   if (myScope.IsEmpty()) { // create a new scope if not yet done
159     // gets all labels with named shapes that are bofore this feature label (before in history)
160     TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
161       owner()->data())->label().Father();
162     int aFeatureID = aFeatureLab.Tag();
163     TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
164     for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
165       if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
166         break;
167       TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
168       for(; aNSIter.More(); aNSIter.Next()) {
169         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
170         if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
171           myScope.Add(aNS->Label());
172         }
173       }
174     }
175   }
176   return myScope;
177 }
178
179 bool Model_AttributeSelection::update()
180 {
181   ResultPtr aContext = context();
182   if (!aContext.get()) return false;
183   TDF_Label aSelLab = selectionLabel();
184   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
185     return aContext->shape() && !aContext->shape()->isNull();
186   }
187
188   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
189     // body: just a named shape, use selection mechanism from OCCT
190     TNaming_Selector aSelector(aSelLab);
191     bool aResult = aSelector.Solve(scope()) == Standard_True;
192     owner()->data()->sendAttributeUpdated(this);
193     return aResult;
194   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
195     // construction: identification by the results indexes, recompute faces and
196     // take the face that more close by the indexes
197     std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr = 
198       std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(
199       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext)->shape());
200     if (aWirePtr && aWirePtr->hasPlane()) { // sketch sub-element
201       TDF_Label aLab = myRef.myRef->Label();
202       // getting a type of selected shape
203       Handle(TDataStd_Integer) aTypeAttr;
204       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
205         return false;
206       }
207       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
208       // selected indexes will be needed in each "if"
209       Handle(TDataStd_IntPackedMap) aSubIds;
210       std::shared_ptr<GeomAPI_Shape> aNewSelected;
211       bool aNoIndexes = 
212         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
213       // for now working only with composite features
214       FeaturePtr aContextFeature = aContext->document()->feature(aContext);
215       CompositeFeaturePtr aComposite = 
216         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
217       if (!aComposite || aComposite->numberOfSubs() == 0) {
218         return false;
219       }
220
221       if (aShapeType == TopAbs_FACE) {
222         // If this is a wire with plane defined thin it is a sketch-like object
223         std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
224         GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
225           aWirePtr->dirY(), aWirePtr->norm(), aWirePtr, aFaces);
226         if (aFaces.empty()) // no faces, update can not work correctly
227           return false;
228         // if there is no edges indexes, any face can be used: take the first
229         std::shared_ptr<GeomAPI_Shape> aNewSelected;
230         if (aNoIndexes) {
231           aNewSelected = *(aFaces.begin());
232         } else { // searching for most looks-like initial face by the indexes
233           // prepare edges of the current resut for the fast searching
234           TColStd_MapOfTransient allCurves;
235           const int aSubNum = aComposite->numberOfSubs();
236           for(int a = 0; a < aSubNum; a++) {
237             if (aSubIds->Contains(aComposite->subFeatureId(a))) {
238               FeaturePtr aSub = aComposite->subFeature(a);
239               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
240               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
241               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
242                 ResultConstructionPtr aConstr = 
243                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
244                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
245                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
246                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
247                   if (!anEdge.IsNull()) {
248                     Standard_Real aFirst, aLast;
249                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
250                     allCurves.Add(aCurve);
251                   }
252                 }
253               }
254             }
255           }
256           // iterate new result faces and searching for these edges
257           std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFacesIter = aFaces.begin();
258           double aBestFound = 0; // best percentage of found edges
259           for(; aFacesIter != aFaces.end(); aFacesIter++) {
260             int aFound = 0, aNotFound = 0;
261             TopExp_Explorer anEdgesExp((*aFacesIter)->impl<TopoDS_Shape>(), TopAbs_EDGE);
262             for(; anEdgesExp.More(); anEdgesExp.Next()) {
263               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
264               if (!anEdge.IsNull()) {
265                 Standard_Real aFirst, aLast;
266                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
267                 if (allCurves.Contains(aCurve)) {
268                   aFound++;
269                 } else {
270                   aNotFound++;
271                 }
272               }
273             }
274             if (aFound + aNotFound != 0) {
275               double aPercentage = double(aFound) / double(aFound + aNotFound);
276               if (aPercentage > aBestFound) {
277                 aBestFound = aPercentage;
278                 aNewSelected = *aFacesIter;
279               }
280             }
281           }
282         }
283         if (aNewSelected) { // store this new selection
284           selectConstruction(aContext, aNewSelected);
285           owner()->data()->sendAttributeUpdated(this);
286           return true;
287         }
288       } else if (aShapeType == TopAbs_EDGE) {
289         // just reselect the edge by the id
290         const int aSubNum = aComposite->numberOfSubs();
291         for(int a = 0; a < aSubNum; a++) {
292           // if aSubIds take any, the first appropriate
293           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
294             // found the appropriate feature
295             FeaturePtr aFeature = aComposite->subFeature(a);
296             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
297               aFeature->results().cbegin();
298             for(;aResIter != aFeature->results().cend(); aResIter++) {
299               ResultConstructionPtr aRes = 
300                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
301               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
302                 selectConstruction(aContext, aRes->shape());
303                 owner()->data()->sendAttributeUpdated(this);
304                 return true;
305               }
306             }
307           }
308         }
309       } else if (aShapeType == TopAbs_VERTEX) {
310         // just reselect the vertex by the id of edge
311         const int aSubNum = aComposite->numberOfSubs();
312         for(int a = 0; a < aSubNum; a++) {
313           // if aSubIds take any, the first appropriate
314           int aFeatureID = aComposite->subFeatureId(a);
315           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
316               aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
317               aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
318             // searching for deltas
319             int aVertexNum = 0;
320             if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
321             else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
322             // found the feature with appropriate edge
323             FeaturePtr aFeature = aComposite->subFeature(a);
324             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
325               aFeature->results().cbegin();
326             for(;aResIter != aFeature->results().cend(); aResIter++) {
327               ResultConstructionPtr aRes = 
328                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
329               if (aRes && aRes->shape()) {
330                 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
331                   selectConstruction(aContext, aRes->shape());
332                   owner()->data()->sendAttributeUpdated(this);
333                   return true;
334                 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
335                   const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
336                   int aVIndex = 1;
337                   for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
338                     if (aVIndex == aVertexNum) { // found!
339                       std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
340                       aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
341                       selectConstruction(aContext, aVertex);
342                       owner()->data()->sendAttributeUpdated(this);
343                       return true;
344                     }
345                     aVIndex++;
346                   }
347                 }
348               }
349             }
350           }
351         }
352       }
353     } else { // simple construction element: the selected is that needed
354       selectConstruction(aContext, aContext->shape());
355       owner()->data()->sendAttributeUpdated(this);
356       return true;
357     }
358   }
359   return false; // unknown case
360 }
361
362
363 void Model_AttributeSelection::selectBody(
364     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
365 {
366   // perform the selection
367   TNaming_Selector aSel(selectionLabel());
368   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
369   TopoDS_Shape aContext;
370
371   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
372   if (aBody)
373     aContext = aBody->shape()->impl<TopoDS_Shape>();
374   else {
375     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
376     if (aConstr) {
377       aContext = aConstr->shape()->impl<TopoDS_Shape>();
378     } else {
379       Events_Error::send("A result with shape is expected");
380       return;
381     }
382   }
383   aSel.Select(aNewShape, aContext);
384 }
385
386 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
387 /// if theID is zero, 
388 static void registerSubShape(TDF_Label& theMainLabel, TopoDS_Shape theShape,
389   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
390   std::string theAdditionalName,
391   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
392 {
393   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
394   TNaming_Builder aBuilder(aLab);
395   aBuilder.Generated(theShape);
396   std::stringstream aName;
397   aName<<theContextFeature->name()<<"/";
398   if (!theAdditionalName.empty())
399     aName<<theAdditionalName<<"/";
400   if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
401   else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
402   else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
403
404   if (theRefs.IsNull()) {
405     aName<<theID;
406   } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
407     TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
408     for(; aRef.More(); aRef.Next()) {
409       aName<<"-"<<aRef.Key();
410     }
411   }
412
413   theDoc->addNamingName(aLab, aName.str());
414   TDataStd_Name::Set(aLab, aName.str().c_str());
415 }
416
417 void Model_AttributeSelection::selectConstruction(
418     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
419 {
420   std::shared_ptr<Model_Document> aMyDoc = 
421     std::dynamic_pointer_cast<Model_Document>(owner()->document());
422   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
423   CompositeFeaturePtr aComposite = 
424     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
425   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
426   if (!aComposite || aComposite->numberOfSubs() == 0) {
427     // saving of context is enough: result construction contains exactly the needed shape
428     TNaming_Builder aBuilder(selectionLabel());
429     aBuilder.Generated(aSubShape);
430     aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
431     TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
432     return;
433   }
434   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
435   TDF_Label aLab = myRef.myRef->Label();
436   // identify the reuslts of sub-object of the composite by edges
437   // save type of the selected shape in integer attribute
438   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
439   TDataStd_Integer::Set(aLab, (int)aShapeType);
440   gp_Pnt aVertexPos;
441   TColStd_MapOfTransient allCurves;
442   if (aShapeType == TopAbs_VERTEX) { // compare positions
443     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
444   } else { 
445     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
446       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
447       Standard_Real aFirst, aLast;
448       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
449       allCurves.Add(aCurve);
450     }
451   }
452   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
453   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
454   aRefs->Clear();
455   const int aSubNum = aComposite->numberOfSubs();
456   for(int a = 0; a < aSubNum; a++) {
457     FeaturePtr aSub = aComposite->subFeature(a);
458     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
459     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
460     // there may be many shapes (circle and center): register if at least one is in selection
461     for(; aRes != aResults.cend(); aRes++) {
462       ResultConstructionPtr aConstr = 
463         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
464       if (!aConstr->shape()) {
465         continue;
466       }
467       if (aShapeType == TopAbs_VERTEX) {
468         if (aConstr->shape()->isVertex()) { // compare vertices positions
469           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
470           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
471           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
472             aRefs->Add(aComposite->subFeatureId(a));
473           }
474         } else { // get first or last vertex of the edge: last is stored with negative sign
475           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
476           int aDelta = kSTART_VERTEX_DELTA;
477           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
478             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
479             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
480               aRefs->Add(aDelta + aComposite->subFeatureId(a));
481               break;
482             }
483             aDelta += kSTART_VERTEX_DELTA;
484           }
485         }
486       } else {
487         if (aConstr->shape()->isEdge()) {
488           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
489           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
490           if (!anEdge.IsNull()) {
491             Standard_Real aFirst, aLast;
492             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
493             if (allCurves.Contains(aCurve)) {
494               int anID = aComposite->subFeatureId(a);
495               aRefs->Add(anID);
496               if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
497                 // add edges to sub-label to support naming for edges selection
498                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
499                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
500                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
501                   Standard_Real aFirst, aLast;
502                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
503                   if (aFaceCurve == aCurve) {
504                     registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
505                   }
506                 }
507               } else { // put vertices of the selected edge to sub-labels
508                 // add edges to sub-label to support naming for edges selection
509                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
510                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
511                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
512                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
513
514                   std::stringstream anAdditionalName; 
515                   registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
516                     "");
517                 }
518               }
519             }
520           }
521         }
522       }
523     }
524   }
525   // store the selected as primitive
526   TNaming_Builder aBuilder(selectionLabel());
527   aBuilder.Generated(aSubShape);
528   registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
529 }
530
531 TDF_Label Model_AttributeSelection::selectionLabel()
532 {
533   return myRef.myRef->Label().FindChild(1);
534 }
535
536 #define FIX_BUG1 1
537 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape, 
538                                              const TDF_Label& theLabel)
539 {
540   std::string aName;
541   // check if the subShape is already in DF
542   Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
543   Handle(TDataStd_Name) anAttr;
544   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document    
545         if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
546           aName = TCollection_AsciiString(anAttr->Get()).ToCString();
547           if(!aName.empty()) {      
548             const TDF_Label& aLabel = theDoc->findNamingName(aName);
549     /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
550                 if(!aLabel.IsEqual(aNS->Label())) {
551                   //aName.erase(); //something is wrong, to be checked!!!
552                   aName += "_SomethingWrong";
553                   return aName;
554                 }*/
555                 const TopoDS_Shape& aShape = aNS->Get();
556                 if(aShape.ShapeType() == TopAbs_COMPOUND) {
557                   std::string aPostFix("_");
558                   TopoDS_Iterator it(aShape);                   
559                   for (int i = 1;it.More();it.Next(), i++) {
560                     if(it.Value() == theShape) {
561                           aPostFix += TCollection_AsciiString (i).ToCString();
562                           aName    += aPostFix;
563                           break;
564                         }
565                         else continue;                                          
566                   }
567                 }
568           }     
569         }
570   }
571   return aName;
572 }
573
574 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
575 {
576 // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
577   TopoDS_Compound aCmp;
578   BRep_Builder BB;
579   BB.MakeCompound(aCmp);
580   TopTools_ListIteratorOfListOfShape it(theAncestors);
581   for(;it.More();it.Next()) {
582         BB.Add(aCmp, it.Value());
583         theSMap.Add(it.Value());
584   }
585   int aNumber(0);
586   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
587   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
588   for (int i = 1; i <= aMap2.Extent(); i++) {
589         const TopoDS_Shape& aKey = aMap2.FindKey(i);
590         const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
591         if(anAncestors.Extent() > 1) aNumber++;
592   }
593   if(aNumber > 1) return false;
594   return true;
595 }
596 std::string Model_AttributeSelection::namingName()
597 {
598   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
599   ResultPtr aCont = context();
600   std::string aName;
601   if(!aSubSh.get() || aSubSh->isNull() || !aCont.get() || aCont->shape()->isNull()) 
602     return aName;
603   TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
604   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
605   std::shared_ptr<Model_Document> aDoc = 
606     std::dynamic_pointer_cast<Model_Document>(aCont->document());
607
608   // check if the subShape is already in DF
609   aName = GetShapeName(aDoc, aSubShape, selectionLabel());
610   if(aName.empty() ) { // not in the document!
611     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
612         switch (aType) {
613           case TopAbs_FACE:
614       // the Face should be in DF. If it is not a case, it is an error ==> to be dbugged                
615                 break;
616           case TopAbs_EDGE:
617                   {
618                   // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
619                   // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
620                   TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
621                   TopTools_IndexedDataMapOfShapeListOfShape aMap;
622                   TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
623                   bool isTrivialCase(true);
624                   for (int i = 1; i <= aMap.Extent(); i++) {
625                         const TopoDS_Shape& aKey = aMap.FindKey(i);
626                         if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
627
628             const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
629                         // check that it is not a trivial case (F1 & F2: aNumber = 1)
630                         isTrivialCase = isTrivial(anAncestors, aSMap);                  
631                         break;
632                   }
633
634                   TopTools_ListOfShape aListOfNbs;
635                   if(!isTrivialCase) { // find Neighbors
636                         TNaming_Localizer aLocalizer;
637                         TopTools_MapOfShape aMap3;
638                         aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
639                         //int n = aMap3.Extent();
640                         TopTools_MapIteratorOfMapOfShape it(aMap3);
641                         for(;it.More();it.Next()) {
642                           const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
643                           //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
644                           const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
645                           TopTools_ListIteratorOfListOfShape it2(aList);
646                           for(;it2.More();it2.Next()) {
647                                 if(aSMap.Contains(it2.Value())) continue; // skip this Face
648                                 aListOfNbs.Append(it2.Value());
649                           }
650                         }
651                   }  // else a trivial case
652                   
653                   // build name of the sub-shape Edge
654                   for(int i=1; i <= aSMap.Extent(); i++) {
655                         const TopoDS_Shape& aFace = aSMap.FindKey(i);
656                         std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
657                         if(i == 1)
658                           aName = aFaceName;
659                         else 
660                           aName += "|" + aFaceName;
661                   }
662                   TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
663                   for (;itl.More();itl.Next()) {
664                         std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
665                         aName += "|" + aFaceName;
666                   }               
667                   }
668                   break;
669
670           case TopAbs_VERTEX:
671                   // name structure (Monifold Topology): 
672                   // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
673                   // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
674                   //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
675                   // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
676                   //                   or compound of 2 open faces.
677                   // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of 
678                   //                   two independent edges (wire or compound)
679                   // implemented 2 first cases
680                   {
681                         TopTools_IndexedDataMapOfShapeListOfShape aMap;
682                     TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
683                         const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
684                         TopTools_ListOfShape aList;
685                         TopTools_MapOfShape aFMap;
686 #ifdef FIX_BUG1
687                         //int n = aList2.Extent(); //bug!
688                         // fix is below
689                         TopTools_ListIteratorOfListOfShape itl2(aList2);
690                     for (int i = 1;itl2.More();itl2.Next(),i++) {
691                           if(aFMap.Add(itl2.Value()))
692                                 aList.Append(itl2.Value());
693                         }
694                         //n = aList.Extent();
695 #endif
696                         TopTools_ListIteratorOfListOfShape itl(aList);
697                     for (int i = 1;itl.More();itl.Next(),i++) {
698                           const TopoDS_Shape& aFace = itl.Value();
699                           std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
700                           if(i == 1)
701                             aName = aFaceName;
702                           else 
703                             aName += "|" + aFaceName;
704                         }
705                   }
706                   break;
707         }
708     // register name                    
709     // aDoc->addNamingName(selectionLabel(), aName);
710         // the selected sub-shape will not be shared and as result it will not require registration
711   }
712   return aName;
713 }
714
715 TopAbs_ShapeEnum translateType (const std::string& theType)
716 {
717   TCollection_AsciiString aStr(theType.c_str());
718   aStr.UpperCase();
719   if(aStr.IsEqual("COMP"))
720         return TopAbs_COMPOUND;
721   else if(aStr.IsEqual("COMS"))
722         return TopAbs_COMPSOLID;
723   else if(aStr.IsEqual("SOLD"))
724         return TopAbs_SOLID;
725   else if(aStr.IsEqual("SHEL"))
726         return TopAbs_SHELL;
727   else if(aStr.IsEqual("FACE"))
728         return TopAbs_FACE;
729   else if(aStr.IsEqual("WIRE"))
730         return TopAbs_WIRE;
731   else if(aStr.IsEqual("EDGE"))
732         return TopAbs_EDGE;
733   else if(aStr.IsEqual("VERT"))
734         return TopAbs_VERTEX;  
735
736   return TopAbs_SHAPE;
737 }
738
739 const TopoDS_Shape getShapeFromCompound(const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
740 {
741   TopoDS_Shape aSelection;
742   std::string::size_type n = theSubShapeName.rfind('/');                        
743   if (n == std::string::npos) n = 0;
744         std::string aSubString = theSubShapeName.substr(n + 1);
745         n = aSubString.rfind('_');
746         if (n == std::string::npos) return aSelection;
747         aSubString = aSubString.substr(n+1);
748         int indx = atoi(aSubString.c_str());
749         TopoDS_Iterator it(theCompound);                        
750         for (int i = 1;it.More();it.Next(), i++) {
751           if(i == indx) {                         
752             aSelection = it.Value();                      
753             break;
754           }
755           else continue;                                                
756         }
757   return aSelection;    
758 }
759
760 const TopoDS_Shape findFaceByName(const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
761 {
762   TopoDS_Shape aFace;
763   std::string::size_type n, nb = theSubShapeName.rfind('/');                    
764   if (nb == std::string::npos) nb = 0;
765   std::string aSubString = theSubShapeName.substr(nb + 1);
766   n = aSubString.rfind('_');
767   if (n != std::string::npos) {
768           std::string aSubStr2 = aSubString.substr(0, n);
769         aSubString  = theSubShapeName.substr(0, nb + 1);
770         aSubString = aSubString + aSubStr2;     
771   } else
772         aSubString = theSubShapeName;
773                                 
774   const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
775   if(aLabel.IsNull()) return aFace;
776   Handle(TNaming_NamedShape) aNS;
777   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
778         const TopoDS_Shape& aShape = aNS->Get();
779         if(!aShape.IsNull()) {
780           if(aShape.ShapeType() == TopAbs_COMPOUND) 
781             aFace = getShapeFromCompound(theSubShapeName, aShape);
782           else 
783                 aFace = aShape;   
784         }
785   }
786   return aFace;
787 }
788
789 int ParseEdgeName(const std::string& theSubShapeName,   std::list<std::string>& theList)
790 {
791   std::string aName = theSubShapeName;
792   std::string aLastName;
793   int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
794   while ((n2 = aName.find('|', n1)) != std::string::npos) {
795     const std::string aName1 = aName.substr(n1, n2); //name of face
796         theList.push_back(aName1);      
797         n1 = n2 + 1;
798         aLastName = aName.substr(n1);
799   }
800   if(!aLastName.empty())
801         theList.push_back(aLastName);
802   return theList.size();
803 }
804
805 const TopoDS_Shape findCommonShape(const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
806 {
807   TopoDS_Shape aShape;
808   std::vector<TopTools_MapOfShape> aVec;
809   TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
810   if(theList.Extent() > 1) {
811         aVec.push_back(aMap1);
812         aVec.push_back(aMap2);
813   }
814   if(theList.Extent() > 2)
815     aVec.push_back(aMap3);
816   if(theList.Extent() == 4)
817     aVec.push_back(aMap4);
818
819   //fill maps
820   TopTools_ListIteratorOfListOfShape it(theList);
821   for(int i = 0;it.More();it.Next(),i++) {
822         const TopoDS_Shape& aFace = it.Value();
823         TopExp_Explorer anExp (aFace, theType);
824         for(;anExp.More();anExp.Next()) {
825           const TopoDS_Shape& anEdge = anExp.Current();
826           if (!anEdge.IsNull())
827                 aVec[i].Add(anExp.Current());
828         }
829   }
830   //trivial case: 2 faces
831   TopTools_ListOfShape aList;
832   TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
833   for(;it2.More();it2.Next()) {
834         if(aVec[1].Contains(it2.Key())) {
835           aShape = it2.Key();
836           if(theList.Extent() == 2)
837             break;
838           else 
839                 aList.Append(it2.Key());
840         }
841   }
842   if(aList.Extent()) {// list of common edges ==> search ny neighbors 
843         if(aVec[2].Extent() && aVec[3].Extent()) {
844           TopTools_ListIteratorOfListOfShape it(aList);
845           for(;it.More();it.Next()) {
846                 const TopoDS_Shape& aCand = it.Value();
847                 // not yet implemented
848
849           }
850         }
851   }
852   return aShape;
853 }
854
855 std::string getContextName(const std::string& theSubShapeName)
856 {
857   std::string aName;
858   std::string::size_type n = theSubShapeName.find('/');                 
859   if (n == std::string::npos) return aName;
860   aName = theSubShapeName.substr(0, n);
861   return aName;
862 }
863 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
864 void Model_AttributeSelection::selectSubShape(const std::string& theType, const std::string& theSubShapeName)
865 {
866   if(theSubShapeName.empty() || theType.empty()) return;
867   TopAbs_ShapeEnum aType = translateType(theType);
868   std::shared_ptr<Model_Document> aDoc =  std::dynamic_pointer_cast<Model_Document>(owner()->document());//std::dynamic_pointer_cast<Model_Document>(aCont->document());
869   std::string aContName = getContextName(theSubShapeName);
870   if(aContName.empty()) return;
871   //ResultPtr aCont = context();
872   ResultPtr aCont = aDoc->findByName(aContName);
873   if(!aCont.get() || aCont->shape()->isNull()) return;
874   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
875   TopAbs_ShapeEnum aContType = aContext.ShapeType();
876   if(aType <= aContType) return; // not applicable
877  
878   
879   TopoDS_Shape aSelection;
880   switch (aType) 
881   {
882   case TopAbs_COMPOUND:
883     break;
884   case TopAbs_COMPSOLID:
885     break;
886   case TopAbs_SOLID:
887     break;
888   case TopAbs_SHELL:
889     break;
890   case TopAbs_FACE:
891     {
892           const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
893           if(!aSelection.IsNull()) {// Select it
894                 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
895         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
896                 setValue(aCont, aShapeToBeSelected);
897           }
898         }
899     break;
900   case TopAbs_WIRE:
901         break;
902   case TopAbs_EDGE:
903         {  
904           TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
905           const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
906       if(!aLabel.IsNull()) {
907         Handle(TNaming_NamedShape) aNS;
908         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
909               const TopoDS_Shape& aShape = aNS->Get();
910               if(!aShape.IsNull()) {
911                 if(aShape.ShapeType() == TopAbs_COMPOUND) 
912                   aSelection = getShapeFromCompound(theSubShapeName, aShape);
913                         else 
914                     aSelection = aShape;          
915                   }
916                 }
917           }
918           if(aSelection.IsNull()) {
919           std::list<std::string> aListofNames;
920           int n = ParseEdgeName(theSubShapeName, aListofNames);
921           if(n > 1 && n < 5) {
922                 TopTools_ListOfShape aList;
923         for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
924                   const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
925                   aList.Append(aFace);          
926                 }
927                 aSelection = findCommonShape(TopAbs_EDGE, aList);
928           }
929           }
930           if(!aSelection.IsNull()) {// Select it
931                 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
932         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
933                 setValue(aCont, aShapeToBeSelected);
934           }
935         }
936     break;
937   case TopAbs_VERTEX:
938         break;
939   default: //TopAbs_SHAPE
940         return;
941   }
942
943 }