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");
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();
77 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
78 if (isOldShape) return; // shape is the same, so context is also unchanged
79 // update the referenced object if needed
80 bool isOldContext = theContext == myRef.value();
84 myRef.setValue(theContext);
86 // do noth use naming if selected shape is result shape itself, but not sub-shape
87 TDF_Label aSelLab = selectionLabel();
88 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
89 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
90 // do not select the whole shape for body:it is already must be in the data framework
91 if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
92 aSelLab.ForgetAllAttributes(true);
93 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
95 selectBody(theContext, theSubShape);
97 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
98 selectConstruction(theContext, theSubShape);
100 myIsInitialized = true;
102 std::string aSelName = namingName();
103 if(!aSelName.empty())
104 TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
107 //selectSubShape("FACE", "Extrusion_1/LateralFace_3");
108 //selectSubShape("FACE", "Extrusion_1/TopFace");
109 //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
110 //selectSubShape("EDGE", "Sketch_1/Edge_6");
112 owner()->data()->sendAttributeUpdated(this);
115 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
117 std::shared_ptr<GeomAPI_Shape> aResult;
118 if (myIsInitialized) {
119 TDF_Label aSelLab = selectionLabel();
120 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
121 ResultPtr aContext = context();
123 return aResult; // empty result
124 return aContext->shape();
127 Handle(TNaming_NamedShape) aSelection;
128 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
129 TopoDS_Shape aSelShape = aSelection->Get();
130 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
131 aResult->setImpl(new TopoDS_Shape(aSelShape));
132 } else { // for simple construction element: just shape of this construction element
133 ResultConstructionPtr aConstr =
134 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
136 return aConstr->shape();
143 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
146 myIsInitialized = myRef.isInitialized();
149 ResultPtr Model_AttributeSelection::context() {
150 return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
154 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
156 ModelAPI_AttributeSelection::setObject(theObject);
157 myRef.setObject(theObject);
160 TDF_LabelMap& Model_AttributeSelection::scope()
162 if (myScope.IsEmpty()) { // create a new scope if not yet done
163 // gets all labels with named shapes that are bofore this feature label (before in history)
164 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
165 owner()->data())->label().Father();
166 int aFeatureID = aFeatureLab.Tag();
167 TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
168 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
169 if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
171 TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
172 for(; aNSIter.More(); aNSIter.Next()) {
173 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
174 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
175 myScope.Add(aNS->Label());
183 bool Model_AttributeSelection::update()
185 ResultPtr aContext = context();
186 if (!aContext.get()) return false;
187 TDF_Label aSelLab = selectionLabel();
188 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
189 return aContext->shape() && !aContext->shape()->isNull();
192 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
193 // body: just a named shape, use selection mechanism from OCCT
194 TNaming_Selector aSelector(aSelLab);
195 bool aResult = aSelector.Solve(scope()) == Standard_True;
196 owner()->data()->sendAttributeUpdated(this);
198 } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
199 // construction: identification by the results indexes, recompute faces and
200 // take the face that more close by the indexes
201 std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr =
202 std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(
203 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext)->shape());
204 if (aWirePtr && aWirePtr->hasPlane()) { // sketch sub-element
205 TDF_Label aLab = myRef.myRef->Label();
206 // getting a type of selected shape
207 Handle(TDataStd_Integer) aTypeAttr;
208 if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
211 TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
212 // selected indexes will be needed in each "if"
213 Handle(TDataStd_IntPackedMap) aSubIds;
214 std::shared_ptr<GeomAPI_Shape> aNewSelected;
216 !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
217 // for now working only with composite features
218 FeaturePtr aContextFeature = aContext->document()->feature(aContext);
219 CompositeFeaturePtr aComposite =
220 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
221 if (!aComposite || aComposite->numberOfSubs() == 0) {
225 if (aShapeType == TopAbs_FACE) {
226 // If this is a wire with plane defined thin it is a sketch-like object
227 std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
228 GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
229 aWirePtr->dirY(), aWirePtr->norm(), aWirePtr, aFaces);
230 if (aFaces.empty()) // no faces, update can not work correctly
232 // if there is no edges indexes, any face can be used: take the first
233 std::shared_ptr<GeomAPI_Shape> aNewSelected;
235 aNewSelected = *(aFaces.begin());
236 } else { // searching for most looks-like initial face by the indexes
237 // prepare edges of the current resut for the fast searching
238 TColStd_MapOfTransient allCurves;
239 const int aSubNum = aComposite->numberOfSubs();
240 for(int a = 0; a < aSubNum; a++) {
241 if (aSubIds->Contains(aComposite->subFeatureId(a))) {
242 FeaturePtr aSub = aComposite->subFeature(a);
243 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
244 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
245 for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
246 ResultConstructionPtr aConstr =
247 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
248 if (aConstr->shape() && aConstr->shape()->isEdge()) {
249 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
250 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
251 if (!anEdge.IsNull()) {
252 Standard_Real aFirst, aLast;
253 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
254 allCurves.Add(aCurve);
260 // iterate new result faces and searching for these edges
261 std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFacesIter = aFaces.begin();
262 double aBestFound = 0; // best percentage of found edges
263 for(; aFacesIter != aFaces.end(); aFacesIter++) {
264 int aFound = 0, aNotFound = 0;
265 TopExp_Explorer anEdgesExp((*aFacesIter)->impl<TopoDS_Shape>(), TopAbs_EDGE);
266 for(; anEdgesExp.More(); anEdgesExp.Next()) {
267 TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
268 if (!anEdge.IsNull()) {
269 Standard_Real aFirst, aLast;
270 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
271 if (allCurves.Contains(aCurve)) {
278 if (aFound + aNotFound != 0) {
279 double aPercentage = double(aFound) / double(aFound + aNotFound);
280 if (aPercentage > aBestFound) {
281 aBestFound = aPercentage;
282 aNewSelected = *aFacesIter;
287 if (aNewSelected) { // store this new selection
288 selectConstruction(aContext, aNewSelected);
289 owner()->data()->sendAttributeUpdated(this);
292 } else if (aShapeType == TopAbs_EDGE) {
293 // just reselect the edge by the id
294 const int aSubNum = aComposite->numberOfSubs();
295 for(int a = 0; a < aSubNum; a++) {
296 // if aSubIds take any, the first appropriate
297 if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
298 // found the appropriate feature
299 FeaturePtr aFeature = aComposite->subFeature(a);
300 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
301 aFeature->results().cbegin();
302 for(;aResIter != aFeature->results().cend(); aResIter++) {
303 ResultConstructionPtr aRes =
304 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
305 if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
306 selectConstruction(aContext, aRes->shape());
307 owner()->data()->sendAttributeUpdated(this);
313 } else if (aShapeType == TopAbs_VERTEX) {
314 // just reselect the vertex by the id of edge
315 const int aSubNum = aComposite->numberOfSubs();
316 for(int a = 0; a < aSubNum; a++) {
317 // if aSubIds take any, the first appropriate
318 int aFeatureID = aComposite->subFeatureId(a);
319 if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
320 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
321 aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
322 // searching for deltas
324 if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
325 else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
326 // found the feature with appropriate edge
327 FeaturePtr aFeature = aComposite->subFeature(a);
328 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
329 aFeature->results().cbegin();
330 for(;aResIter != aFeature->results().cend(); aResIter++) {
331 ResultConstructionPtr aRes =
332 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
333 if (aRes && aRes->shape()) {
334 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
335 selectConstruction(aContext, aRes->shape());
336 owner()->data()->sendAttributeUpdated(this);
338 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
339 const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
341 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
342 if (aVIndex == aVertexNum) { // found!
343 std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
344 aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
345 selectConstruction(aContext, aVertex);
346 owner()->data()->sendAttributeUpdated(this);
357 } else { // simple construction element: the selected is that needed
358 selectConstruction(aContext, aContext->shape());
359 owner()->data()->sendAttributeUpdated(this);
363 return false; // unknown case
367 void Model_AttributeSelection::selectBody(
368 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
370 // perform the selection
371 TNaming_Selector aSel(selectionLabel());
372 TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
373 TopoDS_Shape aContext;
375 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
377 aContext = aBody->shape()->impl<TopoDS_Shape>();
379 ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
381 aContext = aConstr->shape()->impl<TopoDS_Shape>();
383 Events_Error::send("A result with shape is expected");
387 aSel.Select(aNewShape, aContext);
390 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
391 /// if theID is zero,
392 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
393 const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
394 std::string theAdditionalName,
395 Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
397 TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
398 TNaming_Builder aBuilder(aLab);
399 aBuilder.Generated(theShape);
400 std::stringstream aName;
401 aName<<theContextFeature->name()<<"/";
402 if (!theAdditionalName.empty())
403 aName<<theAdditionalName<<"/";
404 if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
405 else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
406 else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
408 if (theRefs.IsNull()) {
410 } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
411 TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
412 for(; aRef.More(); aRef.Next()) {
413 aName<<"-"<<aRef.Key();
417 theDoc->addNamingName(aLab, aName.str());
418 TDataStd_Name::Set(aLab, aName.str().c_str());
421 void Model_AttributeSelection::selectConstruction(
422 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
424 std::shared_ptr<Model_Document> aMyDoc =
425 std::dynamic_pointer_cast<Model_Document>(owner()->document());
426 FeaturePtr aContextFeature = theContext->document()->feature(theContext);
427 CompositeFeaturePtr aComposite =
428 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
429 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
430 if (!aComposite || aComposite->numberOfSubs() == 0) {
431 // saving of context is enough: result construction contains exactly the needed shape
432 TNaming_Builder aBuilder(selectionLabel());
433 aBuilder.Generated(aSubShape);
434 aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
435 TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
438 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
439 TDF_Label aLab = myRef.myRef->Label();
440 // identify the reuslts of sub-object of the composite by edges
441 // save type of the selected shape in integer attribute
442 TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
443 TDataStd_Integer::Set(aLab, (int)aShapeType);
445 TColStd_MapOfTransient allCurves;
446 if (aShapeType == TopAbs_VERTEX) { // compare positions
447 aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
449 for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
450 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
451 Standard_Real aFirst, aLast;
452 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
453 allCurves.Add(aCurve);
456 // iterate and store the result ids of sub-elements and sub-elements to sub-labels
457 Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
459 const int aSubNum = aComposite->numberOfSubs();
460 for(int a = 0; a < aSubNum; a++) {
461 FeaturePtr aSub = aComposite->subFeature(a);
462 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
463 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
464 // there may be many shapes (circle and center): register if at least one is in selection
465 for(; aRes != aResults.cend(); aRes++) {
466 ResultConstructionPtr aConstr =
467 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
468 if (!aConstr->shape()) {
471 if (aShapeType == TopAbs_VERTEX) {
472 if (aConstr->shape()->isVertex()) { // compare vertices positions
473 const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
474 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
475 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
476 aRefs->Add(aComposite->subFeatureId(a));
478 } else { // get first or last vertex of the edge: last is stored with negative sign
479 const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
480 int aDelta = kSTART_VERTEX_DELTA;
481 for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
482 gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
483 if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
484 aRefs->Add(aDelta + aComposite->subFeatureId(a));
487 aDelta += kSTART_VERTEX_DELTA;
491 if (aConstr->shape()->isEdge()) {
492 const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
493 TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
494 if (!anEdge.IsNull()) {
495 Standard_Real aFirst, aLast;
496 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
497 if (allCurves.Contains(aCurve)) {
498 int anID = aComposite->subFeatureId(a);
500 if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
501 // add edges to sub-label to support naming for edges selection
502 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
503 for(; anEdgeExp.More(); anEdgeExp.Next()) {
504 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
505 Standard_Real aFirst, aLast;
506 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
507 if (aFaceCurve == aCurve) {
508 registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
511 } else { // put vertices of the selected edge to sub-labels
512 // add edges to sub-label to support naming for edges selection
513 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
514 int aTagIndex = anID + kSTART_VERTEX_DELTA;
515 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
516 TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
518 std::stringstream anAdditionalName;
519 registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
529 // store the selected as primitive
530 TNaming_Builder aBuilder(selectionLabel());
531 aBuilder.Generated(aSubShape);
532 registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
535 TDF_Label Model_AttributeSelection::selectionLabel()
537 return myRef.myRef->Label().FindChild(1);
541 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
542 const TDF_Label& theLabel)
545 // check if the subShape is already in DF
546 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
547 Handle(TDataStd_Name) anAttr;
548 if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
549 if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
550 aName = TCollection_AsciiString(anAttr->Get()).ToCString();
552 const TDF_Label& aLabel = theDoc->findNamingName(aName);
553 /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
554 if(!aLabel.IsEqual(aNS->Label())) {
555 //aName.erase(); //something is wrong, to be checked!!!
556 aName += "_SomethingWrong";
559 const TopoDS_Shape& aShape = aNS->Get();
560 if(aShape.ShapeType() == TopAbs_COMPOUND) {
561 std::string aPostFix("_");
562 TopoDS_Iterator it(aShape);
563 for (int i = 1;it.More();it.Next(), i++) {
564 if(it.Value() == theShape) {
565 aPostFix += TCollection_AsciiString (i).ToCString();
578 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
580 // a trivial case: F1 & F2, aNumber = 1, i.e. intersection gives 1 edge.
581 TopoDS_Compound aCmp;
583 BB.MakeCompound(aCmp);
584 TopTools_ListIteratorOfListOfShape it(theAncestors);
585 for(;it.More();it.Next()) {
586 BB.Add(aCmp, it.Value());
587 theSMap.Add(it.Value());
590 TopTools_IndexedDataMapOfShapeListOfShape aMap2;
591 TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
592 for (int i = 1; i <= aMap2.Extent(); i++) {
593 const TopoDS_Shape& aKey = aMap2.FindKey(i);
594 const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
595 if(anAncestors.Extent() > 1) aNumber++;
597 if(aNumber > 1) return false;
600 std::string Model_AttributeSelection::namingName()
602 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
603 ResultPtr aCont = context();
605 if(!aSubSh.get() || aSubSh->isNull() || !aCont.get() || aCont->shape()->isNull())
607 TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
609 BRepTools::Write(aSubShape, "Selection.brep");
611 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
612 std::shared_ptr<Model_Document> aDoc =
613 std::dynamic_pointer_cast<Model_Document>(aCont->document());
615 // check if the subShape is already in DF
616 aName = GetShapeName(aDoc, aSubShape, selectionLabel());
617 if(aName.empty() ) { // not in the document!
618 TopAbs_ShapeEnum aType = aSubShape.ShapeType();
621 // the Face should be in DF. If it is not a case, it is an error ==> to be dbugged
625 // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
626 // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
627 TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
628 TopTools_IndexedDataMapOfShapeListOfShape aMap;
629 TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
630 bool isTrivialCase(true);
631 for (int i = 1; i <= aMap.Extent(); i++) {
632 const TopoDS_Shape& aKey = aMap.FindKey(i);
633 if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
635 const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
636 // check that it is not a trivial case (F1 & F2: aNumber = 1)
637 isTrivialCase = isTrivial(anAncestors, aSMap);
641 TopTools_ListOfShape aListOfNbs;
642 if(!isTrivialCase) { // find Neighbors
643 TNaming_Localizer aLocalizer;
644 TopTools_MapOfShape aMap3;
645 aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
646 //int n = aMap3.Extent();
647 TopTools_MapIteratorOfMapOfShape it(aMap3);
648 for(;it.More();it.Next()) {
649 const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
650 //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
651 const TopTools_ListOfShape& aList = aMap.FindFromKey(aNbShape);
652 TopTools_ListIteratorOfListOfShape it2(aList);
653 for(;it2.More();it2.Next()) {
654 if(aSMap.Contains(it2.Value())) continue; // skip this Face
655 aListOfNbs.Append(it2.Value());
658 } // else a trivial case
660 // build name of the sub-shape Edge
661 for(int i=1; i <= aSMap.Extent(); i++) {
662 const TopoDS_Shape& aFace = aSMap.FindKey(i);
663 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
667 aName += "|" + aFaceName;
669 TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
670 for (;itl.More();itl.Next()) {
671 std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
672 aName += "|" + aFaceName;
678 // name structure (Monifold Topology):
679 // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
680 // 2) F1 | F2 - intersection of 2 faces definses a vertex - applicable for case
681 // when 1 faces is cylindrical, conical, spherical or revolution and etc.
682 // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
683 // or compound of 2 open faces.
684 // 4) E1 | E2 - intesection of 2 edges defines a vertex - when we have a case of
685 // two independent edges (wire or compound)
686 // implemented 2 first cases
688 TopTools_IndexedDataMapOfShapeListOfShape aMap;
689 TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
690 const TopTools_ListOfShape& aList2 = aMap.FindFromKey(aSubShape);
691 TopTools_ListOfShape aList;
692 TopTools_MapOfShape aFMap;
694 //int n = aList2.Extent(); //bug!
696 TopTools_ListIteratorOfListOfShape itl2(aList2);
697 for (int i = 1;itl2.More();itl2.Next(),i++) {
698 if(aFMap.Add(itl2.Value()))
699 aList.Append(itl2.Value());
701 //n = aList.Extent();
703 TopTools_ListIteratorOfListOfShape itl(aList);
704 for (int i = 1;itl.More();itl.Next(),i++) {
705 const TopoDS_Shape& aFace = itl.Value();
706 std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
710 aName += "|" + aFaceName;
716 // aDoc->addNamingName(selectionLabel(), aName);
717 // the selected sub-shape will not be shared and as result it will not require registration
722 TopAbs_ShapeEnum translateType (const std::string& theType)
724 TCollection_AsciiString aStr(theType.c_str());
726 if(aStr.IsEqual("COMP"))
727 return TopAbs_COMPOUND;
728 else if(aStr.IsEqual("COMS"))
729 return TopAbs_COMPSOLID;
730 else if(aStr.IsEqual("SOLD"))
732 else if(aStr.IsEqual("SHEL"))
734 else if(aStr.IsEqual("FACE"))
736 else if(aStr.IsEqual("WIRE"))
738 else if(aStr.IsEqual("EDGE"))
740 else if(aStr.IsEqual("VERT"))
741 return TopAbs_VERTEX;
746 const TopoDS_Shape getShapeFromCompound(const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
748 TopoDS_Shape aSelection;
749 std::string::size_type n = theSubShapeName.rfind('/');
750 if (n == std::string::npos) n = 0;
751 std::string aSubString = theSubShapeName.substr(n + 1);
752 n = aSubString.rfind('_');
753 if (n == std::string::npos) return aSelection;
754 aSubString = aSubString.substr(n+1);
755 int indx = atoi(aSubString.c_str());
756 TopoDS_Iterator it(theCompound);
757 for (int i = 1;it.More();it.Next(), i++) {
759 aSelection = it.Value();
767 const TopoDS_Shape findFaceByName(const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
770 std::string::size_type n, nb = theSubShapeName.rfind('/');
771 if (nb == std::string::npos) nb = 0;
772 std::string aSubString = theSubShapeName.substr(nb + 1);
773 n = aSubString.rfind('_');
774 if (n != std::string::npos) {
775 std::string aSubStr2 = aSubString.substr(0, n);
776 aSubString = theSubShapeName.substr(0, nb + 1);
777 aSubString = aSubString + aSubStr2;
779 aSubString = theSubShapeName;
781 const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
782 if(aLabel.IsNull()) return aFace;
783 Handle(TNaming_NamedShape) aNS;
784 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
785 const TopoDS_Shape& aShape = aNS->Get();
786 if(!aShape.IsNull()) {
787 if(aShape.ShapeType() == TopAbs_COMPOUND)
788 aFace = getShapeFromCompound(theSubShapeName, aShape);
796 int ParseName(const std::string& theSubShapeName, std::list<std::string>& theList)
798 std::string aName = theSubShapeName;
799 std::string aLastName;
800 int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
801 while ((n2 = aName.find('|', n1)) != std::string::npos) {
802 const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
803 theList.push_back(aName1);
805 aLastName = aName.substr(n1);
807 if(!aLastName.empty())
808 theList.push_back(aLastName);
809 return theList.size();
812 const TopoDS_Shape findCommonShape(const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
815 std::vector<TopTools_MapOfShape> aVec;
816 TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
817 if(theList.Extent() > 1) {
818 aVec.push_back(aMap1);
819 aVec.push_back(aMap2);
821 if(theList.Extent() > 2)
822 aVec.push_back(aMap3);
823 if(theList.Extent() == 4)
824 aVec.push_back(aMap4);
827 TopTools_ListIteratorOfListOfShape it(theList);
828 for(int i = 0;it.More();it.Next(),i++) {
829 const TopoDS_Shape& aFace = it.Value();
831 TopExp_Explorer anExp (aFace, theType);
832 for(;anExp.More();anExp.Next()) {
833 const TopoDS_Shape& anEdge = anExp.Current();
834 if (!anEdge.IsNull())
835 aVec[i].Add(anExp.Current());
838 TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
839 for(;anExp.More();anExp.Next()) {
840 const TopoDS_Shape& aVertex = anExp.Current();
841 if (!aVertex.IsNull())
842 aVec[i].Add(anExp.Current());
846 //trivial case: 2 faces
847 TopTools_ListOfShape aList;
848 TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
849 for(;it2.More();it2.Next()) {
850 if(aVec[1].Contains(it2.Key())) {
852 if(theList.Extent() == 2)
855 aList.Append(it2.Key());
858 if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors
859 if(aVec[2].Extent() && aVec[3].Extent()) {
860 TopTools_ListIteratorOfListOfShape it(aList);
861 for(;it.More();it.Next()) {
862 const TopoDS_Shape& aCand = it.Value();
863 // not yet completelly implemented, to be rechecked
864 TopoDS_Vertex aV1, aV2;
865 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
867 if(aVec[2].Contains(aV1)) aNum++;
868 else if(aVec[2].Contains(aV2)) aNum++;
869 if(aVec[3].Contains(aV1)) aNum++;
870 else if(aVec[3].Contains(aV2)) aNum++;
879 if(aList.Extent() && aVec.size() == 3) {
881 TopTools_ListIteratorOfListOfShape it(aList);
882 for(;it.More();it.Next()) {
883 const TopoDS_Shape& aCand = it.Value();
884 if(aVec[2].Contains(aCand)) {
893 std::string getContextName(const std::string& theSubShapeName)
896 std::string::size_type n = theSubShapeName.find('/');
897 if (n == std::string::npos) return aName;
898 aName = theSubShapeName.substr(0, n);
901 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
902 void Model_AttributeSelection::selectSubShape(const std::string& theType, const std::string& theSubShapeName)
904 if(theSubShapeName.empty() || theType.empty()) return;
905 TopAbs_ShapeEnum aType = translateType(theType);
906 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(owner()->document());//std::dynamic_pointer_cast<Model_Document>(aCont->document());
907 std::string aContName = getContextName(theSubShapeName);
908 if(aContName.empty()) return;
909 //ResultPtr aCont = context();
910 ResultPtr aCont = aDoc->findByName(aContName);
911 if(!aCont.get() || aCont->shape()->isNull()) return;
912 TopoDS_Shape aContext = aCont->shape()->impl<TopoDS_Shape>();
913 TopAbs_ShapeEnum aContType = aContext.ShapeType();
914 if(aType <= aContType) return; // not applicable
917 TopoDS_Shape aSelection;
920 case TopAbs_COMPOUND:
922 case TopAbs_COMPSOLID:
930 const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
931 if(!aSelection.IsNull()) {// Select it
932 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
933 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
934 setValue(aCont, aShapeToBeSelected);
942 TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
943 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
944 if(!aLabel.IsNull()) {
945 Handle(TNaming_NamedShape) aNS;
946 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
947 const TopoDS_Shape& aShape = aNS->Get();
948 if(!aShape.IsNull()) {
949 if(aShape.ShapeType() == TopAbs_COMPOUND)
950 aSelection = getShapeFromCompound(theSubShapeName, aShape);
956 if(aSelection.IsNull()) {
957 std::list<std::string> aListofNames;
958 int n = ParseName(theSubShapeName, aListofNames);
960 TopTools_ListOfShape aList;
961 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
962 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
965 aSelection = findCommonShape(TopAbs_EDGE, aList);
968 if(!aSelection.IsNull()) {// Select it
969 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
970 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
971 setValue(aCont, aShapeToBeSelected);
977 TopoDS_Shape aSelection;
978 const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
979 if(!aLabel.IsNull()) {
980 Handle(TNaming_NamedShape) aNS;
981 if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
982 const TopoDS_Shape& aShape = aNS->Get();
983 if(!aShape.IsNull()) {
984 if(aShape.ShapeType() == TopAbs_COMPOUND)
985 aSelection = getShapeFromCompound(theSubShapeName, aShape);
991 if(aSelection.IsNull()) {
992 std::list<std::string> aListofNames;
993 int n = ParseName(theSubShapeName, aListofNames);
994 if(n > 1 && n < 4) { // 2 || 3
995 TopTools_ListOfShape aList;
996 for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
997 const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1001 aSelection = findCommonShape(TopAbs_VERTEX, aList);
1004 if(!aSelection.IsNull()) {// Select it
1005 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1006 aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1007 setValue(aCont, aShapeToBeSelected);
1011 default: //TopAbs_SHAPE