1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_AttributeSelection.cpp
5 // Author: Mikhail PONIKAROV
7 #include "Model_AttributeSelection.h"
8 #include "Model_Application.h"
9 #include "Model_Events.h"
10 #include "Model_Data.h"
11 #include "Model_Document.h"
12 #include "Model_SelectionNaming.h"
13 #include <Model_Objects.h>
14 #include <ModelAPI_Feature.h>
15 #include <ModelAPI_ResultBody.h>
16 #include <ModelAPI_ResultConstruction.h>
17 #include <ModelAPI_ResultPart.h>
18 #include <ModelAPI_CompositeFeature.h>
19 #include <ModelAPI_Tools.h>
20 #include <GeomAPI_Shape.h>
21 #include <ModelAPI_Session.h>
22 #include <GeomAPI_PlanarEdges.h>
23 #include <Events_InfoMessage.h>
25 #include <TNaming_Selector.hxx>
26 #include <TNaming_NamedShape.hxx>
27 #include <TNaming_Tool.hxx>
28 #include <TNaming_Builder.hxx>
29 #include <TNaming_Localizer.hxx>
30 #include <TopoDS_Shape.hxx>
31 #include <TopoDS_Compound.hxx>
32 #include <TDataStd_IntPackedMap.hxx>
33 #include <TDataStd_Integer.hxx>
34 #include <TDataStd_UAttribute.hxx>
35 #include <TDataStd_Name.hxx>
36 #include <TopTools_MapOfShape.hxx>
37 #include <TopTools_IndexedMapOfShape.hxx>
38 #include <TopTools_MapIteratorOfMapOfShape.hxx>
39 #include <TopTools_ListOfShape.hxx>
40 #include <NCollection_DataMap.hxx>
41 #include <TopExp_Explorer.hxx>
42 #include <TDF_LabelMap.hxx>
43 #include <BRep_Tool.hxx>
44 #include <BRep_Builder.hxx>
45 #include <TopoDS_Edge.hxx>
48 #include <TColStd_MapOfTransient.hxx>
49 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
50 #include <TopTools_ListIteratorOfListOfShape.hxx>
51 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
53 #include <Precision.hxx>
54 #include <TDF_ChildIterator.hxx>
55 #include <TDF_ChildIDIterator.hxx>
56 #include <TDataStd_Name.hxx>
57 #include <TopAbs_ShapeEnum.hxx>
58 #include <TopoDS_Iterator.hxx>
59 #include <BRep_Builder.hxx>
60 #include <TNaming_SameShapeIterator.hxx>
61 #include <TNaming_Iterator.hxx>
64 //#define DEB_NAMING 1
66 #include <BRepTools.hxx>
68 /// added to the index in the packed map to signalize that the vertex of edge is selected
69 /// (multiplied by the index of the edge)
70 static const int kSTART_VERTEX_DELTA = 1000000;
71 // identifier that there is simple reference: selection equals to context
72 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
73 // simple reference in the construction
74 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
75 // reference to Part sub-object
76 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
77 // selection is invalid after recomputation
78 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
80 // on this label is stored:
81 // TNaming_NamedShape - selected shape
82 // TNaming_Naming - topological selection information (for the body)
83 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
84 // TDataStd_Integer - type of the selected shape (for construction)
85 // TDF_Reference - from ReferenceAttribute, the context
86 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
87 const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
89 if (theTemporarily) { // just keep the stored without DF update
90 myTmpContext = theContext;
91 myTmpSubShape = theSubShape;
92 owner()->data()->sendAttributeUpdated(this);
96 myTmpSubShape.reset();
99 const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
100 bool isOldContext = theContext == myRef.value();
101 bool isOldShape = isOldContext &&
102 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
103 if (isOldShape) return; // shape is the same, so context is also unchanged
104 // update the referenced object if needed
106 myRef.setValue(theContext);
109 // do noth use naming if selected shape is result shape itself, but not sub-shape
110 TDF_Label aSelLab = selectionLabel();
111 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
112 aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
113 aSelLab.ForgetAttribute(kINVALID_SELECTION);
115 bool isDegeneratedEdge = false;
116 // do not use the degenerated edge as a shape, a null context and shape is used in the case
117 if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
118 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
119 if (aSubShape.ShapeType() == TopAbs_EDGE)
120 isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
122 if (!theContext.get() || isDegeneratedEdge) {
123 // to keep the reference attribute label
124 TDF_Label aRefLab = myRef.myRef->Label();
125 aSelLab.ForgetAllAttributes(true);
126 myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
129 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
130 // do not select the whole shape for body:it is already must be in the data framework
131 // equal and null selected objects mean the same: object is equal to context,
132 if (theContext->shape().get() &&
133 (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
134 aSelLab.ForgetAllAttributes(true);
135 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
137 selectBody(theContext, theSubShape);
139 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
140 if (!theSubShape.get()) {
141 // to sub, so the whole result is selected
142 aSelLab.ForgetAllAttributes(true);
143 TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
144 ResultConstructionPtr aConstruction =
145 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
146 if (aConstruction->isInfinite()) {
147 // For correct naming selection, put the shape into the naming structure.
148 // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
149 TNaming_Builder aBuilder(aSelLab);
150 aBuilder.Generated(theContext->shape()->impl<TopoDS_Shape>());
151 std::shared_ptr<Model_Document> aMyDoc =
152 std::dynamic_pointer_cast<Model_Document>(owner()->document());
153 std::string aName = contextName(theContext);
154 // for selection in different document, add the document name
155 aMyDoc->addNamingName(aSelLab, aName);
156 TDataStd_Name::Set(aSelLab, aName.c_str());
157 } else { // for sketch the naming is needed in DS
158 BRep_Builder aCompoundBuilder;
159 TopoDS_Compound aComp;
160 aCompoundBuilder.MakeCompound(aComp);
161 for(int a = 0; a < aConstruction->facesNum(); a++) {
162 TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
163 aCompoundBuilder.Add(aComp, aFace);
165 std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
166 aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
167 selectConstruction(theContext, aShape);
170 selectConstruction(theContext, theSubShape);
172 } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
173 aSelLab.ForgetAllAttributes(true);
174 TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
175 selectPart(theContext, theSubShape);
177 //the attribute initialized state should be changed by sendAttributeUpdated only
178 //myIsInitialized = true;
180 owner()->data()->sendAttributeUpdated(this);
183 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
185 GeomShapePtr aResult;
186 if (myTmpContext.get() || myTmpSubShape.get()) {
187 ResultConstructionPtr aResulConstruction = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
188 if(aResulConstruction.get()) {
189 // it is just reference to construction.
190 return myTmpSubShape;
192 return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
195 TDF_Label aSelLab = selectionLabel();
196 if (aSelLab.IsAttribute(kINVALID_SELECTION))
199 if (myRef.isInitialized()) {
200 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
201 ResultPtr aContext = context();
203 return aResult; // empty result
204 return aContext->shape();
206 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
207 return aResult; // empty result
209 if (aSelLab.IsAttribute(kPART_REF_ID)) {
210 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
211 if (!aPart.get() || !aPart->isActivated())
212 return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
213 Handle(TDataStd_Integer) anIndex;
214 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
215 if (anIndex->Get()) { // special selection attribute was created, use it
216 return aPart->selectionValue(anIndex->Get());
217 } else { // face with name is already in the data model, so try to take it by name
218 Handle(TDataStd_Name) aName;
219 if (selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
220 std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
221 std::size_t aPartEnd = aSubShapeName.find('/');
222 if (aPartEnd != string::npos && aPartEnd != aSubShapeName.rfind('/')) {
223 string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
225 std::string aType; // to reuse already existing selection the type is not needed
226 return aPart->shapeInPart(aNameInPart, aType, anIndex);
233 Handle(TNaming_NamedShape) aSelection;
234 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
235 TopoDS_Shape aSelShape = aSelection->Get();
236 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
237 aResult->setImpl(new TopoDS_Shape(aSelShape));
238 } else { // for simple construction element: just shape of this construction element
239 ResultConstructionPtr aConstr =
240 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
242 return aConstr->shape();
249 bool Model_AttributeSelection::isInvalid()
251 return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
254 bool Model_AttributeSelection::isInitialized()
256 if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
257 std::shared_ptr<GeomAPI_Shape> aResult;
258 if (myRef.isInitialized()) {
259 TDF_Label aSelLab = selectionLabel();
260 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
261 ResultPtr aContext = context();
262 return aContext.get() != NULL;
264 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
268 Handle(TNaming_NamedShape) aSelection;
269 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
270 return !aSelection->Get().IsNull();
271 } else { // for simple construction element: just shape of this construction element
272 ResultConstructionPtr aConstr =
273 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
275 return aConstr->shape().get() != NULL;
283 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
286 myIsInitialized = myRef.isInitialized();
289 void Model_AttributeSelection::setID(const std::string theID)
292 ModelAPI_AttributeSelection::setID(theID);
295 ResultPtr Model_AttributeSelection::context() {
296 if (myTmpContext.get() || myTmpSubShape.get()) {
300 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
301 // for parts there could be same-data result, so take the last enabled
302 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
303 int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
304 for(int a = aSize - 1; a >= 0; a--) {
305 ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
306 if (aPart.get() && aPart->data() == aResult->data()) {
307 ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
308 FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
309 // check that this result is not this-feature result (it is forbidden t oselect itself)
310 if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
320 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
322 ModelAPI_AttributeSelection::setObject(theObject);
323 myRef.setObject(theObject);
326 TDF_LabelMap& Model_AttributeSelection::scope()
328 if (myScope.IsEmpty()) { // create a new scope if not yet done
329 // gets all features with named shapes that are before this feature label (before in history)
330 DocumentPtr aMyDoc = owner()->document();
331 std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
332 std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
333 bool aMePassed = false;
334 CompositeFeaturePtr aComposite =
335 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
336 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
337 CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
338 if (aFeature.get()) {
339 aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
340 if (aCompositeOwner.get()) {
341 aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
344 // for group Scope is not limitet: this is always up to date objects
345 bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
346 for(; aFIter != allFeatures.end(); aFIter++) {
347 if (*aFIter == owner()) { // the left features are created later (except subs of composite)
351 if (isGroup) aMePassed = false;
352 bool isInScope = !aMePassed;
353 if (!isInScope && aComposite.get()) { // try to add sub-elements of composite if this is composite
354 if (aComposite->isSub(*aFIter))
357 // remove the composite-owner of this feature (sketch in extrusion-cut)
358 if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
361 if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
362 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
363 (*aFIter)->data())->label().Father();
364 TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), 1);
365 for(; aNSIter.More(); aNSIter.Next()) {
366 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
367 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
368 myScope.Add(aNS->Label());
377 /// Sets the invalid flag if flag is false, or removes it if "true"
379 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
381 theLab.ForgetAttribute(kINVALID_SELECTION);
383 TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
388 bool Model_AttributeSelection::update()
390 TDF_Label aSelLab = selectionLabel();
391 ResultPtr aContext = context();
393 return setInvalidIfFalse(aSelLab, false);
394 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
395 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
397 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
398 // if there is a sketch, the sketch-naming must be updated
399 ResultConstructionPtr aConstruction =
400 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
401 if (!aConstruction->isInfinite()) {
402 BRep_Builder aCompoundBuilder;
403 TopoDS_Compound aComp;
404 aCompoundBuilder.MakeCompound(aComp);
405 for(int a = 0; a < aConstruction->facesNum(); a++) {
406 TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
407 aCompoundBuilder.Add(aComp, aFace);
409 std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
410 aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
411 selectConstruction(aContext, aShape);
413 // For correct naming selection, put the shape into the naming structure.
414 // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
415 TNaming_Builder aBuilder(aSelLab);
416 aBuilder.Generated(aContext->shape()->impl<TopoDS_Shape>());
417 std::shared_ptr<Model_Document> aMyDoc =
418 std::dynamic_pointer_cast<Model_Document>(owner()->document());
419 std::string aName = contextName(aContext);
420 aMyDoc->addNamingName(aSelLab, aName);
421 TDataStd_Name::Set(aSelLab, aName.c_str());
423 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
426 if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
427 std::shared_ptr<GeomAPI_Shape> aNoSelection;
428 bool aResult = selectPart(aContext, aNoSelection, true);
429 aResult = setInvalidIfFalse(aSelLab, aResult);
431 owner()->data()->sendAttributeUpdated(this);
436 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
437 // body: just a named shape, use selection mechanism from OCCT
438 TNaming_Selector aSelector(aSelLab);
439 bool aResult = aSelector.Solve(scope()) == Standard_True;
440 aResult = setInvalidIfFalse(aSelLab, aResult); // must be before sending of updated attribute (1556)
441 owner()->data()->sendAttributeUpdated(this);
443 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
444 // construction: identification by the results indexes, recompute faces and
445 // take the face that more close by the indexes
446 ResultConstructionPtr aConstructionContext =
447 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
448 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
449 // sketch sub-element
450 if (aConstructionContext &&
451 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
453 TDF_Label aLab = myRef.myRef->Label();
454 // getting a type of selected shape
455 Handle(TDataStd_Integer) aTypeAttr;
456 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
457 return setInvalidIfFalse(aSelLab, false);
459 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
460 // selected indexes will be needed in each "if"
461 Handle(TDataStd_IntPackedMap) aSubIds;
462 std::shared_ptr<GeomAPI_Shape> aNewSelected;
464 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
465 // for now working only with composite features
466 CompositeFeaturePtr aComposite =
467 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
468 if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
469 return setInvalidIfFalse(aSelLab, false);
472 if (aShapeType == TopAbs_FACE || aShapeType == TopAbs_WIRE) { // compound is for the whole sketch selection
473 // If this is a wire with plane defined then it is a sketch-like object
474 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
475 return setInvalidIfFalse(aSelLab, false);
476 // if there is no edges indexes, any face can be used: take the first
477 std::shared_ptr<GeomAPI_Shape> aNewSelected;
479 aNewSelected = aConstructionContext->face(0);
480 } else { // searching for most looks-like initial face by the indexes
481 // prepare edges of the current result for the fast searching
482 NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
483 const int aSubNum = aComposite->numberOfSubs();
484 for(int a = 0; a < aSubNum; a++) {
485 int aSubID = aComposite->subFeatureId(a);
486 if (aSubIds->Contains(aSubID)) {
487 FeaturePtr aSub = aComposite->subFeature(a);
488 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
489 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
490 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
491 ResultConstructionPtr aConstr =
492 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
493 if (aConstr->shape() && aConstr->shape()->isEdge()) {
494 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
495 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
496 if (!anEdge.IsNull()) {
497 Standard_Real aFirst, aLast;
498 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
499 // searching for orientation information
501 Handle(TDataStd_Integer) anInt;
502 if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
503 anOrient = anInt->Get();
505 allCurves.Bind(aCurve, anOrient);
511 aNewSelected = Model_SelectionNaming::findAppropriateFace(
512 aContext, allCurves, aShapeType == TopAbs_WIRE);
514 if (aNewSelected) { // store this new selection
515 selectConstruction(aContext, aNewSelected);
516 setInvalidIfFalse(aSelLab, true);
517 owner()->data()->sendAttributeUpdated(this);
519 } else { // if the selection is not found, put the empty shape: it's better to have disappeared shape, than the old, the lost one
520 TNaming_Builder anEmptyBuilder(selectionLabel());
521 return setInvalidIfFalse(aSelLab, false);
523 } else if (aShapeType == TopAbs_EDGE) {
524 // just reselect the edge by the id
525 const int aSubNum = aComposite->numberOfSubs();
526 for(int a = 0; a < aSubNum; a++) {
527 // if aSubIds take any, the first appropriate
528 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
529 // found the appropriate feature
530 FeaturePtr aFeature = aComposite->subFeature(a);
531 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
532 aFeature->results().cbegin();
533 for(;aResIter != aFeature->results().cend(); aResIter++) {
534 ResultConstructionPtr aRes =
535 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
536 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
537 selectConstruction(aContext, aRes->shape());
538 setInvalidIfFalse(aSelLab, true);
539 owner()->data()->sendAttributeUpdated(this);
545 } else if (aShapeType == TopAbs_VERTEX) {
546 // just reselect the vertex by the id of edge
547 const int aSubNum = aComposite->numberOfSubs();
548 for(int a = 0; a < aSubNum; a++) {
549 // if aSubIds take any, the first appropriate
550 int aFeatureID = aComposite->subFeatureId(a);
551 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
552 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
553 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
554 // searching for deltas
556 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
557 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
558 // found the feature with appropriate edge
559 FeaturePtr aFeature = aComposite->subFeature(a);
560 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
561 aFeature->results().cbegin();
562 for(;aResIter != aFeature->results().cend(); aResIter++) {
563 ResultConstructionPtr aRes =
564 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
565 if (aRes && aRes->shape()) {
566 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
567 selectConstruction(aContext, aRes->shape());
568 setInvalidIfFalse(aSelLab, true);
569 owner()->data()->sendAttributeUpdated(this);
571 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
572 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
574 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
575 if (aVIndex == aVertexNum) { // found!
576 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
577 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
578 selectConstruction(aContext, aVertex);
579 setInvalidIfFalse(aSelLab, true);
580 owner()->data()->sendAttributeUpdated(this);
591 } else { // simple construction element: the selected is that needed
592 selectConstruction(aContext, aContext->shape());
593 setInvalidIfFalse(aSelLab, true);
594 owner()->data()->sendAttributeUpdated(this);
598 return setInvalidIfFalse(aSelLab, false); // unknown case
601 void Model_AttributeSelection::selectBody(
602 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
604 // perform the selection
605 TNaming_Selector aSel(selectionLabel());
606 TopoDS_Shape aContext;
608 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
610 aContext = aBody->shape()->impl<TopoDS_Shape>();
613 std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
615 aContext = aResult->shape()->impl<TopoDS_Shape>();
617 Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
622 // with "recover" feature the selected context may be not up to date (issue 1710)
623 Handle(TNaming_NamedShape) aResult;
624 TDF_Label aSelLab = selectionLabel();
625 TopoDS_Shape aNewContext = aContext;
626 bool isUpdated = true;
627 while(!aNewContext.IsNull() && isUpdated) { // searching for the very last shape that was produced from this one
629 if (!TNaming_Tool::HasLabel(aSelLab, aNewContext)) // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
631 for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
632 TDF_Label aNSLab = anIter.Label();
633 if (!scope().Contains(aNSLab))
635 Handle(TNaming_NamedShape) aNS;
636 if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
637 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
638 if (aShapesIter.Evolution() == TNaming_SELECTED)
639 continue; // don't use the selection evolution
640 if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
641 // found the original shape
642 aNewContext = aShapesIter.NewShape(); // go to the newer shape
650 if (aNewContext.IsNull()) { // a context is already deleted
651 setInvalidIfFalse(aSelLab, false);
652 Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
656 TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
657 if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
658 bool isFound = false;
659 TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
660 for(; anExp.More(); anExp.Next()) {
661 if (anExp.Current().IsEqual(aNewSub)) {
666 if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
667 setInvalidIfFalse(aSelLab, false);
668 Events_InfoMessage("Model_AttributeSelection", "Failed to select sub-shape already modified").send();
674 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
675 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
676 if (aFeatureOwner.get())
677 aFeatureOwner->eraseResults();
678 if (!aContext.IsNull()) {
679 aSel.Select(aNewSub, aNewContext);
683 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
684 /// if theID is zero,
685 /// theOrientation is additional information about the positioning of edge relatively to face
686 /// it is stored in the integer attribute of the edge sub-label:
687 /// -1 is out, 1 is in, 0 is not needed
688 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
689 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
690 std::string theAdditionalName, std::map<int, int>& theOrientations,
691 std::map<int, std::string>& theSubNames, // name of sub-elements by ID to be exported instead of indexes
692 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
693 const int theOrientation = 0)
695 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
696 if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
697 TDataStd_Integer::Set(aLab, theOrientation);
699 TNaming_Builder aBuilder(aLab);
700 aBuilder.Generated(theShape);
701 std::stringstream aName;
702 // add the part name if the selected object is located in other part
703 if (theDoc != theContextFeature->document()) {
704 if (theContextFeature->document() == ModelAPI_Session::get()->moduleDocument()) {
705 aName<<theContextFeature->document()->kind()<<"/";
707 ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
708 ModelAPI_Session::get()->moduleDocument(), theContextFeature->document());
710 aName<<aDocRes->data()->name()<<"/";
714 aName<<theContextFeature->name();
715 if (theShape.ShapeType() != TopAbs_COMPOUND) { // compound means the whole result for construction
717 if (!theAdditionalName.empty())
718 aName<<theAdditionalName<<"/";
719 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
720 else if (theShape.ShapeType() == TopAbs_WIRE) aName<<"Wire";
721 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
722 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
724 if (theRefs.IsNull()) {
726 if (theOrientation == 1)
728 else if (theOrientation == -1)
730 } else { // make a composite name from all sub-elements indexes: "1_2_3_4"
731 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
732 for(; aRef.More(); aRef.Next()) {
733 aName<<"-"<<theSubNames[aRef.Key()];
734 if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
735 if (theOrientations[aRef.Key()] == 1)
737 else if (theOrientations[aRef.Key()] == -1)
744 theDoc->addNamingName(aLab, aName.str());
745 TDataStd_Name::Set(aLab, aName.str().c_str());
748 void Model_AttributeSelection::selectConstruction(
749 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
751 std::shared_ptr<Model_Document> aMyDoc =
752 std::dynamic_pointer_cast<Model_Document>(owner()->document());
753 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
754 CompositeFeaturePtr aComposite =
755 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
756 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
757 if (!aComposite || aComposite->numberOfSubs() == 0) {
758 // saving of context is enough: result construction contains exactly the needed shape
759 TNaming_Builder aBuilder(selectionLabel());
760 aBuilder.Generated(aSubShape);
761 std::string aName = contextName(theContext);
762 aMyDoc->addNamingName(selectionLabel(), aName);
763 TDataStd_Name::Set(selectionLabel(), aName.c_str());
766 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
767 TDF_Label aLab = myRef.myRef->Label();
768 // identify the results of sub-object of the composite by edges
769 // save type of the selected shape in integer attribute
770 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
771 TDataStd_Integer::Set(aLab, (int)aShapeType);
773 TColStd_MapOfTransient allCurves;
774 if (aShapeType == TopAbs_VERTEX) { // compare positions
775 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
777 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
778 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
779 Standard_Real aFirst, aLast;
780 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
781 allCurves.Add(aCurve);
784 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
785 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
786 std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
787 std::map<int, std::string> aSubNames; //map from edges IDs to names of edges
789 const int aSubNum = aComposite->numberOfSubs();
790 for(int a = 0; a < aSubNum; a++) {
791 FeaturePtr aSub = aComposite->subFeature(a);
792 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
793 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
794 // there may be many shapes (circle and center): register if at least one is in selection
795 for(; aRes != aResults.cend(); aRes++) {
796 ResultConstructionPtr aConstr =
797 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
798 if (!aConstr->shape()) {
801 if (aShapeType == TopAbs_VERTEX) {
802 if (aConstr->shape()->isVertex()) { // compare vertices positions
803 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
804 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
805 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
806 aRefs->Add(aComposite->subFeatureId(a));
807 aSubNames[aComposite->subFeatureId(a)] = Model_SelectionNaming::shortName(aConstr);
809 } else { // get first or last vertex of the edge: last is stored with additional delta
810 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
811 int aDelta = kSTART_VERTEX_DELTA;
812 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
813 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
814 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
815 aRefs->Add(aDelta + aComposite->subFeatureId(a));
816 aSubNames[aDelta + aComposite->subFeatureId(a)] =
817 Model_SelectionNaming::shortName(aConstr, aDelta / kSTART_VERTEX_DELTA);
820 aDelta += kSTART_VERTEX_DELTA;
824 if (aConstr->shape()->isEdge()) {
825 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
826 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
827 if (!anEdge.IsNull()) {
828 Standard_Real aFirst, aLast;
829 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
830 if (allCurves.Contains(aCurve)) {
831 int anID = aComposite->subFeatureId(a);
833 aSubNames[anID] = Model_SelectionNaming::shortName(aConstr);
834 if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
835 // add edges to sub-label to support naming for edges selection
836 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
837 for(; anEdgeExp.More(); anEdgeExp.Next()) {
838 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
839 Standard_Real aFirst, aLast;
840 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
841 if (aFaceCurve == aCurve) {
842 int anOrient = Model_SelectionNaming::edgeOrientation(aSubShape, anEdge);
843 anOrientations[anID] = anOrient;
845 selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
846 aSubNames, Handle(TDataStd_IntPackedMap)(), anOrient);
849 } else { // put vertices of the selected edge to sub-labels
850 // add edges to sub-label to support naming for edges selection
851 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
852 int aTagIndex = anID + kSTART_VERTEX_DELTA;
853 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
854 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
856 std::stringstream anAdditionalName;
858 selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations,
868 // store the selected as primitive
869 TNaming_Builder aBuilder(selectionLabel());
870 aBuilder.Generated(aSubShape);
872 selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aSubNames, aRefs);
875 bool Model_AttributeSelection::selectPart(
876 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
877 const bool theUpdate)
879 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
880 if (!aPart.get() || !aPart->isActivated())
881 return true; // postponed naming
883 Handle(TDataStd_Integer) anIndex;
884 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
885 if (anIndex->Get() > 0) {
886 // update the selection by index
887 return aPart->updateInPart(anIndex->Get());
889 return true; // nothing to do, referencing just by name
892 return true; // nothing to do, referencing just by name
894 // store the shape (in case part is not loaded it should be useful
896 std::string aName = theContext->data()->name();
897 if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
898 aShape = theContext->shape()->impl<TopoDS_Shape>();
900 aShape = theSubShape->impl<TopoDS_Shape>();
902 aName += "/" + aPart->nameInPart(theSubShape, anIndex);
903 TDataStd_Integer::Set(selectionLabel(), anIndex);
905 TNaming_Builder aBuilder(selectionLabel());
906 aBuilder.Select(aShape, aShape);
907 // identify by name in the part
908 TDataStd_Name::Set(selectionLabel(), aName.c_str());
909 return !aName.empty();
912 TDF_Label Model_AttributeSelection::selectionLabel()
914 return myRef.myRef->Label().FindChild(1);
917 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
919 std::string aName("");
920 if(!this->isInitialized())
921 return !theDefaultName.empty() ? theDefaultName : aName;
923 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
924 ResultPtr aCont = context();
926 Model_SelectionNaming aSelNaming(selectionLabel());
927 return aSelNaming.namingName(
928 aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
931 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
932 void Model_AttributeSelection::selectSubShape(
933 const std::string& theType, const std::string& theSubShapeName)
935 if(theSubShapeName.empty() || theType.empty()) return;
937 // check this is Part-name: 2 delimiters in the name
938 std::size_t aPartEnd = theSubShapeName.find('/');
939 if (aPartEnd != string::npos && aPartEnd != theSubShapeName.rfind('/')) {
940 std::string aPartName = theSubShapeName.substr(0, aPartEnd);
941 ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
942 if (aFound.get()) { // found such part, so asking it for the name
943 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
944 string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
946 std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
947 if (aSelected.get()) {
948 setValue(aPart, aSelected);
949 TDataStd_Integer::Set(selectionLabel(), anIndex);
955 Model_SelectionNaming aSelNaming(selectionLabel());
956 std::shared_ptr<Model_Document> aDoc =
957 std::dynamic_pointer_cast<Model_Document>(owner()->document());
958 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
960 if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
961 // try to find the last context to find the up to dat shape
962 if (aCont->shape().get() && !aCont->shape()->isNull() &&
963 aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
964 const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
965 if (!aConShape.IsNull()) {
966 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
968 aNS = TNaming_Tool::CurrentNamedShape(aNS);
970 TDF_Label aLab = aNS->Label();
971 while(aLab.Depth() != 7 && aLab.Depth() > 5)
972 aLab = aLab.Father();
973 ObjectPtr anObj = aDoc->objects()->object(aLab);
975 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
983 setValue(aCont, aShapeToBeSelected);
987 int Model_AttributeSelection::Id()
990 std::shared_ptr<GeomAPI_Shape> aSelection = value();
991 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
992 // support for compsolids:
993 if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
994 aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
997 TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
998 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
999 // searching for the latest main shape
1000 if (aSelection && !aSelection->isNull() &&
1001 aContext && !aContext->isNull())
1003 std::shared_ptr<Model_Document> aDoc =
1004 std::dynamic_pointer_cast<Model_Document>(context()->document());
1006 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1007 if (!aNS.IsNull()) {
1008 aMainShape = TNaming_Tool::CurrentShape(aNS);
1012 TopTools_IndexedMapOfShape aSubShapesMap;
1013 TopExp::MapShapes(aMainShape, aSubShapesMap);
1014 anID = aSubShapesMap.FindIndex(aSubShape);
1019 void Model_AttributeSelection::setId(int theID)
1021 const ResultPtr& aContext = context();
1022 std::shared_ptr<GeomAPI_Shape> aSelection;
1024 std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
1025 // support for compsolids:
1026 if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
1027 aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
1029 TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
1030 // searching for the latest main shape
1032 aContextShape && !aContextShape->isNull())
1034 std::shared_ptr<Model_Document> aDoc =
1035 std::dynamic_pointer_cast<Model_Document>(aContext->document());
1037 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1038 if (!aNS.IsNull()) {
1039 aMainShape = TNaming_Tool::CurrentShape(aNS);
1043 TopTools_IndexedMapOfShape aSubShapesMap;
1044 TopExp::MapShapes(aMainShape, aSubShapesMap);
1045 const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1047 std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1048 aResult->setImpl(new TopoDS_Shape(aSelShape));
1050 aSelection = aResult;
1053 setValue(aContext, aSelection);
1056 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1058 std::string aResult;
1059 if (owner()->document() != theContext->document()) {
1060 if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1061 aResult = theContext->document()->kind() + "/";
1063 ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1064 ModelAPI_Session::get()->moduleDocument(), theContext->document());
1065 if (aDocRes.get()) {
1066 aResult = aDocRes->data()->name() + "/";
1070 aResult += theContext->data()->name();