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 <ModelAPI_Feature.h>
14 #include <ModelAPI_ResultBody.h>
15 #include <ModelAPI_ResultConstruction.h>
16 #include <ModelAPI_ResultPart.h>
17 #include <ModelAPI_CompositeFeature.h>
18 #include <ModelAPI_Tools.h>
19 #include <GeomAPI_Shape.h>
20 #include <GeomAPI_PlanarEdges.h>
21 #include <Events_Error.h>
23 #include <TNaming_Selector.hxx>
24 #include <TNaming_NamedShape.hxx>
25 #include <TNaming_Tool.hxx>
26 #include <TNaming_Builder.hxx>
27 #include <TNaming_Localizer.hxx>
28 #include <TopoDS_Shape.hxx>
29 #include <TopoDS_Compound.hxx>
30 #include <TDataStd_IntPackedMap.hxx>
31 #include <TDataStd_Integer.hxx>
32 #include <TDataStd_UAttribute.hxx>
33 #include <TDataStd_Name.hxx>
34 #include <TopTools_MapOfShape.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_MapIteratorOfMapOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <NCollection_DataMap.hxx>
39 #include <TopExp_Explorer.hxx>
40 #include <TDF_LabelMap.hxx>
41 #include <BRep_Tool.hxx>
42 #include <BRep_Builder.hxx>
43 #include <TopoDS_Edge.hxx>
46 #include <TColStd_MapOfTransient.hxx>
47 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
48 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
51 #include <Precision.hxx>
52 #include <TDF_ChildIterator.hxx>
53 #include <TDF_ChildIDIterator.hxx>
54 #include <TDataStd_Name.hxx>
55 #include <TopAbs_ShapeEnum.hxx>
56 #include <TopoDS_Iterator.hxx>
57 #include <TNaming_Iterator.hxx>
58 #include <BRep_Builder.hxx>
60 //#define DEB_NAMING 1
62 #include <BRepTools.hxx>
64 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
65 /// (multiplied by the index of the edge)
66 static const int kSTART_VERTEX_DELTA = 1000000;
67 // identifier that there is simple reference: selection equals to context
68 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
69 // simple reference in the construction
70 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
71 // reference to Part sub-object
72 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
73 // selection is invalid after recomputation
74 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
76 // on this label is stored:
77 // TNaming_NamedShape - selected shape
78 // TNaming_Naming - topological selection information (for the body)
79 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
80 // TDataStd_Integer - type of the selected shape (for construction)
81 // TDF_Reference - from ReferenceAttribute, the context
82 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
83 const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
85 if (theTemporarily) { // just keep the stored without DF update
86 myTmpContext = theContext;
87 myTmpSubShape = theSubShape;
88 owner()->data()->sendAttributeUpdated(this);
92 myTmpSubShape.reset();
95 const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
96 bool isOldContext = theContext == myRef.value();
97 bool isOldShape = isOldContext &&
98 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
99 if (isOldShape) return; // shape is the same, so context is also unchanged
100 // update the referenced object if needed
102 ResultCompSolidPtr anOwner = ModelAPI_Tools::compSolidOwner(theContext);
104 myRef.setValue(anOwner);
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 = theContext->data()->name();
154 aMyDoc->addNamingName(aSelLab, aName);
155 TDataStd_Name::Set(aSelLab, aName.c_str());
156 } else { // for sketch the naming is needed in DS
157 BRep_Builder aCompoundBuilder;
158 TopoDS_Compound aComp;
159 aCompoundBuilder.MakeCompound(aComp);
160 for(int a = 0; a < aConstruction->facesNum(); a++) {
161 TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
162 aCompoundBuilder.Add(aComp, aFace);
164 std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
165 aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
166 selectConstruction(theContext, aShape);
169 selectConstruction(theContext, theSubShape);
171 } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
172 aSelLab.ForgetAllAttributes(true);
173 TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
174 selectPart(theContext, theSubShape);
176 //the attribute initialized state should be changed by sendAttributeUpdated only
177 //myIsInitialized = true;
179 owner()->data()->sendAttributeUpdated(this);
181 std::string aSelName = namingName();
182 if(!aSelName.empty())
183 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
186 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
188 if (myTmpContext.get() || myTmpSubShape.get()) {
189 return myTmpSubShape;
192 std::shared_ptr<GeomAPI_Shape> aResult;
193 TDF_Label aSelLab = selectionLabel();
194 if (aSelLab.IsAttribute(kINVALID_SELECTION))
197 if (myRef.isInitialized()) {
198 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
199 ResultPtr aContext = context();
201 return aResult; // empty result
202 return aContext->shape();
204 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
205 return aResult; // empty result
207 if (aSelLab.IsAttribute(kPART_REF_ID)) {
208 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
209 if (!aPart.get() || !aPart->isActivated())
210 return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
211 Handle(TDataStd_Integer) anIndex;
212 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
213 if (anIndex->Get()) { // special selection attribute was created, use it
214 return aPart->selectionValue(anIndex->Get());
215 } else { // face with name is already in the data model, so try to take it by name
216 Handle(TDataStd_Name) aName;
217 if (selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
218 std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
219 std::size_t aPartEnd = aSubShapeName.find('/');
220 if (aPartEnd != string::npos && aPartEnd != aSubShapeName.rfind('/')) {
221 string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
223 std::string aType; // to reuse already existing selection the type is not needed
224 return aPart->shapeInPart(aNameInPart, aType, anIndex);
231 Handle(TNaming_NamedShape) aSelection;
232 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
233 TopoDS_Shape aSelShape = aSelection->Get();
234 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
235 aResult->setImpl(new TopoDS_Shape(aSelShape));
236 } else { // for simple construction element: just shape of this construction element
237 ResultConstructionPtr aConstr =
238 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
240 return aConstr->shape();
247 bool Model_AttributeSelection::isInvalid()
249 return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
252 bool Model_AttributeSelection::isInitialized()
254 if (ModelAPI_AttributeSelection::isInitialized()) { // additional checkings if it is initialized
255 std::shared_ptr<GeomAPI_Shape> aResult;
256 if (myRef.isInitialized()) {
257 TDF_Label aSelLab = selectionLabel();
258 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
259 ResultPtr aContext = context();
260 return aContext.get() != NULL;
262 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
266 Handle(TNaming_NamedShape) aSelection;
267 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
268 return !aSelection->Get().IsNull();
269 } else { // for simple construction element: just shape of this construction element
270 ResultConstructionPtr aConstr =
271 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
273 return aConstr->shape().get() != NULL;
281 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
284 myIsInitialized = myRef.isInitialized();
287 void Model_AttributeSelection::setID(const std::string theID)
290 ModelAPI_AttributeSelection::setID(theID);
293 ResultPtr Model_AttributeSelection::context() {
294 if (myTmpContext.get() || myTmpSubShape.get()) {
298 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
299 // for parts there could be same-data result, so take the last enabled
300 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
301 int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
302 for(int a = aSize - 1; a >= 0; a--) {
303 ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
304 if (aPart.get() && aPart->data() == aResult->data()) {
305 ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
306 FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
307 // check that this result is not this-feature result (it is forbidden t oselect itself)
308 if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
318 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
320 ModelAPI_AttributeSelection::setObject(theObject);
321 myRef.setObject(theObject);
324 TDF_LabelMap& Model_AttributeSelection::scope()
326 if (myScope.IsEmpty()) { // create a new scope if not yet done
327 // gets all featueres with named shapes that are bofore this feature label (before in history)
328 DocumentPtr aMyDoc = owner()->document();
329 std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
330 std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
331 bool aMePassed = false;
332 CompositeFeaturePtr aComposite =
333 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
334 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
335 CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
336 if (aFeature.get()) {
337 aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
338 if (aCompositeOwner.get()) {
339 aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
342 // for group Scope is not limitet: this is always up to date objects
343 bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
344 for(; aFIter != allFeatures.end(); aFIter++) {
345 if (*aFIter == owner()) { // the left features are created later (except subs of composite)
349 if (isGroup) aMePassed = false;
350 bool isInScope = !aMePassed;
351 if (!isInScope && aComposite.get()) { // try to add sub-elements of composite if this is composite
352 if (aComposite->isSub(*aFIter))
355 // remove the composite-owner of this feature (sketch in extrusion-cut)
356 if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
359 if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
360 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
361 (*aFIter)->data())->label().Father();
362 TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), 1);
363 for(; aNSIter.More(); aNSIter.Next()) {
364 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
365 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
366 myScope.Add(aNS->Label());
375 /// produces theEdge orientation relatively to theContext face
376 int edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
378 if (theContext.ShapeType() != TopAbs_FACE)
380 TopoDS_Face aContext = TopoDS::Face(theContext);
381 if (theEdge.Orientation() == TopAbs_FORWARD)
383 if (theEdge.Orientation() == TopAbs_REVERSED)
388 /// Sets the invalid flag if flag is false, or removes it if "true"
390 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
392 theLab.ForgetAttribute(kINVALID_SELECTION);
394 TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
399 bool Model_AttributeSelection::update()
401 TDF_Label aSelLab = selectionLabel();
402 ResultPtr aContext = context();
404 return setInvalidIfFalse(aSelLab, false);
405 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
406 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
408 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
409 // if there is a sketch, the sketch-naming must be updated
410 ResultConstructionPtr aConstruction =
411 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
412 if (!aConstruction->isInfinite()) {
413 BRep_Builder aCompoundBuilder;
414 TopoDS_Compound aComp;
415 aCompoundBuilder.MakeCompound(aComp);
416 for(int a = 0; a < aConstruction->facesNum(); a++) {
417 TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
418 aCompoundBuilder.Add(aComp, aFace);
420 std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
421 aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
422 selectConstruction(aContext, aShape);
424 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
427 if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
428 std::shared_ptr<GeomAPI_Shape> aNoSelection;
429 return setInvalidIfFalse(aSelLab, selectPart(aContext, aNoSelection, true));
432 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
433 // body: just a named shape, use selection mechanism from OCCT
434 TNaming_Selector aSelector(aSelLab);
435 bool aResult = aSelector.Solve(scope()) == Standard_True;
436 owner()->data()->sendAttributeUpdated(this);
437 return setInvalidIfFalse(aSelLab, aResult);
438 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
439 // construction: identification by the results indexes, recompute faces and
440 // take the face that more close by the indexes
441 ResultConstructionPtr aConstructionContext =
442 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
443 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
444 // sketch sub-element
445 if (aConstructionContext &&
446 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
448 TDF_Label aLab = myRef.myRef->Label();
449 // getting a type of selected shape
450 Handle(TDataStd_Integer) aTypeAttr;
451 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
452 return setInvalidIfFalse(aSelLab, false);
454 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
455 // selected indexes will be needed in each "if"
456 Handle(TDataStd_IntPackedMap) aSubIds;
457 std::shared_ptr<GeomAPI_Shape> aNewSelected;
459 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
460 // for now working only with composite features
461 CompositeFeaturePtr aComposite =
462 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
463 if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
464 return setInvalidIfFalse(aSelLab, false);
467 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
468 // If this is a wire with plane defined thin it is a sketch-like object
469 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
470 return setInvalidIfFalse(aSelLab, false);
471 // if there is no edges indexes, any face can be used: take the first
472 std::shared_ptr<GeomAPI_Shape> aNewSelected;
474 aNewSelected = aConstructionContext->face(0);
475 } else { // searching for most looks-like initial face by the indexes
476 // prepare edges of the current resut for the fast searching
477 NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
478 const int aSubNum = aComposite->numberOfSubs();
479 for(int a = 0; a < aSubNum; a++) {
480 int aSubID = aComposite->subFeatureId(a);
481 if (aSubIds->Contains(aSubID)) {
482 FeaturePtr aSub = aComposite->subFeature(a);
483 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
484 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
485 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
486 ResultConstructionPtr aConstr =
487 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
488 if (aConstr->shape() && aConstr->shape()->isEdge()) {
489 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
490 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
491 if (!anEdge.IsNull()) {
492 Standard_Real aFirst, aLast;
493 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
494 // searching for orientation information
496 Handle(TDataStd_Integer) anInt;
497 if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
498 anOrient = anInt->Get();
500 allCurves.Bind(aCurve, anOrient);
506 int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
507 int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
508 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
509 int aFound = 0, aNotFound = 0, aSameOrientation = 0;
511 TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
512 TopExp_Explorer anEdgesExp(aFace, TopAbs_EDGE);
513 TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
514 for(; anEdgesExp.More(); anEdgesExp.Next()) {
515 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
516 if (!anEdge.IsNull()) {
517 Standard_Real aFirst, aLast;
518 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
519 if (alreadyProcessed.Contains(aCurve))
521 alreadyProcessed.Add(aCurve);
522 if (allCurves.IsBound(aCurve)) {
524 int anOrient = allCurves.Find(aCurve);
525 if (anOrient != 0) { // extra comparision score is orientation
526 if (edgeOrientation(aFace, anEdge) == anOrient)
534 if (aFound + aNotFound != 0) {
535 if (aFound > aBestFound ||
536 (aFound == aBestFound && aSameOrientation > aBestOrient)) {
538 aBestOrient = aSameOrientation;
539 aNewSelected = aConstructionContext->face(aFaceIndex);
544 if (aNewSelected) { // store this new selection
545 selectConstruction(aContext, aNewSelected);
546 owner()->data()->sendAttributeUpdated(this);
547 return setInvalidIfFalse(aSelLab, true);
548 } else { // if the selection is not found, put the empty shape: it's better to have disappeared shape, than the old, the lost one
549 TNaming_Builder anEmptyBuilder(selectionLabel());
550 return setInvalidIfFalse(aSelLab, false);
552 } else if (aShapeType == TopAbs_EDGE) {
553 // just reselect the edge by the id
554 const int aSubNum = aComposite->numberOfSubs();
555 for(int a = 0; a < aSubNum; a++) {
556 // if aSubIds take any, the first appropriate
557 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
558 // found the appropriate feature
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() && aRes->shape()->isEdge()) { // found!
566 selectConstruction(aContext, aRes->shape());
567 owner()->data()->sendAttributeUpdated(this);
568 return setInvalidIfFalse(aSelLab, true);
573 } else if (aShapeType == TopAbs_VERTEX) {
574 // just reselect the vertex by the id of edge
575 const int aSubNum = aComposite->numberOfSubs();
576 for(int a = 0; a < aSubNum; a++) {
577 // if aSubIds take any, the first appropriate
578 int aFeatureID = aComposite->subFeatureId(a);
579 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
580 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
581 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
582 // searching for deltas
584 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
585 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
586 // found the feature with appropriate edge
587 FeaturePtr aFeature = aComposite->subFeature(a);
588 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
589 aFeature->results().cbegin();
590 for(;aResIter != aFeature->results().cend(); aResIter++) {
591 ResultConstructionPtr aRes =
592 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
593 if (aRes && aRes->shape()) {
594 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
595 selectConstruction(aContext, aRes->shape());
596 owner()->data()->sendAttributeUpdated(this);
597 return setInvalidIfFalse(aSelLab, true);
598 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
599 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
601 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
602 if (aVIndex == aVertexNum) { // found!
603 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
604 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
605 selectConstruction(aContext, aVertex);
606 owner()->data()->sendAttributeUpdated(this);
607 return setInvalidIfFalse(aSelLab, true);
617 } else { // simple construction element: the selected is that needed
618 selectConstruction(aContext, aContext->shape());
619 owner()->data()->sendAttributeUpdated(this);
620 return setInvalidIfFalse(aSelLab, true);
623 return setInvalidIfFalse(aSelLab, false); // unknown case
627 void Model_AttributeSelection::selectBody(
628 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
630 // perform the selection
631 TNaming_Selector aSel(selectionLabel());
632 TopoDS_Shape aContext;
634 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
636 aContext = aBody->shape()->impl<TopoDS_Shape>();
639 std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
641 aContext = aResult->shape()->impl<TopoDS_Shape>();
643 Events_Error::send("A result with shape is expected");
647 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
648 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
649 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
650 if (aFeatureOwner.get())
651 aFeatureOwner->eraseResults();
652 if (!aContext.IsNull()) {
653 aSel.Select(aNewShape, aContext);
657 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
658 /// if theID is zero,
659 /// theOrientation is additional information about the positioning of edge relatively to face
660 /// it is stored in the integer attribute of the edge sub-label:
661 /// -1 is out, 1 is in, 0 is not needed
662 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
663 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
664 std::string theAdditionalName, std::map<int, int>& theOrientations,
665 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
666 const int theOrientation = 0)
668 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
669 if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
670 TDataStd_Integer::Set(aLab, theOrientation);
672 TNaming_Builder aBuilder(aLab);
673 aBuilder.Generated(theShape);
674 std::stringstream aName;
675 aName<<theContextFeature->name()<<"/";
676 if (!theAdditionalName.empty())
677 aName<<theAdditionalName<<"/";
678 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
679 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
680 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
682 if (theRefs.IsNull()) {
684 if (theOrientation == 1)
686 else if (theOrientation == -1)
688 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
689 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
690 for(; aRef.More(); aRef.Next()) {
691 aName<<"-"<<aRef.Key();
692 if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
693 if (theOrientations[aRef.Key()] == 1)
695 else if (theOrientations[aRef.Key()] == -1)
701 theDoc->addNamingName(aLab, aName.str());
702 TDataStd_Name::Set(aLab, aName.str().c_str());
705 void Model_AttributeSelection::selectConstruction(
706 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
708 std::shared_ptr<Model_Document> aMyDoc =
709 std::dynamic_pointer_cast<Model_Document>(owner()->document());
710 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
711 CompositeFeaturePtr aComposite =
712 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
713 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
714 if (!aComposite || aComposite->numberOfSubs() == 0) {
715 // saving of context is enough: result construction contains exactly the needed shape
716 TNaming_Builder aBuilder(selectionLabel());
717 aBuilder.Generated(aSubShape);
718 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
719 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
722 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
723 TDF_Label aLab = myRef.myRef->Label();
724 // identify the reuslts of sub-object of the composite by edges
725 // save type of the selected shape in integer attribute
726 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
727 TDataStd_Integer::Set(aLab, (int)aShapeType);
729 TColStd_MapOfTransient allCurves;
730 if (aShapeType == TopAbs_VERTEX) { // compare positions
731 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
733 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
734 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
735 Standard_Real aFirst, aLast;
736 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
737 allCurves.Add(aCurve);
740 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
741 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
742 std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
744 const int aSubNum = aComposite->numberOfSubs();
745 for(int a = 0; a < aSubNum; a++) {
746 FeaturePtr aSub = aComposite->subFeature(a);
747 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
748 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
749 // there may be many shapes (circle and center): register if at least one is in selection
750 for(; aRes != aResults.cend(); aRes++) {
751 ResultConstructionPtr aConstr =
752 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
753 if (!aConstr->shape()) {
756 if (aShapeType == TopAbs_VERTEX) {
757 if (aConstr->shape()->isVertex()) { // compare vertices positions
758 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
759 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
760 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
761 aRefs->Add(aComposite->subFeatureId(a));
763 } else { // get first or last vertex of the edge: last is stored with negative sign
764 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
765 int aDelta = kSTART_VERTEX_DELTA;
766 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
767 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
768 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
769 aRefs->Add(aDelta + aComposite->subFeatureId(a));
772 aDelta += kSTART_VERTEX_DELTA;
776 if (aConstr->shape()->isEdge()) {
777 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
778 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
779 if (!anEdge.IsNull()) {
780 Standard_Real aFirst, aLast;
781 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
782 if (allCurves.Contains(aCurve)) {
783 int anID = aComposite->subFeatureId(a);
785 if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
786 // add edges to sub-label to support naming for edges selection
787 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
788 for(; anEdgeExp.More(); anEdgeExp.Next()) {
789 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
790 Standard_Real aFirst, aLast;
791 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
792 if (aFaceCurve == aCurve) {
793 int anOrient = edgeOrientation(aSubShape, anEdge);
794 anOrientations[anID] = anOrient;
796 selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
797 Handle(TDataStd_IntPackedMap)(), anOrient);
800 } else { // put vertices of the selected edge to sub-labels
801 // add edges to sub-label to support naming for edges selection
802 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
803 int aTagIndex = anID + kSTART_VERTEX_DELTA;
804 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
805 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
807 std::stringstream anAdditionalName;
809 selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations);
818 // store the selected as primitive
819 TNaming_Builder aBuilder(selectionLabel());
820 aBuilder.Generated(aSubShape);
822 selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aRefs);
825 bool Model_AttributeSelection::selectPart(
826 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
827 const bool theUpdate)
829 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
830 if (!aPart.get() || !aPart->isActivated())
831 return true; // postponed naming
833 Handle(TDataStd_Integer) anIndex;
834 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
835 if (anIndex->Get() > 0) {
836 // update the selection by index
837 return aPart->updateInPart(anIndex->Get());
839 return true; // nothing to do, referencing just by name
842 return true; // nothing to do, referencing just by name
844 // store the shape (in case part is not loaded it should be usefull
846 std::string aName = theContext->data()->name();
847 if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
848 aShape = theContext->shape()->impl<TopoDS_Shape>();
850 aShape = theSubShape->impl<TopoDS_Shape>();
852 aName += "/" + aPart->nameInPart(theSubShape, anIndex);
853 TDataStd_Integer::Set(selectionLabel(), anIndex);
855 TNaming_Builder aBuilder(selectionLabel());
856 aBuilder.Select(aShape, aShape);
857 // identify by name in the part
858 TDataStd_Name::Set(selectionLabel(), aName.c_str());
859 return !aName.empty();
862 TDF_Label Model_AttributeSelection::selectionLabel()
864 return myRef.myRef->Label().FindChild(1);
867 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
869 std::string aName("");
870 if(!this->isInitialized())
871 return !theDefaultName.empty() ? theDefaultName : aName;
872 Handle(TDataStd_Name) anAtt;
873 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
874 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
878 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
879 ResultPtr aCont = context();
881 Model_SelectionNaming aSelNaming(selectionLabel());
882 return aSelNaming.namingName(aCont, aSubSh, theDefaultName);
885 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
886 void Model_AttributeSelection::selectSubShape(
887 const std::string& theType, const std::string& theSubShapeName)
889 if(theSubShapeName.empty() || theType.empty()) return;
891 // check this is Part-name: 2 delimiters in the name
892 std::size_t aPartEnd = theSubShapeName.find('/');
893 if (aPartEnd != string::npos && aPartEnd != theSubShapeName.rfind('/')) {
894 std::string aPartName = theSubShapeName.substr(0, aPartEnd);
895 ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
896 if (aFound.get()) { // found such part, so asking it for the name
897 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
898 string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
900 std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
901 if (aSelected.get()) {
902 setValue(aPart, aSelected);
903 TDataStd_Integer::Set(selectionLabel(), anIndex);
909 Model_SelectionNaming aSelNaming(selectionLabel());
910 std::shared_ptr<Model_Document> aDoc =
911 std::dynamic_pointer_cast<Model_Document>(owner()->document());
912 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
914 if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
915 setValue(aCont, aShapeToBeSelected);
919 int Model_AttributeSelection::Id()
922 std::shared_ptr<GeomAPI_Shape> aSelection = value();
923 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
924 TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
925 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
926 // searching for the latest main shape
927 if (aSelection && !aSelection->isNull() &&
928 aContext && !aContext->isNull())
930 std::shared_ptr<Model_Document> aDoc =
931 std::dynamic_pointer_cast<Model_Document>(context()->document());
933 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
935 aMainShape = TNaming_Tool::CurrentShape(aNS);
939 TopTools_IndexedMapOfShape aSubShapesMap;
940 TopExp::MapShapes(aMainShape, aSubShapesMap);
941 anID = aSubShapesMap.FindIndex(aSubShape);