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 <GeomAPI_Shape.h>
19 #include <GeomAPI_PlanarEdges.h>
20 #include <Events_Error.h>
22 #include <TNaming_Selector.hxx>
23 #include <TNaming_NamedShape.hxx>
24 #include <TNaming_Tool.hxx>
25 #include <TNaming_Builder.hxx>
26 #include <TNaming_Localizer.hxx>
27 #include <TopoDS_Shape.hxx>
28 #include <TopoDS_Compound.hxx>
29 #include <TDataStd_IntPackedMap.hxx>
30 #include <TDataStd_Integer.hxx>
31 #include <TDataStd_UAttribute.hxx>
32 #include <TDataStd_Name.hxx>
33 #include <TopTools_MapOfShape.hxx>
34 #include <TopTools_IndexedMapOfShape.hxx>
35 #include <TopTools_MapIteratorOfMapOfShape.hxx>
36 #include <TopTools_ListOfShape.hxx>
37 #include <NCollection_DataMap.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <TDF_LabelMap.hxx>
40 #include <BRep_Tool.hxx>
41 #include <BRep_Builder.hxx>
42 #include <TopoDS_Edge.hxx>
45 #include <TColStd_MapOfTransient.hxx>
46 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
47 #include <TopTools_ListIteratorOfListOfShape.hxx>
48 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
50 #include <Precision.hxx>
51 #include <TDF_ChildIterator.hxx>
52 #include <TDF_ChildIDIterator.hxx>
53 #include <TDataStd_Name.hxx>
54 #include <TopAbs_ShapeEnum.hxx>
55 #include <TopoDS_Iterator.hxx>
56 #include <TNaming_Iterator.hxx>
58 //#define DEB_NAMING 1
60 #include <BRepTools.hxx>
62 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
63 /// (multiplied by the index of the edge)
64 static const int kSTART_VERTEX_DELTA = 1000000;
65 // identifier that there is simple reference: selection equals to context
66 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
67 // simple reference in the construction
68 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
69 // reference to Part sub-object
70 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
71 // selection is invalid after recomputation
72 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
74 // on this label is stored:
75 // TNaming_NamedShape - selected shape
76 // TNaming_Naming - topological selection information (for the body)
77 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
78 // TDataStd_Integer - type of the selected shape (for construction)
79 // TDF_Reference - from ReferenceAttribute, the context
80 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
81 const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
83 if (theTemporarily) { // just keep the stored without DF update
84 myTmpContext = theContext;
85 myTmpSubShape = theSubShape;
86 owner()->data()->sendAttributeUpdated(this);
90 myTmpSubShape.reset();
93 const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
94 bool isOldContext = theContext == myRef.value();
95 bool isOldShape = isOldContext &&
96 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
97 if (isOldShape) return; // shape is the same, so context is also unchanged
98 // update the referenced object if needed
100 myRef.setValue(theContext);
102 // do noth use naming if selected shape is result shape itself, but not sub-shape
103 TDF_Label aSelLab = selectionLabel();
104 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
105 aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
106 aSelLab.ForgetAttribute(kINVALID_SELECTION);
108 bool isDegeneratedEdge = false;
109 // do not use the degenerated edge as a shape, a null context and shape is used in the case
110 if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
111 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
112 if (aSubShape.ShapeType() == TopAbs_EDGE)
113 isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
115 if (!theContext.get() || isDegeneratedEdge) {
116 // to keep the reference attribute label
117 TDF_Label aRefLab = myRef.myRef->Label();
118 aSelLab.ForgetAllAttributes(true);
119 myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
122 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
123 // do not select the whole shape for body:it is already must be in the data framework
124 // equal and null selected objects mean the same: object is equal to context,
125 // TODO: synchronize with GUI later that it must be null always
126 if (theContext->shape().get() &&
127 (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
128 aSelLab.ForgetAllAttributes(true);
129 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
131 selectBody(theContext, theSubShape);
133 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
134 if (!theSubShape.get()) {
135 // to sub, so the whole result is selected
136 aSelLab.ForgetAllAttributes(true);
137 TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
138 // For correct naming selection, put the shape into the naming structure.
139 // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
140 TNaming_Builder aBuilder(aSelLab);
141 aBuilder.Generated(theContext->shape()->impl<TopoDS_Shape>());
142 std::shared_ptr<Model_Document> aMyDoc =
143 std::dynamic_pointer_cast<Model_Document>(owner()->document());
144 std::string aName = theContext->data()->name();
145 aMyDoc->addNamingName(aSelLab, aName);
146 TDataStd_Name::Set(aSelLab, aName.c_str());
148 selectConstruction(theContext, theSubShape);
150 } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
151 aSelLab.ForgetAllAttributes(true);
152 TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
153 selectPart(theContext, theSubShape);
155 //the attribute initialized state should be changed by sendAttributeUpdated only
156 //myIsInitialized = true;
158 owner()->data()->sendAttributeUpdated(this);
160 std::string aSelName = namingName();
161 if(!aSelName.empty())
162 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
165 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
167 if (myTmpContext.get() || myTmpSubShape.get()) {
168 return myTmpSubShape;
171 std::shared_ptr<GeomAPI_Shape> aResult;
172 TDF_Label aSelLab = selectionLabel();
173 if (aSelLab.IsAttribute(kINVALID_SELECTION))
176 if (myRef.isInitialized()) {
177 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
178 ResultPtr aContext = context();
180 return aResult; // empty result
181 return aContext->shape();
183 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
184 return aResult; // empty result
186 if (aSelLab.IsAttribute(kPART_REF_ID)) {
187 /* TODO: implement used text here
188 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
189 if (!aPart.get() || !aPart->isActivated())
190 return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
191 Handle(TDataStd_Integer) anIndex;
192 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
193 return aPart->selectionValue(anIndex->Get());
195 Handle(TDataStd_Name) aName;
196 if (!selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
197 return std::shared_ptr<GeomAPI_Shape>(); // something is wrong
199 return aPart->shapeInPart(TCollection_AsciiString(aName).ToCString());
203 Handle(TNaming_NamedShape) aSelection;
204 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
205 TopoDS_Shape aSelShape = aSelection->Get();
206 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
207 aResult->setImpl(new TopoDS_Shape(aSelShape));
208 } else { // for simple construction element: just shape of this construction element
209 ResultConstructionPtr aConstr =
210 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
212 return aConstr->shape();
219 bool Model_AttributeSelection::isInvalid()
221 return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
224 bool Model_AttributeSelection::isInitialized()
226 if (ModelAPI_AttributeSelection::isInitialized()) { // additional checkings if it is initialized
227 std::shared_ptr<GeomAPI_Shape> aResult;
228 if (myRef.isInitialized()) {
229 TDF_Label aSelLab = selectionLabel();
230 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
231 ResultPtr aContext = context();
232 return aContext.get() != NULL;
234 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
238 Handle(TNaming_NamedShape) aSelection;
239 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
240 return !aSelection->Get().IsNull();
241 } else { // for simple construction element: just shape of this construction element
242 ResultConstructionPtr aConstr =
243 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
245 return aConstr->shape().get() != NULL;
253 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
256 myIsInitialized = myRef.isInitialized();
259 void Model_AttributeSelection::setID(const std::string theID)
262 ModelAPI_AttributeSelection::setID(theID);
265 ResultPtr Model_AttributeSelection::context() {
266 if (myTmpContext.get() || myTmpSubShape.get()) {
270 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
271 // for parts there could be same-data result, so take the last enabled
272 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
273 int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
274 for(int a = aSize - 1; a >= 0; a--) {
275 ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
276 if (aPart.get() && aPart->data() == aResult->data()) {
277 ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
278 FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
279 // check that this result is not this-feature result (it is forbidden t oselect itself)
280 if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
290 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
292 ModelAPI_AttributeSelection::setObject(theObject);
293 myRef.setObject(theObject);
296 TDF_LabelMap& Model_AttributeSelection::scope()
298 if (myScope.IsEmpty()) { // create a new scope if not yet done
299 // gets all featueres with named shapes that are bofore this feature label (before in history)
300 DocumentPtr aMyDoc = owner()->document();
301 std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
302 std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
303 bool aMePassed = false;
304 std::shared_ptr<ModelAPI_CompositeFeature> aComposite =
305 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
306 for(; aFIter != allFeatures.end(); aFIter++) {
307 if (*aFIter == owner()) { // the left features are created later (except subs of composite)
311 bool isInScope = !aMePassed;
312 if (!isInScope && aComposite.get()) { // try to add sub-elements of composite if this is composite
313 if (aComposite->isSub(*aFIter))
316 if (aFIter->get() && (*aFIter)->data()->isValid()) {
317 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
318 (*aFIter)->data())->label().Father();
319 TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), 1);
320 for(; aNSIter.More(); aNSIter.Next()) {
321 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
322 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
323 myScope.Add(aNS->Label());
332 /// produces theEdge orientation relatively to theContext face
333 int edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
335 if (theContext.ShapeType() != TopAbs_FACE)
337 TopoDS_Face aContext = TopoDS::Face(theContext);
338 if (theEdge.Orientation() == TopAbs_FORWARD)
340 if (theEdge.Orientation() == TopAbs_REVERSED)
345 /// Sets the invalid flag if flag is false, or removes it if "true"
347 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
349 theLab.ForgetAttribute(kINVALID_SELECTION);
351 TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
356 bool Model_AttributeSelection::update()
358 TDF_Label aSelLab = selectionLabel();
359 ResultPtr aContext = context();
361 return setInvalidIfFalse(aSelLab, false);
362 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
363 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
365 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
366 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
369 if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
370 std::shared_ptr<GeomAPI_Shape> aNoSelection;
371 return setInvalidIfFalse(aSelLab, selectPart(aContext, aNoSelection, true));
374 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
375 // body: just a named shape, use selection mechanism from OCCT
376 TNaming_Selector aSelector(aSelLab);
377 bool aResult = aSelector.Solve(scope()) == Standard_True;
378 owner()->data()->sendAttributeUpdated(this);
379 return setInvalidIfFalse(aSelLab, aResult);
380 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
381 // construction: identification by the results indexes, recompute faces and
382 // take the face that more close by the indexes
383 ResultConstructionPtr aConstructionContext =
384 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
385 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
386 // sketch sub-element
387 if (aConstructionContext &&
388 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
390 TDF_Label aLab = myRef.myRef->Label();
391 // getting a type of selected shape
392 Handle(TDataStd_Integer) aTypeAttr;
393 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
394 return setInvalidIfFalse(aSelLab, false);
396 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
397 // selected indexes will be needed in each "if"
398 Handle(TDataStd_IntPackedMap) aSubIds;
399 std::shared_ptr<GeomAPI_Shape> aNewSelected;
401 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
402 // for now working only with composite features
403 CompositeFeaturePtr aComposite =
404 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
405 if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
406 return setInvalidIfFalse(aSelLab, false);
409 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
410 // If this is a wire with plane defined thin it is a sketch-like object
411 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
412 return setInvalidIfFalse(aSelLab, false);
413 // if there is no edges indexes, any face can be used: take the first
414 std::shared_ptr<GeomAPI_Shape> aNewSelected;
416 aNewSelected = aConstructionContext->face(0);
417 } else { // searching for most looks-like initial face by the indexes
418 // prepare edges of the current resut for the fast searching
419 NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
420 const int aSubNum = aComposite->numberOfSubs();
421 for(int a = 0; a < aSubNum; a++) {
422 int aSubID = aComposite->subFeatureId(a);
423 if (aSubIds->Contains(aSubID)) {
424 FeaturePtr aSub = aComposite->subFeature(a);
425 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
426 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
427 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
428 ResultConstructionPtr aConstr =
429 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
430 if (aConstr->shape() && aConstr->shape()->isEdge()) {
431 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
432 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
433 if (!anEdge.IsNull()) {
434 Standard_Real aFirst, aLast;
435 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
436 // searching for orientation information
438 Handle(TDataStd_Integer) anInt;
439 if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
440 anOrient = anInt->Get();
442 allCurves.Bind(aCurve, anOrient);
448 double aBestFound = 0; // best percentage of found edges
449 int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
450 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
451 int aFound = 0, aNotFound = 0, aSameOrientation = 0;
453 TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
454 TopExp_Explorer anEdgesExp(aFace, TopAbs_EDGE);
455 TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
456 for(; anEdgesExp.More(); anEdgesExp.Next()) {
457 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
458 if (!anEdge.IsNull()) {
459 Standard_Real aFirst, aLast;
460 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
461 if (alreadyProcessed.Contains(aCurve))
463 alreadyProcessed.Add(aCurve);
464 if (allCurves.IsBound(aCurve)) {
466 int anOrient = allCurves.Find(aCurve);
467 if (anOrient != 0) { // extra comparision score is orientation
468 if (edgeOrientation(aFace, anEdge) == anOrient)
476 if (aFound + aNotFound != 0) {
477 double aSum = aFound + aNotFound;
478 // aSameOrientation: if edges are same, take where orientation is better
479 double aPercentage = double(aFound) / double(aFound + aNotFound);
480 if (aPercentage > aBestFound ||
481 (aPercentage == aBestFound && aSameOrientation > aBestOrient)) {
482 aBestFound = aPercentage;
483 aBestOrient = aSameOrientation;
484 aNewSelected = aConstructionContext->face(aFaceIndex);
489 if (aNewSelected) { // store this new selection
490 selectConstruction(aContext, aNewSelected);
491 owner()->data()->sendAttributeUpdated(this);
492 return setInvalidIfFalse(aSelLab, true);
493 } else { // if the selection is not found, put the empty shape: it's better to have disappeared shape, than the old, the lost one
494 TNaming_Builder anEmptyBuilder(selectionLabel());
495 return setInvalidIfFalse(aSelLab, false);
497 } else if (aShapeType == TopAbs_EDGE) {
498 // just reselect the edge by the id
499 const int aSubNum = aComposite->numberOfSubs();
500 for(int a = 0; a < aSubNum; a++) {
501 // if aSubIds take any, the first appropriate
502 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
503 // found the appropriate feature
504 FeaturePtr aFeature = aComposite->subFeature(a);
505 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
506 aFeature->results().cbegin();
507 for(;aResIter != aFeature->results().cend(); aResIter++) {
508 ResultConstructionPtr aRes =
509 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
510 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
511 selectConstruction(aContext, aRes->shape());
512 owner()->data()->sendAttributeUpdated(this);
513 return setInvalidIfFalse(aSelLab, true);
518 } else if (aShapeType == TopAbs_VERTEX) {
519 // just reselect the vertex by the id of edge
520 const int aSubNum = aComposite->numberOfSubs();
521 for(int a = 0; a < aSubNum; a++) {
522 // if aSubIds take any, the first appropriate
523 int aFeatureID = aComposite->subFeatureId(a);
524 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
525 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
526 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
527 // searching for deltas
529 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
530 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
531 // found the feature with appropriate edge
532 FeaturePtr aFeature = aComposite->subFeature(a);
533 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
534 aFeature->results().cbegin();
535 for(;aResIter != aFeature->results().cend(); aResIter++) {
536 ResultConstructionPtr aRes =
537 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
538 if (aRes && aRes->shape()) {
539 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
540 selectConstruction(aContext, aRes->shape());
541 owner()->data()->sendAttributeUpdated(this);
542 return setInvalidIfFalse(aSelLab, true);
543 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
544 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
546 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
547 if (aVIndex == aVertexNum) { // found!
548 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
549 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
550 selectConstruction(aContext, aVertex);
551 owner()->data()->sendAttributeUpdated(this);
552 return setInvalidIfFalse(aSelLab, true);
562 } else { // simple construction element: the selected is that needed
563 selectConstruction(aContext, aContext->shape());
564 owner()->data()->sendAttributeUpdated(this);
565 return setInvalidIfFalse(aSelLab, true);
568 return setInvalidIfFalse(aSelLab, false); // unknown case
572 void Model_AttributeSelection::selectBody(
573 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
575 // perform the selection
576 TNaming_Selector aSel(selectionLabel());
577 TopoDS_Shape aContext;
579 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
581 aContext = aBody->shape()->impl<TopoDS_Shape>();
584 std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
586 aContext = aResult->shape()->impl<TopoDS_Shape>();
588 Events_Error::send("A result with shape is expected");
592 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
593 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
595 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
596 if (aFeatureOwner.get())
597 aFeatureOwner->eraseResults();
599 if (!aContext.IsNull()) {
600 aSel.Select(aNewShape, aContext);
604 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
605 /// if theID is zero,
606 /// theOrientation is additional information about the positioning of edge relatively to face
607 /// it is stored in the integer attribute of the edge sub-label:
608 /// -1 is out, 1 is in, 0 is not needed
609 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
610 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
611 std::string theAdditionalName, std::map<int, int>& theOrientations,
612 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
613 const int theOrientation = 0)
615 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
616 if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
617 TDataStd_Integer::Set(aLab, theOrientation);
619 TNaming_Builder aBuilder(aLab);
620 aBuilder.Generated(theShape);
621 std::stringstream aName;
622 aName<<theContextFeature->name()<<"/";
623 if (!theAdditionalName.empty())
624 aName<<theAdditionalName<<"/";
625 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
626 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
627 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
629 if (theRefs.IsNull()) {
631 if (theOrientation == 1)
633 else if (theOrientation == -1)
635 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
636 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
637 for(; aRef.More(); aRef.Next()) {
638 aName<<"-"<<aRef.Key();
639 if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
640 if (theOrientations[aRef.Key()] == 1)
642 else if (theOrientations[aRef.Key()] == -1)
648 theDoc->addNamingName(aLab, aName.str());
649 TDataStd_Name::Set(aLab, aName.str().c_str());
652 void Model_AttributeSelection::selectConstruction(
653 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
655 std::shared_ptr<Model_Document> aMyDoc =
656 std::dynamic_pointer_cast<Model_Document>(owner()->document());
657 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
658 CompositeFeaturePtr aComposite =
659 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
660 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
661 if (!aComposite || aComposite->numberOfSubs() == 0) {
662 // saving of context is enough: result construction contains exactly the needed shape
663 TNaming_Builder aBuilder(selectionLabel());
664 aBuilder.Generated(aSubShape);
665 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
666 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
669 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
670 TDF_Label aLab = myRef.myRef->Label();
671 // identify the reuslts of sub-object of the composite by edges
672 // save type of the selected shape in integer attribute
673 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
674 TDataStd_Integer::Set(aLab, (int)aShapeType);
676 TColStd_MapOfTransient allCurves;
677 if (aShapeType == TopAbs_VERTEX) { // compare positions
678 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
680 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
681 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
682 Standard_Real aFirst, aLast;
683 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
684 allCurves.Add(aCurve);
687 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
688 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
689 std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
691 const int aSubNum = aComposite->numberOfSubs();
692 for(int a = 0; a < aSubNum; a++) {
693 FeaturePtr aSub = aComposite->subFeature(a);
694 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
695 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
696 // there may be many shapes (circle and center): register if at least one is in selection
697 for(; aRes != aResults.cend(); aRes++) {
698 ResultConstructionPtr aConstr =
699 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
700 if (!aConstr->shape()) {
703 if (aShapeType == TopAbs_VERTEX) {
704 if (aConstr->shape()->isVertex()) { // compare vertices positions
705 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
706 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
707 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
708 aRefs->Add(aComposite->subFeatureId(a));
710 } else { // get first or last vertex of the edge: last is stored with negative sign
711 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
712 int aDelta = kSTART_VERTEX_DELTA;
713 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
714 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
715 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
716 aRefs->Add(aDelta + aComposite->subFeatureId(a));
719 aDelta += kSTART_VERTEX_DELTA;
723 if (aConstr->shape()->isEdge()) {
724 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
725 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
726 if (!anEdge.IsNull()) {
727 Standard_Real aFirst, aLast;
728 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
729 if (allCurves.Contains(aCurve)) {
730 int anID = aComposite->subFeatureId(a);
732 if (aShapeType != TopAbs_EDGE) { // face nneds the sub-edges on sub-labels
733 // add edges to sub-label to support naming for edges selection
734 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
735 for(; anEdgeExp.More(); anEdgeExp.Next()) {
736 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
737 Standard_Real aFirst, aLast;
738 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
739 if (aFaceCurve == aCurve) {
740 int anOrient = edgeOrientation(aSubShape, anEdge);
741 anOrientations[anID] = anOrient;
743 selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
744 Handle(TDataStd_IntPackedMap)(), anOrient);
747 } else { // put vertices of the selected edge to sub-labels
748 // add edges to sub-label to support naming for edges selection
749 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
750 int aTagIndex = anID + kSTART_VERTEX_DELTA;
751 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
752 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
754 std::stringstream anAdditionalName;
756 selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations);
765 // store the selected as primitive
766 TNaming_Builder aBuilder(selectionLabel());
767 aBuilder.Generated(aSubShape);
769 selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aRefs);
772 bool Model_AttributeSelection::selectPart(
773 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
774 const bool theUpdate)
776 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
777 if (!aPart.get() || !aPart->isActivated())
778 return true; // postponed naming
780 Handle(TDataStd_Integer) anIndex;
781 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
782 if (anIndex->Get() > 0) {
783 // update the selection by index
784 return aPart->updateInPart(anIndex->Get());
786 return true; // nothing to do, referencing just by name
789 return true; // nothing to do, referencing just by name
791 // store the shape (in case part is not loaded it should be usefull
793 std::string aName = theContext->data()->name();
794 if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
795 aShape = theContext->shape()->impl<TopoDS_Shape>();
797 aShape = theSubShape->impl<TopoDS_Shape>();
799 aName += "/" + aPart->nameInPart(theSubShape, anIndex);
800 TDataStd_Integer::Set(selectionLabel(), anIndex);
802 TNaming_Builder aBuilder(selectionLabel());
803 aBuilder.Select(aShape, aShape);
804 // identify by name in the part
805 TDataStd_Name::Set(selectionLabel(), aName.c_str());
806 return !aName.empty();
809 TDF_Label Model_AttributeSelection::selectionLabel()
811 return myRef.myRef->Label().FindChild(1);
814 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
816 std::string aName("");
817 if(!this->isInitialized())
818 return !theDefaultName.empty() ? theDefaultName : aName;
819 Handle(TDataStd_Name) anAtt;
820 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
821 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
825 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
826 ResultPtr aCont = context();
828 Model_SelectionNaming aSelNaming(selectionLabel());
829 return aSelNaming.namingName(aCont, aSubSh, theDefaultName);
832 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
833 void Model_AttributeSelection::selectSubShape(
834 const std::string& theType, const std::string& theSubShapeName)
836 if(theSubShapeName.empty() || theType.empty()) return;
838 Model_SelectionNaming aSelNaming(selectionLabel());
839 std::shared_ptr<Model_Document> aDoc =
840 std::dynamic_pointer_cast<Model_Document>(owner()->document());
841 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
843 if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
844 setValue(aCont, aShapeToBeSelected);
848 int Model_AttributeSelection::Id()
850 std::shared_ptr<GeomAPI_Shape> aSelection = value();
851 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
852 const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
853 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
855 if (aSelection && !aSelection->isNull() &&
856 aContext && !aContext->isNull())
858 TopTools_IndexedMapOfShape aSubShapesMap;
859 TopExp::MapShapes(aMainShape, aSubShapesMap);
860 anID = aSubShapesMap.FindIndex(aSubShape);