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);
88 if (!theContext.get()) {
89 // to keep the reference attribute label
90 TDF_Label aRefLab = myRef.myRef->Label();
91 aSelLab.ForgetAllAttributes(true);
92 myRef.myRef = TDF_Reference::Set(aSelLab, aSelLab);
95 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
96 // do not select the whole shape for body:it is already must be in the data framework
97 if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
98 aSelLab.ForgetAllAttributes(true);
99 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
101 selectBody(theContext, theSubShape);
103 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
104 if (!theSubShape.get()) {
105 // to sub, so the whole result is selected
106 aSelLab.ForgetAllAttributes(true);
107 TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
109 selectConstruction(theContext, theSubShape);
112 myIsInitialized = true;
114 std::string aSelName = namingName();
115 if(!aSelName.empty())
116 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
119 //selectSubShape("FACE", "Extrusion_1/LateralFace_3");
120 //selectSubShape("FACE", "Extrusion_1/TopFace");
121 //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
122 //selectSubShape("EDGE", "Sketch_1/Edge_6");
124 owner()->data()->sendAttributeUpdated(this);
127 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
129 std::shared_ptr<GeomAPI_Shape> aResult;
130 if (myIsInitialized) {
131 TDF_Label aSelLab = selectionLabel();
132 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
133 ResultPtr aContext = context();
135 return aResult; // empty result
136 return aContext->shape();
138 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
139 return aResult; // empty result
142 Handle(TNaming_NamedShape) aSelection;
143 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
144 TopoDS_Shape aSelShape = aSelection->Get();
145 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
146 aResult->setImpl(new TopoDS_Shape(aSelShape));
147 } else { // for simple construction element: just shape of this construction element
148 ResultConstructionPtr aConstr =
149 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
151 return aConstr->shape();
158 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
161 myIsInitialized = myRef.isInitialized();
164 ResultPtr Model_AttributeSelection::context() {
165 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
169 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
171 ModelAPI_AttributeSelection::setObject(theObject);
172 myRef.setObject(theObject);
175 TDF_LabelMap& Model_AttributeSelection::scope()
177 if (myScope.IsEmpty()) { // create a new scope if not yet done
178 // gets all labels with named shapes that are bofore this feature label (before in history)
179 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
180 owner()->data())->label().Father();
181 int aFeatureID = aFeatureLab.Tag();
182 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
183 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
184 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
186 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
187 for(; aNSIter.More(); aNSIter.Next()) {
188 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
189 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
190 myScope.Add(aNS->Label());
198 bool Model_AttributeSelection::update()
200 ResultPtr aContext = context();
201 if (!aContext.get()) return false;
202 TDF_Label aSelLab = selectionLabel();
203 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
204 return aContext->shape() && !aContext->shape()->isNull();
206 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
207 return aContext->shape() && !aContext->shape()->isNull();
210 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
211 // body: just a named shape, use selection mechanism from OCCT
212 TNaming_Selector aSelector(aSelLab);
213 bool aResult = aSelector.Solve(scope()) == Standard_True;
214 owner()->data()->sendAttributeUpdated(this);
216 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
217 // construction: identification by the results indexes, recompute faces and
218 // take the face that more close by the indexes
219 ResultConstructionPtr aConstructionContext =
220 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
221 // sketch sub-element
222 if (aConstructionContext &&
223 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContext).get())
225 TDF_Label aLab = myRef.myRef->Label();
226 // getting a type of selected shape
227 Handle(TDataStd_Integer) aTypeAttr;
228 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
231 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
232 // selected indexes will be needed in each "if"
233 Handle(TDataStd_IntPackedMap) aSubIds;
234 std::shared_ptr<GeomAPI_Shape> aNewSelected;
236 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
237 // for now working only with composite features
238 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
239 CompositeFeaturePtr aComposite =
240 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
241 if (!aComposite || aComposite->numberOfSubs() == 0) {
245 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
246 // If this is a wire with plane defined thin it is a sketch-like object
247 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
249 // if there is no edges indexes, any face can be used: take the first
250 std::shared_ptr<GeomAPI_Shape> aNewSelected;
252 aNewSelected = aConstructionContext->face(0);
253 } else { // searching for most looks-like initial face by the indexes
254 // prepare edges of the current resut for the fast searching
255 TColStd_MapOfTransient allCurves;
256 const int aSubNum = aComposite->numberOfSubs();
257 for(int a = 0; a < aSubNum; a++) {
258 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
259 FeaturePtr aSub = aComposite->subFeature(a);
260 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
261 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
262 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
263 ResultConstructionPtr aConstr =
264 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
265 if (aConstr->shape() && aConstr->shape()->isEdge()) {
266 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
267 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
268 if (!anEdge.IsNull()) {
269 Standard_Real aFirst, aLast;
270 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
271 allCurves.Add(aCurve);
277 double aBestFound = 0; // best percentage of found edges
278 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
279 int aFound = 0, aNotFound = 0;
280 TopExp_Explorer anEdgesExp(
281 aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>(), TopAbs_EDGE);
282 for(; anEdgesExp.More(); anEdgesExp.Next()) {
283 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
284 if (!anEdge.IsNull()) {
285 Standard_Real aFirst, aLast;
286 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
287 if (allCurves.Contains(aCurve)) {
294 if (aFound + aNotFound != 0) {
295 double aPercentage = double(aFound) / double(aFound + aNotFound);
296 if (aPercentage > aBestFound) {
297 aBestFound = aPercentage;
298 aNewSelected = aConstructionContext->face(aFaceIndex);
303 if (aNewSelected) { // store this new selection
304 selectConstruction(aContext, aNewSelected);
305 owner()->data()->sendAttributeUpdated(this);
308 } else if (aShapeType == TopAbs_EDGE) {
309 // just reselect the edge by the id
310 const int aSubNum = aComposite->numberOfSubs();
311 for(int a = 0; a < aSubNum; a++) {
312 // if aSubIds take any, the first appropriate
313 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
314 // found the appropriate feature
315 FeaturePtr aFeature = aComposite->subFeature(a);
316 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
317 aFeature->results().cbegin();
318 for(;aResIter != aFeature->results().cend(); aResIter++) {
319 ResultConstructionPtr aRes =
320 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
321 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
322 selectConstruction(aContext, aRes->shape());
323 owner()->data()->sendAttributeUpdated(this);
329 } else if (aShapeType == TopAbs_VERTEX) {
330 // just reselect the vertex by the id of edge
331 const int aSubNum = aComposite->numberOfSubs();
332 for(int a = 0; a < aSubNum; a++) {
333 // if aSubIds take any, the first appropriate
334 int aFeatureID = aComposite->subFeatureId(a);
335 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
336 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
337 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
338 // searching for deltas
340 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
341 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
342 // found the feature with appropriate edge
343 FeaturePtr aFeature = aComposite->subFeature(a);
344 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
345 aFeature->results().cbegin();
346 for(;aResIter != aFeature->results().cend(); aResIter++) {
347 ResultConstructionPtr aRes =
348 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
349 if (aRes && aRes->shape()) {
350 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
351 selectConstruction(aContext, aRes->shape());
352 owner()->data()->sendAttributeUpdated(this);
354 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
355 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
357 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
358 if (aVIndex == aVertexNum) { // found!
359 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
360 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
361 selectConstruction(aContext, aVertex);
362 owner()->data()->sendAttributeUpdated(this);
373 } else { // simple construction element: the selected is that needed
374 selectConstruction(aContext, aContext->shape());
375 owner()->data()->sendAttributeUpdated(this);
379 return false; // unknown case
383 void Model_AttributeSelection::selectBody(
384 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
386 // perform the selection
387 TNaming_Selector aSel(selectionLabel());
388 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
389 TopoDS_Shape aContext;
391 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
393 aContext = aBody->shape()->impl<TopoDS_Shape>();
395 ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
397 aContext = aConstr->shape()->impl<TopoDS_Shape>();
399 Events_Error::send("A result with shape is expected");
403 //BRepTools::Write(aNewShape, "Selection0.brep");
404 aSel.Select(aNewShape, aContext);
407 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
408 /// if theID is zero,
409 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
410 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
411 std::string theAdditionalName,
412 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
414 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
415 TNaming_Builder aBuilder(aLab);
416 aBuilder.Generated(theShape);
417 std::stringstream aName;
418 aName<<theContextFeature->name()<<"/";
419 if (!theAdditionalName.empty())
420 aName<<theAdditionalName<<"/";
421 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
422 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
423 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
425 if (theRefs.IsNull()) {
427 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
428 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
429 for(; aRef.More(); aRef.Next()) {
430 aName<<"-"<<aRef.Key();
434 theDoc->addNamingName(aLab, aName.str());
435 TDataStd_Name::Set(aLab, aName.str().c_str());
438 void Model_AttributeSelection::selectConstruction(
439 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
441 std::shared_ptr<Model_Document> aMyDoc =
442 std::dynamic_pointer_cast<Model_Document>(owner()->document());
443 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
444 CompositeFeaturePtr aComposite =
445 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
446 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
447 if (!aComposite || aComposite->numberOfSubs() == 0) {
448 // saving of context is enough: result construction contains exactly the needed shape
449 TNaming_Builder aBuilder(selectionLabel());
450 aBuilder.Generated(aSubShape);
451 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
452 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
455 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
456 TDF_Label aLab = myRef.myRef->Label();
457 // identify the reuslts of sub-object of the composite by edges
458 // save type of the selected shape in integer attribute
459 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
460 TDataStd_Integer::Set(aLab, (int)aShapeType);
462 TColStd_MapOfTransient allCurves;
463 if (aShapeType == TopAbs_VERTEX) { // compare positions
464 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
466 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
467 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
468 Standard_Real aFirst, aLast;
469 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
470 allCurves.Add(aCurve);
473 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
474 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
476 const int aSubNum = aComposite->numberOfSubs();
477 for(int a = 0; a < aSubNum; a++) {
478 FeaturePtr aSub = aComposite->subFeature(a);
479 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
480 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
481 // there may be many shapes (circle and center): register if at least one is in selection
482 for(; aRes != aResults.cend(); aRes++) {
483 ResultConstructionPtr aConstr =
484 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
485 if (!aConstr->shape()) {
488 if (aShapeType == TopAbs_VERTEX) {
489 if (aConstr->shape()->isVertex()) { // compare vertices positions
490 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
491 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
492 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
493 aRefs->Add(aComposite->subFeatureId(a));
495 } else { // get first or last vertex of the edge: last is stored with negative sign
496 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
497 int aDelta = kSTART_VERTEX_DELTA;
498 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
499 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
500 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
501 aRefs->Add(aDelta + aComposite->subFeatureId(a));
504 aDelta += kSTART_VERTEX_DELTA;
508 if (aConstr->shape()->isEdge()) {
509 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
510 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
511 if (!anEdge.IsNull()) {
512 Standard_Real aFirst, aLast;
513 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
514 if (allCurves.Contains(aCurve)) {
515 int anID = aComposite->subFeatureId(a);
517 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
518 // add edges to sub-label to support naming for edges selection
519 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
520 for(; anEdgeExp.More(); anEdgeExp.Next()) {
521 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
522 Standard_Real aFirst, aLast;
523 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
524 if (aFaceCurve == aCurve) {
525 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
528 } else { // put vertices of the selected edge to sub-labels
529 // add edges to sub-label to support naming for edges selection
530 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
531 int aTagIndex = anID + kSTART_VERTEX_DELTA;
532 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
533 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
535 std::stringstream anAdditionalName;
536 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
546 // store the selected as primitive
547 TNaming_Builder aBuilder(selectionLabel());
548 aBuilder.Generated(aSubShape);
549 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
552 TDF_Label Model_AttributeSelection::selectionLabel()
554 return myRef.myRef->Label().FindChild(1);
558 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
559 const TDF_Label& theLabel)
562 // check if the subShape is already in DF
563 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
564 Handle(TDataStd_Name) anAttr;
565 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
566 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
567 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
569 const TDF_Label& aLabel = theDoc->findNamingName(aName);
570 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
571 if(!aLabel.IsEqual(aNS->Label())) {
572 //aName.erase(); //something is wrong, to be checked!!!
573 aName += "_SomethingWrong";
576 const TopoDS_Shape& aShape = aNS->Get();
577 if(aShape.ShapeType() == TopAbs_COMPOUND) {
578 std::string aPostFix("_");
579 TopoDS_Iterator it(aShape);
580 for (int i = 1;it.More();it.Next(), i++) {
581 if(it.Value() == theShape) {
582 aPostFix += TCollection_AsciiString (i).ToCString();
595 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
597 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
598 TopoDS_Compound aCmp;
600 BB.MakeCompound(aCmp);
601 TopTools_ListIteratorOfListOfShape it(theAncestors);
602 for(;it.More();it.Next()) {
603 BB.Add(aCmp, it.Value());
604 theSMap.Add(it.Value());
607 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
608 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
609 for (int i = 1; i <= aMap2.Extent(); i++) {
610 const TopoDS_Shape& aKey = aMap2.FindKey(i);
611 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
612 if(anAncestors.Extent() > 1) aNumber++;
614 if(aNumber > 1) return false;
617 std::string Model_AttributeSelection::namingName()
619 std::string aName("");
620 if(!this->isInitialized()) return aName;
621 Handle(TDataStd_Name) anAtt;
622 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
623 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
627 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
628 ResultPtr aCont = context();
629 aName = "Undefined name";
630 if(!aCont.get() || aCont->shape()->isNull())
632 if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
633 return aCont->data()->name();
635 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
636 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
638 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
639 BRepTools::Write(aSubShape, "Selection.brep");
640 BRepTools::Write(aContext, "Context.brep");
643 std::shared_ptr<Model_Document> aDoc =
644 std::dynamic_pointer_cast<Model_Document>(aCont->document());
646 // check if the subShape is already in DF
647 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
648 if(aName.empty() ) { // not in the document!
649 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
652 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
656 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
657 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
658 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
659 aName = "Degenerated_Edge";
662 TopTools_IndexedDataMapOfShapeListOfShape aMap;
663 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
664 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
665 bool isTrivialCase(true);
666 /* for (int i = 1; i <= aMap.Extent(); i++) {
667 const TopoDS_Shape& aKey = aMap.FindKey(i);
668 //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
669 if (aKey.IsSame(aSubShape)) continue;
670 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
671 // check that it is not a trivial case (F1 & F2: aNumber = 1)
672 isTrivialCase = isTrivial(anAncestors, aSMap);
675 if(aMap.Contains(aSubShape)) {
676 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
677 // check that it is not a trivial case (F1 & F2: aNumber = 1)
678 isTrivialCase = isTrivial(anAncestors, aSMap);
681 TopTools_ListOfShape aListOfNbs;
682 if(!isTrivialCase) { // find Neighbors
683 TNaming_Localizer aLocalizer;
684 TopTools_MapOfShape aMap3;
685 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
686 //int n = aMap3.Extent();
687 TopTools_MapIteratorOfMapOfShape it(aMap3);
688 for(;it.More();it.Next()) {
689 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
690 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
691 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
692 TopTools_ListIteratorOfListOfShape it2(aList);
693 for(;it2.More();it2.Next()) {
694 if(aSMap.Contains(it2.Value())) continue; // skip this Face
695 aListOfNbs.Append(it2.Value());
698 } // else a trivial case
700 // build name of the sub-shape Edge
701 for(int i=1; i <= aSMap.Extent(); i++) {
702 const TopoDS_Shape& aFace = aSMap.FindKey(i);
703 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
707 aName += "|" + aFaceName;
709 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
710 for (;itl.More();itl.Next()) {
711 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
712 aName += "|" + aFaceName;
718 // name structure (Monifold Topology):
719 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
720 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
721 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
722 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
723 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
724 // or compound of 2 open faces.
725 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
726 // two independent edges (wire or compound)
727 // implemented 2 first cases
729 TopTools_IndexedDataMapOfShapeListOfShape aMap;
730 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
731 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
732 TopTools_ListOfShape aList;
733 TopTools_MapOfShape aFMap;
735 //int n = aList2.Extent(); //bug! duplication
737 TopTools_ListIteratorOfListOfShape itl2(aList2);
738 for (int i = 1;itl2.More();itl2.Next(),i++) {
739 if(aFMap.Add(itl2.Value()))
740 aList.Append(itl2.Value());
742 //n = aList.Extent();
744 int n = aList.Extent();
745 if(n < 3) { // open topology case or Compound case => via edges
746 TopTools_IndexedDataMapOfShapeListOfShape aMap;
747 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
748 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
749 if(aList22.Extent() >= 2) { // regular solution
752 // bug! duplication; fix is below
754 TopTools_ListOfShape aListE;
755 TopTools_ListIteratorOfListOfShape itl2(aList22);
756 for (int i = 1;itl2.More();itl2.Next(),i++) {
757 if(aFMap.Add(itl2.Value()))
758 aListE.Append(itl2.Value());
762 TopTools_ListIteratorOfListOfShape itl(aListE);
763 for (int i = 1;itl.More();itl.Next(),i++) {
764 const TopoDS_Shape& anEdge = itl.Value();
765 std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
769 aName += "|" + anEdgeName;
772 else { // dangle vertex: if(aList22.Extent() == 1)
773 //it should be already in DF
777 TopTools_ListIteratorOfListOfShape itl(aList);
778 for (int i = 1;itl.More();itl.Next(),i++) {
779 const TopoDS_Shape& aFace = itl.Value();
780 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
784 aName += "|" + aFaceName;
791 // aDoc->addNamingName(selectionLabel(), aName);
792 // the selected sub-shape will not be shared and as result it will not require registration
797 TopAbs_ShapeEnum translateType (const std::string& theType)
799 // map from the textual shape types to OCCT enumeration
800 static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
801 if (MyShapeTypes.size() == 0) {
802 MyShapeTypes["face"] = TopAbs_FACE;
803 MyShapeTypes["faces"] = TopAbs_FACE;
804 MyShapeTypes["vertex"] = TopAbs_VERTEX;
805 MyShapeTypes["vertices"] = TopAbs_VERTEX;
806 MyShapeTypes["wire"] = TopAbs_WIRE;
807 MyShapeTypes["edge"] = TopAbs_EDGE;
808 MyShapeTypes["edges"] = TopAbs_EDGE;
809 MyShapeTypes["shell"] = TopAbs_SHELL;
810 MyShapeTypes["solid"] = TopAbs_SOLID;
811 MyShapeTypes["solids"] = TopAbs_SOLID;
812 MyShapeTypes["FACE"] = TopAbs_FACE;
813 MyShapeTypes["FACES"] = TopAbs_FACE;
814 MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
815 MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
816 MyShapeTypes["WIRE"] = TopAbs_WIRE;
817 MyShapeTypes["EDGE"] = TopAbs_EDGE;
818 MyShapeTypes["EDGES"] = TopAbs_EDGE;
819 MyShapeTypes["SHELL"] = TopAbs_SHELL;
820 MyShapeTypes["SOLID"] = TopAbs_SOLID;
821 MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
823 if (MyShapeTypes.find(theType) != MyShapeTypes.end())
824 return MyShapeTypes[theType];
825 Events_Error::send("Shape type defined in XML is not implemented!");
829 const TopoDS_Shape getShapeFromCompound(const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
831 TopoDS_Shape aSelection;
832 std::string::size_type n = theSubShapeName.rfind('/');
833 if (n == std::string::npos) n = 0;
834 std::string aSubString = theSubShapeName.substr(n + 1);
835 n = aSubString.rfind('_');
836 if (n == std::string::npos) return aSelection;
837 aSubString = aSubString.substr(n+1);
838 int indx = atoi(aSubString.c_str());
839 TopoDS_Iterator it(theCompound);
840 for (int i = 1;it.More();it.Next(), i++) {
842 aSelection = it.Value();
850 const TopoDS_Shape findFaceByName(const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
853 std::string::size_type n, nb = theSubShapeName.rfind('/');
854 if (nb == std::string::npos) nb = 0;
855 std::string aSubString = theSubShapeName.substr(nb + 1);
856 n = aSubString.rfind('_');
857 if (n != std::string::npos) {
858 std::string aSubStr2 = aSubString.substr(0, n);
859 aSubString = theSubShapeName.substr(0, nb + 1);
860 aSubString = aSubString + aSubStr2;
862 aSubString = theSubShapeName;
864 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
865 if(aLabel.IsNull()) return aFace;
866 Handle(TNaming_NamedShape) aNS;
867 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
868 const TopoDS_Shape& aShape = aNS->Get();
869 if(!aShape.IsNull()) {
870 if(aShape.ShapeType() == TopAbs_COMPOUND)
871 aFace = getShapeFromCompound(theSubShapeName, aShape);
879 int ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
881 std::string aName = theSubShapeName;
882 std::string aLastName;
883 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
884 while ((n2 = aName.find('|', n1)) != std::string::npos) {
885 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
886 theList.push_back(aName1);
888 aLastName = aName.substr(n1);
890 if(!aLastName.empty())
891 theList.push_back(aLastName);
892 return theList.size();
895 const TopoDS_Shape findCommonShape(const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
898 std::vector<TopTools_MapOfShape> aVec;
899 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
900 if(theList.Extent() > 1) {
901 aVec.push_back(aMap1);
902 aVec.push_back(aMap2);
904 if(theList.Extent() > 2)
905 aVec.push_back(aMap3);
906 if(theList.Extent() == 4)
907 aVec.push_back(aMap4);
910 TopTools_ListIteratorOfListOfShape it(theList);
911 for(int i = 0;it.More();it.Next(),i++) {
912 const TopoDS_Shape& aFace = it.Value();
914 TopExp_Explorer anExp (aFace, theType);
915 for(;anExp.More();anExp.Next()) {
916 const TopoDS_Shape& anEdge = anExp.Current();
917 if (!anEdge.IsNull())
918 aVec[i].Add(anExp.Current());
921 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
922 for(;anExp.More();anExp.Next()) {
923 const TopoDS_Shape& aVertex = anExp.Current();
924 if (!aVertex.IsNull())
925 aVec[i].Add(anExp.Current());
929 //trivial case: 2 faces
930 TopTools_ListOfShape aList;
931 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
932 for(;it2.More();it2.Next()) {
933 if(aVec[1].Contains(it2.Key())) {
935 if(theList.Extent() == 2)
938 aList.Append(it2.Key());
941 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
942 if(aVec[2].Extent() && aVec[3].Extent()) {
943 TopTools_ListIteratorOfListOfShape it(aList);
944 for(;it.More();it.Next()) {
945 const TopoDS_Shape& aCand = it.Value();
946 // not yet completelly implemented, to be rechecked
947 TopoDS_Vertex aV1, aV2;
948 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
950 if(aVec[2].Contains(aV1)) aNum++;
951 else if(aVec[2].Contains(aV2)) aNum++;
952 if(aVec[3].Contains(aV1)) aNum++;
953 else if(aVec[3].Contains(aV2)) aNum++;
962 if(aList.Extent() && aVec.size() == 3) {
964 TopTools_ListIteratorOfListOfShape it(aList);
965 for(;it.More();it.Next()) {
966 const TopoDS_Shape& aCand = it.Value();
967 if(aVec[2].Contains(aCand)) {
976 std::string getContextName(const std::string& theSubShapeName)
979 std::string::size_type n = theSubShapeName.find('/');
980 if (n == std::string::npos) return aName;
981 aName = theSubShapeName.substr(0, n);
984 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
985 void Model_AttributeSelection::selectSubShape(const std::string& theType, const std::string& theSubShapeName)
987 if(theSubShapeName.empty() || theType.empty()) return;
988 TopAbs_ShapeEnum aType = translateType(theType);
989 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(owner()->document());//std::dynamic_pointer_cast<Model_Document>(aCont->document());
990 std::string aContName = getContextName(theSubShapeName);
991 if(aContName.empty()) return;
992 //ResultPtr aCont = context();
993 ResultPtr aCont = aDoc->findByName(aContName);
994 if(!aCont.get() || aCont->shape()->isNull()) return;
995 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
996 TopAbs_ShapeEnum aContType = aContext.ShapeType();
997 if(aType <= aContType) return; // not applicable
1000 TopoDS_Shape aSelection;
1003 case TopAbs_COMPOUND:
1005 case TopAbs_COMPSOLID:
1013 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1014 if(!aSelection.IsNull()) {// Select it
1015 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1016 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1017 setValue(aCont, aShapeToBeSelected);
1025 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1026 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1027 if(!aLabel.IsNull()) {
1028 Handle(TNaming_NamedShape) aNS;
1029 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1030 const TopoDS_Shape& aShape = aNS->Get();
1031 if(!aShape.IsNull()) {
1032 if(aShape.ShapeType() == TopAbs_COMPOUND)
1033 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1035 aSelection = aShape;
1039 if(aSelection.IsNull()) {
1040 std::list<std::string> aListofNames;
1041 int n = ParseName(theSubShapeName, aListofNames);
1042 if(n > 1 && n < 5) {
1043 TopTools_ListOfShape aList;
1044 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1045 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1046 aList.Append(aFace);
1048 aSelection = findCommonShape(TopAbs_EDGE, aList);
1051 if(!aSelection.IsNull()) {// Select it
1052 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1053 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1054 setValue(aCont, aShapeToBeSelected);
1060 TopoDS_Shape aSelection;
1061 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1062 if(!aLabel.IsNull()) {
1063 Handle(TNaming_NamedShape) aNS;
1064 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1065 const TopoDS_Shape& aShape = aNS->Get();
1066 if(!aShape.IsNull()) {
1067 if(aShape.ShapeType() == TopAbs_COMPOUND)
1068 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1070 aSelection = aShape;
1074 if(aSelection.IsNull()) {
1075 std::list<std::string> aListofNames;
1076 int n = ParseName(theSubShapeName, aListofNames);
1077 if(n > 1 && n < 4) { // 2 || 3
1078 TopTools_ListOfShape aList;
1079 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1080 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1082 aList.Append(aFace);
1084 aSelection = findCommonShape(TopAbs_VERTEX, aList);
1087 if(!aSelection.IsNull()) {// Select it
1088 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1089 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1090 setValue(aCont, aShapeToBeSelected);
1094 default: //TopAbs_SHAPE
1100 int Model_AttributeSelection::Id()
1102 std::shared_ptr<GeomAPI_Shape> aSelection = value();
1103 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1104 const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1105 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1107 if (aSelection && !aSelection->isNull() &&
1108 aContext && !aContext->isNull())
1110 TopTools_IndexedMapOfShape aSubShapesMap;
1111 TopExp::MapShapes(aMainShape, aSubShapesMap);
1112 anID = aSubShapesMap.FindIndex(aSubShape);