]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_ResultConstruction.cpp
Salome HOME
Fix the naming problems for the sketch edges
[modules/shaper.git] / src / Model / Model_ResultConstruction.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_ResultConstruction.h>
22
23 #include <Model_Data.h>
24 #include <ModelAPI_CompositeFeature.h>
25 #include <Model_SelectionNaming.h>
26 #include <ModelAPI_Events.h>
27 #include <Config_PropManager.h>
28 #include <GeomAPI_PlanarEdges.h>
29 #include <GeomAPI_Shape.h>
30 #include <GeomAlgoAPI_SketchBuilder.h>
31 #include <Events_Loop.h>
32
33 #include <TDF_Reference.hxx>
34 #include <TDF_ChildIterator.hxx>
35 #include <TNaming_NamedShape.hxx>
36 #include <TNaming_Builder.hxx>
37 #include <TDataStd_Integer.hxx>
38 #include <TDataStd_IntPackedMap.hxx>
39 #include <TDataStd_Name.hxx>
40 #include <TDataStd_UAttribute.hxx>
41 #include <TColStd_MapOfTransient.hxx>
42 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
43 #include <BRep_Tool.hxx>
44 #include <BRep_Builder.hxx>
45 #include <TopoDS.hxx>
46 #include <TopoDS_Shape.hxx>
47 #include <TopoDS_Edge.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopExp_Explorer.hxx>
50 #include <TNaming_Tool.hxx>
51 #include <Precision.hxx>
52
53 // identifier that it is full result selected, but in external document (for internal index is 0)
54 Standard_GUID kFULL_RESULT_ID("ee87e529-da6f-46af-be25-5e0fefde52f7");
55
56
57 void Model_ResultConstruction::colorConfigInfo(std::string& theSection, std::string& theName,
58                                        std::string& theDefault)
59 {
60   theSection = "Visualization";
61   theName = "result_construction_color";
62   theDefault = DEFAULT_COLOR();
63 }
64
65 void Model_ResultConstruction::setShape(std::shared_ptr<GeomAPI_Shape> theShape)
66 {
67   if (myShape != theShape) {
68     if (!theShape.get() || !theShape->isEqual(myShape)) {
69         static const Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
70         ModelAPI_EventCreator::get()->sendUpdated(data()->owner(), anEvent);
71     }
72     myShape = theShape;
73     if (theShape.get()) {
74       myFacesUpToDate = false;
75       myFaces.clear();
76     }
77   }
78 }
79
80 std::shared_ptr<GeomAPI_Shape> Model_ResultConstruction::shape()
81 {
82   return myShape;
83 }
84
85 Model_ResultConstruction::Model_ResultConstruction()
86 {
87   myIsInHistory = true;
88   myIsInfinite = false;
89   myFacesUpToDate = false;
90 }
91
92 void Model_ResultConstruction::setIsInHistory(const bool isInHistory)
93 {
94   myIsInHistory = isInHistory;
95 }
96
97 int Model_ResultConstruction::facesNum()
98 {
99   if (!myFacesUpToDate) {
100     std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr =
101       std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(myShape);
102     if (aWirePtr.get()) {
103       std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
104       GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
105         aWirePtr->norm(), aWirePtr, aFaces);
106       std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFIter = aFaces.begin();
107       for(; aFIter != aFaces.end(); aFIter++) {
108         std::shared_ptr<GeomAPI_Face> aFace(new GeomAPI_Face(*aFIter));
109         if (aFace.get() && !aFace->isNull())
110           myFaces.push_back(aFace);
111       }
112     }
113     myFacesUpToDate = true;
114   }
115   return int(myFaces.size());
116 }
117
118 std::shared_ptr<GeomAPI_Face> Model_ResultConstruction::face(const int theIndex)
119 {
120   return myFaces[theIndex];
121 }
122
123 bool Model_ResultConstruction::isInfinite()
124 {
125   return myIsInfinite;
126 }
127
128 void Model_ResultConstruction::setInfinite(const bool theInfinite)
129 {
130   myIsInfinite = theInfinite;
131 }
132
133 void Model_ResultConstruction::setIsConcealed(const bool theValue)
134 {
135   // do nothing: the construction element is never consealed
136 }
137
138 static const int kSTART_VERTEX_DELTA = 1000000;
139
140 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape, std::string theFullName,
141   const int theID, std::shared_ptr<Model_Document> theDoc,
142   bool theSelectionMode)
143 {
144   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
145   TNaming_Builder aBuilder(aLab);
146   // wire never happens as sub, it must be generated to be found
147   // by SelectionNaming TNaming_Tool::NamedShape
148   if (theSelectionMode && theShape.ShapeType() != TopAbs_WIRE)
149     aBuilder.Select(theShape, theShape);
150   else
151     aBuilder.Generated(theShape);
152
153   theDoc->addNamingName(aLab, theFullName);
154   TDataStd_Name::Set(aLab, theFullName.c_str());
155 }
156
157 // generates a full-name for sub-element of the composite feature (sketch)
158 std::string fullName(CompositeFeaturePtr theComposite, const TopoDS_Shape& theSubShape,
159   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
160 {
161   TopAbs_ShapeEnum aShapeType = theSubShape.ShapeType();
162   gp_Pnt aVertexPos;
163   TColStd_MapOfTransient allCurves;
164   if (aShapeType == TopAbs_VERTEX) { // compare positions
165     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(theSubShape));
166   } else {
167     for(TopExp_Explorer anEdgeExp(theSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
168       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
169       Standard_Real aFirst, aLast;
170       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
171       allCurves.Add(aCurve);
172     }
173   }
174   std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
175   std::map<int, std::string> aSubNames; //map from edges IDs to names of edges
176   TColStd_PackedMapOfInteger aRefs; // indixes of sub-elements in composite
177
178   const int aSubNum = theComposite->numberOfSubs();
179   for(int a = 0; a < aSubNum; a++) {
180     FeaturePtr aSub = theComposite->subFeature(a);
181     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
182     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
183     // there may be many shapes (circle and center): register if at least one is in selection
184     for(; aRes != aResults.cend(); aRes++) {
185       ResultConstructionPtr aConstr =
186         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
187       if (!aConstr->shape()) {
188         continue;
189       }
190       if (aShapeType == TopAbs_VERTEX) {
191         if (aConstr->shape()->isVertex()) { // compare vertices positions
192           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
193           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
194           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
195             aRefs.Add(theComposite->subFeatureId(a));
196             aSubNames[theComposite->subFeatureId(a)] = Model_SelectionNaming::shortName(aConstr);
197           }
198         } else { // get first or last vertex of the edge: last is stored with additional delta
199           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
200           int aDelta = kSTART_VERTEX_DELTA;
201           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
202             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
203             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
204               aRefs.Add(aDelta + theComposite->subFeatureId(a));
205               aSubNames[aDelta + theComposite->subFeatureId(a)] =
206                 Model_SelectionNaming::shortName(aConstr, aDelta / kSTART_VERTEX_DELTA);
207               break;
208             }
209             aDelta += kSTART_VERTEX_DELTA;
210           }
211         }
212       } else {
213         if (aConstr->shape()->isEdge()) {
214           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
215           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
216           if (!anEdge.IsNull()) {
217             Standard_Real aFirst, aLast;
218             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
219             if (allCurves.Contains(aCurve)) {
220               int anID = theComposite->subFeatureId(a);
221               aRefs.Add(anID);
222               aSubNames[anID] = Model_SelectionNaming::shortName(aConstr);
223               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
224                 // add edges to sub-label to support naming for edges selection
225                 TopExp_Explorer anEdgeExp(theSubShape, TopAbs_EDGE);
226                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
227                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
228                   Standard_Real aFirst, aLast;
229                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
230                   if (aFaceCurve == aCurve) {
231                     int anOrient = Model_SelectionNaming::edgeOrientation(theSubShape, anEdge);
232                     anOrientations[anID] = anOrient;
233                   }
234                 }
235               }
236             }
237           }
238         }
239       }
240     }
241   }
242   std::stringstream aName;
243   // #1839 : do not store name of the feature in the tree, since this name could be changed
244   if (theSubShape.ShapeType() != TopAbs_COMPOUND) { // compound means the whole construction result
245     if (theSubShape.ShapeType() == TopAbs_FACE) aName<<"Face";
246     else if (theSubShape.ShapeType() == TopAbs_WIRE) aName<<"Wire";
247     else if (theSubShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
248     else if (theSubShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
249
250     // make a composite name from all sub-elements indexes: "1_2_3_4"
251     TColStd_MapIteratorOfPackedMapOfInteger aRef(aRefs);
252     for(; aRef.More(); aRef.Next()) {
253       aName<<"-"<<aSubNames[aRef.Key()];
254       if (anOrientations.find(aRef.Key()) != anOrientations.end()) {
255         if (anOrientations[aRef.Key()] == 1)
256           aName<<"f";
257         else if (anOrientations[aRef.Key()] == -1)
258           aName<<"r";
259       }
260     }
261   }
262   if (!theRefs.IsNull()) {
263     Handle(TColStd_HPackedMapOfInteger) aMap = new TColStd_HPackedMapOfInteger(aRefs);
264     theRefs->ChangeMap(aMap);
265   }
266   return aName.str();
267 }
268
269 // stores shape and name on sub-label of the main stored shape
270 static void saveSubName(CompositeFeaturePtr theComposite,
271   TDF_Label& theLab, const bool isSelectionMode, TopoDS_Shape aSub,
272   std::shared_ptr<Model_Document> theDoc, std::string theFullName)
273 {
274   // trying to store the edge of composite result, not sketch sub as it is
275   if (aSub.ShapeType() == TopAbs_EDGE) {
276     ResultPtr aRes = theComposite->firstResult();
277     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<Model_ResultConstruction>(aRes);
278     if (aConstr.get()) {
279       Standard_Real aSubFirst, aSubLast;
280       TopoDS_Edge aSubEdge = TopoDS::Edge(aSub);
281       Handle(Geom_Curve) aSubCurve = BRep_Tool::Curve(aSubEdge, aSubFirst, aSubLast);
282       for(int aFaceIndex = 0; aFaceIndex < aConstr->facesNum(); aFaceIndex++) {
283         GeomShapePtr aGFace = aConstr->face(aFaceIndex);
284         TopoDS_Shape aFace = aGFace->impl<TopoDS_Shape>();
285         for(TopExp_Explorer anExp(aFace, TopAbs_EDGE); anExp.More(); anExp.Next()) {
286           TopoDS_Edge anEdge = TopoDS::Edge(anExp.Current());
287           Standard_Real aFirst, aLast;
288           Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
289           if (aCurve == aSubCurve &&
290               ((fabs(aFirst - aSubFirst) < 1.e-9 &&  fabs(aLast - aSubLast) < 1.e-9)) ||
291               (fabs(aFirst - aSubLast) < 1.e-9 &&  fabs(aLast - aSubFirst) < 1.e-9)) {
292             aSub = anEdge;
293             break;
294           }
295         }
296       }
297     }
298   }
299
300   TNaming_Builder aBuilder(theLab);
301   if (isSelectionMode)
302     aBuilder.Select(aSub, aSub);
303   else
304     aBuilder.Generated(aSub);
305   theDoc->addNamingName(theLab, theFullName.c_str());
306   TDataStd_Name::Set(theLab, theFullName.c_str());
307 }
308
309
310 TDF_Label Model_ResultConstruction::startLabel(
311   const std::shared_ptr<ModelAPI_Document> theExtDoc, bool& theExternal)
312 {
313   theExternal = theExtDoc.get() && theExtDoc != document();
314   if (theExternal) { // external document is used
315     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(theExtDoc);
316     return aDoc->extConstructionsLabel();
317   }
318   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
319   return aData->label();
320 }
321
322 int Model_ResultConstruction::select(const std::shared_ptr<GeomAPI_Shape>& theSubShape,
323   const std::shared_ptr<ModelAPI_Document> theExtDoc, const int theIndex)
324 {
325   int anIndex; // resulting index of the sub-label
326   TopoDS_Shape aSubShape;
327   if (theSubShape.get()) {
328     aSubShape = theSubShape->impl<TopoDS_Shape>();
329   } else if (shape().get()) {
330     aSubShape = shape()->impl<TopoDS_Shape>();
331   }
332   // if external document requires this selection, put the naming structures to this doc
333   // to support the naming mechanism in this document correctly
334   bool anExternal;
335   TDF_Label aDataLab = startLabel(theExtDoc, anExternal);
336   if (theIndex == -1) {
337     anIndex = anExternal ? 2 : 1; // for the external doc don't mind about the main shape
338
339     if (theSubShape.get() || anExternal) { // searching for already selected sub (or whole for ext)
340       // iterate all the already presented shapes to see the same
341       TDF_ChildIterator aSubsIter(aDataLab, Standard_False);
342       for(; aSubsIter.More(); aSubsIter.Next()) {
343         const TDF_Label aLab = aSubsIter.Value();
344         if (aLab.Tag() == 1) // skip the root shape label
345           continue;
346         Handle(TNaming_NamedShape) aNS;
347         if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
348           if (aNS->Get().IsSame(aSubShape)) {
349             return aLab.Tag() - 1; // found exactly the needed shape, nothing else to do
350           }
351         }
352         anIndex = aLab.Tag(); // searching for the latest index
353       }
354       anIndex = (anIndex == 1) ? 2 : (anIndex + 1); // next after 1-root, or next after all
355     }
356   } else {
357     anIndex = theIndex + 1;
358   }
359
360   // set the naming structure at index
361   TDF_Label aLab = aDataLab.FindChild(anIndex, Standard_True);
362
363   // if the subshape is part of a result face, select the whole face (#1997)
364   bool isSelectionMode = false; // and other don't set shapes - all the naming is in face label
365   if (!aSubShape.IsNull() && aSubShape.ShapeType() > TopAbs_FACE) {
366     for(int aFaceIndex = 0; aFaceIndex < facesNum(); aFaceIndex++) {
367       TopExp_Explorer anExp(face(aFaceIndex)->impl<TopoDS_Shape>(), aSubShape.ShapeType());
368       for(; anExp.More(); anExp.Next()) {
369         if (aSubShape.IsSame(anExp.Current())) { // this is the case: select the whole face
370           // here just store the face index (to update face if update of edge is needed)
371           TNaming_Builder aBuilder(aLab);
372           aBuilder.Select(aSubShape, aSubShape);
373           int aFaceSelID = select(face(aFaceIndex), theExtDoc, -1);
374           TDF_Reference::Set(aLab, aLab.Father().FindChild(aFaceSelID));
375           isSelectionMode = true;
376           break;
377         }
378       }
379     }
380   }
381
382   // external full result is not identified by index == 0, so, add here the ID
383   if (!theSubShape.get()) {
384     TDataStd_UAttribute::Set(aLab, kFULL_RESULT_ID);
385     // empty NS
386     TNaming_Builder aBuilder(aLab);
387     // store all sub-faces naming since faces may be used for extrusion, where all edges are needed
388     Handle(TDataStd_IntPackedMap) anIndices = TDataStd_IntPackedMap::Set(aLab);
389     std::list<int> aFacesIndexes;
390     for(int a = 0; a < facesNum(); a++) {
391       anIndices->Add(select(face(a), theExtDoc, -1));
392     }
393     return anIndex - 1;
394   }
395
396   { // this to have erased Builder after the shape was generated (NS on this label may be changed)
397     TNaming_Builder aBuilder(aLab);
398     if (aSubShape.IsNull()) {
399       return anIndex - 1; // just keep empty named shape
400     }
401     // wire never happens as sub, it must be generated to be found
402     // by SelectionNaming TNaming_Tool::NamedShape
403     if (isSelectionMode && aSubShape.ShapeType() != TopAbs_WIRE) {
404       aBuilder.Select(aSubShape, aSubShape);
405     } else {
406       aBuilder.Generated(aSubShape);
407     }
408   }
409
410   if (anIndex == 1 && isInfinite()) { // infinitive results has no sub-selection
411     return anIndex - 1;
412   }
413   ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
414   FeaturePtr aThisFeature = document()->feature(aThisPtr);
415   CompositeFeaturePtr aComposite =
416     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aThisFeature);
417   if (!aComposite || aComposite->numberOfSubs() == 0) {
418     // saving of context is enough: result construction contains exactly the needed shape
419     return anIndex - 1;
420   }
421
422   // identify the results of sub-object of the composite by edges
423   // save type of the selected shape in integer attribute
424   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
425   TDataStd_Integer::Set(aLab, (int)aShapeType);
426   gp_Pnt aVertexPos;
427   TColStd_MapOfTransient allCurves;
428   if (aShapeType == TopAbs_VERTEX) { // compare positions
429     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
430   } else {
431     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
432       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
433       Standard_Real aFirst, aLast;
434       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
435       allCurves.Add(aCurve);
436     }
437   }
438   std::shared_ptr<Model_Document> aMyDoc =
439     std::dynamic_pointer_cast<Model_Document>(document());
440   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
441   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
442   const int aSubNum = aComposite->numberOfSubs();
443   // subs are placed one by one  because of #2248): sketch curve may produce several edges
444   int aSubLabId = 1;
445
446   for(int a = 0; a < aSubNum; a++) {
447     FeaturePtr aSub = aComposite->subFeature(a);
448     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
449     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
450     // there may be many shapes (circle and center): register if at least one is in selection
451     for(; aRes != aResults.cend(); aRes++) {
452       ResultConstructionPtr aConstr =
453         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
454       if (!aConstr->shape()) {
455         continue;
456       }
457       if (aShapeType != TopAbs_VERTEX) {
458         if (aConstr->shape()->isEdge()) {
459           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
460           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
461           if (!anEdge.IsNull()) {
462             Standard_Real aFirst, aLast;
463             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
464             if (allCurves.Contains(aCurve)) {
465               int anID = aComposite->subFeatureId(a);
466               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
467                 // add edges to sub-label to support naming for edges selection
468                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
469                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
470                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
471                   Standard_Real aFirst, aLast;
472                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
473                   if (aFaceCurve == aCurve) {
474                     TDF_Label aSubLab = aLab.FindChild(anID);
475                     TDF_Label aShapeSubLab = aLab.FindChild(aSubLabId++);
476                     std::string aFullNameSub = fullName(aComposite, anEdge);
477                     saveSubName(aComposite,
478                       aShapeSubLab, isSelectionMode, anEdge, aMyDoc, aFullNameSub);
479
480                     int anOrient = Model_SelectionNaming::edgeOrientation(aSubShape, anEdge);
481                     if (anOrient != 0) {
482                       // store the orientation of edge relatively to face if needed
483                       TDataStd_Integer::Set(aSubLab, anOrient);
484                     }
485                   }
486                 }
487               } else { // put vertices of the selected edge to sub-labels
488                 // add edges to sub-label to support naming for edges selection
489                 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
490                       anEdgeExp.More(); anEdgeExp.Next()) {
491                     TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
492                     TDF_Label aShapeSubLab = aLab.FindChild(aSubLabId++);
493                     std::string aFullNameSub = fullName(aComposite, aV);
494                     saveSubName(aComposite,
495                       aShapeSubLab, isSelectionMode, aV, aMyDoc, aFullNameSub);
496                 }
497               }
498             }
499           }
500         }
501       }
502     }
503   }
504   std::string aFullName = fullName(aComposite, aSubShape, aRefs);
505   // store the selected as primitive
506   registerSubShape(aLab, aSubShape, aFullName, 0, aMyDoc, isSelectionMode);
507   return anIndex - 1;
508 }
509
510 std::shared_ptr<GeomAPI_Shape> Model_ResultConstruction::shape(const int theIndex,
511   const std::shared_ptr<ModelAPI_Document> theExtDoc)
512 {
513   std::shared_ptr<GeomAPI_Shape> aResult;
514   if (theIndex == 0)
515     return aResult; // the whole shape, so, NULL
516
517   bool isExt;
518   TDF_Label aLab = startLabel(theExtDoc, isExt).FindChild(theIndex + 1);
519   if (!aLab.IsNull()) { // index is not bad
520     Handle(TNaming_NamedShape) aSelection;
521     if (aLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
522       TopoDS_Shape aSelShape = aSelection->Get();
523       if (aSelShape.IsNull())
524         return aResult; // shape equal to context => null
525       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
526       aResult->setImpl(new TopoDS_Shape(aSelShape));
527     }
528   }
529
530   return aResult;
531 }
532
533 bool Model_ResultConstruction::update(const int theIndex,
534   const std::shared_ptr<ModelAPI_Document> theExtDoc, bool& theModified)
535 {
536   theModified = false;
537   bool anExt;
538   TDF_Label aLab = startLabel(theExtDoc, anExt).FindChild(theIndex + 1, Standard_True);
539   if (theIndex == 0 || aLab.IsAttribute(kFULL_RESULT_ID)) { // full for external same as index == 0
540     // it is just reference to construction, not sub-shape
541     // if there is a sketch, the sketch-naming must be updated
542     if (!isInfinite()) {
543       // update all faces named by the whole result
544       bool aRes = true;
545       Handle(TDataStd_IntPackedMap) anIndices;
546       if (aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), anIndices)) {
547         NCollection_Map<TopoDS_Shape> aFaces; // collect faces, updated in the tree
548         TColStd_MapIteratorOfPackedMapOfInteger anIndexIter(anIndices->GetMap());
549         Handle(TColStd_HPackedMapOfInteger) aNewPackedMap =
550           new TColStd_HPackedMapOfInteger; // with only faces that are ok
551         // iterate to find existing faces, updated
552         for(; anIndexIter.More(); anIndexIter.Next()) {
553           if (update(anIndexIter.Key(), theExtDoc, theModified)) {
554             GeomShapePtr aFace = shape(anIndexIter.Key(), theExtDoc);
555             if (!aFaces.Contains(aFace->impl<TopoDS_Shape>())) {
556               aNewPackedMap->ChangeMap().Add(anIndexIter.Key());
557               aFaces.Add(aFace->impl<TopoDS_Shape>());
558             }
559           }
560         }
561         // then iterate all existing faces to find new faces
562         int aCurrentFacesNum = facesNum();
563         for(int a = 0; a < aCurrentFacesNum; a++) {
564           GeomShapePtr aFace = face(a);
565           if (!aFaces.Contains(aFace->impl<TopoDS_Shape>())) {
566             // add this one
567             int aNewFaceIndex = select(aFace, theExtDoc, -1);
568             if (aNewFaceIndex > 0) {
569               aNewPackedMap->ChangeMap().Add(aNewFaceIndex);
570             }
571           }
572         }
573         anIndices->ChangeMap(aNewPackedMap);
574       }
575       return aRes;
576     } else {
577       // For correct naming selection, put the shape into the naming structure.
578       // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
579       TNaming_Builder aBuilder(aLab);
580       aBuilder.Generated(shape()->impl<TopoDS_Shape>());
581     }
582     return shape() && !shape()->isNull();
583   }
584   // construction: identification by the results indexes, recompute faces and
585   // take the face that more close by the indexes
586   ResultPtr aThisPtr = std::dynamic_pointer_cast<ModelAPI_Result>(data()->owner());
587   FeaturePtr aContextFeature = document()->feature(aThisPtr);
588
589   // sketch sub-element
590   if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
591   {
592     // update the referenced object if it is sub
593     Handle(TDF_Reference) aRef;
594     if (aLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
595       int aFaceIndex = aRef->Get().Tag();
596       // don't check selection ,since face may disappear, but the shape stays correct
597       Model_ResultConstruction::update(aFaceIndex, theExtDoc, theModified);
598     }
599     // getting a type of selected shape
600     Handle(TDataStd_Integer) aTypeAttr;
601     if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
602       return false;
603     }
604     TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
605     // selected indexes will be needed in each "if"
606     Handle(TDataStd_IntPackedMap) aSubIds;
607     std::shared_ptr<GeomAPI_Shape> aNewSelected;
608     bool aNoIndexes =
609       !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
610     // for now working only with composite features
611     CompositeFeaturePtr aComposite =
612       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
613     if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
614       return false;
615     }
616
617     if (aShapeType == TopAbs_FACE || aShapeType == TopAbs_WIRE) {
618       // compound is for the whole sketch selection
619       // If this is a wire with plane defined then it is a sketch-like object
620       if (!facesNum()) // no faces, update can not work correctly
621         return false;
622       // if there is no edges indexes, any face can be used: take the first
623       std::shared_ptr<GeomAPI_Shape> aNewSelected;
624       if (aNoIndexes) {
625         aNewSelected = face(0);
626       } else { // searching for most looks-like initial face by the indexes
627         // prepare edges of the current result for the fast searching
628         // curves and orientations of edges
629         NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
630         const int aSubNum = aComposite->numberOfSubs();
631         for(int a = 0; a < aSubNum; a++) {
632           int aSubID = aComposite->subFeatureId(a);
633           if (aSubIds->Contains(aSubID)) {
634             FeaturePtr aSub = aComposite->subFeature(a);
635             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
636             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
637             for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
638               ResultConstructionPtr aConstr =
639                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
640               if (aConstr->shape() && aConstr->shape()->isEdge()) {
641                 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
642                 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
643                 if (!anEdge.IsNull()) {
644                   Standard_Real aFirst, aLast;
645                   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
646                   // searching for orientation information
647                   int anOrient = 0;
648                   Handle(TDataStd_Integer) anInt;
649                   if (aLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)) {
650                     anOrient = anInt->Get();
651                   }
652                   allCurves.Bind(aCurve, anOrient);
653                 }
654               }
655             }
656           }
657         }
658         aNewSelected = Model_SelectionNaming::findAppropriateFace(
659           aThisPtr, allCurves, aShapeType == TopAbs_WIRE);
660       }
661       if (aNewSelected) { // store this new selection
662         select(aNewSelected, theExtDoc, theIndex);
663         theModified = true;
664         return true;
665       } else {
666         // if the selection is not found, put the empty shape:
667         // it's better to have disappeared shape, than the old, the lost one
668         TNaming_Builder anEmptyBuilder(aLab);
669         return false;
670       }
671     } else if (aShapeType == TopAbs_EDGE) {
672       // just reselect the edge by the id
673       const int aSubNum = aComposite->numberOfSubs();
674       for(int a = 0; a < aSubNum; a++) {
675         // if aSubIds take any, the first appropriate
676         if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
677           // found the appropriate feature
678           FeaturePtr aFeature = aComposite->subFeature(a);
679           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
680             aFeature->results().cbegin();
681           for(;aResIter != aFeature->results().cend(); aResIter++) {
682             ResultConstructionPtr aRes =
683               std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
684             if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
685               select(aRes->shape(), theExtDoc, theIndex);
686               theModified = true;
687               return true;
688             }
689           }
690         }
691       }
692     } else if (aShapeType == TopAbs_VERTEX) {
693       // just reselect the vertex by the id of edge
694       const int aSubNum = aComposite->numberOfSubs();
695       for(int a = 0; a < aSubNum; a++) {
696         // if aSubIds take any, the first appropriate
697         int aFeatureID = aComposite->subFeatureId(a);
698         if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
699           aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
700           aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
701             // searching for deltas
702             int aVertexNum = 0;
703             if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
704             else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
705             // found the feature with appropriate edge
706             FeaturePtr aFeature = aComposite->subFeature(a);
707             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
708               aFeature->results().cbegin();
709             for(;aResIter != aFeature->results().cend(); aResIter++) {
710               ResultConstructionPtr aRes =
711                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
712               if (aRes && aRes->shape()) {
713                 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
714                   select(aRes->shape(), theExtDoc, theIndex);
715                   theModified = true;
716                   return true;
717                 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
718                   const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
719                   int aVIndex = 1;
720                   for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
721                     if (aVIndex == aVertexNum) { // found!
722                       std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
723                       aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
724                       select(aVertex, theExtDoc, theIndex);
725                       theModified = true;
726                       return true;
727                     }
728                     aVIndex++;
729                   }
730                 }
731               }
732             }
733         }
734       }
735     }
736   } else { // simple construction element: the selected is that needed
737     select(shape(), theExtDoc, theIndex);
738     theModified = true;
739     return true;
740   }
741   return false; // unknown case
742 }