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