1 // Copyright (C) 2014-2017 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
21 #include "Model_AttributeSelection.h"
22 #include "Model_Application.h"
23 #include "Model_Events.h"
24 #include "Model_Data.h"
25 #include "Model_Document.h"
26 #include "Model_SelectionNaming.h"
27 #include <Model_Objects.h>
28 #include <Model_AttributeSelectionList.h>
29 #include <Model_ResultConstruction.h>
30 #include <ModelAPI_Feature.h>
31 #include <ModelAPI_ResultBody.h>
32 #include <ModelAPI_ResultBody.h>
33 #include <ModelAPI_ResultConstruction.h>
34 #include <ModelAPI_ResultPart.h>
35 #include <ModelAPI_CompositeFeature.h>
36 #include <ModelAPI_Tools.h>
37 #include <ModelAPI_Session.h>
38 #include <ModelAPI_Validator.h>
39 #include <Events_InfoMessage.h>
40 #include <GeomAPI_Edge.h>
41 #include <GeomAPI_Pnt.h>
42 #include <GeomAPI_Vertex.h>
43 #include <GeomAlgoAPI_CompoundBuilder.h>
45 #include <TNaming_Selector.hxx>
46 #include <TNaming_NamedShape.hxx>
47 #include <TNaming_Tool.hxx>
48 #include <TNaming_Builder.hxx>
49 #include <TNaming_SameShapeIterator.hxx>
50 #include <TNaming_Iterator.hxx>
51 #include <TDataStd_Integer.hxx>
52 #include <TDataStd_UAttribute.hxx>
53 #include <TDataStd_Name.hxx>
54 #include <TopTools_ListOfShape.hxx>
55 #include <TopTools_DataMapOfShapeShape.hxx>
56 #include <TopTools_MapOfShape.hxx>
57 #include <TopExp_Explorer.hxx>
58 #include <BRep_Tool.hxx>
61 #include <TDF_ChildIterator.hxx>
62 #include <TDF_ChildIDIterator.hxx>
63 #include <TopoDS_Iterator.hxx>
64 #include <TDF_ChildIDIterator.hxx>
65 #include <Geom_Circle.hxx>
66 #include <Geom_Ellipse.hxx>
67 #include <BRep_Builder.hxx>
69 //#define DEB_NAMING 1
71 #include <BRepTools.hxx>
73 /// added to the index in the packed map to signalize that the vertex of edge is selected
74 /// (multiplied by the index of the edge)
75 static const int kSTART_VERTEX_DELTA = 1000000;
76 // identifier that there is simple reference: selection equals to context
77 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
78 // reference to Part sub-object
79 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
80 // selection is invalid after recomputation
81 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
83 // identifier of the selection of the center of circle on edge
84 Standard_GUID kCIRCLE_CENTER("d0d0e0f1-217a-4b95-8fbb-0c4132f23718");
85 // identifier of the selection of the first focus point of ellipse on edge
86 Standard_GUID kELLIPSE_CENTER1("f70df04c-3168-4dc9-87a4-f1f840c1275d");
87 // identifier of the selection of the second focus point of ellipse on edge
88 Standard_GUID kELLIPSE_CENTER2("1395ae73-8e02-4cf8-b204-06ff35873a32");
90 // prefix for the whole feature context identification
91 const static std::string kWHOLE_FEATURE = "all-in-";
93 // on this label is stored:
94 // TNaming_NamedShape - selected shape
95 // TNaming_Naming - topological selection information (for the body)
96 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
97 // TDataStd_Integer - type of the selected shape (for construction)
98 // TDF_Reference - from ReferenceAttribute, the context
99 bool Model_AttributeSelection::setValue(const ObjectPtr& theContext,
100 const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
102 if (theTemporarily &&
103 (!theContext.get() || theContext->groupName() != ModelAPI_Feature::group())) {
104 // just keep the stored without DF update
105 myTmpContext = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
106 myTmpSubShape = theSubShape;
107 owner()->data()->sendAttributeUpdated(this);
110 myTmpContext.reset();
111 myTmpSubShape.reset();
112 myTmpCenterType = NOT_CENTER;
116 const std::shared_ptr<GeomAPI_Shape>& anOldShape = internalValue(aType);
117 bool isOldContext = theContext == myRef.value();
118 bool isOldShape = isOldContext &&
119 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
120 if (isOldShape) return false; // shape is the same, so context is also unchanged
121 bool aToUnblock = false;
122 // update the referenced object if needed
124 aToUnblock = !owner()->data()->blockSendAttributeUpdated(true);
125 myRef.setValue(theContext);
128 // do noth use naming if selected shape is result shape itself, but not sub-shape
129 TDF_Label aSelLab = selectionLabel();
130 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
131 aSelLab.ForgetAttribute(kINVALID_SELECTION);
132 aSelLab.ForgetAttribute(kCIRCLE_CENTER);
133 aSelLab.ForgetAttribute(kELLIPSE_CENTER1);
134 aSelLab.ForgetAttribute(kELLIPSE_CENTER2);
136 bool isDegeneratedEdge = false;
137 // do not use the degenerated edge as a shape, a null context and shape is used in the case
138 if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
139 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
140 if (aSubShape.ShapeType() == TopAbs_EDGE)
141 isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
143 if (!theContext.get() || isDegeneratedEdge) {
144 // to keep the reference attribute label
145 TDF_Label aRefLab = myRef.myRef->Label();
146 aSelLab.ForgetAllAttributes(true);
147 myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
149 owner()->data()->blockSendAttributeUpdated(false);
152 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
153 ResultBodyPtr aContextBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);
154 // do not select the whole shape for body:it is already must be in the data framework
155 // equal and null selected objects mean the same: object is equal to context,
156 if (aContextBody->shape().get() &&
157 (aContextBody->shape()->isEqual(theSubShape) || !theSubShape.get())) {
158 aSelLab.ForgetAllAttributes(true);
159 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
161 selectBody(aContextBody, theSubShape);
163 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
164 ResultConstructionPtr aContextConstruction =
165 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
166 aSelLab.ForgetAllAttributes(true); // to remove old selection data
167 std::shared_ptr<Model_ResultConstruction> aConstruction =
168 std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
169 std::shared_ptr<GeomAPI_Shape> aSubShape;
170 if (theSubShape.get() && !aContextConstruction->shape()->isEqual(theSubShape))
171 aSubShape = theSubShape; // the whole context
172 if (aConstruction->isInfinite()) {
173 // For correct naming selection, put the shape into the naming structure.
174 // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
175 TNaming_Builder aBuilder(aSelLab);
176 aBuilder.Generated(aContextConstruction->shape()->impl<TopoDS_Shape>());
178 int anIndex = aConstruction->select(theSubShape, owner()->document());
179 TDataStd_Integer::Set(aSelLab, anIndex);
180 } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
181 aSelLab.ForgetAllAttributes(true);
182 TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
183 selectPart(std::dynamic_pointer_cast<ModelAPI_Result>(theContext), theSubShape);
184 } else { // check the feature context: parent-Part of this feature should not be used
185 FeaturePtr aFeatureContext = std::dynamic_pointer_cast<ModelAPI_Feature>(theContext);
186 if (aFeatureContext.get()) {
187 if (owner()->document() != aFeatureContext->document()) {
188 aSelLab.ForgetAllAttributes(true);
189 myRef.setValue(ObjectPtr());
191 owner()->data()->blockSendAttributeUpdated(false);
197 owner()->data()->sendAttributeUpdated(this);
200 owner()->data()->blockSendAttributeUpdated(false);
205 void Model_AttributeSelection::setValueCenter(
206 const ObjectPtr& theContext, const std::shared_ptr<GeomAPI_Edge>& theEdge,
207 const CenterType theCenterType, const bool theTemporarily)
209 bool anUpdated = setValue(theContext, theEdge, theTemporarily);
210 if (theTemporarily) {
211 myTmpCenterType = theCenterType;
212 } else { // store in the data structure
213 TDF_Label aSelLab = selectionLabel();
214 switch(theCenterType) {
217 anUpdated = !aSelLab.IsAttribute(kCIRCLE_CENTER);
218 TDataStd_UAttribute::Set(aSelLab, kCIRCLE_CENTER);
220 case ELLIPSE_FIRST_FOCUS:
222 anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER1);
223 TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER1);
225 case ELLIPSE_SECOND_FOCUS:
227 anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER2);
228 TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER2);
232 owner()->data()->sendAttributeUpdated(this);
236 void Model_AttributeSelection::selectValue(
237 const std::shared_ptr<ModelAPI_AttributeSelection>& theSource)
240 std::shared_ptr<GeomAPI_Shape> aValue =
241 std::dynamic_pointer_cast<Model_AttributeSelection>(theSource)->internalValue(aType);
242 if (!aValue.get() || aType == NOT_CENTER) {
243 setValue(theSource->context(), aValue);
245 std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge);
246 anEdge->setImpl(new TopoDS_Shape(aValue->impl<TopoDS_Shape>()));
247 setValueCenter(theSource->context(), anEdge, aType);
251 void Model_AttributeSelection::removeTemporaryValues()
253 if (myTmpContext.get() || myTmpSubShape.get()) {
254 myTmpContext.reset();
255 myTmpSubShape.reset();
259 // returns the center of the edge: circular or elliptical
260 GeomShapePtr centerByEdge(GeomShapePtr theEdge, ModelAPI_AttributeSelection::CenterType theType)
262 if (theType != ModelAPI_AttributeSelection::NOT_CENTER && theEdge.get() != NULL) {
263 TopoDS_Shape aShape = theEdge->impl<TopoDS_Shape>();
264 if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_EDGE) {
265 TopoDS_Edge anEdge = TopoDS::Edge(aShape);
266 double aFirst, aLast;
267 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
268 if (!aCurve.IsNull()) {
269 TopoDS_Vertex aVertex;
270 BRep_Builder aBuilder;
271 if (theType == ModelAPI_AttributeSelection::CIRCLE_CENTER) {
272 Handle(Geom_Circle) aCirc = Handle(Geom_Circle)::DownCast(aCurve);
273 if (!aCirc.IsNull()) {
274 aBuilder.MakeVertex(aVertex, aCirc->Location(), Precision::Confusion());
277 Handle(Geom_Ellipse) anEll = Handle(Geom_Ellipse)::DownCast(aCurve);
278 if (!anEll.IsNull()) {
279 aBuilder.MakeVertex(aVertex,
280 theType == ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS ?
281 anEll->Focus1() : anEll->Focus2(), Precision::Confusion());
284 if (!aVertex.IsNull()) {
285 std::shared_ptr<GeomAPI_Vertex> aResult(new GeomAPI_Vertex);
286 aResult->setImpl(new TopoDS_Vertex(aVertex));
292 return theEdge; // no vertex, so, return the initial edge
295 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
297 if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
298 return std::shared_ptr<GeomAPI_Shape>();
299 CenterType aType = NOT_CENTER;
300 std::shared_ptr<GeomAPI_Shape> aResult = internalValue(aType);
301 return centerByEdge(aResult, aType);
304 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::internalValue(CenterType& theType)
306 theType = NOT_CENTER;
307 GeomShapePtr aResult;
308 if (myTmpContext.get() || myTmpSubShape.get()) {
309 theType = myTmpCenterType;
310 ResultConstructionPtr aResulConstruction =
311 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
312 if(aResulConstruction.get()) {
313 // it is just reference to construction.
314 return myTmpSubShape;
316 return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
319 TDF_Label aSelLab = selectionLabel();
320 if (aSelLab.IsAttribute(kINVALID_SELECTION))
323 if (aSelLab.IsAttribute(kCIRCLE_CENTER))
324 theType = CIRCLE_CENTER;
325 else if (aSelLab.IsAttribute(kELLIPSE_CENTER1))
326 theType = ELLIPSE_FIRST_FOCUS;
327 else if (aSelLab.IsAttribute(kELLIPSE_CENTER2))
328 theType = ELLIPSE_SECOND_FOCUS;
331 if (myRef.isInitialized()) {
332 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
333 ResultPtr aContext = context();
335 return aResult; // empty result
336 return aContext->shape();
338 if (aSelLab.IsAttribute(kPART_REF_ID)) {
339 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
340 if (!aPart.get() || !aPart->isActivated())
341 return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
342 Handle(TDataStd_Integer) anIndex;
343 if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
344 if (anIndex->Get()) { // special selection attribute was created, use it
345 return aPart->selectionValue(anIndex->Get());
346 } else { // face with name is already in the data model, so try to take it by name
347 Handle(TDataStd_Name) aName;
348 if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
349 std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
350 std::size_t aPartEnd = aSubShapeName.find('/');
351 if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
352 std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
354 std::string aType; // to reuse already existing selection the type is not needed
355 return aPart->shapeInPart(aNameInPart, aType, anIndex);
362 std::shared_ptr<Model_ResultConstruction> aConstr =
363 std::dynamic_pointer_cast<Model_ResultConstruction>(context());
365 if (aConstr->isInfinite())
366 return aResult; // empty result
368 if (!aConstr.get()) { // for construction context, return empty result as usual even
369 // the whole feature is selected
370 FeaturePtr aFeature = contextFeature();
371 if (aFeature.get()) {
372 std::list<GeomShapePtr> allShapes;
373 std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
374 for (; aRes != aFeature->results().cend(); aRes++) {
375 if (aRes->get() && !(*aRes)->isDisabled()) {
376 GeomShapePtr aShape = (*aRes)->shape();
377 if (aShape.get() && !aShape->isNull()) {
378 allShapes.push_back(aShape);
382 return GeomAlgoAPI_CompoundBuilder::compound(allShapes);
386 Handle(TNaming_NamedShape) aSelection;
387 if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
388 TopoDS_Shape aSelShape = aSelection->Get();
389 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
390 aResult->setImpl(new TopoDS_Shape(aSelShape));
391 } else if (aConstr) { // simple construction element: just shape of this construction element
392 Handle(TDataStd_Integer) anIndex;
393 if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
394 if (anIndex->Get() == 0) // it is just reference to construction, nothing is in value
396 return aConstr->shape(anIndex->Get(), owner()->document());
403 bool Model_AttributeSelection::isInvalid()
405 return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
408 bool Model_AttributeSelection::isInitialized()
410 if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
411 std::shared_ptr<GeomAPI_Shape> aResult;
412 if (myRef.isInitialized()) {
413 TDF_Label aSelLab = selectionLabel();
414 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
415 ResultPtr aContext = context();
416 return aContext.get() != NULL;
418 Handle(TNaming_NamedShape) aSelection;
419 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
420 return !aSelection->Get().IsNull();
421 } else { // for simple construction element: just shape of this construction element
422 std::shared_ptr<Model_ResultConstruction> aConstr =
423 std::dynamic_pointer_cast<Model_ResultConstruction>(context());
425 Handle(TDataStd_Integer) anIndex;
426 if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
427 // for the whole shape it may return null, so, if index exists, returns true
431 // for the whole feature, a feature object
432 FeaturePtr aFeat = contextFeature();
441 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
444 myIsInitialized = myRef.isInitialized();
448 void Model_AttributeSelection::setID(const std::string theID)
451 ModelAPI_AttributeSelection::setID(theID);
454 ResultPtr Model_AttributeSelection::context()
456 if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
459 if (myTmpContext.get() || myTmpSubShape.get()) {
463 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
464 // for parts there could be same-data result, so take the last enabled
466 if(aResult->groupName() == ModelAPI_ResultPart::group()) {
467 int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
468 for(int a = aSize - 1; a >= 0; a--) {
469 ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
470 if(aPart.get() && aPart->data() == aResult->data()) {
471 ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
472 FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
473 // check that this result is not this-feature result (it is forbidden t oselect itself)
474 if(anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
480 } else { // if feature - construction is selected, it has only one result, return this result
481 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
482 if (aFeature.get() && aFeature->results().size() == 1 &&
483 aFeature->firstResult()->groupName() == ModelAPI_ResultConstruction::group())
484 return aFeature->firstResult();
489 FeaturePtr Model_AttributeSelection::contextFeature() {
490 if (myTmpContext.get() || myTmpSubShape.get()) {
491 return FeaturePtr(); // feature can not be selected temporarily
493 return std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
495 ObjectPtr Model_AttributeSelection::contextObject() {
496 FeaturePtr aRes = contextFeature();
503 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
505 ModelAPI_AttributeSelection::setObject(theObject);
506 myRef.setObject(theObject);
509 TDF_LabelMap& Model_AttributeSelection::scope()
511 if (myScope.IsEmpty()) { // create a new scope if not yet done
512 // gets all features with named shapes that are before this feature label (before in history)
513 DocumentPtr aMyDoc = owner()->document();
514 std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
515 std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
516 bool aMePassed = false;
517 CompositeFeaturePtr aComposite =
518 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
519 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
520 CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
521 if (aFeature.get()) {
522 aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
523 if (aCompositeOwner.get()) {
524 aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
527 // for group Scope is not limitet: this is always up to date objects
528 // this causes problem in galeries.py
529 //bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
530 for(; aFIter != allFeatures.end(); aFIter++) {
531 if (*aFIter == owner()) { // the left features are created later (except subs of composite)
535 //if (isGroup) aMePassed = false;
536 bool isInScope = !aMePassed;
537 if (!isInScope && aComposite.get()) {
538 // try to add sub-elements of composite if this is composite
539 if (aComposite->isSub(*aFIter))
542 // remove the composite-owner of this feature (sketch in extrusion-cut)
543 if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
546 if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
547 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
548 (*aFIter)->data())->label().Father();
549 TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), true);
550 for(; aNSIter.More(); aNSIter.Next()) {
551 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
552 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
553 myScope.Add(aNS->Label());
558 // also add all naming labels created for external constructions
559 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aMyDoc);
560 TDF_Label anExtDocLab = aDoc->extConstructionsLabel();
561 TDF_ChildIDIterator aNSIter(anExtDocLab, TNaming_NamedShape::GetID(), true);
562 for(; aNSIter.More(); aNSIter.Next()) {
563 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
564 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
565 myScope.Add(aNS->Label());
572 /// Sets the invalid flag if flag is false, or removes it if "true"
574 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
576 theLab.ForgetAttribute(kINVALID_SELECTION);
578 TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
583 void Model_AttributeSelection::split(
584 ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
586 TopTools_ListOfShape aSubs;
587 for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
588 if (!anExplorer.Value().IsNull() &&
589 anExplorer.Value().ShapeType() == theType) {
590 aSubs.Append(anExplorer.Value());
591 } else { // invalid case; bad result shape, so, impossible to split easily
596 if (aSubs.Extent() > 1) { // ok to split
597 TopTools_ListIteratorOfListOfShape aSub(aSubs);
598 GeomShapePtr aSubSh(new GeomAPI_Shape);
599 aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
600 setValue(theContext, aSubSh);
601 for(aSub.Next(); aSub.More(); aSub.Next()) {
602 GeomShapePtr aSubSh(new GeomAPI_Shape);
603 aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
604 myParent->append(theContext, aSubSh);
609 bool Model_AttributeSelection::update()
611 FeaturePtr aContextFeature = contextFeature();
612 if (aContextFeature.get()) {
615 TDF_Label aSelLab = selectionLabel();
616 ResultPtr aContext = context();
618 return setInvalidIfFalse(aSelLab, false);
619 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
620 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
623 if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
624 std::shared_ptr<GeomAPI_Shape> aNoSelection;
625 bool aResult = selectPart(aContext, aNoSelection, true);
626 aResult = setInvalidIfFalse(aSelLab, aResult);
628 owner()->data()->sendAttributeUpdated(this);
633 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
634 // body: just a named shape, use selection mechanism from OCCT
635 TNaming_Selector aSelector(aSelLab);
636 TopoDS_Shape anOldShape;
637 if (!aSelector.NamedShape().IsNull()) {
638 anOldShape = aSelector.NamedShape()->Get();
640 bool aResult = aSelector.Solve(scope()) == Standard_True;
641 // must be before sending of updated attribute (1556)
642 aResult = setInvalidIfFalse(aSelLab, aResult);
643 TopoDS_Shape aNewShape;
644 if (!aSelector.NamedShape().IsNull()) {
645 aNewShape = aSelector.NamedShape()->Get();
647 if (anOldShape.IsNull() || aNewShape.IsNull() ||
648 !anOldShape.IsEqual(aSelector.NamedShape()->Get())) {
649 // shape type shoud not not changed: if shape becomes compound of such shapes, then split
650 if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
651 anOldShape.ShapeType() != aNewShape.ShapeType() &&
652 (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID))
654 split(aContext, aNewShape, anOldShape.ShapeType());
656 owner()->data()->sendAttributeUpdated(this); // send updated if shape is changed
661 if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
662 Handle(TDataStd_Integer) anIndex;
663 if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
664 std::shared_ptr<Model_ResultConstruction> aConstructionContext =
665 std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
666 bool aModified = true;
667 bool aValid = aConstructionContext->update(anIndex->Get(), owner()->document(), aModified);
668 setInvalidIfFalse(aSelLab, aValid);
669 if (aConstructionContext->isInfinite()) {
670 // Update the selected shape.
671 TNaming_Builder aBuilder(aSelLab);
672 aBuilder.Generated(aConstructionContext->shape()->impl<TopoDS_Shape>());
675 owner()->data()->sendAttributeUpdated(this);
679 return setInvalidIfFalse(aSelLab, false); // unknown case
682 void Model_AttributeSelection::selectBody(
683 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
685 // perform the selection
686 TNaming_Selector aSel(selectionLabel());
687 TopoDS_Shape aContext;
689 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);//myRef.value()
691 aContext = aBody->shape()->impl<TopoDS_Shape>();
694 std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
696 aContext = aResult->shape()->impl<TopoDS_Shape>();
698 Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
703 // with "recover" feature the selected context may be not up to date (issue 1710)
704 Handle(TNaming_NamedShape) aResult;
705 TDF_Label aSelLab = selectionLabel();
706 TopoDS_Shape aNewContext = aContext;
707 bool isUpdated = true;
708 while(!aNewContext.IsNull() && isUpdated) {
709 // searching for the very last shape that was produced from this one
711 if (!TNaming_Tool::HasLabel(aSelLab, aNewContext))
712 // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
714 for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
715 TDF_Label aNSLab = anIter.Label();
716 if (!scope().Contains(aNSLab))
718 Handle(TNaming_NamedShape) aNS;
719 if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
720 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
721 if (aShapesIter.Evolution() == TNaming_SELECTED)
722 continue; // don't use the selection evolution
723 if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
724 // found the original shape
725 aNewContext = aShapesIter.NewShape(); // go to the newer shape
733 if (aNewContext.IsNull()) { // a context is already deleted
734 setInvalidIfFalse(aSelLab, false);
735 Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
739 TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
740 if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
741 bool isFound = false;
742 TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
743 for(; anExp.More(); anExp.Next()) {
744 if (anExp.Current().IsSame(aNewSub)) {
749 if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
750 // if context is sub-result of compound/compsolid, selection of sub-shape better propagate to
751 // the main result (which is may be modified); the case is in 1799
752 ResultBodyPtr aMain = ModelAPI_Tools::bodyOwner(theContext);
753 while(ModelAPI_Tools::bodyOwner(aMain).get())
754 aMain = ModelAPI_Tools::bodyOwner(theContext);
756 selectBody(aMain, theSubShape);
759 setInvalidIfFalse(aSelLab, false);
760 Events_InfoMessage("Model_AttributeSelection",
761 "Failed to select sub-shape already modified").send();
766 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
767 if (!aContext.IsNull()) {
768 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
769 bool aEraseResults = false;
770 if (aFeatureOwner.get()) {
771 aEraseResults = !aFeatureOwner->results().empty();
772 if (aEraseResults) // erase results without flash deleted and redisplay: do it after Select
773 aFeatureOwner->removeResults(0, false, false);
775 aSel.Select(aNewSub, aNewContext);
777 if (aEraseResults) { // flash after Select : in Groups it makes selection with shift working
778 static Events_Loop* aLoop = Events_Loop::loop();
779 static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
780 aLoop->flush(kDeletedEvent);
785 bool Model_AttributeSelection::selectPart(
786 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
787 const bool theUpdate)
789 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
790 if (!aPart.get() || !aPart->isActivated())
791 return true; // postponed naming
793 Handle(TDataStd_Integer) anIndex;
794 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
795 // by internal selection
796 if (anIndex->Get() > 0) {
797 // update the selection by index
798 return aPart->updateInPart(anIndex->Get());
800 return true; // nothing to do, referencing just by name
803 return true; // nothing to do, referencing just by name
805 // store the shape (in case part is not loaded it should be useful
807 std::string aName = theContext->data()->name();
808 if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
809 aShape = theContext->shape()->impl<TopoDS_Shape>();
811 aShape = theSubShape->impl<TopoDS_Shape>();
813 aName += "/" + aPart->nameInPart(theSubShape, anIndex);
814 TDataStd_Integer::Set(selectionLabel(), anIndex);
816 TNaming_Builder aBuilder(selectionLabel());
817 aBuilder.Select(aShape, aShape);
818 // identify by name in the part
819 TDataStd_Name::Set(selectionLabel(), aName.c_str());
820 return !aName.empty();
823 TDF_Label Model_AttributeSelection::selectionLabel()
825 return myRef.myRef->Label().FindChild(1);
828 /// prefixes of the shape names with centers defined
829 static std::map<ModelAPI_AttributeSelection::CenterType, std::string> kCENTERS_PREFIX;
831 /// returns the map that contains all possible prefixes of the center-names
832 static std::map<ModelAPI_AttributeSelection::CenterType, std::string>& centersMap()
834 if (kCENTERS_PREFIX.empty()) { // fill map by initial values
835 kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = "__cc";
836 kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = "__eff";
837 kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = "__esf";
839 return kCENTERS_PREFIX;
842 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
844 std::string aName("");
845 if(!this->isInitialized())
846 return !theDefaultName.empty() ? theDefaultName : aName;
848 CenterType aCenterType = NOT_CENTER;
849 std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
850 ResultPtr aCont = context();
853 (aCont->groupName() == ModelAPI_ResultConstruction::group() && contextFeature().get())) {
854 // selection of a full feature
855 FeaturePtr aFeatureCont = contextFeature();
856 if (aFeatureCont.get()) {
857 return kWHOLE_FEATURE + aFeatureCont->name();
859 // in case of selection of removed result
863 Model_SelectionNaming aSelNaming(selectionLabel());
864 std::string aResult = aSelNaming.namingName(
865 aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
866 if (aCenterType != NOT_CENTER) {
867 aResult += centersMap()[aCenterType];
872 // returns the center type and modifies the shape name if this name is center-name
873 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
875 std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
876 centersMap().begin();
877 for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
878 std::size_t aFound = theShapeName.find(aPrefixIter->second);
879 if (aFound != std::string::npos &&
880 aFound == theShapeName.size() - aPrefixIter->second.size()) {
881 theShapeName = theShapeName.substr(0, aFound);
882 return aPrefixIter->first;
885 return ModelAPI_AttributeSelection::NOT_CENTER;
888 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
889 void Model_AttributeSelection::selectSubShape(
890 const std::string& theType, const std::string& theSubShapeName)
892 if(theSubShapeName.empty() || theType.empty()) return;
894 std::string aSubShapeName = theSubShapeName;
895 CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
896 centerTypeByName(aSubShapeName) : NOT_CENTER;
897 std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
899 // first iteration is selection by name without center prefix, second - in case of problem,
900 // try with initial name
901 for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--) {
902 if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
903 aSubShapeName = theSubShapeName;
904 aCenterType = NOT_CENTER;
906 } else if (aUseCenter != 1) continue;
908 // check this is Part-name: 2 delimiters in the name
909 std::size_t aPartEnd = aSubShapeName.find('/');
910 if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
911 std::string aPartName = aSubShapeName.substr(0, aPartEnd);
912 ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
913 if (aFound.get()) { // found such part, so asking it for the name
914 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
915 std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
917 std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, aType, anIndex);
918 if (aSelected.get()) {
919 if (aCenterType != NOT_CENTER) {
920 if (!aSelected->isEdge())
922 std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aSelected));
923 setValueCenter(aPart, aSelectedEdge, aCenterType);
925 setValue(aPart, aSelected);
926 TDataStd_Integer::Set(selectionLabel(), anIndex);
932 std::shared_ptr<Model_Document> aDoc =
933 std::dynamic_pointer_cast<Model_Document>(owner()->document());
934 // check this is a whole feature context
935 if (aSubShapeName.size() > kWHOLE_FEATURE.size() &&
936 aSubShapeName.substr(0, kWHOLE_FEATURE.size()) == kWHOLE_FEATURE) {
937 std::string aFeatureName = aSubShapeName.substr(kWHOLE_FEATURE.size());
938 ObjectPtr anObj = aDoc->objectByName(ModelAPI_Feature::group(), aFeatureName);
940 static const GeomShapePtr anEmptyShape;
941 setValue(anObj, anEmptyShape);
946 Model_SelectionNaming aSelNaming(selectionLabel());
947 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
949 if (aSelNaming.selectSubShape(aType, aSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
950 // try to find the last context to find the up to date shape
951 if (aCont->shape().get() && !aCont->shape()->isNull() &&
952 aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
953 const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
954 if (!aConShape.IsNull()) {
955 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
957 aNS = TNaming_Tool::CurrentNamedShape(aNS);
958 if (!aNS.IsNull() && scope().Contains(aNS->Label())) { // scope check is for 2228
959 TDF_Label aLab = aNS->Label();
960 if (aLab.Depth() % 2 == 0)
961 aLab = aLab.Father();
962 ObjectPtr anObj = aDoc->objects()->object(aLab);
963 while(!anObj.get() && aLab.Depth() > 5) {
964 aLab = aLab.Father().Father();
965 anObj = aDoc->objects()->object(aLab);
969 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
977 // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
978 if (aCont.get() && aShapeToBeSelected.get()) {
979 ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aCont);
980 if (aComp && aComp->numberOfSubs()) {
981 std::list<ResultPtr> allSubs;
982 ModelAPI_Tools::allSubs(aComp, allSubs);
983 std::list<ResultPtr>::iterator aS = allSubs.begin();
984 for(; aS != allSubs.end(); aS++) {
985 ResultBodyPtr aSub = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aS);
986 if (aSub && aSub->numberOfSubs() == 0 && aSub->shape().get() &&
987 aSub->shape()->isSubShape(aShapeToBeSelected)) {
994 // try to find the latest active result that must be used instead of the selected
995 // to set the active context (like in GUI selection), not concealed one
996 bool aFindNewContext = true;
997 while(aFindNewContext && aCont.get()) {
998 aFindNewContext = false;
999 // take references to all results: root one, any sub
1000 ResultBodyPtr aCompContext = ModelAPI_Tools::bodyOwner(aCont, true);
1001 std::list<ResultPtr> allRes;
1002 if (aCompContext.get()) {
1003 ModelAPI_Tools::allSubs(aCompContext, allRes);
1004 allRes.push_back(aCompContext);
1006 allRes.push_back(aCont);
1008 for(std::list<ResultPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
1009 ResultPtr aResCont = *aSub;
1010 ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResCont);
1011 // only lower and higher level subs are counted
1012 if (aResBody.get() && aResBody->numberOfSubs() > 0 && aResBody != aCompContext)
1014 const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
1015 std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1016 for(; !aFindNewContext && aRef != aRefs.end(); aRef++) {
1017 if (!aRef->get() || !(*aRef)->owner().get())
1019 // concealed attribute only
1020 FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1021 if (!ModelAPI_Session::get()->validators()->isConcealed(
1022 aRefFeat->getKind(), (*aRef)->id()))
1024 // search the feature result that contains sub-shape selected
1025 std::list<std::shared_ptr<ModelAPI_Result> > aResults;
1027 // take all sub-results or one result
1028 std::list<ResultPtr> aRefFeatResults;
1029 ModelAPI_Tools::allResults(aRefFeat, aRefFeatResults);
1030 std::list<ResultPtr>::iterator aRefResIter = aRefFeatResults.begin();
1031 for(; aRefResIter != aRefFeatResults.end(); aRefResIter++) {
1032 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefResIter);
1033 if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1034 aResults.push_back(aBody);
1036 std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
1037 for(; aResIter != aResults.end(); aResIter++) {
1038 if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
1040 GeomShapePtr aShape = (*aResIter)->shape();
1041 GeomShapePtr aSelectedShape =
1042 aShapeToBeSelected.get() ? aShapeToBeSelected : aCont->shape();
1043 if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
1044 aCont = *aResIter; // found new context (produced from this) with same subshape
1045 aFindNewContext = true; // continue searching futher
1053 if (aCenterType != NOT_CENTER) {
1054 if (!aShapeToBeSelected->isEdge())
1056 std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
1057 setValueCenter(aCont, aSelectedEdge, aCenterType);
1059 setValue(aCont, aShapeToBeSelected);
1064 TDF_Label aSelLab = selectionLabel();
1065 setInvalidIfFalse(aSelLab, false);
1070 // Check the point is within shape's bounding box
1071 static bool isPointWithinBB(const GeomPointPtr& thePoint, const GeomShapePtr& theShape)
1073 double aXMin, aXMax, aYMin, aYMax, aZMin, aZMax;
1074 theShape->computeSize(aXMin, aYMin, aZMin, aXMax, aYMax, aZMax);
1075 return thePoint->x() >= aXMin - Precision::Confusion() &&
1076 thePoint->x() <= aXMax + Precision::Confusion() &&
1077 thePoint->y() >= aYMin - Precision::Confusion() &&
1078 thePoint->y() <= aYMax + Precision::Confusion() &&
1079 thePoint->z() >= aZMin - Precision::Confusion() &&
1080 thePoint->z() <= aZMax + Precision::Confusion();
1083 // Select sub-shape of the given type, which contains the given point
1084 static GeomShapePtr findSubShape(const GeomShapePtr& theShape,
1085 const GeomAPI_Shape::ShapeType& theType,
1086 const GeomPointPtr& thePoint)
1088 std::list<GeomShapePtr> aSubs = theShape->subShapes(theType);
1089 for (std::list<GeomShapePtr>::const_iterator aSubIt = aSubs.begin();
1090 aSubIt != aSubs.end(); ++aSubIt) {
1091 if ((*aSubIt)->middlePoint()->distance(thePoint) < Precision::Confusion())
1096 return GeomShapePtr();
1099 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1100 const GeomPointPtr& thePoint)
1102 if (theType.empty() || !thePoint)
1105 GeomAPI_Shape::ShapeType aType = GeomAPI_Shape::shapeTypeByStr(theType);
1106 GeomShapePtr aFoundSubShape;
1108 std::list<FeaturePtr> aFeatures = owner()->document()->allFeatures();
1109 // Process results of all features from the last to the first
1110 // to find appropriate sub-shape
1111 for (std::list<FeaturePtr>::const_reverse_iterator anIt = aFeatures.rbegin();
1112 anIt != aFeatures.rend(); ++anIt) {
1113 const std::list<ResultPtr>& aResults = (*anIt)->results();
1114 for (std::list<ResultPtr>::const_iterator aResIt = aResults.begin();
1115 aResIt != aResults.end(); ++aResIt) {
1116 GeomShapePtr aCurShape = (*aResIt)->shape();
1117 // first of all, check the point is within bounding box of the result
1118 if (!isPointWithinBB(thePoint, aCurShape))
1120 // now, process all sub-shapes of the given type and check their inner points
1121 aFoundSubShape = findSubShape(aCurShape, aType, thePoint);
1122 if (aFoundSubShape) {
1123 setValue(*aResIt, aFoundSubShape);
1127 // special case for ResultConstruction if the FACE is selected
1128 ResultConstructionPtr aResConstr =
1129 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIt);
1130 if (aResConstr && aType >= GeomAPI_Shape::FACE) {
1131 int aNbFaces = aResConstr->facesNum();
1132 for (int aFaceInd = 0; aFaceInd < aNbFaces; ++aFaceInd) {
1133 GeomFacePtr aCurFace = aResConstr->face(aFaceInd);
1134 // check the point is within bounding box of the face
1135 if (!isPointWithinBB(thePoint, aCurFace))
1137 aFoundSubShape = findSubShape(aCurFace, aType, thePoint);
1138 if (aFoundSubShape) {
1139 setValue(*aResIt, aFoundSubShape);
1147 TDF_Label aSelLab = selectionLabel();
1148 setInvalidIfFalse(aSelLab, false);
1152 int Model_AttributeSelection::Id()
1155 std::shared_ptr<GeomAPI_Shape> aSelection = value();
1156 ResultPtr aContextRes = context();
1157 // support for compsolids:
1158 while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1159 aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1161 std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1164 TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1165 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1166 // searching for the latest main shape
1167 if (aSelection && !aSelection->isNull() && aContext && !aContext->isNull())
1169 std::shared_ptr<Model_Document> aDoc =
1170 std::dynamic_pointer_cast<Model_Document>(context()->document());
1172 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1173 if (!aNS.IsNull()) {
1174 aMainShape = TNaming_Tool::CurrentShape(aNS);
1178 TopTools_IndexedMapOfShape aSubShapesMap;
1179 TopExp::MapShapes(aMainShape, aSubShapesMap);
1180 anID = aSubShapesMap.FindIndex(aSubShape);
1185 void Model_AttributeSelection::setId(int theID)
1187 std::shared_ptr<GeomAPI_Shape> aSelection;
1189 ResultPtr aContextRes = context();
1190 // support for compsolids:
1191 while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1192 aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1194 std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1196 TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1197 // searching for the latest main shape
1198 if (theID > 0 && aContext && !aContext->isNull())
1200 std::shared_ptr<Model_Document> aDoc =
1201 std::dynamic_pointer_cast<Model_Document>(aContextRes->document());
1203 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1204 if (!aNS.IsNull()) {
1205 aMainShape = TNaming_Tool::CurrentShape(aNS);
1209 TopTools_IndexedMapOfShape aSubShapesMap;
1210 TopExp::MapShapes(aMainShape, aSubShapesMap);
1211 const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1213 std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1214 aResult->setImpl(new TopoDS_Shape(aSelShape));
1216 aSelection = aResult;
1219 setValue(aContextRes, aSelection);
1222 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1224 std::string aResult;
1225 if (owner()->document() != theContext->document()) {
1226 if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1227 aResult = theContext->document()->kind() + "/";
1229 ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1230 ModelAPI_Session::get()->moduleDocument(), theContext->document());
1231 if (aDocRes.get()) {
1232 aResult = aDocRes->data()->name() + "/";
1236 aResult += theContext->data()->name();
1240 void Model_AttributeSelection::computeValues(
1241 ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1242 TopTools_ListOfShape& theShapes)
1244 bool aWasWholeContext = theValShape.IsNull();
1245 if (aWasWholeContext) {
1246 //theShapes.Append(theValShape);
1248 theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1250 //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1251 TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1252 //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
1253 //theShapes.Append(aNewContShape);
1256 // if a new value is unchanged in the new context, do nothing: value is correct
1257 TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
1258 for(; aSubExp.More(); aSubExp.Next()) {
1259 if (aSubExp.Current().IsSame(theValShape)) {
1260 theShapes.Append(theValShape);
1264 // if new context becomes compsolid, the resulting sub may be in sub-solids
1265 std::list<ResultPtr> aNewToIterate;
1266 aNewToIterate.push_back(theNewContext);
1267 ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theNewContext);
1269 std::list<ResultPtr> allNewContextSubs;
1270 ModelAPI_Tools::allSubs(aComp, allNewContextSubs);
1271 std::list<ResultPtr>::iterator aSub = allNewContextSubs.begin();
1272 for(; aSub != allNewContextSubs.end(); aSub++) {
1273 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aSub);
1274 if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1275 aNewToIterate.push_back(aBody);
1279 // first iteration: searching for the whole shape appearance (like face of the box)
1280 // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1281 int aToFindPart = 0;
1282 TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1283 TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1284 for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1285 std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1286 for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1287 std::shared_ptr<Model_Data> aNewData =
1288 std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1289 TDF_Label aNewLab = aNewData->label();
1290 // searching for produced sub-shape fully on some label
1291 TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1292 for(; aNSIter.More(); aNSIter.Next()) {
1293 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1294 for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1295 if (aToFindPart == 0) { // search shape is fully inside
1296 if (aPairIter.OldShape().IsSame(theValShape)) {
1297 if (aPairIter.NewShape().IsNull()) {// value was removed
1301 theShapes.Append(aPairIter.NewShape());
1303 } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1304 TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1305 for(; anExp.More(); anExp.Next()) {
1306 if (anExp.Current().IsSame(theValShape)) { // found a new container
1307 if (aPairIter.NewShape().IsNull()) {// value was removed
1311 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1312 anOlds.Add(aPairIter.OldShape());
1321 if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1322 // map of sub-shapes -> number of occurences of these shapes in containers
1323 NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1324 TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1325 for(; aContIter.More(); aContIter.Next()) {
1326 TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1327 for(; aSubExp.More(); aSubExp.Next()) {
1328 if (!aSubs.IsBound(aSubExp.Current())) {
1329 aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1331 // store old to know how many olds produced this shape
1332 aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1335 // if sub is appeared same times in containers as the number of old shapes that contain it
1336 int aCountInOld = anOlds.Size();
1337 NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1339 for(; aSubsIter.More(); aSubsIter.Next()) {
1340 if (aSubsIter.Value().Size() == aCountInOld) {
1341 theShapes.Append(aSubsIter.Key());
1345 if (theShapes.IsEmpty()) { // nothing was changed
1346 theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1350 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1351 const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1352 TDF_Label theAccessLabel,
1353 std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1355 std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1356 TopTools_ListOfShape aResContShapes;
1357 // iterate context and shape, but also if it is sub-shape of main shape, check also it
1358 TopTools_ListOfShape aContextList;
1359 aContextList.Append(theContShape);
1360 if (theContext.get()) {
1361 ResultPtr aComposite = ModelAPI_Tools::bodyOwner(theContext);
1362 if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1363 aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1365 for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1366 TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1367 for(; aModifIter.More(); aModifIter.Next()) {
1368 TDF_Label anObjLab = aModifIter.Label().Father();
1369 ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1370 (theDoc->objects()->object(anObjLab));
1371 if (!aModifierObj.get()) {
1372 // #2241: shape may be sub-element of new object, not main (shell created from faces)
1373 if (!anObjLab.IsRoot())
1374 aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1375 (theDoc->objects()->object(anObjLab.Father()));
1376 if (!aModifierObj.get())
1379 FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1380 if (!aModifierFeat.get())
1382 FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1383 if (aModifierFeat == aThisFeature || theDoc->objects()->isLater(aModifierFeat, aThisFeature))
1384 continue; // the modifier feature is later than this, so, should not be used
1385 FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1386 if (aCurrentModifierFeat == aModifierFeat ||
1387 theDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
1388 continue; // the current modifier is later than the found, so, useless
1389 Handle(TNaming_NamedShape) aNewNS;
1390 aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1391 if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1392 aResults.insert(aModifierObj);
1393 //TNaming_Iterator aPairIter(aNewNS);
1394 //aResContShapes.Append(aPairIter.NewShape());
1395 aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1396 } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1397 aResults.insert(ResultPtr());
1398 } else { // not-precessed modification => don't support it
1403 if (aResults.empty())
1404 return false; // no modifications found, must stay the same
1405 // iterate all results to find futher modifications
1406 std::set<ResultPtr>::iterator aResIter = aResults.begin();
1407 for(; aResIter != aResults.end(); aResIter++) {
1408 if (aResIter->get() != NULL) {
1409 // compute new values by two contextes: the old and the new
1410 TopTools_ListOfShape aValShapes;
1411 computeValues(theContext, *aResIter, theValShape, aValShapes);
1413 TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1414 for(; aNewVal.More(); aNewVal.Next()) {
1415 std::list<ResultPtr> aNewRes;
1416 TopTools_ListOfShape aNewUpdatedVal;
1417 TopoDS_Shape aNewValSh = aNewVal.Value();
1418 TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1419 if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1420 aNewValSh.Nullify();
1421 if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1422 theAccessLabel, aNewRes, aNewUpdatedVal))
1424 // appeand new results instead of the current ones
1425 std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1426 TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1427 for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1428 theResults.push_back(*aNewIter);
1429 theValShapes.Append(aNewUpdVal.Value());
1431 } else { // the current result is good
1432 theResults.push_back(*aResIter);
1433 theValShapes.Append(aNewValSh);
1438 return true; // theResults must be empty: everything is deleted
1441 void Model_AttributeSelection::updateInHistory()
1443 ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1444 // only bodies and parts may be modified later in the history, don't do anything otherwise
1445 if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1446 aContext->groupName() != ModelAPI_ResultPart::group()))
1448 std::shared_ptr<Model_Document> aDoc =
1449 std::dynamic_pointer_cast<Model_Document>(aContext->document());
1450 std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1451 if (!aContData.get() || !aContData->isValid())
1453 TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
1454 Handle(TNaming_NamedShape) aContNS;
1455 if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1456 bool aFoundNewContext = true;
1457 ResultPtr aNewContext = aContext;
1458 while(aFoundNewContext) {
1459 aFoundNewContext = false;
1460 // parts have no shape in result, so, trace references using the Part info
1461 if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1462 ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1463 if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1464 const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1465 std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1466 for(; aRef != aRefs.end(); aRef++) {
1467 // to avoid detection of part changes by local selection only
1468 AttributeSelectionPtr aSel =
1469 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1470 if (aSel.get() && !aSel->value()->isSame(aSel->context()->shape()))
1473 FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1474 if (aRefFeat.get() && aRefFeat != owner()) {
1475 FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1476 if (aDoc->objects()->isLater(aThisFeature, aRefFeat)) { // found better feature
1477 aFoundNewContext = true;
1478 aNewContext = aRefFeat->firstResult();
1485 if (aNewContext != aContext) {
1486 setValue(aNewContext, value());
1490 FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1491 FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1492 // iterate the context shape modifications in order to find a feature that is upper in history
1493 // that this one and is really modifies the referenced result to refer to it
1494 ResultPtr aModifierResFound;
1495 TNaming_Iterator aPairIter(aContNS);
1496 if (!aPairIter.More())
1498 TopoDS_Shape aNewCShape = aPairIter.NewShape();
1499 bool anIterate = true;
1500 // trying to update also the sub-shape selected
1501 GeomShapePtr aSubShape = value();
1502 if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1504 TopoDS_Shape aValShape;
1505 if (aSubShape.get()) {
1506 aValShape = aSubShape->impl<TopoDS_Shape>();
1509 std::list<ResultPtr> aNewContexts;
1510 TopTools_ListOfShape aValShapes;
1511 if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1513 // update scope to reset to a new one
1516 std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1517 TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1518 if (aNewCont == aNewContexts.end()) { // all results were deleted
1519 ResultPtr anEmptyContext;
1520 std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1521 setValue(anEmptyContext, anEmptyShape); // nullify the selection
1525 GeomShapePtr aValueShape;
1526 if (!aNewValues.Value().IsNull()) {
1527 aValueShape = std::make_shared<GeomAPI_Shape>();
1528 aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1530 setValue(*aNewCont, aValueShape);
1531 // if there are more than one result, put them by "append" into "parent" list
1533 for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1534 aNewCont++, aNewValues.Next()) {
1535 GeomShapePtr aValueShape;
1536 if (!aNewValues.Value().IsNull()) {
1537 aValueShape = std::make_shared<GeomAPI_Shape>();
1538 aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1541 // Check that list has the same type of shape selection before adding.
1542 GeomAPI_Shape::ShapeType aListShapeType = GeomAPI_Shape::SHAPE;
1543 if (myParent->selectionType() == "VERTEX") aListShapeType = GeomAPI_Shape::VERTEX;
1544 else if (myParent->selectionType() == "EDGE") aListShapeType = GeomAPI_Shape::EDGE;
1545 else if (myParent->selectionType() == "FACE") aListShapeType = GeomAPI_Shape::FACE;
1547 GeomAPI_Shape::ShapeType aShapeShapeType = GeomAPI_Shape::SHAPE;
1548 if (aValueShape.get()) {
1549 aShapeShapeType = aValueShape->shapeType();
1551 (*aNewCont)->shape()->shapeType();
1554 if (aListShapeType != GeomAPI_Shape::SHAPE && aListShapeType != aShapeShapeType) {
1558 myParent->append(*aNewCont, aValueShape);
1564 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1566 myParent = theParent;