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 <GeomAlgoAPI_SketchBuilder.h>
19 #include <Events_Error.h>
21 #include <TNaming_Selector.hxx>
22 #include <TNaming_NamedShape.hxx>
23 #include <TNaming_Tool.hxx>
24 #include <TNaming_Builder.hxx>
25 #include <TNaming_Localizer.hxx>
26 #include <TopoDS_Shape.hxx>
27 #include <TopoDS_Compound.hxx>
28 #include <TDataStd_IntPackedMap.hxx>
29 #include <TDataStd_Integer.hxx>
30 #include <TDataStd_UAttribute.hxx>
31 #include <TDataStd_Name.hxx>
32 #include <TopTools_MapOfShape.hxx>
33 #include <TopTools_IndexedMapOfShape.hxx>
34 #include <TopTools_MapIteratorOfMapOfShape.hxx>
35 #include <TopTools_ListOfShape.hxx>
36 #include <TopExp_Explorer.hxx>
37 #include <TDF_LabelMap.hxx>
38 #include <BRep_Tool.hxx>
39 #include <BRep_Builder.hxx>
40 #include <TopoDS_Edge.hxx>
43 #include <TColStd_MapOfTransient.hxx>
44 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_ListIteratorOfListOfShape.hxx>
46 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
48 #include <Precision.hxx>
49 #include <TDF_ChildIterator.hxx>
50 #include <TDF_ChildIDIterator.hxx>
51 #include <TDataStd_Name.hxx>
52 #include <TopAbs_ShapeEnum.hxx>
53 #include <TopoDS_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);
89 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
90 // do not select the whole shape for body:it is already must be in the data framework
91 if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
92 aSelLab.ForgetAllAttributes(true);
93 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
95 selectBody(theContext, theSubShape);
97 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
98 if (!theSubShape.get()) {
99 // to sub, so the whole result is selected
100 aSelLab.ForgetAllAttributes(true);
101 TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
103 selectConstruction(theContext, theSubShape);
106 myIsInitialized = true;
108 std::string aSelName = namingName();
109 if(!aSelName.empty())
110 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
113 //selectSubShape("FACE", "Extrusion_1/LateralFace_3");
114 //selectSubShape("FACE", "Extrusion_1/TopFace");
115 //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
116 //selectSubShape("EDGE", "Sketch_1/Edge_6");
118 owner()->data()->sendAttributeUpdated(this);
121 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
123 std::shared_ptr<GeomAPI_Shape> aResult;
124 if (myIsInitialized) {
125 TDF_Label aSelLab = selectionLabel();
126 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
127 ResultPtr aContext = context();
129 return aResult; // empty result
130 return aContext->shape();
132 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
133 return aResult; // empty result
136 Handle(TNaming_NamedShape) aSelection;
137 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
138 TopoDS_Shape aSelShape = aSelection->Get();
139 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
140 aResult->setImpl(new TopoDS_Shape(aSelShape));
141 } else { // for simple construction element: just shape of this construction element
142 ResultConstructionPtr aConstr =
143 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
145 return aConstr->shape();
152 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
155 myIsInitialized = myRef.isInitialized();
158 ResultPtr Model_AttributeSelection::context() {
159 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
163 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
165 ModelAPI_AttributeSelection::setObject(theObject);
166 myRef.setObject(theObject);
169 TDF_LabelMap& Model_AttributeSelection::scope()
171 if (myScope.IsEmpty()) { // create a new scope if not yet done
172 // gets all labels with named shapes that are bofore this feature label (before in history)
173 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
174 owner()->data())->label().Father();
175 int aFeatureID = aFeatureLab.Tag();
176 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
177 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
178 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
180 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
181 for(; aNSIter.More(); aNSIter.Next()) {
182 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
183 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
184 myScope.Add(aNS->Label());
192 bool Model_AttributeSelection::update()
194 ResultPtr aContext = context();
195 if (!aContext.get()) return false;
196 TDF_Label aSelLab = selectionLabel();
197 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
198 return aContext->shape() && !aContext->shape()->isNull();
200 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
201 return aContext->shape() && !aContext->shape()->isNull();
204 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
205 // body: just a named shape, use selection mechanism from OCCT
206 TNaming_Selector aSelector(aSelLab);
207 bool aResult = aSelector.Solve(scope()) == Standard_True;
208 owner()->data()->sendAttributeUpdated(this);
210 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
211 // construction: identification by the results indexes, recompute faces and
212 // take the face that more close by the indexes
213 std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr =
214 std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(
215 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext)->shape());
216 if (aWirePtr && aWirePtr->hasPlane()) { // sketch sub-element
217 TDF_Label aLab = myRef.myRef->Label();
218 // getting a type of selected shape
219 Handle(TDataStd_Integer) aTypeAttr;
220 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
223 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
224 // selected indexes will be needed in each "if"
225 Handle(TDataStd_IntPackedMap) aSubIds;
226 std::shared_ptr<GeomAPI_Shape> aNewSelected;
228 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
229 // for now working only with composite features
230 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
231 CompositeFeaturePtr aComposite =
232 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
233 if (!aComposite || aComposite->numberOfSubs() == 0) {
237 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
238 // If this is a wire with plane defined thin it is a sketch-like object
239 std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
240 GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
241 aWirePtr->dirY(), aWirePtr->norm(), aWirePtr, aFaces);
242 if (aFaces.empty()) // no faces, update can not work correctly
244 // if there is no edges indexes, any face can be used: take the first
245 std::shared_ptr<GeomAPI_Shape> aNewSelected;
247 aNewSelected = *(aFaces.begin());
248 } else { // searching for most looks-like initial face by the indexes
249 // prepare edges of the current resut for the fast searching
250 TColStd_MapOfTransient allCurves;
251 const int aSubNum = aComposite->numberOfSubs();
252 for(int a = 0; a < aSubNum; a++) {
253 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
254 FeaturePtr aSub = aComposite->subFeature(a);
255 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
256 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
257 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
258 ResultConstructionPtr aConstr =
259 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
260 if (aConstr->shape() && aConstr->shape()->isEdge()) {
261 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
262 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
263 if (!anEdge.IsNull()) {
264 Standard_Real aFirst, aLast;
265 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
266 allCurves.Add(aCurve);
272 // iterate new result faces and searching for these edges
273 std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFacesIter = aFaces.begin();
274 double aBestFound = 0; // best percentage of found edges
275 for(; aFacesIter != aFaces.end(); aFacesIter++) {
276 int aFound = 0, aNotFound = 0;
277 TopExp_Explorer anEdgesExp((*aFacesIter)->impl<TopoDS_Shape>(), TopAbs_EDGE);
278 for(; anEdgesExp.More(); anEdgesExp.Next()) {
279 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
280 if (!anEdge.IsNull()) {
281 Standard_Real aFirst, aLast;
282 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
283 if (allCurves.Contains(aCurve)) {
290 if (aFound + aNotFound != 0) {
291 double aPercentage = double(aFound) / double(aFound + aNotFound);
292 if (aPercentage > aBestFound) {
293 aBestFound = aPercentage;
294 aNewSelected = *aFacesIter;
299 if (aNewSelected) { // store this new selection
300 selectConstruction(aContext, aNewSelected);
301 owner()->data()->sendAttributeUpdated(this);
304 } else if (aShapeType == TopAbs_EDGE) {
305 // just reselect the edge by the id
306 const int aSubNum = aComposite->numberOfSubs();
307 for(int a = 0; a < aSubNum; a++) {
308 // if aSubIds take any, the first appropriate
309 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
310 // found the appropriate feature
311 FeaturePtr aFeature = aComposite->subFeature(a);
312 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
313 aFeature->results().cbegin();
314 for(;aResIter != aFeature->results().cend(); aResIter++) {
315 ResultConstructionPtr aRes =
316 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
317 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
318 selectConstruction(aContext, aRes->shape());
319 owner()->data()->sendAttributeUpdated(this);
325 } else if (aShapeType == TopAbs_VERTEX) {
326 // just reselect the vertex by the id of edge
327 const int aSubNum = aComposite->numberOfSubs();
328 for(int a = 0; a < aSubNum; a++) {
329 // if aSubIds take any, the first appropriate
330 int aFeatureID = aComposite->subFeatureId(a);
331 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
332 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
333 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
334 // searching for deltas
336 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
337 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
338 // found the feature with appropriate edge
339 FeaturePtr aFeature = aComposite->subFeature(a);
340 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
341 aFeature->results().cbegin();
342 for(;aResIter != aFeature->results().cend(); aResIter++) {
343 ResultConstructionPtr aRes =
344 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
345 if (aRes && aRes->shape()) {
346 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
347 selectConstruction(aContext, aRes->shape());
348 owner()->data()->sendAttributeUpdated(this);
350 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
351 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
353 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
354 if (aVIndex == aVertexNum) { // found!
355 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
356 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
357 selectConstruction(aContext, aVertex);
358 owner()->data()->sendAttributeUpdated(this);
369 } else { // simple construction element: the selected is that needed
370 selectConstruction(aContext, aContext->shape());
371 owner()->data()->sendAttributeUpdated(this);
375 return false; // unknown case
379 void Model_AttributeSelection::selectBody(
380 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
382 // perform the selection
383 TNaming_Selector aSel(selectionLabel());
384 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
385 TopoDS_Shape aContext;
387 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
389 aContext = aBody->shape()->impl<TopoDS_Shape>();
391 ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
393 aContext = aConstr->shape()->impl<TopoDS_Shape>();
395 Events_Error::send("A result with shape is expected");
399 //BRepTools::Write(aNewShape, "Selection0.brep");
400 aSel.Select(aNewShape, aContext);
403 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
404 /// if theID is zero,
405 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
406 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
407 std::string theAdditionalName,
408 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
410 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
411 TNaming_Builder aBuilder(aLab);
412 aBuilder.Generated(theShape);
413 std::stringstream aName;
414 aName<<theContextFeature->name()<<"/";
415 if (!theAdditionalName.empty())
416 aName<<theAdditionalName<<"/";
417 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
418 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
419 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
421 if (theRefs.IsNull()) {
423 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
424 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
425 for(; aRef.More(); aRef.Next()) {
426 aName<<"-"<<aRef.Key();
430 theDoc->addNamingName(aLab, aName.str());
431 TDataStd_Name::Set(aLab, aName.str().c_str());
434 void Model_AttributeSelection::selectConstruction(
435 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
437 std::shared_ptr<Model_Document> aMyDoc =
438 std::dynamic_pointer_cast<Model_Document>(owner()->document());
439 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
440 CompositeFeaturePtr aComposite =
441 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
442 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
443 if (!aComposite || aComposite->numberOfSubs() == 0) {
444 // saving of context is enough: result construction contains exactly the needed shape
445 TNaming_Builder aBuilder(selectionLabel());
446 aBuilder.Generated(aSubShape);
447 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
448 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
451 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
452 TDF_Label aLab = myRef.myRef->Label();
453 // identify the reuslts of sub-object of the composite by edges
454 // save type of the selected shape in integer attribute
455 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
456 TDataStd_Integer::Set(aLab, (int)aShapeType);
458 TColStd_MapOfTransient allCurves;
459 if (aShapeType == TopAbs_VERTEX) { // compare positions
460 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
462 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
463 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
464 Standard_Real aFirst, aLast;
465 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
466 allCurves.Add(aCurve);
469 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
470 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
472 const int aSubNum = aComposite->numberOfSubs();
473 for(int a = 0; a < aSubNum; a++) {
474 FeaturePtr aSub = aComposite->subFeature(a);
475 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
476 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
477 // there may be many shapes (circle and center): register if at least one is in selection
478 for(; aRes != aResults.cend(); aRes++) {
479 ResultConstructionPtr aConstr =
480 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
481 if (!aConstr->shape()) {
484 if (aShapeType == TopAbs_VERTEX) {
485 if (aConstr->shape()->isVertex()) { // compare vertices positions
486 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
487 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
488 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
489 aRefs->Add(aComposite->subFeatureId(a));
491 } else { // get first or last vertex of the edge: last is stored with negative sign
492 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
493 int aDelta = kSTART_VERTEX_DELTA;
494 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
495 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
496 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
497 aRefs->Add(aDelta + aComposite->subFeatureId(a));
500 aDelta += kSTART_VERTEX_DELTA;
504 if (aConstr->shape()->isEdge()) {
505 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
506 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
507 if (!anEdge.IsNull()) {
508 Standard_Real aFirst, aLast;
509 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
510 if (allCurves.Contains(aCurve)) {
511 int anID = aComposite->subFeatureId(a);
513 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
514 // add edges to sub-label to support naming for edges selection
515 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
516 for(; anEdgeExp.More(); anEdgeExp.Next()) {
517 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
518 Standard_Real aFirst, aLast;
519 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
520 if (aFaceCurve == aCurve) {
521 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
524 } else { // put vertices of the selected edge to sub-labels
525 // add edges to sub-label to support naming for edges selection
526 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
527 int aTagIndex = anID + kSTART_VERTEX_DELTA;
528 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
529 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
531 std::stringstream anAdditionalName;
532 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
542 // store the selected as primitive
543 TNaming_Builder aBuilder(selectionLabel());
544 aBuilder.Generated(aSubShape);
545 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
548 TDF_Label Model_AttributeSelection::selectionLabel()
550 return myRef.myRef->Label().FindChild(1);
554 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
555 const TDF_Label& theLabel)
558 // check if the subShape is already in DF
559 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
560 Handle(TDataStd_Name) anAttr;
561 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
562 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
563 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
565 const TDF_Label& aLabel = theDoc->findNamingName(aName);
566 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
567 if(!aLabel.IsEqual(aNS->Label())) {
568 //aName.erase(); //something is wrong, to be checked!!!
569 aName += "_SomethingWrong";
572 const TopoDS_Shape& aShape = aNS->Get();
573 if(aShape.ShapeType() == TopAbs_COMPOUND) {
574 std::string aPostFix("_");
575 TopoDS_Iterator it(aShape);
576 for (int i = 1;it.More();it.Next(), i++) {
577 if(it.Value() == theShape) {
578 aPostFix += TCollection_AsciiString (i).ToCString();
591 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
593 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
594 TopoDS_Compound aCmp;
596 BB.MakeCompound(aCmp);
597 TopTools_ListIteratorOfListOfShape it(theAncestors);
598 for(;it.More();it.Next()) {
599 BB.Add(aCmp, it.Value());
600 theSMap.Add(it.Value());
603 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
604 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
605 for (int i = 1; i <= aMap2.Extent(); i++) {
606 const TopoDS_Shape& aKey = aMap2.FindKey(i);
607 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
608 if(anAncestors.Extent() > 1) aNumber++;
610 if(aNumber > 1) return false;
613 std::string Model_AttributeSelection::namingName()
615 std::string aName("");
616 if(!this->isInitialized()) return aName;
617 Handle(TDataStd_Name) anAtt;
618 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
619 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
623 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
624 ResultPtr aCont = context();
625 aName = "Undefined name";
626 if(!aCont.get() || aCont->shape()->isNull())
628 if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
629 return aCont->data()->name();
631 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
632 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
634 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
635 BRepTools::Write(aSubShape, "Selection.brep");
636 BRepTools::Write(aContext, "Context.brep");
639 std::shared_ptr<Model_Document> aDoc =
640 std::dynamic_pointer_cast<Model_Document>(aCont->document());
642 // check if the subShape is already in DF
643 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
644 if(aName.empty() ) { // not in the document!
645 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
648 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
652 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
653 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
654 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
655 aName = "Degenerated_Edge";
658 TopTools_IndexedDataMapOfShapeListOfShape aMap;
659 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
660 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
661 bool isTrivialCase(true);
662 /* for (int i = 1; i <= aMap.Extent(); i++) {
663 const TopoDS_Shape& aKey = aMap.FindKey(i);
664 //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
665 if (aKey.IsSame(aSubShape)) continue;
666 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
667 // check that it is not a trivial case (F1 & F2: aNumber = 1)
668 isTrivialCase = isTrivial(anAncestors, aSMap);
671 if(aMap.Contains(aSubShape)) {
672 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
673 // check that it is not a trivial case (F1 & F2: aNumber = 1)
674 isTrivialCase = isTrivial(anAncestors, aSMap);
677 TopTools_ListOfShape aListOfNbs;
678 if(!isTrivialCase) { // find Neighbors
679 TNaming_Localizer aLocalizer;
680 TopTools_MapOfShape aMap3;
681 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
682 //int n = aMap3.Extent();
683 TopTools_MapIteratorOfMapOfShape it(aMap3);
684 for(;it.More();it.Next()) {
685 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
686 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
687 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
688 TopTools_ListIteratorOfListOfShape it2(aList);
689 for(;it2.More();it2.Next()) {
690 if(aSMap.Contains(it2.Value())) continue; // skip this Face
691 aListOfNbs.Append(it2.Value());
694 } // else a trivial case
696 // build name of the sub-shape Edge
697 for(int i=1; i <= aSMap.Extent(); i++) {
698 const TopoDS_Shape& aFace = aSMap.FindKey(i);
699 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
703 aName += "|" + aFaceName;
705 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
706 for (;itl.More();itl.Next()) {
707 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
708 aName += "|" + aFaceName;
714 // name structure (Monifold Topology):
715 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
716 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
717 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
718 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
719 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
720 // or compound of 2 open faces.
721 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
722 // two independent edges (wire or compound)
723 // implemented 2 first cases
725 TopTools_IndexedDataMapOfShapeListOfShape aMap;
726 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
727 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
728 TopTools_ListOfShape aList;
729 TopTools_MapOfShape aFMap;
731 //int n = aList2.Extent(); //bug! duplication
733 TopTools_ListIteratorOfListOfShape itl2(aList2);
734 for (int i = 1;itl2.More();itl2.Next(),i++) {
735 if(aFMap.Add(itl2.Value()))
736 aList.Append(itl2.Value());
738 //n = aList.Extent();
740 int n = aList.Extent();
741 if(n < 3) { // open topology case or Compound case => via edges
742 TopTools_IndexedDataMapOfShapeListOfShape aMap;
743 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
744 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
745 if(aList22.Extent() >= 2) { // regular solution
748 // bug! duplication; fix is below
750 TopTools_ListOfShape aListE;
751 TopTools_ListIteratorOfListOfShape itl2(aList22);
752 for (int i = 1;itl2.More();itl2.Next(),i++) {
753 if(aFMap.Add(itl2.Value()))
754 aListE.Append(itl2.Value());
758 TopTools_ListIteratorOfListOfShape itl(aListE);
759 for (int i = 1;itl.More();itl.Next(),i++) {
760 const TopoDS_Shape& anEdge = itl.Value();
761 std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
765 aName += "|" + anEdgeName;
768 else { // dangle vertex: if(aList22.Extent() == 1)
769 //it should be already in DF
773 TopTools_ListIteratorOfListOfShape itl(aList);
774 for (int i = 1;itl.More();itl.Next(),i++) {
775 const TopoDS_Shape& aFace = itl.Value();
776 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
780 aName += "|" + aFaceName;
787 // aDoc->addNamingName(selectionLabel(), aName);
788 // the selected sub-shape will not be shared and as result it will not require registration
793 TopAbs_ShapeEnum translateType (const std::string& theType)
795 // map from the textual shape types to OCCT enumeration
796 static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
797 if (MyShapeTypes.size() == 0) {
798 MyShapeTypes["face"] = TopAbs_FACE;
799 MyShapeTypes["faces"] = TopAbs_FACE;
800 MyShapeTypes["vertex"] = TopAbs_VERTEX;
801 MyShapeTypes["vertices"] = TopAbs_VERTEX;
802 MyShapeTypes["wire"] = TopAbs_WIRE;
803 MyShapeTypes["edge"] = TopAbs_EDGE;
804 MyShapeTypes["edges"] = TopAbs_EDGE;
805 MyShapeTypes["shell"] = TopAbs_SHELL;
806 MyShapeTypes["solid"] = TopAbs_SOLID;
807 MyShapeTypes["solids"] = TopAbs_SOLID;
808 MyShapeTypes["FACE"] = TopAbs_FACE;
809 MyShapeTypes["FACES"] = TopAbs_FACE;
810 MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
811 MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
812 MyShapeTypes["WIRE"] = TopAbs_WIRE;
813 MyShapeTypes["EDGE"] = TopAbs_EDGE;
814 MyShapeTypes["EDGES"] = TopAbs_EDGE;
815 MyShapeTypes["SHELL"] = TopAbs_SHELL;
816 MyShapeTypes["SOLID"] = TopAbs_SOLID;
817 MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
819 if (MyShapeTypes.find(theType) != MyShapeTypes.end())
820 return MyShapeTypes[theType];
821 Events_Error::send("Shape type defined in XML is not implemented!");
825 const TopoDS_Shape getShapeFromCompound(const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
827 TopoDS_Shape aSelection;
828 std::string::size_type n = theSubShapeName.rfind('/');
829 if (n == std::string::npos) n = 0;
830 std::string aSubString = theSubShapeName.substr(n + 1);
831 n = aSubString.rfind('_');
832 if (n == std::string::npos) return aSelection;
833 aSubString = aSubString.substr(n+1);
834 int indx = atoi(aSubString.c_str());
835 TopoDS_Iterator it(theCompound);
836 for (int i = 1;it.More();it.Next(), i++) {
838 aSelection = it.Value();
846 const TopoDS_Shape findFaceByName(const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
849 std::string::size_type n, nb = theSubShapeName.rfind('/');
850 if (nb == std::string::npos) nb = 0;
851 std::string aSubString = theSubShapeName.substr(nb + 1);
852 n = aSubString.rfind('_');
853 if (n != std::string::npos) {
854 std::string aSubStr2 = aSubString.substr(0, n);
855 aSubString = theSubShapeName.substr(0, nb + 1);
856 aSubString = aSubString + aSubStr2;
858 aSubString = theSubShapeName;
860 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
861 if(aLabel.IsNull()) return aFace;
862 Handle(TNaming_NamedShape) aNS;
863 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
864 const TopoDS_Shape& aShape = aNS->Get();
865 if(!aShape.IsNull()) {
866 if(aShape.ShapeType() == TopAbs_COMPOUND)
867 aFace = getShapeFromCompound(theSubShapeName, aShape);
875 int ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
877 std::string aName = theSubShapeName;
878 std::string aLastName;
879 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
880 while ((n2 = aName.find('|', n1)) != std::string::npos) {
881 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
882 theList.push_back(aName1);
884 aLastName = aName.substr(n1);
886 if(!aLastName.empty())
887 theList.push_back(aLastName);
888 return theList.size();
891 const TopoDS_Shape findCommonShape(const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
894 std::vector<TopTools_MapOfShape> aVec;
895 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
896 if(theList.Extent() > 1) {
897 aVec.push_back(aMap1);
898 aVec.push_back(aMap2);
900 if(theList.Extent() > 2)
901 aVec.push_back(aMap3);
902 if(theList.Extent() == 4)
903 aVec.push_back(aMap4);
906 TopTools_ListIteratorOfListOfShape it(theList);
907 for(int i = 0;it.More();it.Next(),i++) {
908 const TopoDS_Shape& aFace = it.Value();
910 TopExp_Explorer anExp (aFace, theType);
911 for(;anExp.More();anExp.Next()) {
912 const TopoDS_Shape& anEdge = anExp.Current();
913 if (!anEdge.IsNull())
914 aVec[i].Add(anExp.Current());
917 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
918 for(;anExp.More();anExp.Next()) {
919 const TopoDS_Shape& aVertex = anExp.Current();
920 if (!aVertex.IsNull())
921 aVec[i].Add(anExp.Current());
925 //trivial case: 2 faces
926 TopTools_ListOfShape aList;
927 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
928 for(;it2.More();it2.Next()) {
929 if(aVec[1].Contains(it2.Key())) {
931 if(theList.Extent() == 2)
934 aList.Append(it2.Key());
937 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
938 if(aVec[2].Extent() && aVec[3].Extent()) {
939 TopTools_ListIteratorOfListOfShape it(aList);
940 for(;it.More();it.Next()) {
941 const TopoDS_Shape& aCand = it.Value();
942 // not yet completelly implemented, to be rechecked
943 TopoDS_Vertex aV1, aV2;
944 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
946 if(aVec[2].Contains(aV1)) aNum++;
947 else if(aVec[2].Contains(aV2)) aNum++;
948 if(aVec[3].Contains(aV1)) aNum++;
949 else if(aVec[3].Contains(aV2)) aNum++;
958 if(aList.Extent() && aVec.size() == 3) {
960 TopTools_ListIteratorOfListOfShape it(aList);
961 for(;it.More();it.Next()) {
962 const TopoDS_Shape& aCand = it.Value();
963 if(aVec[2].Contains(aCand)) {
972 std::string getContextName(const std::string& theSubShapeName)
975 std::string::size_type n = theSubShapeName.find('/');
976 if (n == std::string::npos) return aName;
977 aName = theSubShapeName.substr(0, n);
980 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
981 void Model_AttributeSelection::selectSubShape(const std::string& theType, const std::string& theSubShapeName)
983 if(theSubShapeName.empty() || theType.empty()) return;
984 TopAbs_ShapeEnum aType = translateType(theType);
985 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(owner()->document());//std::dynamic_pointer_cast<Model_Document>(aCont->document());
986 std::string aContName = getContextName(theSubShapeName);
987 if(aContName.empty()) return;
988 //ResultPtr aCont = context();
989 ResultPtr aCont = aDoc->findByName(aContName);
990 if(!aCont.get() || aCont->shape()->isNull()) return;
991 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
992 TopAbs_ShapeEnum aContType = aContext.ShapeType();
993 if(aType <= aContType) return; // not applicable
996 TopoDS_Shape aSelection;
999 case TopAbs_COMPOUND:
1001 case TopAbs_COMPSOLID:
1009 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1010 if(!aSelection.IsNull()) {// Select it
1011 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1012 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1013 setValue(aCont, aShapeToBeSelected);
1021 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1022 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1023 if(!aLabel.IsNull()) {
1024 Handle(TNaming_NamedShape) aNS;
1025 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1026 const TopoDS_Shape& aShape = aNS->Get();
1027 if(!aShape.IsNull()) {
1028 if(aShape.ShapeType() == TopAbs_COMPOUND)
1029 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1031 aSelection = aShape;
1035 if(aSelection.IsNull()) {
1036 std::list<std::string> aListofNames;
1037 int n = ParseName(theSubShapeName, aListofNames);
1038 if(n > 1 && n < 5) {
1039 TopTools_ListOfShape aList;
1040 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1041 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1042 aList.Append(aFace);
1044 aSelection = findCommonShape(TopAbs_EDGE, aList);
1047 if(!aSelection.IsNull()) {// Select it
1048 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1049 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1050 setValue(aCont, aShapeToBeSelected);
1056 TopoDS_Shape aSelection;
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 const TopoDS_Shape& aShape = aNS->Get();
1062 if(!aShape.IsNull()) {
1063 if(aShape.ShapeType() == TopAbs_COMPOUND)
1064 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1066 aSelection = aShape;
1070 if(aSelection.IsNull()) {
1071 std::list<std::string> aListofNames;
1072 int n = ParseName(theSubShapeName, aListofNames);
1073 if(n > 1 && n < 4) { // 2 || 3
1074 TopTools_ListOfShape aList;
1075 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1076 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1078 aList.Append(aFace);
1080 aSelection = findCommonShape(TopAbs_VERTEX, aList);
1083 if(!aSelection.IsNull()) {// Select it
1084 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1085 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1086 setValue(aCont, aShapeToBeSelected);
1090 default: //TopAbs_SHAPE
1096 int Model_AttributeSelection::Id()
1098 std::shared_ptr<GeomAPI_Shape> aSelection = value();
1099 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1100 const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1101 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1103 if (aSelection && !aSelection->isNull() &&
1104 aContext && !aContext->isNull())
1106 TopTools_IndexedMapOfShape aSubShapesMap;
1107 TopExp::MapShapes(aMainShape, aSubShapesMap);
1108 anID = aSubShapesMap.FindIndex(aSubShape);