1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_AttributeSelection.h
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 <ModelAPI_Feature.h>
13 #include <ModelAPI_ResultBody.h>
14 #include <ModelAPI_ResultConstruction.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <GeomAPI_Shape.h>
17 #include <GeomAPI_PlanarEdges.h>
18 #include <Events_Error.h>
20 #include <TNaming_Selector.hxx>
21 #include <TNaming_NamedShape.hxx>
22 #include <TNaming_Tool.hxx>
23 #include <TNaming_Builder.hxx>
24 #include <TNaming_Localizer.hxx>
25 #include <TopoDS_Shape.hxx>
26 #include <TopoDS_Compound.hxx>
27 #include <TDataStd_IntPackedMap.hxx>
28 #include <TDataStd_Integer.hxx>
29 #include <TDataStd_UAttribute.hxx>
30 #include <TDataStd_Name.hxx>
31 #include <TopTools_MapOfShape.hxx>
32 #include <TopTools_IndexedMapOfShape.hxx>
33 #include <TopTools_MapIteratorOfMapOfShape.hxx>
34 #include <TopTools_ListOfShape.hxx>
35 #include <TopExp_Explorer.hxx>
36 #include <TDF_LabelMap.hxx>
37 #include <BRep_Tool.hxx>
38 #include <BRep_Builder.hxx>
39 #include <TopoDS_Edge.hxx>
42 #include <TColStd_MapOfTransient.hxx>
43 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
47 #include <Precision.hxx>
48 #include <TDF_ChildIterator.hxx>
49 #include <TDF_ChildIDIterator.hxx>
50 #include <TDataStd_Name.hxx>
51 #include <TopAbs_ShapeEnum.hxx>
52 #include <TopoDS_Iterator.hxx>
53 #include <TNaming_Iterator.hxx>
55 //#define DEB_NAMING 1
57 #include <BRepTools.hxx>
59 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
60 /// (multiplied by the index of the edge)
61 static const int kSTART_VERTEX_DELTA = 1000000;
62 // identifier that there is simple reference: selection equals to context
63 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
64 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
66 // on this label is stored:
67 // TNaming_NamedShape - selected shape
68 // TNaming_Naming - topological selection information (for the body)
69 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
70 // TDataStd_Integer - type of the selected shape (for construction)
71 // TDF_Reference - from ReferenceAttribute, the context
73 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
74 const std::shared_ptr<GeomAPI_Shape>& theSubShape)
76 const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
77 bool isOldContext = theContext == myRef.value();
78 bool isOldShape = isOldContext &&
79 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
80 if (isOldShape) return; // shape is the same, so context is also unchanged
81 // update the referenced object if needed
83 myRef.setValue(theContext);
85 // do noth use naming if selected shape is result shape itself, but not sub-shape
86 TDF_Label aSelLab = selectionLabel();
87 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
88 aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
90 bool isDegeneratedEdge = false;
91 // do not use the degenerated edge as a shape, a null context and shape is used in the case
92 if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
93 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
94 if (aSubShape.ShapeType() == TopAbs_EDGE)
95 isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
97 if (!theContext.get() || isDegeneratedEdge) {
98 // to keep the reference attribute label
99 TDF_Label aRefLab = myRef.myRef->Label();
100 aSelLab.ForgetAllAttributes(true);
101 myRef.myRef = TDF_Reference::Set(aSelLab, aSelLab);
104 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
105 // do not select the whole shape for body:it is already must be in the data framework
106 if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
107 aSelLab.ForgetAllAttributes(true);
108 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
110 selectBody(theContext, theSubShape);
112 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
113 if (!theSubShape.get()) {
114 // to sub, so the whole result is selected
115 aSelLab.ForgetAllAttributes(true);
116 TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
118 selectConstruction(theContext, theSubShape);
121 //the attribute initialized state should be changed by sendAttributeUpdated only
122 //myIsInitialized = true;
124 std::string aSelName = namingName();
125 if(!aSelName.empty())
126 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
129 //selectSubShape("FACE", "Extrusion_1/LateralFace_3");
130 //selectSubShape("FACE", "Extrusion_1/TopFace");
131 //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
132 //selectSubShape("EDGE", "Sketch_1/Edge_6");
134 owner()->data()->sendAttributeUpdated(this);
137 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
139 std::shared_ptr<GeomAPI_Shape> aResult;
140 if (myRef.isInitialized()) {
141 TDF_Label aSelLab = selectionLabel();
142 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
143 ResultPtr aContext = context();
145 return aResult; // empty result
146 return aContext->shape();
148 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
149 return aResult; // empty result
152 Handle(TNaming_NamedShape) aSelection;
153 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
154 TopoDS_Shape aSelShape = aSelection->Get();
155 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
156 aResult->setImpl(new TopoDS_Shape(aSelShape));
157 } else { // for simple construction element: just shape of this construction element
158 ResultConstructionPtr aConstr =
159 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
161 return aConstr->shape();
168 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
171 myIsInitialized = myRef.isInitialized();
174 void Model_AttributeSelection::setID(const std::string theID)
177 ModelAPI_AttributeSelection::setID(theID);
180 ResultPtr Model_AttributeSelection::context() {
181 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
185 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
187 ModelAPI_AttributeSelection::setObject(theObject);
188 myRef.setObject(theObject);
191 TDF_LabelMap& Model_AttributeSelection::scope()
193 if (myScope.IsEmpty()) { // create a new scope if not yet done
194 // gets all labels with named shapes that are bofore this feature label (before in history)
195 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
196 owner()->data())->label().Father();
197 int aFeatureID = aFeatureLab.Tag();
198 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
199 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
200 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
202 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
203 for(; aNSIter.More(); aNSIter.Next()) {
204 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
205 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
206 myScope.Add(aNS->Label());
214 bool Model_AttributeSelection::update()
216 ResultPtr aContext = context();
217 if (!aContext.get()) return false;
218 TDF_Label aSelLab = selectionLabel();
219 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
220 return aContext->shape() && !aContext->shape()->isNull();
222 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
223 return aContext->shape() && !aContext->shape()->isNull();
226 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
227 // body: just a named shape, use selection mechanism from OCCT
228 TNaming_Selector aSelector(aSelLab);
229 bool aResult = aSelector.Solve(scope()) == Standard_True;
230 owner()->data()->sendAttributeUpdated(this);
232 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
233 // construction: identification by the results indexes, recompute faces and
234 // take the face that more close by the indexes
235 ResultConstructionPtr aConstructionContext =
236 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
237 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
238 // sketch sub-element
239 if (aConstructionContext &&
240 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
242 TDF_Label aLab = myRef.myRef->Label();
243 // getting a type of selected shape
244 Handle(TDataStd_Integer) aTypeAttr;
245 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
248 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
249 // selected indexes will be needed in each "if"
250 Handle(TDataStd_IntPackedMap) aSubIds;
251 std::shared_ptr<GeomAPI_Shape> aNewSelected;
253 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
254 // for now working only with composite features
255 CompositeFeaturePtr aComposite =
256 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
257 if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
261 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
262 // If this is a wire with plane defined thin it is a sketch-like object
263 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
265 // if there is no edges indexes, any face can be used: take the first
266 std::shared_ptr<GeomAPI_Shape> aNewSelected;
268 aNewSelected = aConstructionContext->face(0);
269 } else { // searching for most looks-like initial face by the indexes
270 // prepare edges of the current resut for the fast searching
271 TColStd_MapOfTransient allCurves;
272 const int aSubNum = aComposite->numberOfSubs();
273 for(int a = 0; a < aSubNum; a++) {
274 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
275 FeaturePtr aSub = aComposite->subFeature(a);
276 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
277 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
278 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
279 ResultConstructionPtr aConstr =
280 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
281 if (aConstr->shape() && aConstr->shape()->isEdge()) {
282 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
283 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
284 if (!anEdge.IsNull()) {
285 Standard_Real aFirst, aLast;
286 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
287 allCurves.Add(aCurve);
293 double aBestFound = 0; // best percentage of found edges
294 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
295 int aFound = 0, aNotFound = 0;
296 TopExp_Explorer anEdgesExp(
297 aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>(), TopAbs_EDGE);
298 for(; anEdgesExp.More(); anEdgesExp.Next()) {
299 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
300 if (!anEdge.IsNull()) {
301 Standard_Real aFirst, aLast;
302 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
303 if (allCurves.Contains(aCurve)) {
310 if (aFound + aNotFound != 0) {
311 double aPercentage = double(aFound) / double(aFound + aNotFound);
312 if (aPercentage > aBestFound) {
313 aBestFound = aPercentage;
314 aNewSelected = aConstructionContext->face(aFaceIndex);
319 if (aNewSelected) { // store this new selection
320 selectConstruction(aContext, aNewSelected);
321 owner()->data()->sendAttributeUpdated(this);
324 } else if (aShapeType == TopAbs_EDGE) {
325 // just reselect the edge by the id
326 const int aSubNum = aComposite->numberOfSubs();
327 for(int a = 0; a < aSubNum; a++) {
328 // if aSubIds take any, the first appropriate
329 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
330 // found the appropriate feature
331 FeaturePtr aFeature = aComposite->subFeature(a);
332 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
333 aFeature->results().cbegin();
334 for(;aResIter != aFeature->results().cend(); aResIter++) {
335 ResultConstructionPtr aRes =
336 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
337 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
338 selectConstruction(aContext, aRes->shape());
339 owner()->data()->sendAttributeUpdated(this);
345 } else if (aShapeType == TopAbs_VERTEX) {
346 // just reselect the vertex by the id of edge
347 const int aSubNum = aComposite->numberOfSubs();
348 for(int a = 0; a < aSubNum; a++) {
349 // if aSubIds take any, the first appropriate
350 int aFeatureID = aComposite->subFeatureId(a);
351 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
352 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
353 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
354 // searching for deltas
356 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
357 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
358 // found the feature with appropriate edge
359 FeaturePtr aFeature = aComposite->subFeature(a);
360 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
361 aFeature->results().cbegin();
362 for(;aResIter != aFeature->results().cend(); aResIter++) {
363 ResultConstructionPtr aRes =
364 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
365 if (aRes && aRes->shape()) {
366 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
367 selectConstruction(aContext, aRes->shape());
368 owner()->data()->sendAttributeUpdated(this);
370 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
371 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
373 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
374 if (aVIndex == aVertexNum) { // found!
375 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
376 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
377 selectConstruction(aContext, aVertex);
378 owner()->data()->sendAttributeUpdated(this);
389 } else { // simple construction element: the selected is that needed
390 selectConstruction(aContext, aContext->shape());
391 owner()->data()->sendAttributeUpdated(this);
395 return false; // unknown case
399 void Model_AttributeSelection::selectBody(
400 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
402 // perform the selection
403 TNaming_Selector aSel(selectionLabel());
404 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
405 TopoDS_Shape aContext;
407 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
409 aContext = aBody->shape()->impl<TopoDS_Shape>();
411 ResultConstructionPtr aConstr =
412 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
414 aContext = aConstr->shape()->impl<TopoDS_Shape>();
416 Events_Error::send("A result with shape is expected");
420 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
421 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
422 if (aFeatureOwner.get())
423 aFeatureOwner->eraseResults();
425 aSel.Select(aNewShape, aContext);
428 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
429 /// if theID is zero,
430 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
431 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
432 std::string theAdditionalName,
433 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
435 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
436 TNaming_Builder aBuilder(aLab);
437 aBuilder.Generated(theShape);
438 std::stringstream aName;
439 aName<<theContextFeature->name()<<"/";
440 if (!theAdditionalName.empty())
441 aName<<theAdditionalName<<"/";
442 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
443 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
444 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
446 if (theRefs.IsNull()) {
448 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
449 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
450 for(; aRef.More(); aRef.Next()) {
451 aName<<"-"<<aRef.Key();
455 theDoc->addNamingName(aLab, aName.str());
456 TDataStd_Name::Set(aLab, aName.str().c_str());
459 void Model_AttributeSelection::selectConstruction(
460 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
462 std::shared_ptr<Model_Document> aMyDoc =
463 std::dynamic_pointer_cast<Model_Document>(owner()->document());
464 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
465 CompositeFeaturePtr aComposite =
466 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
467 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
468 if (!aComposite || aComposite->numberOfSubs() == 0) {
469 // saving of context is enough: result construction contains exactly the needed shape
470 TNaming_Builder aBuilder(selectionLabel());
471 aBuilder.Generated(aSubShape);
472 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
473 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
476 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
477 TDF_Label aLab = myRef.myRef->Label();
478 // identify the reuslts of sub-object of the composite by edges
479 // save type of the selected shape in integer attribute
480 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
481 TDataStd_Integer::Set(aLab, (int)aShapeType);
483 TColStd_MapOfTransient allCurves;
484 if (aShapeType == TopAbs_VERTEX) { // compare positions
485 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
487 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
488 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
489 Standard_Real aFirst, aLast;
490 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
491 allCurves.Add(aCurve);
494 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
495 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
497 const int aSubNum = aComposite->numberOfSubs();
498 for(int a = 0; a < aSubNum; a++) {
499 FeaturePtr aSub = aComposite->subFeature(a);
500 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
501 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
502 // there may be many shapes (circle and center): register if at least one is in selection
503 for(; aRes != aResults.cend(); aRes++) {
504 ResultConstructionPtr aConstr =
505 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
506 if (!aConstr->shape()) {
509 if (aShapeType == TopAbs_VERTEX) {
510 if (aConstr->shape()->isVertex()) { // compare vertices positions
511 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
512 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
513 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
514 aRefs->Add(aComposite->subFeatureId(a));
516 } else { // get first or last vertex of the edge: last is stored with negative sign
517 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
518 int aDelta = kSTART_VERTEX_DELTA;
519 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
520 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
521 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
522 aRefs->Add(aDelta + aComposite->subFeatureId(a));
525 aDelta += kSTART_VERTEX_DELTA;
529 if (aConstr->shape()->isEdge()) {
530 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
531 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
532 if (!anEdge.IsNull()) {
533 Standard_Real aFirst, aLast;
534 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
535 if (allCurves.Contains(aCurve)) {
536 int anID = aComposite->subFeatureId(a);
538 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
539 // add edges to sub-label to support naming for edges selection
540 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
541 for(; anEdgeExp.More(); anEdgeExp.Next()) {
542 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
543 Standard_Real aFirst, aLast;
544 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
545 if (aFaceCurve == aCurve) {
546 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
549 } else { // put vertices of the selected edge to sub-labels
550 // add edges to sub-label to support naming for edges selection
551 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
552 int aTagIndex = anID + kSTART_VERTEX_DELTA;
553 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
554 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
556 std::stringstream anAdditionalName;
557 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
567 // store the selected as primitive
568 TNaming_Builder aBuilder(selectionLabel());
569 aBuilder.Generated(aSubShape);
570 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
573 TDF_Label Model_AttributeSelection::selectionLabel()
575 return myRef.myRef->Label().FindChild(1);
579 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
580 const TDF_Label& theLabel)
583 // check if the subShape is already in DF
584 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
585 Handle(TDataStd_Name) anAttr;
586 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
587 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
588 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
590 const TDF_Label& aLabel = theDoc->findNamingName(aName);
591 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
592 if(!aLabel.IsEqual(aNS->Label())) {
593 //aName.erase(); //something is wrong, to be checked!!!
594 aName += "_SomethingWrong";
598 static const std::string aPostFix("_");
599 TNaming_Iterator anItL(aNS);
600 for(int i = 1; anItL.More(); anItL.Next(), i++) {
601 if(anItL.NewShape() == theShape) {
603 aName += TCollection_AsciiString (i).ToCString();
607 /* MPV: the code below does not work because of TNaming_Tool.cxx line 145: aNS->Get() uses maps
608 const TopoDS_Shape& aShape = aNS->Get();
609 if(aShape.ShapeType() == TopAbs_COMPOUND) {
610 std::string aPostFix("_");
611 TopoDS_Iterator it(aShape);
612 for (int i = 1;it.More();it.Next(), i++) {
613 if(it.Value() == theShape) {
614 aPostFix += TCollection_AsciiString (i).ToCString();
628 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
630 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
631 TopoDS_Compound aCmp;
633 BB.MakeCompound(aCmp);
634 TopTools_ListIteratorOfListOfShape it(theAncestors);
635 for(;it.More();it.Next()) {
636 BB.Add(aCmp, it.Value());
637 theSMap.Add(it.Value());
640 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
641 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
642 for (int i = 1; i <= aMap2.Extent(); i++) {
643 const TopoDS_Shape& aKey = aMap2.FindKey(i);
644 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
645 if(anAncestors.Extent() > 1) aNumber++;
647 if(aNumber > 1) return false;
650 std::string Model_AttributeSelection::namingName()
652 std::string aName("");
653 if(!this->isInitialized()) return aName;
654 Handle(TDataStd_Name) anAtt;
655 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
656 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
660 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
661 ResultPtr aCont = context();
662 aName = "Undefined name";
663 if(!aCont.get() || aCont->shape()->isNull())
665 if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
666 return aCont->data()->name();
668 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
669 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
671 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
672 BRepTools::Write(aSubShape, "Selection.brep");
673 BRepTools::Write(aContext, "Context.brep");
676 std::shared_ptr<Model_Document> aDoc =
677 std::dynamic_pointer_cast<Model_Document>(aCont->document());
679 // check if the subShape is already in DF
680 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
681 if(aName.empty() ) { // not in the document!
682 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
685 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
689 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
690 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
691 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
692 aName = "Degenerated_Edge";
695 TopTools_IndexedDataMapOfShapeListOfShape aMap;
696 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
697 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
698 bool isTrivialCase(true);
699 /* for (int i = 1; i <= aMap.Extent(); i++) {
700 const TopoDS_Shape& aKey = aMap.FindKey(i);
701 //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
702 if (aKey.IsSame(aSubShape)) continue;
703 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
704 // check that it is not a trivial case (F1 & F2: aNumber = 1)
705 isTrivialCase = isTrivial(anAncestors, aSMap);
708 if(aMap.Contains(aSubShape)) {
709 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
710 // check that it is not a trivial case (F1 & F2: aNumber = 1)
711 isTrivialCase = isTrivial(anAncestors, aSMap);
714 TopTools_ListOfShape aListOfNbs;
715 if(!isTrivialCase) { // find Neighbors
716 TNaming_Localizer aLocalizer;
717 TopTools_MapOfShape aMap3;
718 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
719 //int n = aMap3.Extent();
720 TopTools_MapIteratorOfMapOfShape it(aMap3);
721 for(;it.More();it.Next()) {
722 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
723 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
724 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
725 TopTools_ListIteratorOfListOfShape it2(aList);
726 for(;it2.More();it2.Next()) {
727 if(aSMap.Contains(it2.Value())) continue; // skip this Face
728 aListOfNbs.Append(it2.Value());
731 } // else a trivial case
733 // build name of the sub-shape Edge
734 for(int i=1; i <= aSMap.Extent(); i++) {
735 const TopoDS_Shape& aFace = aSMap.FindKey(i);
736 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
740 aName += "|" + aFaceName;
742 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
743 for (;itl.More();itl.Next()) {
744 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
745 aName += "|" + aFaceName;
751 // name structure (Monifold Topology):
752 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
753 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
754 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
755 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
756 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
757 // or compound of 2 open faces.
758 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
759 // two independent edges (wire or compound)
760 // implemented 2 first cases
762 TopTools_IndexedDataMapOfShapeListOfShape aMap;
763 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
764 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
765 TopTools_ListOfShape aList;
766 TopTools_MapOfShape aFMap;
768 //int n = aList2.Extent(); //bug! duplication
770 TopTools_ListIteratorOfListOfShape itl2(aList2);
771 for (int i = 1;itl2.More();itl2.Next(),i++) {
772 if(aFMap.Add(itl2.Value()))
773 aList.Append(itl2.Value());
775 //n = aList.Extent();
777 int n = aList.Extent();
778 if(n < 3) { // open topology case or Compound case => via edges
779 TopTools_IndexedDataMapOfShapeListOfShape aMap;
780 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
781 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
782 if(aList22.Extent() >= 2) { // regular solution
785 // bug! duplication; fix is below
787 TopTools_ListOfShape aListE;
788 TopTools_ListIteratorOfListOfShape itl2(aList22);
789 for (int i = 1;itl2.More();itl2.Next(),i++) {
790 if(aFMap.Add(itl2.Value()))
791 aListE.Append(itl2.Value());
795 TopTools_ListIteratorOfListOfShape itl(aListE);
796 for (int i = 1;itl.More();itl.Next(),i++) {
797 const TopoDS_Shape& anEdge = itl.Value();
798 std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
802 aName += "|" + anEdgeName;
805 else { // dangle vertex: if(aList22.Extent() == 1)
806 //it should be already in DF
810 TopTools_ListIteratorOfListOfShape itl(aList);
811 for (int i = 1;itl.More();itl.Next(),i++) {
812 const TopoDS_Shape& aFace = itl.Value();
813 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
817 aName += "|" + aFaceName;
824 // aDoc->addNamingName(selectionLabel(), aName);
825 // the selected sub-shape will not be shared and as result it will not require registration
830 TopAbs_ShapeEnum translateType (const std::string& theType)
832 // map from the textual shape types to OCCT enumeration
833 static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
834 if (MyShapeTypes.size() == 0) {
835 MyShapeTypes["face"] = TopAbs_FACE;
836 MyShapeTypes["faces"] = TopAbs_FACE;
837 MyShapeTypes["vertex"] = TopAbs_VERTEX;
838 MyShapeTypes["vertices"] = TopAbs_VERTEX;
839 MyShapeTypes["wire"] = TopAbs_WIRE;
840 MyShapeTypes["edge"] = TopAbs_EDGE;
841 MyShapeTypes["edges"] = TopAbs_EDGE;
842 MyShapeTypes["shell"] = TopAbs_SHELL;
843 MyShapeTypes["solid"] = TopAbs_SOLID;
844 MyShapeTypes["solids"] = TopAbs_SOLID;
845 MyShapeTypes["FACE"] = TopAbs_FACE;
846 MyShapeTypes["FACES"] = TopAbs_FACE;
847 MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
848 MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
849 MyShapeTypes["WIRE"] = TopAbs_WIRE;
850 MyShapeTypes["EDGE"] = TopAbs_EDGE;
851 MyShapeTypes["EDGES"] = TopAbs_EDGE;
852 MyShapeTypes["SHELL"] = TopAbs_SHELL;
853 MyShapeTypes["SOLID"] = TopAbs_SOLID;
854 MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
856 if (MyShapeTypes.find(theType) != MyShapeTypes.end())
857 return MyShapeTypes[theType];
858 Events_Error::send("Shape type defined in XML is not implemented!");
862 const TopoDS_Shape getShapeFromNS(
863 const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
865 TopoDS_Shape aSelection;
866 std::string::size_type n = theSubShapeName.rfind('/');
867 if (n == std::string::npos) n = 0;
868 std::string aSubString = theSubShapeName.substr(n + 1);
869 n = aSubString.rfind('_');
870 if (n == std::string::npos) return aSelection;
871 aSubString = aSubString.substr(n+1);
872 int indx = atoi(aSubString.c_str());
874 TNaming_Iterator anItL(theNS);
875 for(int i = 1; anItL.More(); anItL.Next(), i++) {
877 return anItL.NewShape();
883 const TopoDS_Shape findFaceByName(
884 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
887 std::string::size_type n, nb = theSubShapeName.rfind('/');
888 if (nb == std::string::npos) nb = 0;
889 std::string aSubString = theSubShapeName.substr(nb + 1);
890 n = aSubString.rfind('_');
891 if (n != std::string::npos) {
892 std::string aSubStr2 = aSubString.substr(0, n);
893 aSubString = theSubShapeName.substr(0, nb + 1);
894 aSubString = aSubString + aSubStr2;
896 aSubString = theSubShapeName;
898 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
899 if(aLabel.IsNull()) return aFace;
900 Handle(TNaming_NamedShape) aNS;
901 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
902 aFace = getShapeFromNS(theSubShapeName, aNS);
907 int ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
909 std::string aName = theSubShapeName;
910 std::string aLastName;
911 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
912 while ((n2 = aName.find('|', n1)) != std::string::npos) {
913 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
914 theList.push_back(aName1);
916 aLastName = aName.substr(n1);
918 if(!aLastName.empty())
919 theList.push_back(aLastName);
920 return theList.size();
923 const TopoDS_Shape findCommonShape(
924 const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
927 std::vector<TopTools_MapOfShape> aVec;
928 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
929 if(theList.Extent() > 1) {
930 aVec.push_back(aMap1);
931 aVec.push_back(aMap2);
933 if(theList.Extent() > 2)
934 aVec.push_back(aMap3);
935 if(theList.Extent() == 4)
936 aVec.push_back(aMap4);
939 TopTools_ListIteratorOfListOfShape it(theList);
940 for(int i = 0;it.More();it.Next(),i++) {
941 const TopoDS_Shape& aFace = it.Value();
943 TopExp_Explorer anExp (aFace, theType);
944 for(;anExp.More();anExp.Next()) {
945 const TopoDS_Shape& anEdge = anExp.Current();
946 if (!anEdge.IsNull())
947 aVec[i].Add(anExp.Current());
950 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
951 for(;anExp.More();anExp.Next()) {
952 const TopoDS_Shape& aVertex = anExp.Current();
953 if (!aVertex.IsNull())
954 aVec[i].Add(anExp.Current());
958 //trivial case: 2 faces
959 TopTools_ListOfShape aList;
960 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
961 for(;it2.More();it2.Next()) {
962 if(aVec[1].Contains(it2.Key())) {
964 if(theList.Extent() == 2)
967 aList.Append(it2.Key());
970 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
971 if(aVec[2].Extent() && aVec[3].Extent()) {
972 TopTools_ListIteratorOfListOfShape it(aList);
973 for(;it.More();it.Next()) {
974 const TopoDS_Shape& aCand = it.Value();
975 // not yet completelly implemented, to be rechecked
976 TopoDS_Vertex aV1, aV2;
977 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
979 if(aVec[2].Contains(aV1)) aNum++;
980 else if(aVec[2].Contains(aV2)) aNum++;
981 if(aVec[3].Contains(aV1)) aNum++;
982 else if(aVec[3].Contains(aV2)) aNum++;
991 if(aList.Extent() && aVec.size() == 3) {
993 TopTools_ListIteratorOfListOfShape it(aList);
994 for(;it.More();it.Next()) {
995 const TopoDS_Shape& aCand = it.Value();
996 if(aVec[2].Contains(aCand)) {
1005 std::string getContextName(const std::string& theSubShapeName)
1008 std::string::size_type n = theSubShapeName.find('/');
1009 if (n == std::string::npos) return aName;
1010 aName = theSubShapeName.substr(0, n);
1013 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
1014 void Model_AttributeSelection::selectSubShape(
1015 const std::string& theType, const std::string& theSubShapeName)
1017 if(theSubShapeName.empty() || theType.empty()) return;
1018 TopAbs_ShapeEnum aType = translateType(theType);
1019 std::shared_ptr<Model_Document> aDoc =
1020 std::dynamic_pointer_cast<Model_Document>(owner()->document());
1021 std::string aContName = getContextName(theSubShapeName);
1022 if(aContName.empty()) return;
1023 //ResultPtr aCont = context();
1024 ResultPtr aCont = aDoc->findByName(aContName);
1025 if(!aCont.get() || aCont->shape()->isNull()) return;
1026 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
1027 TopAbs_ShapeEnum aContType = aContext.ShapeType();
1028 if(aType <= aContType) return; // not applicable
1031 TopoDS_Shape aSelection;
1034 case TopAbs_COMPOUND:
1036 case TopAbs_COMPSOLID:
1044 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1045 if(!aSelection.IsNull()) {// Select it
1046 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1047 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1048 setValue(aCont, aShapeToBeSelected);
1056 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1057 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1058 if(!aLabel.IsNull()) {
1059 Handle(TNaming_NamedShape) aNS;
1060 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1061 aSelection = getShapeFromNS(theSubShapeName, aNS);
1064 if(aSelection.IsNull()) {
1065 std::list<std::string> aListofNames;
1066 int n = ParseName(theSubShapeName, aListofNames);
1067 if(n > 1 && n < 5) {
1068 TopTools_ListOfShape aList;
1069 std::list<std::string>::iterator it =aListofNames.begin();
1070 for(;it != aListofNames.end();it++){
1071 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1072 aList.Append(aFace);
1074 aSelection = findCommonShape(TopAbs_EDGE, aList);
1077 if(!aSelection.IsNull()) {// Select it
1078 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1079 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1080 setValue(aCont, aShapeToBeSelected);
1086 TopoDS_Shape aSelection;
1087 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1088 if(!aLabel.IsNull()) {
1089 Handle(TNaming_NamedShape) aNS;
1090 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1091 aSelection = getShapeFromNS(theSubShapeName, aNS);
1094 if(aSelection.IsNull()) {
1095 std::list<std::string> aListofNames;
1096 int n = ParseName(theSubShapeName, aListofNames);
1097 if(n > 1 && n < 4) { // 2 || 3
1098 TopTools_ListOfShape aList;
1099 std::list<std::string>::iterator it = aListofNames.begin();
1100 for(; it != aListofNames.end(); it++){
1101 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1103 aList.Append(aFace);
1105 aSelection = findCommonShape(TopAbs_VERTEX, aList);
1108 if(!aSelection.IsNull()) {// Select it
1109 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1110 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1111 setValue(aCont, aShapeToBeSelected);
1115 default: //TopAbs_SHAPE
1121 int Model_AttributeSelection::Id()
1123 std::shared_ptr<GeomAPI_Shape> aSelection = value();
1124 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1125 const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1126 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1128 if (aSelection && !aSelection->isNull() &&
1129 aContext && !aContext->isNull())
1131 TopTools_IndexedMapOfShape aSubShapesMap;
1132 TopExp::MapShapes(aMainShape, aSubShapesMap);
1133 anID = aSubShapesMap.FindIndex(aSubShape);