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.get()) {
90 // to keep the reference attribute label
91 TDF_Label aRefLab = myRef.myRef->Label();
92 aSelLab.ForgetAllAttributes(true);
93 myRef.myRef = TDF_Reference::Set(aSelLab, aSelLab);
96 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
97 // do not select the whole shape for body:it is already must be in the data framework
98 if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
99 aSelLab.ForgetAllAttributes(true);
100 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
102 selectBody(theContext, theSubShape);
104 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
105 if (!theSubShape.get()) {
106 // to sub, so the whole result is selected
107 aSelLab.ForgetAllAttributes(true);
108 TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
110 selectConstruction(theContext, theSubShape);
113 myIsInitialized = true;
115 std::string aSelName = namingName();
116 if(!aSelName.empty())
117 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
120 //selectSubShape("FACE", "Extrusion_1/LateralFace_3");
121 //selectSubShape("FACE", "Extrusion_1/TopFace");
122 //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
123 //selectSubShape("EDGE", "Sketch_1/Edge_6");
125 owner()->data()->sendAttributeUpdated(this);
128 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
130 std::shared_ptr<GeomAPI_Shape> aResult;
131 if (myIsInitialized) {
132 TDF_Label aSelLab = selectionLabel();
133 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
134 ResultPtr aContext = context();
136 return aResult; // empty result
137 return aContext->shape();
139 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
140 return aResult; // empty result
143 Handle(TNaming_NamedShape) aSelection;
144 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
145 TopoDS_Shape aSelShape = aSelection->Get();
146 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
147 aResult->setImpl(new TopoDS_Shape(aSelShape));
148 } else { // for simple construction element: just shape of this construction element
149 ResultConstructionPtr aConstr =
150 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
152 return aConstr->shape();
159 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
162 myIsInitialized = myRef.isInitialized();
165 ResultPtr Model_AttributeSelection::context() {
166 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
170 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
172 ModelAPI_AttributeSelection::setObject(theObject);
173 myRef.setObject(theObject);
176 TDF_LabelMap& Model_AttributeSelection::scope()
178 if (myScope.IsEmpty()) { // create a new scope if not yet done
179 // gets all labels with named shapes that are bofore this feature label (before in history)
180 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
181 owner()->data())->label().Father();
182 int aFeatureID = aFeatureLab.Tag();
183 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
184 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
185 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
187 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
188 for(; aNSIter.More(); aNSIter.Next()) {
189 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
190 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
191 myScope.Add(aNS->Label());
199 bool Model_AttributeSelection::update()
201 ResultPtr aContext = context();
202 if (!aContext.get()) return false;
203 TDF_Label aSelLab = selectionLabel();
204 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
205 return aContext->shape() && !aContext->shape()->isNull();
207 if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
208 return aContext->shape() && !aContext->shape()->isNull();
211 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
212 // body: just a named shape, use selection mechanism from OCCT
213 TNaming_Selector aSelector(aSelLab);
214 bool aResult = aSelector.Solve(scope()) == Standard_True;
215 owner()->data()->sendAttributeUpdated(this);
217 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
218 // construction: identification by the results indexes, recompute faces and
219 // take the face that more close by the indexes
220 std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr =
221 std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(
222 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext)->shape());
223 if (aWirePtr && aWirePtr->hasPlane()) { // sketch sub-element
224 TDF_Label aLab = myRef.myRef->Label();
225 // getting a type of selected shape
226 Handle(TDataStd_Integer) aTypeAttr;
227 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
230 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
231 // selected indexes will be needed in each "if"
232 Handle(TDataStd_IntPackedMap) aSubIds;
233 std::shared_ptr<GeomAPI_Shape> aNewSelected;
235 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
236 // for now working only with composite features
237 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
238 CompositeFeaturePtr aComposite =
239 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
240 if (!aComposite || aComposite->numberOfSubs() == 0) {
244 if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
245 // If this is a wire with plane defined thin it is a sketch-like object
246 std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
247 GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
248 aWirePtr->dirY(), aWirePtr->norm(), aWirePtr, aFaces);
249 if (aFaces.empty()) // no faces, update can not work correctly
251 // if there is no edges indexes, any face can be used: take the first
252 std::shared_ptr<GeomAPI_Shape> aNewSelected;
254 aNewSelected = *(aFaces.begin());
255 } else { // searching for most looks-like initial face by the indexes
256 // prepare edges of the current resut for the fast searching
257 TColStd_MapOfTransient allCurves;
258 const int aSubNum = aComposite->numberOfSubs();
259 for(int a = 0; a < aSubNum; a++) {
260 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
261 FeaturePtr aSub = aComposite->subFeature(a);
262 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
263 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
264 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
265 ResultConstructionPtr aConstr =
266 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
267 if (aConstr->shape() && aConstr->shape()->isEdge()) {
268 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
269 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
270 if (!anEdge.IsNull()) {
271 Standard_Real aFirst, aLast;
272 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
273 allCurves.Add(aCurve);
279 // iterate new result faces and searching for these edges
280 std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFacesIter = aFaces.begin();
281 double aBestFound = 0; // best percentage of found edges
282 for(; aFacesIter != aFaces.end(); aFacesIter++) {
283 int aFound = 0, aNotFound = 0;
284 TopExp_Explorer anEdgesExp((*aFacesIter)->impl<TopoDS_Shape>(), TopAbs_EDGE);
285 for(; anEdgesExp.More(); anEdgesExp.Next()) {
286 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
287 if (!anEdge.IsNull()) {
288 Standard_Real aFirst, aLast;
289 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
290 if (allCurves.Contains(aCurve)) {
297 if (aFound + aNotFound != 0) {
298 double aPercentage = double(aFound) / double(aFound + aNotFound);
299 if (aPercentage > aBestFound) {
300 aBestFound = aPercentage;
301 aNewSelected = *aFacesIter;
306 if (aNewSelected) { // store this new selection
307 selectConstruction(aContext, aNewSelected);
308 owner()->data()->sendAttributeUpdated(this);
311 } else if (aShapeType == TopAbs_EDGE) {
312 // just reselect the edge by the id
313 const int aSubNum = aComposite->numberOfSubs();
314 for(int a = 0; a < aSubNum; a++) {
315 // if aSubIds take any, the first appropriate
316 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
317 // found the appropriate feature
318 FeaturePtr aFeature = aComposite->subFeature(a);
319 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
320 aFeature->results().cbegin();
321 for(;aResIter != aFeature->results().cend(); aResIter++) {
322 ResultConstructionPtr aRes =
323 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
324 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
325 selectConstruction(aContext, aRes->shape());
326 owner()->data()->sendAttributeUpdated(this);
332 } else if (aShapeType == TopAbs_VERTEX) {
333 // just reselect the vertex by the id of edge
334 const int aSubNum = aComposite->numberOfSubs();
335 for(int a = 0; a < aSubNum; a++) {
336 // if aSubIds take any, the first appropriate
337 int aFeatureID = aComposite->subFeatureId(a);
338 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
339 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
340 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
341 // searching for deltas
343 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
344 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
345 // found the feature with appropriate edge
346 FeaturePtr aFeature = aComposite->subFeature(a);
347 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
348 aFeature->results().cbegin();
349 for(;aResIter != aFeature->results().cend(); aResIter++) {
350 ResultConstructionPtr aRes =
351 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
352 if (aRes && aRes->shape()) {
353 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
354 selectConstruction(aContext, aRes->shape());
355 owner()->data()->sendAttributeUpdated(this);
357 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
358 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
360 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
361 if (aVIndex == aVertexNum) { // found!
362 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
363 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
364 selectConstruction(aContext, aVertex);
365 owner()->data()->sendAttributeUpdated(this);
376 } else { // simple construction element: the selected is that needed
377 selectConstruction(aContext, aContext->shape());
378 owner()->data()->sendAttributeUpdated(this);
382 return false; // unknown case
386 void Model_AttributeSelection::selectBody(
387 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
389 // perform the selection
390 TNaming_Selector aSel(selectionLabel());
391 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
392 TopoDS_Shape aContext;
394 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
396 aContext = aBody->shape()->impl<TopoDS_Shape>();
398 ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
400 aContext = aConstr->shape()->impl<TopoDS_Shape>();
402 Events_Error::send("A result with shape is expected");
406 //BRepTools::Write(aNewShape, "Selection0.brep");
407 aSel.Select(aNewShape, aContext);
410 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
411 /// if theID is zero,
412 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
413 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
414 std::string theAdditionalName,
415 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
417 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
418 TNaming_Builder aBuilder(aLab);
419 aBuilder.Generated(theShape);
420 std::stringstream aName;
421 aName<<theContextFeature->name()<<"/";
422 if (!theAdditionalName.empty())
423 aName<<theAdditionalName<<"/";
424 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
425 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
426 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
428 if (theRefs.IsNull()) {
430 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
431 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
432 for(; aRef.More(); aRef.Next()) {
433 aName<<"-"<<aRef.Key();
437 theDoc->addNamingName(aLab, aName.str());
438 TDataStd_Name::Set(aLab, aName.str().c_str());
441 void Model_AttributeSelection::selectConstruction(
442 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
444 std::shared_ptr<Model_Document> aMyDoc =
445 std::dynamic_pointer_cast<Model_Document>(owner()->document());
446 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
447 CompositeFeaturePtr aComposite =
448 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
449 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
450 if (!aComposite || aComposite->numberOfSubs() == 0) {
451 // saving of context is enough: result construction contains exactly the needed shape
452 TNaming_Builder aBuilder(selectionLabel());
453 aBuilder.Generated(aSubShape);
454 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
455 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
458 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
459 TDF_Label aLab = myRef.myRef->Label();
460 // identify the reuslts of sub-object of the composite by edges
461 // save type of the selected shape in integer attribute
462 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
463 TDataStd_Integer::Set(aLab, (int)aShapeType);
465 TColStd_MapOfTransient allCurves;
466 if (aShapeType == TopAbs_VERTEX) { // compare positions
467 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
469 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
470 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
471 Standard_Real aFirst, aLast;
472 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
473 allCurves.Add(aCurve);
476 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
477 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
479 const int aSubNum = aComposite->numberOfSubs();
480 for(int a = 0; a < aSubNum; a++) {
481 FeaturePtr aSub = aComposite->subFeature(a);
482 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
483 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
484 // there may be many shapes (circle and center): register if at least one is in selection
485 for(; aRes != aResults.cend(); aRes++) {
486 ResultConstructionPtr aConstr =
487 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
488 if (!aConstr->shape()) {
491 if (aShapeType == TopAbs_VERTEX) {
492 if (aConstr->shape()->isVertex()) { // compare vertices positions
493 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
494 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
495 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
496 aRefs->Add(aComposite->subFeatureId(a));
498 } else { // get first or last vertex of the edge: last is stored with negative sign
499 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
500 int aDelta = kSTART_VERTEX_DELTA;
501 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
502 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
503 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
504 aRefs->Add(aDelta + aComposite->subFeatureId(a));
507 aDelta += kSTART_VERTEX_DELTA;
511 if (aConstr->shape()->isEdge()) {
512 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
513 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
514 if (!anEdge.IsNull()) {
515 Standard_Real aFirst, aLast;
516 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
517 if (allCurves.Contains(aCurve)) {
518 int anID = aComposite->subFeatureId(a);
520 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
521 // add edges to sub-label to support naming for edges selection
522 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
523 for(; anEdgeExp.More(); anEdgeExp.Next()) {
524 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
525 Standard_Real aFirst, aLast;
526 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
527 if (aFaceCurve == aCurve) {
528 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
531 } else { // put vertices of the selected edge to sub-labels
532 // add edges to sub-label to support naming for edges selection
533 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
534 int aTagIndex = anID + kSTART_VERTEX_DELTA;
535 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
536 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
538 std::stringstream anAdditionalName;
539 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
549 // store the selected as primitive
550 TNaming_Builder aBuilder(selectionLabel());
551 aBuilder.Generated(aSubShape);
552 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
555 TDF_Label Model_AttributeSelection::selectionLabel()
557 return myRef.myRef->Label().FindChild(1);
561 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
562 const TDF_Label& theLabel)
565 // check if the subShape is already in DF
566 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
567 Handle(TDataStd_Name) anAttr;
568 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
569 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
570 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
572 const TDF_Label& aLabel = theDoc->findNamingName(aName);
573 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
574 if(!aLabel.IsEqual(aNS->Label())) {
575 //aName.erase(); //something is wrong, to be checked!!!
576 aName += "_SomethingWrong";
579 const TopoDS_Shape& aShape = aNS->Get();
580 if(aShape.ShapeType() == TopAbs_COMPOUND) {
581 std::string aPostFix("_");
582 TopoDS_Iterator it(aShape);
583 for (int i = 1;it.More();it.Next(), i++) {
584 if(it.Value() == theShape) {
585 aPostFix += TCollection_AsciiString (i).ToCString();
598 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
600 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
601 TopoDS_Compound aCmp;
603 BB.MakeCompound(aCmp);
604 TopTools_ListIteratorOfListOfShape it(theAncestors);
605 for(;it.More();it.Next()) {
606 BB.Add(aCmp, it.Value());
607 theSMap.Add(it.Value());
610 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
611 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
612 for (int i = 1; i <= aMap2.Extent(); i++) {
613 const TopoDS_Shape& aKey = aMap2.FindKey(i);
614 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
615 if(anAncestors.Extent() > 1) aNumber++;
617 if(aNumber > 1) return false;
620 std::string Model_AttributeSelection::namingName()
622 std::string aName("");
623 if(!this->isInitialized()) return aName;
624 Handle(TDataStd_Name) anAtt;
625 if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
626 aName = TCollection_AsciiString(anAtt->Get()).ToCString();
630 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
631 ResultPtr aCont = context();
632 aName = "Undefined name";
633 if(!aCont.get() || aCont->shape()->isNull())
635 if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
636 return aCont->data()->name();
638 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
639 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
641 if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
642 BRepTools::Write(aSubShape, "Selection.brep");
643 BRepTools::Write(aContext, "Context.brep");
646 std::shared_ptr<Model_Document> aDoc =
647 std::dynamic_pointer_cast<Model_Document>(aCont->document());
649 // check if the subShape is already in DF
650 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
651 if(aName.empty() ) { // not in the document!
652 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
655 // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
659 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
660 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
661 if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
662 aName = "Degenerated_Edge";
665 TopTools_IndexedDataMapOfShapeListOfShape aMap;
666 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
667 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
668 bool isTrivialCase(true);
669 /* for (int i = 1; i <= aMap.Extent(); i++) {
670 const TopoDS_Shape& aKey = aMap.FindKey(i);
671 //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
672 if (aKey.IsSame(aSubShape)) continue;
673 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
674 // check that it is not a trivial case (F1 & F2: aNumber = 1)
675 isTrivialCase = isTrivial(anAncestors, aSMap);
678 if(aMap.Contains(aSubShape)) {
679 const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
680 // check that it is not a trivial case (F1 & F2: aNumber = 1)
681 isTrivialCase = isTrivial(anAncestors, aSMap);
684 TopTools_ListOfShape aListOfNbs;
685 if(!isTrivialCase) { // find Neighbors
686 TNaming_Localizer aLocalizer;
687 TopTools_MapOfShape aMap3;
688 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
689 //int n = aMap3.Extent();
690 TopTools_MapIteratorOfMapOfShape it(aMap3);
691 for(;it.More();it.Next()) {
692 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
693 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
694 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
695 TopTools_ListIteratorOfListOfShape it2(aList);
696 for(;it2.More();it2.Next()) {
697 if(aSMap.Contains(it2.Value())) continue; // skip this Face
698 aListOfNbs.Append(it2.Value());
701 } // else a trivial case
703 // build name of the sub-shape Edge
704 for(int i=1; i <= aSMap.Extent(); i++) {
705 const TopoDS_Shape& aFace = aSMap.FindKey(i);
706 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
710 aName += "|" + aFaceName;
712 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
713 for (;itl.More();itl.Next()) {
714 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
715 aName += "|" + aFaceName;
721 // name structure (Monifold Topology):
722 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
723 // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
724 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
725 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
726 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
727 // or compound of 2 open faces.
728 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
729 // two independent edges (wire or compound)
730 // implemented 2 first cases
732 TopTools_IndexedDataMapOfShapeListOfShape aMap;
733 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
734 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
735 TopTools_ListOfShape aList;
736 TopTools_MapOfShape aFMap;
738 //int n = aList2.Extent(); //bug! duplication
740 TopTools_ListIteratorOfListOfShape itl2(aList2);
741 for (int i = 1;itl2.More();itl2.Next(),i++) {
742 if(aFMap.Add(itl2.Value()))
743 aList.Append(itl2.Value());
745 //n = aList.Extent();
747 int n = aList.Extent();
748 if(n < 3) { // open topology case or Compound case => via edges
749 TopTools_IndexedDataMapOfShapeListOfShape aMap;
750 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
751 const TopTools_ListOfShape& aList22 = aMap.FindFromKey(aSubShape);
752 if(aList22.Extent() >= 2) { // regular solution
755 // bug! duplication; fix is below
757 TopTools_ListOfShape aListE;
758 TopTools_ListIteratorOfListOfShape itl2(aList22);
759 for (int i = 1;itl2.More();itl2.Next(),i++) {
760 if(aFMap.Add(itl2.Value()))
761 aListE.Append(itl2.Value());
765 TopTools_ListIteratorOfListOfShape itl(aListE);
766 for (int i = 1;itl.More();itl.Next(),i++) {
767 const TopoDS_Shape& anEdge = itl.Value();
768 std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
772 aName += "|" + anEdgeName;
775 else { // dangle vertex: if(aList22.Extent() == 1)
776 //it should be already in DF
780 TopTools_ListIteratorOfListOfShape itl(aList);
781 for (int i = 1;itl.More();itl.Next(),i++) {
782 const TopoDS_Shape& aFace = itl.Value();
783 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
787 aName += "|" + aFaceName;
794 // aDoc->addNamingName(selectionLabel(), aName);
795 // the selected sub-shape will not be shared and as result it will not require registration
800 TopAbs_ShapeEnum translateType (const std::string& theType)
802 // map from the textual shape types to OCCT enumeration
803 static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
804 if (MyShapeTypes.size() == 0) {
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;
815 MyShapeTypes["FACE"] = TopAbs_FACE;
816 MyShapeTypes["FACES"] = TopAbs_FACE;
817 MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
818 MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
819 MyShapeTypes["WIRE"] = TopAbs_WIRE;
820 MyShapeTypes["EDGE"] = TopAbs_EDGE;
821 MyShapeTypes["EDGES"] = TopAbs_EDGE;
822 MyShapeTypes["SHELL"] = TopAbs_SHELL;
823 MyShapeTypes["SOLID"] = TopAbs_SOLID;
824 MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
826 if (MyShapeTypes.find(theType) != MyShapeTypes.end())
827 return MyShapeTypes[theType];
828 Events_Error::send("Shape type defined in XML is not implemented!");
832 const TopoDS_Shape getShapeFromCompound(const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
834 TopoDS_Shape aSelection;
835 std::string::size_type n = theSubShapeName.rfind('/');
836 if (n == std::string::npos) n = 0;
837 std::string aSubString = theSubShapeName.substr(n + 1);
838 n = aSubString.rfind('_');
839 if (n == std::string::npos) return aSelection;
840 aSubString = aSubString.substr(n+1);
841 int indx = atoi(aSubString.c_str());
842 TopoDS_Iterator it(theCompound);
843 for (int i = 1;it.More();it.Next(), i++) {
845 aSelection = it.Value();
853 const TopoDS_Shape findFaceByName(const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
856 std::string::size_type n, nb = theSubShapeName.rfind('/');
857 if (nb == std::string::npos) nb = 0;
858 std::string aSubString = theSubShapeName.substr(nb + 1);
859 n = aSubString.rfind('_');
860 if (n != std::string::npos) {
861 std::string aSubStr2 = aSubString.substr(0, n);
862 aSubString = theSubShapeName.substr(0, nb + 1);
863 aSubString = aSubString + aSubStr2;
865 aSubString = theSubShapeName;
867 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
868 if(aLabel.IsNull()) return aFace;
869 Handle(TNaming_NamedShape) aNS;
870 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
871 const TopoDS_Shape& aShape = aNS->Get();
872 if(!aShape.IsNull()) {
873 if(aShape.ShapeType() == TopAbs_COMPOUND)
874 aFace = getShapeFromCompound(theSubShapeName, aShape);
882 int ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
884 std::string aName = theSubShapeName;
885 std::string aLastName;
886 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
887 while ((n2 = aName.find('|', n1)) != std::string::npos) {
888 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
889 theList.push_back(aName1);
891 aLastName = aName.substr(n1);
893 if(!aLastName.empty())
894 theList.push_back(aLastName);
895 return theList.size();
898 const TopoDS_Shape findCommonShape(const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
901 std::vector<TopTools_MapOfShape> aVec;
902 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
903 if(theList.Extent() > 1) {
904 aVec.push_back(aMap1);
905 aVec.push_back(aMap2);
907 if(theList.Extent() > 2)
908 aVec.push_back(aMap3);
909 if(theList.Extent() == 4)
910 aVec.push_back(aMap4);
913 TopTools_ListIteratorOfListOfShape it(theList);
914 for(int i = 0;it.More();it.Next(),i++) {
915 const TopoDS_Shape& aFace = it.Value();
917 TopExp_Explorer anExp (aFace, theType);
918 for(;anExp.More();anExp.Next()) {
919 const TopoDS_Shape& anEdge = anExp.Current();
920 if (!anEdge.IsNull())
921 aVec[i].Add(anExp.Current());
924 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
925 for(;anExp.More();anExp.Next()) {
926 const TopoDS_Shape& aVertex = anExp.Current();
927 if (!aVertex.IsNull())
928 aVec[i].Add(anExp.Current());
932 //trivial case: 2 faces
933 TopTools_ListOfShape aList;
934 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
935 for(;it2.More();it2.Next()) {
936 if(aVec[1].Contains(it2.Key())) {
938 if(theList.Extent() == 2)
941 aList.Append(it2.Key());
944 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
945 if(aVec[2].Extent() && aVec[3].Extent()) {
946 TopTools_ListIteratorOfListOfShape it(aList);
947 for(;it.More();it.Next()) {
948 const TopoDS_Shape& aCand = it.Value();
949 // not yet completelly implemented, to be rechecked
950 TopoDS_Vertex aV1, aV2;
951 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
953 if(aVec[2].Contains(aV1)) aNum++;
954 else if(aVec[2].Contains(aV2)) aNum++;
955 if(aVec[3].Contains(aV1)) aNum++;
956 else if(aVec[3].Contains(aV2)) aNum++;
965 if(aList.Extent() && aVec.size() == 3) {
967 TopTools_ListIteratorOfListOfShape it(aList);
968 for(;it.More();it.Next()) {
969 const TopoDS_Shape& aCand = it.Value();
970 if(aVec[2].Contains(aCand)) {
979 std::string getContextName(const std::string& theSubShapeName)
982 std::string::size_type n = theSubShapeName.find('/');
983 if (n == std::string::npos) return aName;
984 aName = theSubShapeName.substr(0, n);
987 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
988 void Model_AttributeSelection::selectSubShape(const std::string& theType, const std::string& theSubShapeName)
990 if(theSubShapeName.empty() || theType.empty()) return;
991 TopAbs_ShapeEnum aType = translateType(theType);
992 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(owner()->document());//std::dynamic_pointer_cast<Model_Document>(aCont->document());
993 std::string aContName = getContextName(theSubShapeName);
994 if(aContName.empty()) return;
995 //ResultPtr aCont = context();
996 ResultPtr aCont = aDoc->findByName(aContName);
997 if(!aCont.get() || aCont->shape()->isNull()) return;
998 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
999 TopAbs_ShapeEnum aContType = aContext.ShapeType();
1000 if(aType <= aContType) return; // not applicable
1003 TopoDS_Shape aSelection;
1006 case TopAbs_COMPOUND:
1008 case TopAbs_COMPSOLID:
1016 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1017 if(!aSelection.IsNull()) {// Select it
1018 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1019 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1020 setValue(aCont, aShapeToBeSelected);
1028 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1029 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1030 if(!aLabel.IsNull()) {
1031 Handle(TNaming_NamedShape) aNS;
1032 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1033 const TopoDS_Shape& aShape = aNS->Get();
1034 if(!aShape.IsNull()) {
1035 if(aShape.ShapeType() == TopAbs_COMPOUND)
1036 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1038 aSelection = aShape;
1042 if(aSelection.IsNull()) {
1043 std::list<std::string> aListofNames;
1044 int n = ParseName(theSubShapeName, aListofNames);
1045 if(n > 1 && n < 5) {
1046 TopTools_ListOfShape aList;
1047 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1048 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1049 aList.Append(aFace);
1051 aSelection = findCommonShape(TopAbs_EDGE, aList);
1054 if(!aSelection.IsNull()) {// Select it
1055 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1056 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1057 setValue(aCont, aShapeToBeSelected);
1063 TopoDS_Shape aSelection;
1064 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1065 if(!aLabel.IsNull()) {
1066 Handle(TNaming_NamedShape) aNS;
1067 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1068 const TopoDS_Shape& aShape = aNS->Get();
1069 if(!aShape.IsNull()) {
1070 if(aShape.ShapeType() == TopAbs_COMPOUND)
1071 aSelection = getShapeFromCompound(theSubShapeName, aShape);
1073 aSelection = aShape;
1077 if(aSelection.IsNull()) {
1078 std::list<std::string> aListofNames;
1079 int n = ParseName(theSubShapeName, aListofNames);
1080 if(n > 1 && n < 4) { // 2 || 3
1081 TopTools_ListOfShape aList;
1082 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1083 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1085 aList.Append(aFace);
1087 aSelection = findCommonShape(TopAbs_VERTEX, aList);
1090 if(!aSelection.IsNull()) {// Select it
1091 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1092 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1093 setValue(aCont, aShapeToBeSelected);
1097 default: //TopAbs_SHAPE
1103 int Model_AttributeSelection::Id()
1105 std::shared_ptr<GeomAPI_Shape> aSelection = value();
1106 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1107 const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1108 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1110 if (aSelection && !aSelection->isNull() &&
1111 aContext && !aContext->isNull())
1113 TopTools_IndexedMapOfShape aSubShapesMap;
1114 TopExp::MapShapes(aMainShape, aSubShapesMap);
1115 anID = aSubShapesMap.FindIndex(aSubShape);