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 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
56 /// (multiplied by the index of the edge)
57 static const int kSTART_VERTEX_DELTA = 1000000;
58 // identifier that there is simple reference: selection equals to context
59 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
61 // on this label is stored:
62 // TNaming_NamedShape - selected shape
63 // TNaming_Naming - topological selection information (for the body)
64 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
65 // TDataStd_Integer - type of the selected shape (for construction)
66 // TDF_Reference - from ReferenceAttribute, the context
68 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
69 const std::shared_ptr<GeomAPI_Shape>& theSubShape)
71 const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
73 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
74 if (isOldShape) return; // shape is the same, so context is also unchanged
75 // update the referenced object if needed
76 bool isOldContext = theContext == myRef.value();
80 myRef.setValue(theContext);
82 // do noth use naming if selected shape is result shape itself, but not sub-shape
83 TDF_Label aSelLab = selectionLabel();
84 if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
85 aSelLab.ForgetAllAttributes(true);
86 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
88 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
89 if (theContext->groupName() == ModelAPI_ResultBody::group())
90 selectBody(theContext, theSubShape);
91 else if (theContext->groupName() == ModelAPI_ResultConstruction::group())
92 selectConstruction(theContext, theSubShape);
95 std::string aSelName = namingName();
97 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
100 //selectSubShape("FACE", "Extrusion_1/LateralFace_3");
101 //selectSubShape("FACE", "Extrusion_1/TopFace");
102 //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
103 //selectSubShape("EDGE", "Sketch_1/Edge_6");
105 myIsInitialized = true;
106 owner()->data()->sendAttributeUpdated(this);
109 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
111 std::shared_ptr<GeomAPI_Shape> aResult;
112 if (myIsInitialized) {
113 TDF_Label aSelLab = selectionLabel();
114 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
115 ResultPtr aContext = context();
117 return aResult; // empty result
118 return aContext->shape();
121 Handle(TNaming_NamedShape) aSelection;
122 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
123 TopoDS_Shape aSelShape = aSelection->Get();
124 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
125 aResult->setImpl(new TopoDS_Shape(aSelShape));
126 } else { // for simple construction element: just shape of this construction element
127 ResultConstructionPtr aConstr =
128 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
130 return aConstr->shape();
137 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
140 myIsInitialized = myRef.isInitialized();
143 ResultPtr Model_AttributeSelection::context() {
144 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
148 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
150 ModelAPI_AttributeSelection::setObject(theObject);
151 myRef.setObject(theObject);
154 TDF_LabelMap& Model_AttributeSelection::scope()
156 if (myScope.IsEmpty()) { // create a new scope if not yet done
157 // gets all labels with named shapes that are bofore this feature label (before in history)
158 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
159 owner()->data())->label().Father();
160 int aFeatureID = aFeatureLab.Tag();
161 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
162 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
163 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
165 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
166 for(; aNSIter.More(); aNSIter.Next()) {
167 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
168 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
169 myScope.Add(aNS->Label());
177 bool Model_AttributeSelection::update()
179 ResultPtr aContext = context();
180 if (!aContext.get()) return false;
181 TDF_Label aSelLab = selectionLabel();
182 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
183 return aContext->shape() && !aContext->shape()->isNull();
186 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
187 // body: just a named shape, use selection mechanism from OCCT
188 TNaming_Selector aSelector(aSelLab);
189 bool aResult = aSelector.Solve(scope()) == Standard_True;
190 owner()->data()->sendAttributeUpdated(this);
192 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
193 // construction: identification by the results indexes, recompute faces and
194 // take the face that more close by the indexes
195 std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr =
196 std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(
197 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext)->shape());
198 if (aWirePtr && aWirePtr->hasPlane()) { // sketch sub-element
199 TDF_Label aLab = myRef.myRef->Label();
200 // getting a type of selected shape
201 Handle(TDataStd_Integer) aTypeAttr;
202 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
205 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
206 // selected indexes will be needed in each "if"
207 Handle(TDataStd_IntPackedMap) aSubIds;
208 std::shared_ptr<GeomAPI_Shape> aNewSelected;
210 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
211 // for now working only with composite features
212 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
213 CompositeFeaturePtr aComposite =
214 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
215 if (!aComposite || aComposite->numberOfSubs() == 0) {
219 if (aShapeType == TopAbs_FACE) {
220 // If this is a wire with plane defined thin it is a sketch-like object
221 std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
222 GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
223 aWirePtr->dirY(), aWirePtr->norm(), aWirePtr, aFaces);
224 if (aFaces.empty()) // no faces, update can not work correctly
226 // if there is no edges indexes, any face can be used: take the first
227 std::shared_ptr<GeomAPI_Shape> aNewSelected;
229 aNewSelected = *(aFaces.begin());
230 } else { // searching for most looks-like initial face by the indexes
231 // prepare edges of the current resut for the fast searching
232 TColStd_MapOfTransient allCurves;
233 const int aSubNum = aComposite->numberOfSubs();
234 for(int a = 0; a < aSubNum; a++) {
235 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
236 FeaturePtr aSub = aComposite->subFeature(a);
237 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
238 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
239 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
240 ResultConstructionPtr aConstr =
241 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
242 if (aConstr->shape() && aConstr->shape()->isEdge()) {
243 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
244 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
245 if (!anEdge.IsNull()) {
246 Standard_Real aFirst, aLast;
247 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
248 allCurves.Add(aCurve);
254 // iterate new result faces and searching for these edges
255 std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFacesIter = aFaces.begin();
256 double aBestFound = 0; // best percentage of found edges
257 for(; aFacesIter != aFaces.end(); aFacesIter++) {
258 int aFound = 0, aNotFound = 0;
259 TopExp_Explorer anEdgesExp((*aFacesIter)->impl<TopoDS_Shape>(), TopAbs_EDGE);
260 for(; anEdgesExp.More(); anEdgesExp.Next()) {
261 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
262 if (!anEdge.IsNull()) {
263 Standard_Real aFirst, aLast;
264 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
265 if (allCurves.Contains(aCurve)) {
272 if (aFound + aNotFound != 0) {
273 double aPercentage = double(aFound) / double(aFound + aNotFound);
274 if (aPercentage > aBestFound) {
275 aBestFound = aPercentage;
276 aNewSelected = *aFacesIter;
281 if (aNewSelected) { // store this new selection
282 selectConstruction(aContext, aNewSelected);
283 owner()->data()->sendAttributeUpdated(this);
286 } else if (aShapeType == TopAbs_EDGE) {
287 // just reselect the edge by the id
288 const int aSubNum = aComposite->numberOfSubs();
289 for(int a = 0; a < aSubNum; a++) {
290 // if aSubIds take any, the first appropriate
291 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
292 // found the appropriate feature
293 FeaturePtr aFeature = aComposite->subFeature(a);
294 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
295 aFeature->results().cbegin();
296 for(;aResIter != aFeature->results().cend(); aResIter++) {
297 ResultConstructionPtr aRes =
298 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
299 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
300 selectConstruction(aContext, aRes->shape());
301 owner()->data()->sendAttributeUpdated(this);
307 } else if (aShapeType == TopAbs_VERTEX) {
308 // just reselect the vertex by the id of edge
309 const int aSubNum = aComposite->numberOfSubs();
310 for(int a = 0; a < aSubNum; a++) {
311 // if aSubIds take any, the first appropriate
312 int aFeatureID = aComposite->subFeatureId(a);
313 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
314 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
315 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
316 // searching for deltas
318 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
319 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
320 // found the feature with appropriate edge
321 FeaturePtr aFeature = aComposite->subFeature(a);
322 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
323 aFeature->results().cbegin();
324 for(;aResIter != aFeature->results().cend(); aResIter++) {
325 ResultConstructionPtr aRes =
326 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
327 if (aRes && aRes->shape()) {
328 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
329 selectConstruction(aContext, aRes->shape());
330 owner()->data()->sendAttributeUpdated(this);
332 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
333 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
335 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
336 if (aVIndex == aVertexNum) { // found!
337 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
338 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
339 selectConstruction(aContext, aVertex);
340 owner()->data()->sendAttributeUpdated(this);
351 } else { // simple construction element: the selected is that needed
352 owner()->data()->sendAttributeUpdated(this);
356 return false; // unknown case
360 void Model_AttributeSelection::selectBody(
361 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
363 // perform the selection
364 TNaming_Selector aSel(selectionLabel());
365 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
366 TopoDS_Shape aContext;
368 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
370 aContext = aBody->shape()->impl<TopoDS_Shape>();
372 ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
374 aContext = aConstr->shape()->impl<TopoDS_Shape>();
376 Events_Error::send("A result with shape is expected");
380 aSel.Select(aNewShape, aContext);
383 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
384 /// if theID is zero,
385 static void registerSubShape(TDF_Label& theMainLabel, TopoDS_Shape theShape,
386 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
387 std::string theAdditionalName,
388 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
390 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
391 TNaming_Builder aBuilder(aLab);
392 aBuilder.Generated(theShape);
393 std::stringstream aName;
394 aName<<theContextFeature->name()<<"/";
395 if (!theAdditionalName.empty())
396 aName<<theAdditionalName<<"/";
397 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
398 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
399 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
401 if (theRefs.IsNull()) {
403 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
404 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
405 for(; aRef.More(); aRef.Next()) {
406 aName<<"_"<<aRef.Key();
410 theDoc->addNamingName(aLab, aName.str());
411 TDataStd_Name::Set(aLab, aName.str().c_str());
414 void Model_AttributeSelection::selectConstruction(
415 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
417 std::shared_ptr<Model_Document> aMyDoc =
418 std::dynamic_pointer_cast<Model_Document>(owner()->document());
419 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
420 CompositeFeaturePtr aComposite =
421 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
422 if (!aComposite || aComposite->numberOfSubs() == 0) {
423 return; // saving of context is enough: result construction contains exactly the needed shape
425 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
426 TDF_Label aLab = myRef.myRef->Label();
427 // identify the reuslts of sub-object of the composite by edges
428 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
429 // save type of the selected shape in integer attribute
430 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
431 TDataStd_Integer::Set(aLab, (int)aShapeType);
433 TColStd_MapOfTransient allCurves;
434 if (aShapeType == TopAbs_VERTEX) { // compare positions
435 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
437 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
438 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
439 Standard_Real aFirst, aLast;
440 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
441 allCurves.Add(aCurve);
444 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
445 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
447 const int aSubNum = aComposite->numberOfSubs();
448 for(int a = 0; a < aSubNum; a++) {
449 FeaturePtr aSub = aComposite->subFeature(a);
450 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
451 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
452 // there may be many shapes (circle and center): register if at least one is in selection
453 for(; aRes != aResults.cend(); aRes++) {
454 ResultConstructionPtr aConstr =
455 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
456 if (!aConstr->shape()) {
459 if (aShapeType == TopAbs_VERTEX) {
460 if (aConstr->shape()->isVertex()) { // compare vertices positions
461 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
462 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
463 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
464 aRefs->Add(aComposite->subFeatureId(a));
466 } else { // get first or last vertex of the edge: last is stored with negative sign
467 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
468 int aDelta = kSTART_VERTEX_DELTA;
469 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
470 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
471 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
472 aRefs->Add(aDelta + aComposite->subFeatureId(a));
475 aDelta += kSTART_VERTEX_DELTA;
479 if (aConstr->shape()->isEdge()) {
480 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
481 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
482 if (!anEdge.IsNull()) {
483 Standard_Real aFirst, aLast;
484 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
485 if (allCurves.Contains(aCurve)) {
486 int anID = aComposite->subFeatureId(a);
488 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
489 // add edges to sub-label to support naming for edges selection
490 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
491 for(; anEdgeExp.More(); anEdgeExp.Next()) {
492 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
493 Standard_Real aFirst, aLast;
494 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
495 if (aFaceCurve == aCurve) {
496 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
499 } else { // put vertices of the selected edge to sub-labels
500 // add edges to sub-label to support naming for edges selection
501 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
502 int aTagIndex = anID + kSTART_VERTEX_DELTA;
503 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
504 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
506 std::stringstream anAdditionalName;
507 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
517 // store the selected as primitive
518 TNaming_Builder aBuilder(selectionLabel());
519 aBuilder.Generated(aSubShape);
520 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
523 TDF_Label Model_AttributeSelection::selectionLabel()
525 return myRef.myRef->Label().FindChild(1);
529 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
530 const TDF_Label& theLabel)
533 // check if the subShape is already in DF
534 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
535 Handle(TDataStd_Name) anAttr;
536 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
537 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
538 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
540 const TDF_Label& aLabel = theDoc->findNamingName(aName);
541 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
542 if(!aLabel.IsEqual(aNS->Label())) {
543 //aName.erase(); //something is wrong, to be checked!!!
544 aName += "_SomethingWrong";
547 const TopoDS_Shape& aShape = aNS->Get();
548 if(aShape.ShapeType() == TopAbs_COMPOUND) {
549 std::string aPostFix("_");
550 TopoDS_Iterator it(aShape);
551 for (int i = 1;it.More();it.Next(), i++) {
552 if(it.Value() == theShape) {
553 aPostFix += TCollection_AsciiString (i).ToCString();
566 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
568 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
569 TopoDS_Compound aCmp;
571 BB.MakeCompound(aCmp);
572 TopTools_ListIteratorOfListOfShape it(theAncestors);
573 for(;it.More();it.Next()) {
574 BB.Add(aCmp, it.Value());
575 theSMap.Add(it.Value());
578 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
579 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
580 for (int i = 1; i <= aMap2.Extent(); i++) {
581 const TopoDS_Shape& aKey = aMap2.FindKey(i);
582 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
583 if(anAncestors.Extent() > 1) aNumber++;
585 if(aNumber > 1) return false;
588 std::string Model_AttributeSelection::namingName()
590 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
591 ResultPtr aCont = context();
593 if(!aSubSh.get() || aSubSh->isNull() || !aCont.get() || aCont->shape()->isNull())
595 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
596 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
597 std::shared_ptr<Model_Document> aDoc =
598 std::dynamic_pointer_cast<Model_Document>(aCont->document());
600 // check if the subShape is already in DF
601 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
602 if(aName.empty() ) { // not in the document!
603 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
606 // the Face should be in DF. If it is not a case, it is an error ==> to be dbugged
610 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
611 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
612 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
613 TopTools_IndexedDataMapOfShapeListOfShape aMap;
614 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
615 bool isTrivialCase(true);
616 for (int i = 1; i <= aMap.Extent(); i++) {
617 const TopoDS_Shape& aKey = aMap.FindKey(i);
618 if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
620 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
621 // check that it is not a trivial case (F1 & F2: aNumber = 1)
622 isTrivialCase = isTrivial(anAncestors, aSMap);
626 TopTools_ListOfShape aListOfNbs;
627 if(!isTrivialCase) { // find Neighbors
628 TNaming_Localizer aLocalizer;
629 TopTools_MapOfShape aMap3;
630 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
631 //int n = aMap3.Extent();
632 TopTools_MapIteratorOfMapOfShape it(aMap3);
633 for(;it.More();it.Next()) {
634 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
635 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
636 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
637 TopTools_ListIteratorOfListOfShape it2(aList);
638 for(;it2.More();it2.Next()) {
639 if(aSMap.Contains(it2.Value())) continue; // skip this Face
640 aListOfNbs.Append(it2.Value());
643 } // else a trivial case
645 // build name of the sub-shape Edge
646 for(int i=1; i <= aSMap.Extent(); i++) {
647 const TopoDS_Shape& aFace = aSMap.FindKey(i);
648 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
652 aName += "|" + aFaceName;
654 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
655 for (;itl.More();itl.Next()) {
656 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
657 aName += "|" + aFaceName;
663 // name structure (Monifold Topology):
664 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
665 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
666 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
667 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
668 // or compound of 2 open faces.
669 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
670 // two independent edges (wire or compound)
671 // implemented 2 first cases
673 TopTools_IndexedDataMapOfShapeListOfShape aMap;
674 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
675 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
676 TopTools_ListOfShape aList;
677 TopTools_MapOfShape aFMap;
679 //int n = aList2.Extent(); //bug!
681 TopTools_ListIteratorOfListOfShape itl2(aList2);
682 for (int i = 1;itl2.More();itl2.Next(),i++) {
683 if(aFMap.Add(itl2.Value()))
684 aList.Append(itl2.Value());
686 //n = aList.Extent();
688 TopTools_ListIteratorOfListOfShape itl(aList);
689 for (int i = 1;itl.More();itl.Next(),i++) {
690 const TopoDS_Shape& aFace = itl.Value();
691 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
695 aName += "|" + aFaceName;
701 // aDoc->addNamingName(selectionLabel(), aName);
702 // the selected sub-shape will not be shared and as result it will not require registration
707 TopAbs_ShapeEnum translateType (const std::string& theType)
709 TCollection_AsciiString aStr(theType.c_str());
711 if(aStr.IsEqual("COMP"))
712 return TopAbs_COMPOUND;
713 else if(aStr.IsEqual("COMS"))
714 return TopAbs_COMPSOLID;
715 else if(aStr.IsEqual("SOLD"))
717 else if(aStr.IsEqual("SHEL"))
719 else if(aStr.IsEqual("FACE"))
721 else if(aStr.IsEqual("WIRE"))
723 else if(aStr.IsEqual("EDGE"))
725 else if(aStr.IsEqual("VERT"))
726 return TopAbs_VERTEX;
731 const TopoDS_Shape getShapeFromCompound(const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
733 TopoDS_Shape aSelection;
734 std::string::size_type n = theSubShapeName.rfind('/');
735 if (n == std::string::npos) n = 0;
736 std::string aSubString = theSubShapeName.substr(n + 1);
737 n = aSubString.rfind('_');
738 if (n == std::string::npos) return aSelection;
739 aSubString = aSubString.substr(n+1);
740 int indx = atoi(aSubString.c_str());
741 TopoDS_Iterator it(theCompound);
742 for (int i = 1;it.More();it.Next(), i++) {
744 aSelection = it.Value();
752 const TopoDS_Shape findFaceByName(const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
755 std::string::size_type n, nb = theSubShapeName.rfind('/');
756 if (nb == std::string::npos) nb = 0;
757 std::string aSubString = theSubShapeName.substr(nb + 1);
758 n = aSubString.rfind('_');
759 if (n != std::string::npos) {
760 std::string aSubStr2 = aSubString.substr(0, n);
761 aSubString = theSubShapeName.substr(0, nb + 1);
762 aSubString = aSubString + aSubStr2;
764 aSubString = theSubShapeName;
766 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
767 if(aLabel.IsNull()) return aFace;
768 Handle(TNaming_NamedShape) aNS;
769 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
770 const TopoDS_Shape& aShape = aNS->Get();
771 if(!aShape.IsNull()) {
772 if(aShape.ShapeType() == TopAbs_COMPOUND)
773 aFace = getShapeFromCompound(theSubShapeName, aShape);
781 int ParseEdgeName(const std::string& theSubShapeName, std::list<std::string>& theList)
783 std::string aName = theSubShapeName;
784 std::string aLastName;
785 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
786 while ((n2 = aName.find('|', n1)) != std::string::npos) {
787 const std::string aName1 = aName.substr(n1, n2); //name of face
788 theList.push_back(aName1);
790 aLastName = aName.substr(n1);
792 if(!aLastName.empty())
793 theList.push_back(aLastName);
794 return theList.size();
797 const TopoDS_Shape findCommonShape(const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
800 std::vector<TopTools_MapOfShape> aVec;
801 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
802 if(theList.Extent() > 1) {
803 aVec.push_back(aMap1);
804 aVec.push_back(aMap2);
806 if(theList.Extent() > 2)
807 aVec.push_back(aMap3);
808 if(theList.Extent() == 4)
809 aVec.push_back(aMap4);
812 TopTools_ListIteratorOfListOfShape it(theList);
813 for(int i = 0;it.More();it.Next(),i++) {
814 const TopoDS_Shape& aFace = it.Value();
815 TopExp_Explorer anExp (aFace, theType);
816 for(;anExp.More();anExp.Next()) {
817 const TopoDS_Shape& anEdge = anExp.Current();
818 if (!anEdge.IsNull())
819 aVec[i].Add(anExp.Current());
822 //trivial case: 2 faces
823 TopTools_ListOfShape aList;
824 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
825 for(;it2.More();it2.Next()) {
826 if(aVec[1].Contains(it2.Key())) {
828 if(theList.Extent() == 2)
831 aList.Append(it2.Key());
834 if(aList.Extent()) {// list of common edges ==> search ny neighbors
835 if(aVec[2].Extent() && aVec[3].Extent()) {
836 TopTools_ListIteratorOfListOfShape it(aList);
837 for(;it.More();it.Next()) {
838 const TopoDS_Shape& aCand = it.Value();
839 // not yet implemented
847 std::string getContextName(const std::string& theSubShapeName)
850 std::string::size_type n = theSubShapeName.find('/');
851 if (n == std::string::npos) return aName;
852 aName = theSubShapeName.substr(0, n);
855 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
856 void Model_AttributeSelection::selectSubShape(const std::string& theType, const std::string& theSubShapeName)
858 if(theSubShapeName.empty() || theType.empty()) return;
859 TopAbs_ShapeEnum aType = translateType(theType);
860 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(owner()->document());//std::dynamic_pointer_cast<Model_Document>(aCont->document());
861 std::string aContName = getContextName(theSubShapeName);
862 if(aContName.empty()) return;
863 //ResultPtr aCont = context();
864 ResultPtr aCont = aDoc->findByName(aContName);
865 if(!aCont.get() || aCont->shape()->isNull()) return;
866 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
867 TopAbs_ShapeEnum aContType = aContext.ShapeType();
868 if(aType <= aContType) return; // not applicable
871 TopoDS_Shape aSelection;
874 case TopAbs_COMPOUND:
876 case TopAbs_COMPSOLID:
884 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
885 if(!aSelection.IsNull()) {// Select it
886 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
887 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
888 setValue(aCont, aShapeToBeSelected);
896 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
897 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
898 if(!aLabel.IsNull()) {
899 Handle(TNaming_NamedShape) aNS;
900 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
901 const TopoDS_Shape& aShape = aNS->Get();
902 if(!aShape.IsNull()) {
903 if(aShape.ShapeType() == TopAbs_COMPOUND)
904 aSelection = getShapeFromCompound(theSubShapeName, aShape);
910 if(aSelection.IsNull()) {
911 std::list<std::string> aListofNames;
912 int n = ParseEdgeName(theSubShapeName, aListofNames);
914 TopTools_ListOfShape aList;
915 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
916 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
919 aSelection = findCommonShape(TopAbs_EDGE, aList);
922 if(!aSelection.IsNull()) {// Select it
923 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
924 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
925 setValue(aCont, aShapeToBeSelected);
931 default: //TopAbs_SHAPE