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));
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 ResultPtr Model_AttributeSelection::context() {
175 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
179 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
181 ModelAPI_AttributeSelection::setObject(theObject);
182 myRef.setObject(theObject);
185 TDF_LabelMap& Model_AttributeSelection::scope()
187 if (myScope.IsEmpty()) { // create a new scope if not yet done
188 // gets all labels with named shapes that are bofore this feature label (before in history)
189 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
190 owner()->data())->label().Father();
191 int aFeatureID = aFeatureLab.Tag();
192 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
193 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
194 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
196 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
197 for(; aNSIter.More(); aNSIter.Next()) {
198 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
199 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
200 myScope.Add(aNS->Label());
208 bool Model_AttributeSelection::update()
210 ResultPtr aContext = context();
211 if (!aContext.get()) return false;
212 TDF_Label aSelLab = selectionLabel();
213 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
214 return aContext->shape() && !aContext->shape()->isNull();
216 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
217 return aContext->shape() && !aContext->shape()->isNull();
220 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
221 // body: just a named shape, use selection mechanism from OCCT
222 TNaming_Selector aSelector(aSelLab);
223 bool aResult = aSelector.Solve(scope()) == Standard_True;
224 owner()->data()->sendAttributeUpdated(this);
226 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
227 // construction: identification by the results indexes, recompute faces and
228 // take the face that more close by the indexes
229 ResultConstructionPtr aConstructionContext =
230 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
231 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
232 // sketch sub-element
233 if (aConstructionContext &&
234 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
236 TDF_Label aLab = myRef.myRef->Label();
237 // getting a type of selected shape
238 Handle(TDataStd_Integer) aTypeAttr;
239 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
242 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
243 // selected indexes will be needed in each "if"
244 Handle(TDataStd_IntPackedMap) aSubIds;
245 std::shared_ptr<GeomAPI_Shape> aNewSelected;
247 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
248 // for now working only with composite features
249 CompositeFeaturePtr aComposite =
250 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
251 if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
255 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
256 // If this is a wire with plane defined thin it is a sketch-like object
257 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
259 // if there is no edges indexes, any face can be used: take the first
260 std::shared_ptr<GeomAPI_Shape> aNewSelected;
262 aNewSelected = aConstructionContext->face(0);
263 } else { // searching for most looks-like initial face by the indexes
264 // prepare edges of the current resut for the fast searching
265 TColStd_MapOfTransient allCurves;
266 const int aSubNum = aComposite->numberOfSubs();
267 for(int a = 0; a < aSubNum; a++) {
268 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
269 FeaturePtr aSub = aComposite->subFeature(a);
270 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
271 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
272 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
273 ResultConstructionPtr aConstr =
274 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
275 if (aConstr->shape() && aConstr->shape()->isEdge()) {
276 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
277 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
278 if (!anEdge.IsNull()) {
279 Standard_Real aFirst, aLast;
280 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
281 allCurves.Add(aCurve);
287 double aBestFound = 0; // best percentage of found edges
288 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
289 int aFound = 0, aNotFound = 0;
290 TopExp_Explorer anEdgesExp(
291 aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>(), TopAbs_EDGE);
292 for(; anEdgesExp.More(); anEdgesExp.Next()) {
293 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
294 if (!anEdge.IsNull()) {
295 Standard_Real aFirst, aLast;
296 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
297 if (allCurves.Contains(aCurve)) {
304 if (aFound + aNotFound != 0) {
305 double aPercentage = double(aFound) / double(aFound + aNotFound);
306 if (aPercentage > aBestFound) {
307 aBestFound = aPercentage;
308 aNewSelected = aConstructionContext->face(aFaceIndex);
313 if (aNewSelected) { // store this new selection
314 selectConstruction(aContext, aNewSelected);
315 owner()->data()->sendAttributeUpdated(this);
318 } else if (aShapeType == TopAbs_EDGE) {
319 // just reselect the edge by the id
320 const int aSubNum = aComposite->numberOfSubs();
321 for(int a = 0; a < aSubNum; a++) {
322 // if aSubIds take any, the first appropriate
323 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
324 // found the appropriate feature
325 FeaturePtr aFeature = aComposite->subFeature(a);
326 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
327 aFeature->results().cbegin();
328 for(;aResIter != aFeature->results().cend(); aResIter++) {
329 ResultConstructionPtr aRes =
330 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
331 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
332 selectConstruction(aContext, aRes->shape());
333 owner()->data()->sendAttributeUpdated(this);
339 } else if (aShapeType == TopAbs_VERTEX) {
340 // just reselect the vertex by the id of edge
341 const int aSubNum = aComposite->numberOfSubs();
342 for(int a = 0; a < aSubNum; a++) {
343 // if aSubIds take any, the first appropriate
344 int aFeatureID = aComposite->subFeatureId(a);
345 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
346 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
347 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
348 // searching for deltas
350 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
351 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
352 // found the feature with appropriate edge
353 FeaturePtr aFeature = aComposite->subFeature(a);
354 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
355 aFeature->results().cbegin();
356 for(;aResIter != aFeature->results().cend(); aResIter++) {
357 ResultConstructionPtr aRes =
358 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
359 if (aRes && aRes->shape()) {
360 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
361 selectConstruction(aContext, aRes->shape());
362 owner()->data()->sendAttributeUpdated(this);
364 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
365 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
367 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
368 if (aVIndex == aVertexNum) { // found!
369 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
370 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
371 selectConstruction(aContext, aVertex);
372 owner()->data()->sendAttributeUpdated(this);
383 } else { // simple construction element: the selected is that needed
384 selectConstruction(aContext, aContext->shape());
385 owner()->data()->sendAttributeUpdated(this);
389 return false; // unknown case
393 void Model_AttributeSelection::selectBody(
394 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
396 // perform the selection
397 TNaming_Selector aSel(selectionLabel());
398 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
399 TopoDS_Shape aContext;
401 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
403 aContext = aBody->shape()->impl<TopoDS_Shape>();
405 ResultConstructionPtr aConstr =
406 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
408 aContext = aConstr->shape()->impl<TopoDS_Shape>();
410 Events_Error::send("A result with shape is expected");
414 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
415 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
416 if (aFeatureOwner.get())
417 aFeatureOwner->eraseResults();
419 aSel.Select(aNewShape, aContext);
422 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
423 /// if theID is zero,
424 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
425 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
426 std::string theAdditionalName,
427 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
429 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
430 TNaming_Builder aBuilder(aLab);
431 aBuilder.Generated(theShape);
432 std::stringstream aName;
433 aName<<theContextFeature->name()<<"/";
434 if (!theAdditionalName.empty())
435 aName<<theAdditionalName<<"/";
436 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
437 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
438 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
440 if (theRefs.IsNull()) {
442 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
443 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
444 for(; aRef.More(); aRef.Next()) {
445 aName<<"-"<<aRef.Key();
449 theDoc->addNamingName(aLab, aName.str());
450 TDataStd_Name::Set(aLab, aName.str().c_str());
453 void Model_AttributeSelection::selectConstruction(
454 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
456 std::shared_ptr<Model_Document> aMyDoc =
457 std::dynamic_pointer_cast<Model_Document>(owner()->document());
458 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
459 CompositeFeaturePtr aComposite =
460 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
461 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
462 if (!aComposite || aComposite->numberOfSubs() == 0) {
463 // saving of context is enough: result construction contains exactly the needed shape
464 TNaming_Builder aBuilder(selectionLabel());
465 aBuilder.Generated(aSubShape);
466 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
467 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
470 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
471 TDF_Label aLab = myRef.myRef->Label();
472 // identify the reuslts of sub-object of the composite by edges
473 // save type of the selected shape in integer attribute
474 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
475 TDataStd_Integer::Set(aLab, (int)aShapeType);
477 TColStd_MapOfTransient allCurves;
478 if (aShapeType == TopAbs_VERTEX) { // compare positions
479 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
481 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
482 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
483 Standard_Real aFirst, aLast;
484 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
485 allCurves.Add(aCurve);
488 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
489 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
491 const int aSubNum = aComposite->numberOfSubs();
492 for(int a = 0; a < aSubNum; a++) {
493 FeaturePtr aSub = aComposite->subFeature(a);
494 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
495 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
496 // there may be many shapes (circle and center): register if at least one is in selection
497 for(; aRes != aResults.cend(); aRes++) {
498 ResultConstructionPtr aConstr =
499 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
500 if (!aConstr->shape()) {
503 if (aShapeType == TopAbs_VERTEX) {
504 if (aConstr->shape()->isVertex()) { // compare vertices positions
505 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
506 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
507 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
508 aRefs->Add(aComposite->subFeatureId(a));
510 } else { // get first or last vertex of the edge: last is stored with negative sign
511 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
512 int aDelta = kSTART_VERTEX_DELTA;
513 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
514 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
515 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
516 aRefs->Add(aDelta + aComposite->subFeatureId(a));
519 aDelta += kSTART_VERTEX_DELTA;
523 if (aConstr->shape()->isEdge()) {
524 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
525 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
526 if (!anEdge.IsNull()) {
527 Standard_Real aFirst, aLast;
528 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
529 if (allCurves.Contains(aCurve)) {
530 int anID = aComposite->subFeatureId(a);
532 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
533 // add edges to sub-label to support naming for edges selection
534 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
535 for(; anEdgeExp.More(); anEdgeExp.Next()) {
536 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
537 Standard_Real aFirst, aLast;
538 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
539 if (aFaceCurve == aCurve) {
540 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
543 } else { // put vertices of the selected edge to sub-labels
544 // add edges to sub-label to support naming for edges selection
545 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
546 int aTagIndex = anID + kSTART_VERTEX_DELTA;
547 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
548 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
550 std::stringstream anAdditionalName;
551 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
561 // store the selected as primitive
562 TNaming_Builder aBuilder(selectionLabel());
563 aBuilder.Generated(aSubShape);
564 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
567 TDF_Label Model_AttributeSelection::selectionLabel()
569 return myRef.myRef->Label().FindChild(1);
573 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
574 const TDF_Label& theLabel)
577 // check if the subShape is already in DF
578 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
579 Handle(TDataStd_Name) anAttr;
580 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
581 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
582 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
584 const TDF_Label& aLabel = theDoc->findNamingName(aName);
585 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
586 if(!aLabel.IsEqual(aNS->Label())) {
587 //aName.erase(); //something is wrong, to be checked!!!
588 aName += "_SomethingWrong";
592 static const std::string aPostFix("_");
593 TNaming_Iterator anItL(aNS);
594 for(int i = 1; anItL.More(); anItL.Next(), i++) {
595 if(anItL.NewShape() == theShape) {
597 aName += TCollection_AsciiString (i).ToCString();
601 /* MPV: the code below does not work because of TNaming_Tool.cxx line 145: aNS->Get() uses maps
602 const TopoDS_Shape& aShape = aNS->Get();
603 if(aShape.ShapeType() == TopAbs_COMPOUND) {
604 std::string aPostFix("_");
605 TopoDS_Iterator it(aShape);
606 for (int i = 1;it.More();it.Next(), i++) {
607 if(it.Value() == theShape) {
608 aPostFix += TCollection_AsciiString (i).ToCString();
622 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
624 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
625 TopoDS_Compound aCmp;
627 BB.MakeCompound(aCmp);
628 TopTools_ListIteratorOfListOfShape it(theAncestors);
629 for(;it.More();it.Next()) {
630 BB.Add(aCmp, it.Value());
631 theSMap.Add(it.Value());
634 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
635 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
636 for (int i = 1; i <= aMap2.Extent(); i++) {
637 const TopoDS_Shape& aKey = aMap2.FindKey(i);
638 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
639 if(anAncestors.Extent() > 1) aNumber++;
641 if(aNumber > 1) return false;
644 std::string Model_AttributeSelection::namingName()
646 std::string aName("");
647 if(!this->isInitialized()) return aName;
648 Handle(TDataStd_Name) anAtt;
649 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
650 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
654 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
655 ResultPtr aCont = context();
656 aName = "Undefined name";
657 if(!aCont.get() || aCont->shape()->isNull())
659 if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
660 return aCont->data()->name();
662 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
663 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
665 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
666 BRepTools::Write(aSubShape, "Selection.brep");
667 BRepTools::Write(aContext, "Context.brep");
670 std::shared_ptr<Model_Document> aDoc =
671 std::dynamic_pointer_cast<Model_Document>(aCont->document());
673 // check if the subShape is already in DF
674 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
675 if(aName.empty() ) { // not in the document!
676 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
679 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
683 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
684 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
685 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
686 aName = "Degenerated_Edge";
689 TopTools_IndexedDataMapOfShapeListOfShape aMap;
690 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
691 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
692 bool isTrivialCase(true);
693 /* for (int i = 1; i <= aMap.Extent(); i++) {
694 const TopoDS_Shape& aKey = aMap.FindKey(i);
695 //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
696 if (aKey.IsSame(aSubShape)) continue;
697 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
698 // check that it is not a trivial case (F1 & F2: aNumber = 1)
699 isTrivialCase = isTrivial(anAncestors, aSMap);
702 if(aMap.Contains(aSubShape)) {
703 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
704 // check that it is not a trivial case (F1 & F2: aNumber = 1)
705 isTrivialCase = isTrivial(anAncestors, aSMap);
708 TopTools_ListOfShape aListOfNbs;
709 if(!isTrivialCase) { // find Neighbors
710 TNaming_Localizer aLocalizer;
711 TopTools_MapOfShape aMap3;
712 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
713 //int n = aMap3.Extent();
714 TopTools_MapIteratorOfMapOfShape it(aMap3);
715 for(;it.More();it.Next()) {
716 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
717 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
718 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
719 TopTools_ListIteratorOfListOfShape it2(aList);
720 for(;it2.More();it2.Next()) {
721 if(aSMap.Contains(it2.Value())) continue; // skip this Face
722 aListOfNbs.Append(it2.Value());
725 } // else a trivial case
727 // build name of the sub-shape Edge
728 for(int i=1; i <= aSMap.Extent(); i++) {
729 const TopoDS_Shape& aFace = aSMap.FindKey(i);
730 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
734 aName += "|" + aFaceName;
736 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
737 for (;itl.More();itl.Next()) {
738 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
739 aName += "|" + aFaceName;
745 // name structure (Monifold Topology):
746 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
747 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
748 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
749 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
750 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
751 // or compound of 2 open faces.
752 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
753 // two independent edges (wire or compound)
754 // implemented 2 first cases
756 TopTools_IndexedDataMapOfShapeListOfShape aMap;
757 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
758 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
759 TopTools_ListOfShape aList;
760 TopTools_MapOfShape aFMap;
762 //int n = aList2.Extent(); //bug! duplication
764 TopTools_ListIteratorOfListOfShape itl2(aList2);
765 for (int i = 1;itl2.More();itl2.Next(),i++) {
766 if(aFMap.Add(itl2.Value()))
767 aList.Append(itl2.Value());
769 //n = aList.Extent();
771 int n = aList.Extent();
772 if(n < 3) { // open topology case or Compound case => via edges
773 TopTools_IndexedDataMapOfShapeListOfShape aMap;
774 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
775 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
776 if(aList22.Extent() >= 2) { // regular solution
779 // bug! duplication; fix is below
781 TopTools_ListOfShape aListE;
782 TopTools_ListIteratorOfListOfShape itl2(aList22);
783 for (int i = 1;itl2.More();itl2.Next(),i++) {
784 if(aFMap.Add(itl2.Value()))
785 aListE.Append(itl2.Value());
789 TopTools_ListIteratorOfListOfShape itl(aListE);
790 for (int i = 1;itl.More();itl.Next(),i++) {
791 const TopoDS_Shape& anEdge = itl.Value();
792 std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
796 aName += "|" + anEdgeName;
799 else { // dangle vertex: if(aList22.Extent() == 1)
800 //it should be already in DF
804 TopTools_ListIteratorOfListOfShape itl(aList);
805 for (int i = 1;itl.More();itl.Next(),i++) {
806 const TopoDS_Shape& aFace = itl.Value();
807 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
811 aName += "|" + aFaceName;
818 // aDoc->addNamingName(selectionLabel(), aName);
819 // the selected sub-shape will not be shared and as result it will not require registration
824 TopAbs_ShapeEnum translateType (const std::string& theType)
826 // map from the textual shape types to OCCT enumeration
827 static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
828 if (MyShapeTypes.size() == 0) {
829 MyShapeTypes["face"] = TopAbs_FACE;
830 MyShapeTypes["faces"] = TopAbs_FACE;
831 MyShapeTypes["vertex"] = TopAbs_VERTEX;
832 MyShapeTypes["vertices"] = TopAbs_VERTEX;
833 MyShapeTypes["wire"] = TopAbs_WIRE;
834 MyShapeTypes["edge"] = TopAbs_EDGE;
835 MyShapeTypes["edges"] = TopAbs_EDGE;
836 MyShapeTypes["shell"] = TopAbs_SHELL;
837 MyShapeTypes["solid"] = TopAbs_SOLID;
838 MyShapeTypes["solids"] = TopAbs_SOLID;
839 MyShapeTypes["FACE"] = TopAbs_FACE;
840 MyShapeTypes["FACES"] = TopAbs_FACE;
841 MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
842 MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
843 MyShapeTypes["WIRE"] = TopAbs_WIRE;
844 MyShapeTypes["EDGE"] = TopAbs_EDGE;
845 MyShapeTypes["EDGES"] = TopAbs_EDGE;
846 MyShapeTypes["SHELL"] = TopAbs_SHELL;
847 MyShapeTypes["SOLID"] = TopAbs_SOLID;
848 MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
850 if (MyShapeTypes.find(theType) != MyShapeTypes.end())
851 return MyShapeTypes[theType];
852 Events_Error::send("Shape type defined in XML is not implemented!");
856 const TopoDS_Shape getShapeFromNS(
857 const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
859 TopoDS_Shape aSelection;
860 std::string::size_type n = theSubShapeName.rfind('/');
861 if (n == std::string::npos) n = 0;
862 std::string aSubString = theSubShapeName.substr(n + 1);
863 n = aSubString.rfind('_');
864 if (n == std::string::npos) return aSelection;
865 aSubString = aSubString.substr(n+1);
866 int indx = atoi(aSubString.c_str());
868 TNaming_Iterator anItL(theNS);
869 for(int i = 1; anItL.More(); anItL.Next(), i++) {
871 return anItL.NewShape();
877 const TopoDS_Shape findFaceByName(
878 const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
881 std::string::size_type n, nb = theSubShapeName.rfind('/');
882 if (nb == std::string::npos) nb = 0;
883 std::string aSubString = theSubShapeName.substr(nb + 1);
884 n = aSubString.rfind('_');
885 if (n != std::string::npos) {
886 std::string aSubStr2 = aSubString.substr(0, n);
887 aSubString = theSubShapeName.substr(0, nb + 1);
888 aSubString = aSubString + aSubStr2;
890 aSubString = theSubShapeName;
892 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
893 if(aLabel.IsNull()) return aFace;
894 Handle(TNaming_NamedShape) aNS;
895 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
896 aFace = getShapeFromNS(theSubShapeName, aNS);
901 int ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
903 std::string aName = theSubShapeName;
904 std::string aLastName;
905 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
906 while ((n2 = aName.find('|', n1)) != std::string::npos) {
907 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
908 theList.push_back(aName1);
910 aLastName = aName.substr(n1);
912 if(!aLastName.empty())
913 theList.push_back(aLastName);
914 return theList.size();
917 const TopoDS_Shape findCommonShape(
918 const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
921 std::vector<TopTools_MapOfShape> aVec;
922 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
923 if(theList.Extent() > 1) {
924 aVec.push_back(aMap1);
925 aVec.push_back(aMap2);
927 if(theList.Extent() > 2)
928 aVec.push_back(aMap3);
929 if(theList.Extent() == 4)
930 aVec.push_back(aMap4);
933 TopTools_ListIteratorOfListOfShape it(theList);
934 for(int i = 0;it.More();it.Next(),i++) {
935 const TopoDS_Shape& aFace = it.Value();
937 TopExp_Explorer anExp (aFace, theType);
938 for(;anExp.More();anExp.Next()) {
939 const TopoDS_Shape& anEdge = anExp.Current();
940 if (!anEdge.IsNull())
941 aVec[i].Add(anExp.Current());
944 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
945 for(;anExp.More();anExp.Next()) {
946 const TopoDS_Shape& aVertex = anExp.Current();
947 if (!aVertex.IsNull())
948 aVec[i].Add(anExp.Current());
952 //trivial case: 2 faces
953 TopTools_ListOfShape aList;
954 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
955 for(;it2.More();it2.Next()) {
956 if(aVec[1].Contains(it2.Key())) {
958 if(theList.Extent() == 2)
961 aList.Append(it2.Key());
964 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
965 if(aVec[2].Extent() && aVec[3].Extent()) {
966 TopTools_ListIteratorOfListOfShape it(aList);
967 for(;it.More();it.Next()) {
968 const TopoDS_Shape& aCand = it.Value();
969 // not yet completelly implemented, to be rechecked
970 TopoDS_Vertex aV1, aV2;
971 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
973 if(aVec[2].Contains(aV1)) aNum++;
974 else if(aVec[2].Contains(aV2)) aNum++;
975 if(aVec[3].Contains(aV1)) aNum++;
976 else if(aVec[3].Contains(aV2)) aNum++;
985 if(aList.Extent() && aVec.size() == 3) {
987 TopTools_ListIteratorOfListOfShape it(aList);
988 for(;it.More();it.Next()) {
989 const TopoDS_Shape& aCand = it.Value();
990 if(aVec[2].Contains(aCand)) {
999 std::string getContextName(const std::string& theSubShapeName)
1002 std::string::size_type n = theSubShapeName.find('/');
1003 if (n == std::string::npos) return aName;
1004 aName = theSubShapeName.substr(0, n);
1007 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
1008 void Model_AttributeSelection::selectSubShape(
1009 const std::string& theType, const std::string& theSubShapeName)
1011 if(theSubShapeName.empty() || theType.empty()) return;
1012 TopAbs_ShapeEnum aType = translateType(theType);
1013 std::shared_ptr<Model_Document> aDoc =
1014 std::dynamic_pointer_cast<Model_Document>(owner()->document());
1015 std::string aContName = getContextName(theSubShapeName);
1016 if(aContName.empty()) return;
1017 //ResultPtr aCont = context();
1018 ResultPtr aCont = aDoc->findByName(aContName);
1019 if(!aCont.get() || aCont->shape()->isNull()) return;
1020 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
1021 TopAbs_ShapeEnum aContType = aContext.ShapeType();
1022 if(aType <= aContType) return; // not applicable
1025 TopoDS_Shape aSelection;
1028 case TopAbs_COMPOUND:
1030 case TopAbs_COMPSOLID:
1038 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1039 if(!aSelection.IsNull()) {// Select it
1040 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1041 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1042 setValue(aCont, aShapeToBeSelected);
1050 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1051 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1052 if(!aLabel.IsNull()) {
1053 Handle(TNaming_NamedShape) aNS;
1054 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1055 aSelection = getShapeFromNS(theSubShapeName, aNS);
1058 if(aSelection.IsNull()) {
1059 std::list<std::string> aListofNames;
1060 int n = ParseName(theSubShapeName, aListofNames);
1061 if(n > 1 && n < 5) {
1062 TopTools_ListOfShape aList;
1063 std::list<std::string>::iterator it =aListofNames.begin();
1064 for(;it != aListofNames.end();it++){
1065 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1066 aList.Append(aFace);
1068 aSelection = findCommonShape(TopAbs_EDGE, aList);
1071 if(!aSelection.IsNull()) {// Select it
1072 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1073 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1074 setValue(aCont, aShapeToBeSelected);
1080 TopoDS_Shape aSelection;
1081 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1082 if(!aLabel.IsNull()) {
1083 Handle(TNaming_NamedShape) aNS;
1084 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1085 aSelection = getShapeFromNS(theSubShapeName, aNS);
1088 if(aSelection.IsNull()) {
1089 std::list<std::string> aListofNames;
1090 int n = ParseName(theSubShapeName, aListofNames);
1091 if(n > 1 && n < 4) { // 2 || 3
1092 TopTools_ListOfShape aList;
1093 std::list<std::string>::iterator it = aListofNames.begin();
1094 for(; it != aListofNames.end(); it++){
1095 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1097 aList.Append(aFace);
1099 aSelection = findCommonShape(TopAbs_VERTEX, aList);
1102 if(!aSelection.IsNull()) {// Select it
1103 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1104 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1105 setValue(aCont, aShapeToBeSelected);
1109 default: //TopAbs_SHAPE
1115 int Model_AttributeSelection::Id()
1117 std::shared_ptr<GeomAPI_Shape> aSelection = value();
1118 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1119 const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1120 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1122 if (aSelection && !aSelection->isNull() &&
1123 aContext && !aContext->isNull())
1125 TopTools_IndexedMapOfShape aSubShapesMap;
1126 TopExp::MapShapes(aMainShape, aSubShapesMap);
1127 anID = aSubShapesMap.FindIndex(aSubShape);