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->groupName() == ModelAPI_ResultBody::group()) {
89 // do not select the whole shape for body:it is already must be in the data framework
90 if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
91 aSelLab.ForgetAllAttributes(true);
92 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
94 selectBody(theContext, theSubShape);
96 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
97 if (!theSubShape.get()) {
98 // to sub, so the whole result is selected
99 aSelLab.ForgetAllAttributes(true);
100 TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
102 selectConstruction(theContext, theSubShape);
105 myIsInitialized = true;
107 std::string aSelName = namingName();
108 if(!aSelName.empty())
109 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
112 //selectSubShape("FACE", "Extrusion_1/LateralFace_3");
113 //selectSubShape("FACE", "Extrusion_1/TopFace");
114 //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
115 //selectSubShape("EDGE", "Sketch_1/Edge_6");
117 owner()->data()->sendAttributeUpdated(this);
120 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
122 std::shared_ptr<GeomAPI_Shape> aResult;
123 if (myIsInitialized) {
124 TDF_Label aSelLab = selectionLabel();
125 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
126 ResultPtr aContext = context();
128 return aResult; // empty result
129 return aContext->shape();
131 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
132 return aResult; // empty result
135 Handle(TNaming_NamedShape) aSelection;
136 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
137 TopoDS_Shape aSelShape = aSelection->Get();
138 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
139 aResult->setImpl(new TopoDS_Shape(aSelShape));
140 } else { // for simple construction element: just shape of this construction element
141 ResultConstructionPtr aConstr =
142 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
144 return aConstr->shape();
151 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
154 myIsInitialized = myRef.isInitialized();
157 ResultPtr Model_AttributeSelection::context() {
158 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
162 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
164 ModelAPI_AttributeSelection::setObject(theObject);
165 myRef.setObject(theObject);
168 TDF_LabelMap& Model_AttributeSelection::scope()
170 if (myScope.IsEmpty()) { // create a new scope if not yet done
171 // gets all labels with named shapes that are bofore this feature label (before in history)
172 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
173 owner()->data())->label().Father();
174 int aFeatureID = aFeatureLab.Tag();
175 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
176 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
177 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
179 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
180 for(; aNSIter.More(); aNSIter.Next()) {
181 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
182 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
183 myScope.Add(aNS->Label());
191 bool Model_AttributeSelection::update()
193 ResultPtr aContext = context();
194 if (!aContext.get()) return false;
195 TDF_Label aSelLab = selectionLabel();
196 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
197 return aContext->shape() && !aContext->shape()->isNull();
199 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
200 return aContext->shape() && !aContext->shape()->isNull();
203 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
204 // body: just a named shape, use selection mechanism from OCCT
205 TNaming_Selector aSelector(aSelLab);
206 bool aResult = aSelector.Solve(scope()) == Standard_True;
207 owner()->data()->sendAttributeUpdated(this);
209 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
210 // construction: identification by the results indexes, recompute faces and
211 // take the face that more close by the indexes
212 ResultConstructionPtr aConstructionContext =
213 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
214 // sketch sub-element
215 if (aConstructionContext &&
216 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContext).get())
218 TDF_Label aLab = myRef.myRef->Label();
219 // getting a type of selected shape
220 Handle(TDataStd_Integer) aTypeAttr;
221 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
224 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
225 // selected indexes will be needed in each "if"
226 Handle(TDataStd_IntPackedMap) aSubIds;
227 std::shared_ptr<GeomAPI_Shape> aNewSelected;
229 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
230 // for now working only with composite features
231 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
232 CompositeFeaturePtr aComposite =
233 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
234 if (!aComposite || aComposite->numberOfSubs() == 0) {
238 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
239 // If this is a wire with plane defined thin it is a sketch-like object
240 if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
242 // if there is no edges indexes, any face can be used: take the first
243 std::shared_ptr<GeomAPI_Shape> aNewSelected;
245 aNewSelected = aConstructionContext->face(0);
246 } else { // searching for most looks-like initial face by the indexes
247 // prepare edges of the current resut for the fast searching
248 TColStd_MapOfTransient allCurves;
249 const int aSubNum = aComposite->numberOfSubs();
250 for(int a = 0; a < aSubNum; a++) {
251 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
252 FeaturePtr aSub = aComposite->subFeature(a);
253 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
254 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
255 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
256 ResultConstructionPtr aConstr =
257 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
258 if (aConstr->shape() && aConstr->shape()->isEdge()) {
259 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
260 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
261 if (!anEdge.IsNull()) {
262 Standard_Real aFirst, aLast;
263 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
264 allCurves.Add(aCurve);
270 double aBestFound = 0; // best percentage of found edges
271 for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
272 int aFound = 0, aNotFound = 0;
273 TopExp_Explorer anEdgesExp(
274 aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>(), TopAbs_EDGE);
275 for(; anEdgesExp.More(); anEdgesExp.Next()) {
276 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
277 if (!anEdge.IsNull()) {
278 Standard_Real aFirst, aLast;
279 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
280 if (allCurves.Contains(aCurve)) {
287 if (aFound + aNotFound != 0) {
288 double aPercentage = double(aFound) / double(aFound + aNotFound);
289 if (aPercentage > aBestFound) {
290 aBestFound = aPercentage;
291 aNewSelected = aConstructionContext->face(aFaceIndex);
296 if (aNewSelected) { // store this new selection
297 selectConstruction(aContext, aNewSelected);
298 owner()->data()->sendAttributeUpdated(this);
301 } else if (aShapeType == TopAbs_EDGE) {
302 // just reselect the edge by the id
303 const int aSubNum = aComposite->numberOfSubs();
304 for(int a = 0; a < aSubNum; a++) {
305 // if aSubIds take any, the first appropriate
306 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
307 // found the appropriate feature
308 FeaturePtr aFeature = aComposite->subFeature(a);
309 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
310 aFeature->results().cbegin();
311 for(;aResIter != aFeature->results().cend(); aResIter++) {
312 ResultConstructionPtr aRes =
313 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
314 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
315 selectConstruction(aContext, aRes->shape());
316 owner()->data()->sendAttributeUpdated(this);
322 } else if (aShapeType == TopAbs_VERTEX) {
323 // just reselect the vertex by the id of edge
324 const int aSubNum = aComposite->numberOfSubs();
325 for(int a = 0; a < aSubNum; a++) {
326 // if aSubIds take any, the first appropriate
327 int aFeatureID = aComposite->subFeatureId(a);
328 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
329 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
330 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
331 // searching for deltas
333 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
334 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
335 // found the feature with appropriate edge
336 FeaturePtr aFeature = aComposite->subFeature(a);
337 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
338 aFeature->results().cbegin();
339 for(;aResIter != aFeature->results().cend(); aResIter++) {
340 ResultConstructionPtr aRes =
341 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
342 if (aRes && aRes->shape()) {
343 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
344 selectConstruction(aContext, aRes->shape());
345 owner()->data()->sendAttributeUpdated(this);
347 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
348 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
350 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
351 if (aVIndex == aVertexNum) { // found!
352 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
353 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
354 selectConstruction(aContext, aVertex);
355 owner()->data()->sendAttributeUpdated(this);
366 } else { // simple construction element: the selected is that needed
367 selectConstruction(aContext, aContext->shape());
368 owner()->data()->sendAttributeUpdated(this);
372 return false; // unknown case
376 void Model_AttributeSelection::selectBody(
377 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
379 // perform the selection
380 TNaming_Selector aSel(selectionLabel());
381 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
382 TopoDS_Shape aContext;
384 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
386 aContext = aBody->shape()->impl<TopoDS_Shape>();
388 ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
390 aContext = aConstr->shape()->impl<TopoDS_Shape>();
392 Events_Error::send("A result with shape is expected");
396 //BRepTools::Write(aNewShape, "Selection0.brep");
397 aSel.Select(aNewShape, aContext);
400 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
401 /// if theID is zero,
402 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
403 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
404 std::string theAdditionalName,
405 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
407 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
408 TNaming_Builder aBuilder(aLab);
409 aBuilder.Generated(theShape);
410 std::stringstream aName;
411 aName<<theContextFeature->name()<<"/";
412 if (!theAdditionalName.empty())
413 aName<<theAdditionalName<<"/";
414 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
415 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
416 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
418 if (theRefs.IsNull()) {
420 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
421 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
422 for(; aRef.More(); aRef.Next()) {
423 aName<<"-"<<aRef.Key();
427 theDoc->addNamingName(aLab, aName.str());
428 TDataStd_Name::Set(aLab, aName.str().c_str());
431 void Model_AttributeSelection::selectConstruction(
432 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
434 std::shared_ptr<Model_Document> aMyDoc =
435 std::dynamic_pointer_cast<Model_Document>(owner()->document());
436 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
437 CompositeFeaturePtr aComposite =
438 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
439 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
440 if (!aComposite || aComposite->numberOfSubs() == 0) {
441 // saving of context is enough: result construction contains exactly the needed shape
442 TNaming_Builder aBuilder(selectionLabel());
443 aBuilder.Generated(aSubShape);
444 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
445 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
448 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
449 TDF_Label aLab = myRef.myRef->Label();
450 // identify the reuslts of sub-object of the composite by edges
451 // save type of the selected shape in integer attribute
452 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
453 TDataStd_Integer::Set(aLab, (int)aShapeType);
455 TColStd_MapOfTransient allCurves;
456 if (aShapeType == TopAbs_VERTEX) { // compare positions
457 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
459 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
460 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
461 Standard_Real aFirst, aLast;
462 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
463 allCurves.Add(aCurve);
466 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
467 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
469 const int aSubNum = aComposite->numberOfSubs();
470 for(int a = 0; a < aSubNum; a++) {
471 FeaturePtr aSub = aComposite->subFeature(a);
472 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
473 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
474 // there may be many shapes (circle and center): register if at least one is in selection
475 for(; aRes != aResults.cend(); aRes++) {
476 ResultConstructionPtr aConstr =
477 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
478 if (!aConstr->shape()) {
481 if (aShapeType == TopAbs_VERTEX) {
482 if (aConstr->shape()->isVertex()) { // compare vertices positions
483 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
484 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
485 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
486 aRefs->Add(aComposite->subFeatureId(a));
488 } else { // get first or last vertex of the edge: last is stored with negative sign
489 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
490 int aDelta = kSTART_VERTEX_DELTA;
491 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
492 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
493 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
494 aRefs->Add(aDelta + aComposite->subFeatureId(a));
497 aDelta += kSTART_VERTEX_DELTA;
501 if (aConstr->shape()->isEdge()) {
502 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
503 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
504 if (!anEdge.IsNull()) {
505 Standard_Real aFirst, aLast;
506 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
507 if (allCurves.Contains(aCurve)) {
508 int anID = aComposite->subFeatureId(a);
510 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
511 // add edges to sub-label to support naming for edges selection
512 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
513 for(; anEdgeExp.More(); anEdgeExp.Next()) {
514 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
515 Standard_Real aFirst, aLast;
516 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
517 if (aFaceCurve == aCurve) {
518 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
521 } else { // put vertices of the selected edge to sub-labels
522 // add edges to sub-label to support naming for edges selection
523 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
524 int aTagIndex = anID + kSTART_VERTEX_DELTA;
525 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
526 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
528 std::stringstream anAdditionalName;
529 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
539 // store the selected as primitive
540 TNaming_Builder aBuilder(selectionLabel());
541 aBuilder.Generated(aSubShape);
542 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
545 TDF_Label Model_AttributeSelection::selectionLabel()
547 return myRef.myRef->Label().FindChild(1);
551 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
552 const TDF_Label& theLabel)
555 // check if the subShape is already in DF
556 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
557 Handle(TDataStd_Name) anAttr;
558 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
559 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
560 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
562 const TDF_Label& aLabel = theDoc->findNamingName(aName);
563 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
564 if(!aLabel.IsEqual(aNS->Label())) {
565 //aName.erase(); //something is wrong, to be checked!!!
566 aName += "_SomethingWrong";
569 const TopoDS_Shape& aShape = aNS->Get();
570 if(aShape.ShapeType() == TopAbs_COMPOUND) {
571 std::string aPostFix("_");
572 TopoDS_Iterator it(aShape);
573 for (int i = 1;it.More();it.Next(), i++) {
574 if(it.Value() == theShape) {
575 aPostFix += TCollection_AsciiString (i).ToCString();
588 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
590 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
591 TopoDS_Compound aCmp;
593 BB.MakeCompound(aCmp);
594 TopTools_ListIteratorOfListOfShape it(theAncestors);
595 for(;it.More();it.Next()) {
596 BB.Add(aCmp, it.Value());
597 theSMap.Add(it.Value());
600 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
601 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
602 for (int i = 1; i <= aMap2.Extent(); i++) {
603 const TopoDS_Shape& aKey = aMap2.FindKey(i);
604 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
605 if(anAncestors.Extent() > 1) aNumber++;
607 if(aNumber > 1) return false;
610 std::string Model_AttributeSelection::namingName()
612 std::string aName("");
613 if(!this->isInitialized()) return aName;
614 Handle(TDataStd_Name) anAtt;
615 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
616 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
620 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
621 ResultPtr aCont = context();
622 aName = "Undefined name";
623 if(!aCont.get() || aCont->shape()->isNull())
625 if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
626 return aCont->data()->name();
628 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
629 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
631 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
632 BRepTools::Write(aSubShape, "Selection.brep");
633 BRepTools::Write(aContext, "Context.brep");
636 std::shared_ptr<Model_Document> aDoc =
637 std::dynamic_pointer_cast<Model_Document>(aCont->document());
639 // check if the subShape is already in DF
640 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
641 if(aName.empty() ) { // not in the document!
642 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
645 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
649 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
650 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
651 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
652 aName = "Degenerated_Edge";
655 TopTools_IndexedDataMapOfShapeListOfShape aMap;
656 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
657 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
658 bool isTrivialCase(true);
659 /* for (int i = 1; i <= aMap.Extent(); i++) {
660 const TopoDS_Shape& aKey = aMap.FindKey(i);
661 //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
662 if (aKey.IsSame(aSubShape)) continue;
663 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
664 // check that it is not a trivial case (F1 & F2: aNumber = 1)
665 isTrivialCase = isTrivial(anAncestors, aSMap);
668 if(aMap.Contains(aSubShape)) {
669 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
670 // check that it is not a trivial case (F1 & F2: aNumber = 1)
671 isTrivialCase = isTrivial(anAncestors, aSMap);
674 TopTools_ListOfShape aListOfNbs;
675 if(!isTrivialCase) { // find Neighbors
676 TNaming_Localizer aLocalizer;
677 TopTools_MapOfShape aMap3;
678 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
679 //int n = aMap3.Extent();
680 TopTools_MapIteratorOfMapOfShape it(aMap3);
681 for(;it.More();it.Next()) {
682 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
683 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
684 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
685 TopTools_ListIteratorOfListOfShape it2(aList);
686 for(;it2.More();it2.Next()) {
687 if(aSMap.Contains(it2.Value())) continue; // skip this Face
688 aListOfNbs.Append(it2.Value());
691 } // else a trivial case
693 // build name of the sub-shape Edge
694 for(int i=1; i <= aSMap.Extent(); i++) {
695 const TopoDS_Shape& aFace = aSMap.FindKey(i);
696 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
700 aName += "|" + aFaceName;
702 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
703 for (;itl.More();itl.Next()) {
704 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
705 aName += "|" + aFaceName;
711 // name structure (Monifold Topology):
712 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
713 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
714 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
715 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
716 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
717 // or compound of 2 open faces.
718 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
719 // two independent edges (wire or compound)
720 // implemented 2 first cases
722 TopTools_IndexedDataMapOfShapeListOfShape aMap;
723 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
724 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
725 TopTools_ListOfShape aList;
726 TopTools_MapOfShape aFMap;
728 //int n = aList2.Extent(); //bug! duplication
730 TopTools_ListIteratorOfListOfShape itl2(aList2);
731 for (int i = 1;itl2.More();itl2.Next(),i++) {
732 if(aFMap.Add(itl2.Value()))
733 aList.Append(itl2.Value());
735 //n = aList.Extent();
737 int n = aList.Extent();
738 if(n < 3) { // open topology case or Compound case => via edges
739 TopTools_IndexedDataMapOfShapeListOfShape aMap;
740 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
741 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
742 if(aList22.Extent() >= 2) { // regular solution
745 // bug! duplication; fix is below
747 TopTools_ListOfShape aListE;
748 TopTools_ListIteratorOfListOfShape itl2(aList22);
749 for (int i = 1;itl2.More();itl2.Next(),i++) {
750 if(aFMap.Add(itl2.Value()))
751 aListE.Append(itl2.Value());
755 TopTools_ListIteratorOfListOfShape itl(aListE);
756 for (int i = 1;itl.More();itl.Next(),i++) {
757 const TopoDS_Shape& anEdge = itl.Value();
758 std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
762 aName += "|" + anEdgeName;
765 else { // dangle vertex: if(aList22.Extent() == 1)
766 //it should be already in DF
770 TopTools_ListIteratorOfListOfShape itl(aList);
771 for (int i = 1;itl.More();itl.Next(),i++) {
772 const TopoDS_Shape& aFace = itl.Value();
773 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
777 aName += "|" + aFaceName;
784 // aDoc->addNamingName(selectionLabel(), aName);
785 // the selected sub-shape will not be shared and as result it will not require registration
790 TopAbs_ShapeEnum translateType (const std::string& theType)
792 // map from the textual shape types to OCCT enumeration
793 static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
794 if (MyShapeTypes.size() == 0) {
795 MyShapeTypes["face"] = TopAbs_FACE;
796 MyShapeTypes["faces"] = TopAbs_FACE;
797 MyShapeTypes["vertex"] = TopAbs_VERTEX;
798 MyShapeTypes["vertices"] = TopAbs_VERTEX;
799 MyShapeTypes["wire"] = TopAbs_WIRE;
800 MyShapeTypes["edge"] = TopAbs_EDGE;
801 MyShapeTypes["edges"] = TopAbs_EDGE;
802 MyShapeTypes["shell"] = TopAbs_SHELL;
803 MyShapeTypes["solid"] = TopAbs_SOLID;
804 MyShapeTypes["solids"] = TopAbs_SOLID;
805 MyShapeTypes["FACE"] = TopAbs_FACE;
806 MyShapeTypes["FACES"] = TopAbs_FACE;
807 MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
808 MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
809 MyShapeTypes["WIRE"] = TopAbs_WIRE;
810 MyShapeTypes["EDGE"] = TopAbs_EDGE;
811 MyShapeTypes["EDGES"] = TopAbs_EDGE;
812 MyShapeTypes["SHELL"] = TopAbs_SHELL;
813 MyShapeTypes["SOLID"] = TopAbs_SOLID;
814 MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
816 if (MyShapeTypes.find(theType) != MyShapeTypes.end())
817 return MyShapeTypes[theType];
818 Events_Error::send("Shape type defined in XML is not implemented!");
822 const TopoDS_Shape getShapeFromCompound(const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
824 TopoDS_Shape aSelection;
825 std::string::size_type n = theSubShapeName.rfind('/');
826 if (n == std::string::npos) n = 0;
827 std::string aSubString = theSubShapeName.substr(n + 1);
828 n = aSubString.rfind('_');
829 if (n == std::string::npos) return aSelection;
830 aSubString = aSubString.substr(n+1);
831 int indx = atoi(aSubString.c_str());
832 TopoDS_Iterator it(theCompound);
833 for (int i = 1;it.More();it.Next(), i++) {
835 aSelection = it.Value();
843 const TopoDS_Shape findFaceByName(const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
846 std::string::size_type n, nb = theSubShapeName.rfind('/');
847 if (nb == std::string::npos) nb = 0;
848 std::string aSubString = theSubShapeName.substr(nb + 1);
849 n = aSubString.rfind('_');
850 if (n != std::string::npos) {
851 std::string aSubStr2 = aSubString.substr(0, n);
852 aSubString = theSubShapeName.substr(0, nb + 1);
853 aSubString = aSubString + aSubStr2;
855 aSubString = theSubShapeName;
857 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
858 if(aLabel.IsNull()) return aFace;
859 Handle(TNaming_NamedShape) aNS;
860 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
861 const TopoDS_Shape& aShape = aNS->Get();
862 if(!aShape.IsNull()) {
863 if(aShape.ShapeType() == TopAbs_COMPOUND)
864 aFace = getShapeFromCompound(theSubShapeName, aShape);
872 int ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
874 std::string aName = theSubShapeName;
875 std::string aLastName;
876 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
877 while ((n2 = aName.find('|', n1)) != std::string::npos) {
878 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
879 theList.push_back(aName1);
881 aLastName = aName.substr(n1);
883 if(!aLastName.empty())
884 theList.push_back(aLastName);
885 return theList.size();
888 const TopoDS_Shape findCommonShape(const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
891 std::vector<TopTools_MapOfShape> aVec;
892 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
893 if(theList.Extent() > 1) {
894 aVec.push_back(aMap1);
895 aVec.push_back(aMap2);
897 if(theList.Extent() > 2)
898 aVec.push_back(aMap3);
899 if(theList.Extent() == 4)
900 aVec.push_back(aMap4);
903 TopTools_ListIteratorOfListOfShape it(theList);
904 for(int i = 0;it.More();it.Next(),i++) {
905 const TopoDS_Shape& aFace = it.Value();
907 TopExp_Explorer anExp (aFace, theType);
908 for(;anExp.More();anExp.Next()) {
909 const TopoDS_Shape& anEdge = anExp.Current();
910 if (!anEdge.IsNull())
911 aVec[i].Add(anExp.Current());
914 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
915 for(;anExp.More();anExp.Next()) {
916 const TopoDS_Shape& aVertex = anExp.Current();
917 if (!aVertex.IsNull())
918 aVec[i].Add(anExp.Current());
922 //trivial case: 2 faces
923 TopTools_ListOfShape aList;
924 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
925 for(;it2.More();it2.Next()) {
926 if(aVec[1].Contains(it2.Key())) {
928 if(theList.Extent() == 2)
931 aList.Append(it2.Key());
934 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
935 if(aVec[2].Extent() && aVec[3].Extent()) {
936 TopTools_ListIteratorOfListOfShape it(aList);
937 for(;it.More();it.Next()) {
938 const TopoDS_Shape& aCand = it.Value();
939 // not yet completelly implemented, to be rechecked
940 TopoDS_Vertex aV1, aV2;
941 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
943 if(aVec[2].Contains(aV1)) aNum++;
944 else if(aVec[2].Contains(aV2)) aNum++;
945 if(aVec[3].Contains(aV1)) aNum++;
946 else if(aVec[3].Contains(aV2)) aNum++;
955 if(aList.Extent() && aVec.size() == 3) {
957 TopTools_ListIteratorOfListOfShape it(aList);
958 for(;it.More();it.Next()) {
959 const TopoDS_Shape& aCand = it.Value();
960 if(aVec[2].Contains(aCand)) {
969 std::string getContextName(const std::string& theSubShapeName)
972 std::string::size_type n = theSubShapeName.find('/');
973 if (n == std::string::npos) return aName;
974 aName = theSubShapeName.substr(0, n);
977 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
978 void Model_AttributeSelection::selectSubShape(const std::string& theType, const std::string& theSubShapeName)
980 if(theSubShapeName.empty() || theType.empty()) return;
981 TopAbs_ShapeEnum aType = translateType(theType);
982 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(owner()->document());//std::dynamic_pointer_cast<Model_Document>(aCont->document());
983 std::string aContName = getContextName(theSubShapeName);
984 if(aContName.empty()) return;
985 //ResultPtr aCont = context();
986 ResultPtr aCont = aDoc->findByName(aContName);
987 if(!aCont.get() || aCont->shape()->isNull()) return;
988 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
989 TopAbs_ShapeEnum aContType = aContext.ShapeType();
990 if(aType <= aContType) return; // not applicable
993 TopoDS_Shape aSelection;
996 case TopAbs_COMPOUND:
998 case TopAbs_COMPSOLID:
1006 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1007 if(!aSelection.IsNull()) {// Select it
1008 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1009 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1010 setValue(aCont, aShapeToBeSelected);
1018 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1019 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1020 if(!aLabel.IsNull()) {
1021 Handle(TNaming_NamedShape) aNS;
1022 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1023 const TopoDS_Shape& aShape = aNS->Get();
1024 if(!aShape.IsNull()) {
1025 if(aShape.ShapeType() == TopAbs_COMPOUND)
1026 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1028 aSelection = aShape;
1032 if(aSelection.IsNull()) {
1033 std::list<std::string> aListofNames;
1034 int n = ParseName(theSubShapeName, aListofNames);
1035 if(n > 1 && n < 5) {
1036 TopTools_ListOfShape aList;
1037 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1038 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1039 aList.Append(aFace);
1041 aSelection = findCommonShape(TopAbs_EDGE, aList);
1044 if(!aSelection.IsNull()) {// Select it
1045 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1046 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1047 setValue(aCont, aShapeToBeSelected);
1053 TopoDS_Shape aSelection;
1054 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1055 if(!aLabel.IsNull()) {
1056 Handle(TNaming_NamedShape) aNS;
1057 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1058 const TopoDS_Shape& aShape = aNS->Get();
1059 if(!aShape.IsNull()) {
1060 if(aShape.ShapeType() == TopAbs_COMPOUND)
1061 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1063 aSelection = aShape;
1067 if(aSelection.IsNull()) {
1068 std::list<std::string> aListofNames;
1069 int n = ParseName(theSubShapeName, aListofNames);
1070 if(n > 1 && n < 4) { // 2 || 3
1071 TopTools_ListOfShape aList;
1072 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1073 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1075 aList.Append(aFace);
1077 aSelection = findCommonShape(TopAbs_VERTEX, aList);
1080 if(!aSelection.IsNull()) {// Select it
1081 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1082 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1083 setValue(aCont, aShapeToBeSelected);
1087 default: //TopAbs_SHAPE
1093 int Model_AttributeSelection::Id()
1095 std::shared_ptr<GeomAPI_Shape> aSelection = value();
1096 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1097 const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1098 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1100 if (aSelection && !aSelection->isNull() &&
1101 aContext && !aContext->isNull())
1103 TopTools_IndexedMapOfShape aSubShapesMap;
1104 TopExp::MapShapes(aMainShape, aSubShapesMap);
1105 anID = aSubShapesMap.FindIndex(aSubShape);