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>
54 //#define DEB_NAMING 1
56 #include <BRepTools.hxx>
58 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
59 /// (multiplied by the index of the edge)
60 static const int kSTART_VERTEX_DELTA = 1000000;
61 // identifier that there is simple reference: selection equals to context
62 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
63 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
65 // on this label is stored:
66 // TNaming_NamedShape - selected shape
67 // TNaming_Naming - topological selection information (for the body)
68 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
69 // TDataStd_Integer - type of the selected shape (for construction)
70 // TDF_Reference - from ReferenceAttribute, the context
72 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
73 const std::shared_ptr<GeomAPI_Shape>& theSubShape)
75 const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
76 bool isOldContext = theContext == myRef.value();
77 bool isOldShape = isOldContext &&
78 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
79 if (isOldShape) return; // shape is the same, so context is also unchanged
80 // update the referenced object if needed
82 myRef.setValue(theContext);
84 // do noth use naming if selected shape is result shape itself, but not sub-shape
85 TDF_Label aSelLab = selectionLabel();
86 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
87 aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
89 bool isDegeneratedEdge = false;
90 // do not use the degenerated edge as a shape, a null context and shape is used in the case
91 if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
92 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
93 if (aSubShape.ShapeType() == TopAbs_EDGE)
94 isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape));
96 if (!theContext.get() || isDegeneratedEdge) {
97 // to keep the reference attribute label
98 TDF_Label aRefLab = myRef.myRef->Label();
99 aSelLab.ForgetAllAttributes(true);
100 myRef.myRef = TDF_Reference::Set(aSelLab, aSelLab);
103 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
104 // do not select the whole shape for body:it is already must be in the data framework
105 if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
106 aSelLab.ForgetAllAttributes(true);
107 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
109 selectBody(theContext, theSubShape);
111 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
112 if (!theSubShape.get()) {
113 // to sub, so the whole result is selected
114 aSelLab.ForgetAllAttributes(true);
115 TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
117 selectConstruction(theContext, theSubShape);
120 myIsInitialized = true;
122 std::string aSelName = namingName();
123 if(!aSelName.empty())
124 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
127 //selectSubShape("FACE", "Extrusion_1/LateralFace_3");
128 //selectSubShape("FACE", "Extrusion_1/TopFace");
129 //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
130 //selectSubShape("EDGE", "Sketch_1/Edge_6");
132 owner()->data()->sendAttributeUpdated(this);
135 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
137 std::shared_ptr<GeomAPI_Shape> aResult;
138 if (myIsInitialized) {
139 TDF_Label aSelLab = selectionLabel();
140 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
141 ResultPtr aContext = context();
143 return aResult; // empty result
144 return aContext->shape();
146 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
147 return aResult; // empty result
150 Handle(TNaming_NamedShape) aSelection;
151 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
152 TopoDS_Shape aSelShape = aSelection->Get();
153 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
154 aResult->setImpl(new TopoDS_Shape(aSelShape));
155 } else { // for simple construction element: just shape of this construction element
156 ResultConstructionPtr aConstr =
157 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
159 return aConstr->shape();
166 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
169 myIsInitialized = myRef.isInitialized();
172 ResultPtr Model_AttributeSelection::context() {
173 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
177 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
179 ModelAPI_AttributeSelection::setObject(theObject);
180 myRef.setObject(theObject);
183 TDF_LabelMap& Model_AttributeSelection::scope()
185 if (myScope.IsEmpty()) { // create a new scope if not yet done
186 // gets all labels with named shapes that are bofore this feature label (before in history)
187 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
188 owner()->data())->label().Father();
189 int aFeatureID = aFeatureLab.Tag();
190 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
191 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
192 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
194 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
195 for(; aNSIter.More(); aNSIter.Next()) {
196 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
197 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
198 myScope.Add(aNS->Label());
206 bool Model_AttributeSelection::update()
208 ResultPtr aContext = context();
209 if (!aContext.get()) return false;
210 TDF_Label aSelLab = selectionLabel();
211 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
212 return aContext->shape() && !aContext->shape()->isNull();
214 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
215 return aContext->shape() && !aContext->shape()->isNull();
218 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
219 // body: just a named shape, use selection mechanism from OCCT
220 TNaming_Selector aSelector(aSelLab);
221 bool aResult = aSelector.Solve(scope()) == Standard_True;
222 owner()->data()->sendAttributeUpdated(this);
224 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
225 // construction: identification by the results indexes, recompute faces and
226 // take the face that more close by the indexes
227 ResultConstructionPtr aConstructionContext =
228 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
229 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
230 // sketch sub-element
231 if (aConstructionContext &&
232 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
234 TDF_Label aLab = myRef.myRef->Label();
235 // getting a type of selected shape
236 Handle(TDataStd_Integer) aTypeAttr;
237 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
240 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
241 // selected indexes will be needed in each "if"
242 Handle(TDataStd_IntPackedMap) aSubIds;
243 std::shared_ptr<GeomAPI_Shape> aNewSelected;
245 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
246 // for now working only with composite features
247 CompositeFeaturePtr aComposite =
248 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
249 if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
253 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
254 // If this is a wire with plane defined thin it is a sketch-like object
255 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
257 // if there is no edges indexes, any face can be used: take the first
258 std::shared_ptr<GeomAPI_Shape> aNewSelected;
260 aNewSelected = aConstructionContext->face(0);
261 } else { // searching for most looks-like initial face by the indexes
262 // prepare edges of the current resut for the fast searching
263 TColStd_MapOfTransient allCurves;
264 const int aSubNum = aComposite->numberOfSubs();
265 for(int a = 0; a < aSubNum; a++) {
266 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
267 FeaturePtr aSub = aComposite->subFeature(a);
268 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
269 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
270 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
271 ResultConstructionPtr aConstr =
272 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
273 if (aConstr->shape() && aConstr->shape()->isEdge()) {
274 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
275 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
276 if (!anEdge.IsNull()) {
277 Standard_Real aFirst, aLast;
278 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
279 allCurves.Add(aCurve);
285 double aBestFound = 0; // best percentage of found edges
286 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
287 int aFound = 0, aNotFound = 0;
288 TopExp_Explorer anEdgesExp(
289 aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>(), TopAbs_EDGE);
290 for(; anEdgesExp.More(); anEdgesExp.Next()) {
291 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
292 if (!anEdge.IsNull()) {
293 Standard_Real aFirst, aLast;
294 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
295 if (allCurves.Contains(aCurve)) {
302 if (aFound + aNotFound != 0) {
303 double aPercentage = double(aFound) / double(aFound + aNotFound);
304 if (aPercentage > aBestFound) {
305 aBestFound = aPercentage;
306 aNewSelected = aConstructionContext->face(aFaceIndex);
311 if (aNewSelected) { // store this new selection
312 selectConstruction(aContext, aNewSelected);
313 owner()->data()->sendAttributeUpdated(this);
316 } else if (aShapeType == TopAbs_EDGE) {
317 // just reselect the edge by the id
318 const int aSubNum = aComposite->numberOfSubs();
319 for(int a = 0; a < aSubNum; a++) {
320 // if aSubIds take any, the first appropriate
321 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
322 // found the appropriate feature
323 FeaturePtr aFeature = aComposite->subFeature(a);
324 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
325 aFeature->results().cbegin();
326 for(;aResIter != aFeature->results().cend(); aResIter++) {
327 ResultConstructionPtr aRes =
328 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
329 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
330 selectConstruction(aContext, aRes->shape());
331 owner()->data()->sendAttributeUpdated(this);
337 } else if (aShapeType == TopAbs_VERTEX) {
338 // just reselect the vertex by the id of edge
339 const int aSubNum = aComposite->numberOfSubs();
340 for(int a = 0; a < aSubNum; a++) {
341 // if aSubIds take any, the first appropriate
342 int aFeatureID = aComposite->subFeatureId(a);
343 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
344 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
345 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
346 // searching for deltas
348 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
349 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
350 // found the feature with appropriate edge
351 FeaturePtr aFeature = aComposite->subFeature(a);
352 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
353 aFeature->results().cbegin();
354 for(;aResIter != aFeature->results().cend(); aResIter++) {
355 ResultConstructionPtr aRes =
356 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
357 if (aRes && aRes->shape()) {
358 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
359 selectConstruction(aContext, aRes->shape());
360 owner()->data()->sendAttributeUpdated(this);
362 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
363 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
365 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
366 if (aVIndex == aVertexNum) { // found!
367 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
368 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
369 selectConstruction(aContext, aVertex);
370 owner()->data()->sendAttributeUpdated(this);
381 } else { // simple construction element: the selected is that needed
382 selectConstruction(aContext, aContext->shape());
383 owner()->data()->sendAttributeUpdated(this);
387 return false; // unknown case
391 void Model_AttributeSelection::selectBody(
392 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
394 // perform the selection
395 TNaming_Selector aSel(selectionLabel());
396 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
397 TopoDS_Shape aContext;
399 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
401 aContext = aBody->shape()->impl<TopoDS_Shape>();
403 ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
405 aContext = aConstr->shape()->impl<TopoDS_Shape>();
407 Events_Error::send("A result with shape is expected");
411 //BRepTools::Write(aNewShape, "Selection0.brep");
412 aSel.Select(aNewShape, aContext);
415 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
416 /// if theID is zero,
417 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
418 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
419 std::string theAdditionalName,
420 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
422 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
423 TNaming_Builder aBuilder(aLab);
424 aBuilder.Generated(theShape);
425 std::stringstream aName;
426 aName<<theContextFeature->name()<<"/";
427 if (!theAdditionalName.empty())
428 aName<<theAdditionalName<<"/";
429 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
430 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
431 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
433 if (theRefs.IsNull()) {
435 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
436 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
437 for(; aRef.More(); aRef.Next()) {
438 aName<<"-"<<aRef.Key();
442 theDoc->addNamingName(aLab, aName.str());
443 TDataStd_Name::Set(aLab, aName.str().c_str());
446 void Model_AttributeSelection::selectConstruction(
447 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
449 std::shared_ptr<Model_Document> aMyDoc =
450 std::dynamic_pointer_cast<Model_Document>(owner()->document());
451 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
452 CompositeFeaturePtr aComposite =
453 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
454 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
455 if (!aComposite || aComposite->numberOfSubs() == 0) {
456 // saving of context is enough: result construction contains exactly the needed shape
457 TNaming_Builder aBuilder(selectionLabel());
458 aBuilder.Generated(aSubShape);
459 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
460 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
463 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
464 TDF_Label aLab = myRef.myRef->Label();
465 // identify the reuslts of sub-object of the composite by edges
466 // save type of the selected shape in integer attribute
467 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
468 TDataStd_Integer::Set(aLab, (int)aShapeType);
470 TColStd_MapOfTransient allCurves;
471 if (aShapeType == TopAbs_VERTEX) { // compare positions
472 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
474 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
475 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
476 Standard_Real aFirst, aLast;
477 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
478 allCurves.Add(aCurve);
481 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
482 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
484 const int aSubNum = aComposite->numberOfSubs();
485 for(int a = 0; a < aSubNum; a++) {
486 FeaturePtr aSub = aComposite->subFeature(a);
487 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
488 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
489 // there may be many shapes (circle and center): register if at least one is in selection
490 for(; aRes != aResults.cend(); aRes++) {
491 ResultConstructionPtr aConstr =
492 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
493 if (!aConstr->shape()) {
496 if (aShapeType == TopAbs_VERTEX) {
497 if (aConstr->shape()->isVertex()) { // compare vertices positions
498 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
499 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
500 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
501 aRefs->Add(aComposite->subFeatureId(a));
503 } else { // get first or last vertex of the edge: last is stored with negative sign
504 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
505 int aDelta = kSTART_VERTEX_DELTA;
506 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
507 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
508 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
509 aRefs->Add(aDelta + aComposite->subFeatureId(a));
512 aDelta += kSTART_VERTEX_DELTA;
516 if (aConstr->shape()->isEdge()) {
517 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
518 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
519 if (!anEdge.IsNull()) {
520 Standard_Real aFirst, aLast;
521 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
522 if (allCurves.Contains(aCurve)) {
523 int anID = aComposite->subFeatureId(a);
525 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
526 // add edges to sub-label to support naming for edges selection
527 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
528 for(; anEdgeExp.More(); anEdgeExp.Next()) {
529 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
530 Standard_Real aFirst, aLast;
531 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
532 if (aFaceCurve == aCurve) {
533 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
536 } else { // put vertices of the selected edge to sub-labels
537 // add edges to sub-label to support naming for edges selection
538 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
539 int aTagIndex = anID + kSTART_VERTEX_DELTA;
540 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
541 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
543 std::stringstream anAdditionalName;
544 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
554 // store the selected as primitive
555 TNaming_Builder aBuilder(selectionLabel());
556 aBuilder.Generated(aSubShape);
557 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
560 TDF_Label Model_AttributeSelection::selectionLabel()
562 return myRef.myRef->Label().FindChild(1);
566 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
567 const TDF_Label& theLabel)
570 // check if the subShape is already in DF
571 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
572 Handle(TDataStd_Name) anAttr;
573 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
574 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
575 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
577 const TDF_Label& aLabel = theDoc->findNamingName(aName);
578 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
579 if(!aLabel.IsEqual(aNS->Label())) {
580 //aName.erase(); //something is wrong, to be checked!!!
581 aName += "_SomethingWrong";
584 const TopoDS_Shape& aShape = aNS->Get();
585 if(aShape.ShapeType() == TopAbs_COMPOUND) {
586 std::string aPostFix("_");
587 TopoDS_Iterator it(aShape);
588 for (int i = 1;it.More();it.Next(), i++) {
589 if(it.Value() == theShape) {
590 aPostFix += TCollection_AsciiString (i).ToCString();
603 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
605 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
606 TopoDS_Compound aCmp;
608 BB.MakeCompound(aCmp);
609 TopTools_ListIteratorOfListOfShape it(theAncestors);
610 for(;it.More();it.Next()) {
611 BB.Add(aCmp, it.Value());
612 theSMap.Add(it.Value());
615 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
616 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
617 for (int i = 1; i <= aMap2.Extent(); i++) {
618 const TopoDS_Shape& aKey = aMap2.FindKey(i);
619 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
620 if(anAncestors.Extent() > 1) aNumber++;
622 if(aNumber > 1) return false;
625 std::string Model_AttributeSelection::namingName()
627 std::string aName("");
628 if(!this->isInitialized()) return aName;
629 Handle(TDataStd_Name) anAtt;
630 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
631 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
635 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
636 ResultPtr aCont = context();
637 aName = "Undefined name";
638 if(!aCont.get() || aCont->shape()->isNull())
640 if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
641 return aCont->data()->name();
643 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
644 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
646 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
647 BRepTools::Write(aSubShape, "Selection.brep");
648 BRepTools::Write(aContext, "Context.brep");
651 std::shared_ptr<Model_Document> aDoc =
652 std::dynamic_pointer_cast<Model_Document>(aCont->document());
654 // check if the subShape is already in DF
655 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
656 if(aName.empty() ) { // not in the document!
657 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
660 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
664 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
665 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
666 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
667 aName = "Degenerated_Edge";
670 TopTools_IndexedDataMapOfShapeListOfShape aMap;
671 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
672 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
673 bool isTrivialCase(true);
674 /* for (int i = 1; i <= aMap.Extent(); i++) {
675 const TopoDS_Shape& aKey = aMap.FindKey(i);
676 //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
677 if (aKey.IsSame(aSubShape)) continue;
678 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
679 // check that it is not a trivial case (F1 & F2: aNumber = 1)
680 isTrivialCase = isTrivial(anAncestors, aSMap);
683 if(aMap.Contains(aSubShape)) {
684 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
685 // check that it is not a trivial case (F1 & F2: aNumber = 1)
686 isTrivialCase = isTrivial(anAncestors, aSMap);
689 TopTools_ListOfShape aListOfNbs;
690 if(!isTrivialCase) { // find Neighbors
691 TNaming_Localizer aLocalizer;
692 TopTools_MapOfShape aMap3;
693 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
694 //int n = aMap3.Extent();
695 TopTools_MapIteratorOfMapOfShape it(aMap3);
696 for(;it.More();it.Next()) {
697 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
698 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
699 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
700 TopTools_ListIteratorOfListOfShape it2(aList);
701 for(;it2.More();it2.Next()) {
702 if(aSMap.Contains(it2.Value())) continue; // skip this Face
703 aListOfNbs.Append(it2.Value());
706 } // else a trivial case
708 // build name of the sub-shape Edge
709 for(int i=1; i <= aSMap.Extent(); i++) {
710 const TopoDS_Shape& aFace = aSMap.FindKey(i);
711 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
715 aName += "|" + aFaceName;
717 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
718 for (;itl.More();itl.Next()) {
719 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
720 aName += "|" + aFaceName;
726 // name structure (Monifold Topology):
727 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
728 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
729 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
730 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
731 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
732 // or compound of 2 open faces.
733 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
734 // two independent edges (wire or compound)
735 // implemented 2 first cases
737 TopTools_IndexedDataMapOfShapeListOfShape aMap;
738 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
739 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
740 TopTools_ListOfShape aList;
741 TopTools_MapOfShape aFMap;
743 //int n = aList2.Extent(); //bug! duplication
745 TopTools_ListIteratorOfListOfShape itl2(aList2);
746 for (int i = 1;itl2.More();itl2.Next(),i++) {
747 if(aFMap.Add(itl2.Value()))
748 aList.Append(itl2.Value());
750 //n = aList.Extent();
752 int n = aList.Extent();
753 if(n < 3) { // open topology case or Compound case => via edges
754 TopTools_IndexedDataMapOfShapeListOfShape aMap;
755 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
756 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
757 if(aList22.Extent() >= 2) { // regular solution
760 // bug! duplication; fix is below
762 TopTools_ListOfShape aListE;
763 TopTools_ListIteratorOfListOfShape itl2(aList22);
764 for (int i = 1;itl2.More();itl2.Next(),i++) {
765 if(aFMap.Add(itl2.Value()))
766 aListE.Append(itl2.Value());
770 TopTools_ListIteratorOfListOfShape itl(aListE);
771 for (int i = 1;itl.More();itl.Next(),i++) {
772 const TopoDS_Shape& anEdge = itl.Value();
773 std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
777 aName += "|" + anEdgeName;
780 else { // dangle vertex: if(aList22.Extent() == 1)
781 //it should be already in DF
785 TopTools_ListIteratorOfListOfShape itl(aList);
786 for (int i = 1;itl.More();itl.Next(),i++) {
787 const TopoDS_Shape& aFace = itl.Value();
788 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
792 aName += "|" + aFaceName;
799 // aDoc->addNamingName(selectionLabel(), aName);
800 // the selected sub-shape will not be shared and as result it will not require registration
805 TopAbs_ShapeEnum translateType (const std::string& theType)
807 // map from the textual shape types to OCCT enumeration
808 static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
809 if (MyShapeTypes.size() == 0) {
810 MyShapeTypes["face"] = TopAbs_FACE;
811 MyShapeTypes["faces"] = TopAbs_FACE;
812 MyShapeTypes["vertex"] = TopAbs_VERTEX;
813 MyShapeTypes["vertices"] = TopAbs_VERTEX;
814 MyShapeTypes["wire"] = TopAbs_WIRE;
815 MyShapeTypes["edge"] = TopAbs_EDGE;
816 MyShapeTypes["edges"] = TopAbs_EDGE;
817 MyShapeTypes["shell"] = TopAbs_SHELL;
818 MyShapeTypes["solid"] = TopAbs_SOLID;
819 MyShapeTypes["solids"] = TopAbs_SOLID;
820 MyShapeTypes["FACE"] = TopAbs_FACE;
821 MyShapeTypes["FACES"] = TopAbs_FACE;
822 MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
823 MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
824 MyShapeTypes["WIRE"] = TopAbs_WIRE;
825 MyShapeTypes["EDGE"] = TopAbs_EDGE;
826 MyShapeTypes["EDGES"] = TopAbs_EDGE;
827 MyShapeTypes["SHELL"] = TopAbs_SHELL;
828 MyShapeTypes["SOLID"] = TopAbs_SOLID;
829 MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
831 if (MyShapeTypes.find(theType) != MyShapeTypes.end())
832 return MyShapeTypes[theType];
833 Events_Error::send("Shape type defined in XML is not implemented!");
837 const TopoDS_Shape getShapeFromCompound(const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
839 TopoDS_Shape aSelection;
840 std::string::size_type n = theSubShapeName.rfind('/');
841 if (n == std::string::npos) n = 0;
842 std::string aSubString = theSubShapeName.substr(n + 1);
843 n = aSubString.rfind('_');
844 if (n == std::string::npos) return aSelection;
845 aSubString = aSubString.substr(n+1);
846 int indx = atoi(aSubString.c_str());
847 TopoDS_Iterator it(theCompound);
848 for (int i = 1;it.More();it.Next(), i++) {
850 aSelection = it.Value();
858 const TopoDS_Shape findFaceByName(const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
861 std::string::size_type n, nb = theSubShapeName.rfind('/');
862 if (nb == std::string::npos) nb = 0;
863 std::string aSubString = theSubShapeName.substr(nb + 1);
864 n = aSubString.rfind('_');
865 if (n != std::string::npos) {
866 std::string aSubStr2 = aSubString.substr(0, n);
867 aSubString = theSubShapeName.substr(0, nb + 1);
868 aSubString = aSubString + aSubStr2;
870 aSubString = theSubShapeName;
872 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
873 if(aLabel.IsNull()) return aFace;
874 Handle(TNaming_NamedShape) aNS;
875 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
876 const TopoDS_Shape& aShape = aNS->Get();
877 if(!aShape.IsNull()) {
878 if(aShape.ShapeType() == TopAbs_COMPOUND)
879 aFace = getShapeFromCompound(theSubShapeName, aShape);
887 int ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
889 std::string aName = theSubShapeName;
890 std::string aLastName;
891 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
892 while ((n2 = aName.find('|', n1)) != std::string::npos) {
893 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
894 theList.push_back(aName1);
896 aLastName = aName.substr(n1);
898 if(!aLastName.empty())
899 theList.push_back(aLastName);
900 return theList.size();
903 const TopoDS_Shape findCommonShape(const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
906 std::vector<TopTools_MapOfShape> aVec;
907 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
908 if(theList.Extent() > 1) {
909 aVec.push_back(aMap1);
910 aVec.push_back(aMap2);
912 if(theList.Extent() > 2)
913 aVec.push_back(aMap3);
914 if(theList.Extent() == 4)
915 aVec.push_back(aMap4);
918 TopTools_ListIteratorOfListOfShape it(theList);
919 for(int i = 0;it.More();it.Next(),i++) {
920 const TopoDS_Shape& aFace = it.Value();
922 TopExp_Explorer anExp (aFace, theType);
923 for(;anExp.More();anExp.Next()) {
924 const TopoDS_Shape& anEdge = anExp.Current();
925 if (!anEdge.IsNull())
926 aVec[i].Add(anExp.Current());
929 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
930 for(;anExp.More();anExp.Next()) {
931 const TopoDS_Shape& aVertex = anExp.Current();
932 if (!aVertex.IsNull())
933 aVec[i].Add(anExp.Current());
937 //trivial case: 2 faces
938 TopTools_ListOfShape aList;
939 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
940 for(;it2.More();it2.Next()) {
941 if(aVec[1].Contains(it2.Key())) {
943 if(theList.Extent() == 2)
946 aList.Append(it2.Key());
949 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
950 if(aVec[2].Extent() && aVec[3].Extent()) {
951 TopTools_ListIteratorOfListOfShape it(aList);
952 for(;it.More();it.Next()) {
953 const TopoDS_Shape& aCand = it.Value();
954 // not yet completelly implemented, to be rechecked
955 TopoDS_Vertex aV1, aV2;
956 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
958 if(aVec[2].Contains(aV1)) aNum++;
959 else if(aVec[2].Contains(aV2)) aNum++;
960 if(aVec[3].Contains(aV1)) aNum++;
961 else if(aVec[3].Contains(aV2)) aNum++;
970 if(aList.Extent() && aVec.size() == 3) {
972 TopTools_ListIteratorOfListOfShape it(aList);
973 for(;it.More();it.Next()) {
974 const TopoDS_Shape& aCand = it.Value();
975 if(aVec[2].Contains(aCand)) {
984 std::string getContextName(const std::string& theSubShapeName)
987 std::string::size_type n = theSubShapeName.find('/');
988 if (n == std::string::npos) return aName;
989 aName = theSubShapeName.substr(0, n);
992 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
993 void Model_AttributeSelection::selectSubShape(const std::string& theType, const std::string& theSubShapeName)
995 if(theSubShapeName.empty() || theType.empty()) return;
996 TopAbs_ShapeEnum aType = translateType(theType);
997 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(owner()->document());//std::dynamic_pointer_cast<Model_Document>(aCont->document());
998 std::string aContName = getContextName(theSubShapeName);
999 if(aContName.empty()) return;
1000 //ResultPtr aCont = context();
1001 ResultPtr aCont = aDoc->findByName(aContName);
1002 if(!aCont.get() || aCont->shape()->isNull()) return;
1003 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
1004 TopAbs_ShapeEnum aContType = aContext.ShapeType();
1005 if(aType <= aContType) return; // not applicable
1008 TopoDS_Shape aSelection;
1011 case TopAbs_COMPOUND:
1013 case TopAbs_COMPSOLID:
1021 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1022 if(!aSelection.IsNull()) {// Select it
1023 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1024 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1025 setValue(aCont, aShapeToBeSelected);
1033 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1034 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1035 if(!aLabel.IsNull()) {
1036 Handle(TNaming_NamedShape) aNS;
1037 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1038 const TopoDS_Shape& aShape = aNS->Get();
1039 if(!aShape.IsNull()) {
1040 if(aShape.ShapeType() == TopAbs_COMPOUND)
1041 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1043 aSelection = aShape;
1047 if(aSelection.IsNull()) {
1048 std::list<std::string> aListofNames;
1049 int n = ParseName(theSubShapeName, aListofNames);
1050 if(n > 1 && n < 5) {
1051 TopTools_ListOfShape aList;
1052 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1053 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1054 aList.Append(aFace);
1056 aSelection = findCommonShape(TopAbs_EDGE, aList);
1059 if(!aSelection.IsNull()) {// Select it
1060 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1061 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1062 setValue(aCont, aShapeToBeSelected);
1068 TopoDS_Shape aSelection;
1069 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1070 if(!aLabel.IsNull()) {
1071 Handle(TNaming_NamedShape) aNS;
1072 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1073 const TopoDS_Shape& aShape = aNS->Get();
1074 if(!aShape.IsNull()) {
1075 if(aShape.ShapeType() == TopAbs_COMPOUND)
1076 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1078 aSelection = aShape;
1082 if(aSelection.IsNull()) {
1083 std::list<std::string> aListofNames;
1084 int n = ParseName(theSubShapeName, aListofNames);
1085 if(n > 1 && n < 4) { // 2 || 3
1086 TopTools_ListOfShape aList;
1087 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1088 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1090 aList.Append(aFace);
1092 aSelection = findCommonShape(TopAbs_VERTEX, aList);
1095 if(!aSelection.IsNull()) {// Select it
1096 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1097 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1098 setValue(aCont, aShapeToBeSelected);
1102 default: //TopAbs_SHAPE
1108 int Model_AttributeSelection::Id()
1110 std::shared_ptr<GeomAPI_Shape> aSelection = value();
1111 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1112 const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1113 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1115 if (aSelection && !aSelection->isNull() &&
1116 aContext && !aContext->isNull())
1118 TopTools_IndexedMapOfShape aSubShapesMap;
1119 TopExp::MapShapes(aMainShape, aSubShapesMap);
1120 anID = aSubShapesMap.FindIndex(aSubShape);