Salome HOME
Change behavior of the point-line distance constraint (in solver connector)
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Sketch.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <Config_PropManager.h>
21
22 #include <GeomAlgoAPI_CompoundBuilder.h>
23 #include <GeomAlgoAPI_FaceBuilder.h>
24
25 #include <GeomAPI_Dir.h>
26 #include <GeomAPI_PlanarEdges.h>
27 #include <GeomAPI_ShapeIterator.h>
28 #include <GeomAPI_Vertex.h>
29
30 #include <GeomDataAPI_Point2D.h>
31 #include <GeomAlgoAPI_PointBuilder.h>
32
33 #include <ModelAPI_AttributeRefList.h>
34 #include <ModelAPI_AttributeString.h>
35 #include <ModelAPI_Data.h>
36 #include <ModelAPI_Document.h>
37 #include <ModelAPI_Feature.h>
38 #include <ModelAPI_Object.h>
39 #include <ModelAPI_ResultConstruction.h>
40 #include <ModelAPI_Validator.h>
41 #include <ModelAPI_Session.h>
42 #include <ModelAPI_Events.h>
43
44 #include <SketchPlugin_Sketch.h>
45 #include <SketchPlugin_Feature.h>
46 #include <SketchPlugin_IntersectionPoint.h>
47 #include <SketchPlugin_Projection.h>
48 #include <SketchPlugin_SketchEntity.h>
49 #include <SketchPlugin_Tools.h>
50
51 #include <Events_InfoMessage.h>
52 #include <Events_Loop.h>
53
54 #include <memory>
55
56 #include <math.h>
57 #include <vector>
58
59 SketchPlugin_Sketch::SketchPlugin_Sketch()
60 {
61 }
62
63 void SketchPlugin_Sketch::initAttributes()
64 {
65   data()->addAttribute(SketchPlugin_Sketch::ORIGIN_ID(), GeomDataAPI_Point::typeId());
66   data()->addAttribute(SketchPlugin_Sketch::DIRX_ID(), GeomDataAPI_Dir::typeId());
67   data()->addAttribute(SketchPlugin_Sketch::NORM_ID(), GeomDataAPI_Dir::typeId());
68   data()->addAttribute(SketchPlugin_Sketch::FEATURES_ID(), ModelAPI_AttributeRefList::typeId());
69   // the selected face, base for the sketcher plane, not obligatory
70   data()->addAttribute(SketchPlugin_SketchEntity::EXTERNAL_ID(),
71     ModelAPI_AttributeSelection::typeId());
72   ModelAPI_Session::get()->validators()->registerNotObligatory(
73     getKind(), SketchPlugin_SketchEntity::EXTERNAL_ID());
74   data()->addAttribute(SketchPlugin_Sketch::SOLVER_ERROR(), ModelAPI_AttributeString::typeId());
75   ModelAPI_Session::get()->validators()->registerNotObligatory(
76     getKind(), SketchPlugin_Sketch::SOLVER_ERROR());
77   data()->addAttribute(SketchPlugin_Sketch::SOLVER_DOF(), ModelAPI_AttributeString::typeId());
78   ModelAPI_Session::get()->validators()->registerNotObligatory(
79     getKind(), SketchPlugin_Sketch::SOLVER_DOF());
80 }
81
82 void SketchPlugin_Sketch::execute()
83 {
84   if (!data()->isValid())
85     return;
86   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
87       ModelAPI_AttributeRefList>(data()->attribute(SketchPlugin_Sketch::FEATURES_ID()));
88
89   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
90       data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
91   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
92       data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
93   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
94       data()->attribute(SketchPlugin_Sketch::NORM_ID()));
95
96   std::list<ObjectPtr> aFeatures = aRefList->list();
97   if (aFeatures.empty()) // actually, this must be avoided by the validators
98     return;
99
100   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
101   std::shared_ptr<SketchPlugin_Feature> aFeature;
102   std::list<std::shared_ptr<GeomAPI_Shape> > aFeaturesPreview;
103   for (; anIt != aLast; anIt++) {
104     aFeature = std::dynamic_pointer_cast<SketchPlugin_Feature>(*anIt);
105     if (aFeature) {
106       if (!aFeature->sketch()) // on load document the back references are missed
107         aFeature->setSketch(this);
108       // do not include into the result the external edges with disabled flag "Include into result"
109       if (aFeature->data()->attribute(SketchPlugin_SketchEntity::EXTERNAL_ID())) {
110         if (aFeature->data()->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->context()) {
111           const std::string& anAttrName =
112               aFeature->getKind() == SketchPlugin_Projection::ID() ?
113               SketchPlugin_Projection::INCLUDE_INTO_RESULT() :
114               SketchPlugin_IntersectionPoint::INCLUDE_INTO_RESULT();
115           AttributeBooleanPtr aKeepResult = aFeature->boolean(anAttrName);
116           if (!aKeepResult || !aKeepResult->value())
117             continue;
118         }
119       }
120       // do not include the construction entities in the result
121       if (aFeature->data()->attribute(SketchPlugin_SketchEntity::AUXILIARY_ID())) {
122         if (aFeature->data()->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value())
123           continue;
124       }
125
126       const std::list<std::shared_ptr<ModelAPI_Result> >& aRes = aFeature->results();
127       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter = aRes.cbegin();
128       for (; aResIter != aRes.cend(); aResIter++) {
129         std::shared_ptr<ModelAPI_ResultConstruction> aConstr = std::dynamic_pointer_cast<
130             ModelAPI_ResultConstruction>(*aResIter);
131         if (aConstr) {
132           std::shared_ptr<GeomAPI_Shape> aShape = aConstr->shape();
133           if (aShape)
134             aFeaturesPreview.push_back(aShape);
135         }
136       }
137     }
138   }
139
140   // Collect all edges as one big wire
141   std::shared_ptr<GeomAPI_PlanarEdges> aBigWire(new GeomAPI_PlanarEdges);
142   std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator aShapeIt = aFeaturesPreview.begin();
143   for (; aShapeIt != aFeaturesPreview.end(); ++aShapeIt) {
144     aBigWire->addEdge(*aShapeIt);
145   }
146   aBigWire->setPlane(anOrigin->pnt(), aDirX->dir(), aNorm->dir());
147   std::shared_ptr<ModelAPI_ResultConstruction> aConstr = document()->createConstruction(data());
148   aConstr->setShape(aBigWire);
149   setResult(aConstr);
150 }
151
152 std::shared_ptr<ModelAPI_Feature> SketchPlugin_Sketch::addFeature(std::string theID)
153 {
154   // Set last feature of the sketch as current feature.
155   // Reason: Changing of parameter through Python API may lead to creation of new features
156   //         (e.g. changing number of copies in MultiRotation). If the sketch is not the last
157   //         feature in the Object Browser, then new features will be added to the end feature.
158   //         Therefore, setting any feature below the sketch as a current feature will disable
159   //         these newly created features.
160   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
161       ModelAPI_AttributeRefList>(data()->attribute(SketchPlugin_Sketch::FEATURES_ID()));
162   int aSize = aRefList->size(false);
163   ObjectPtr aLastObject = aSize == 0 ? data()->owner() : aRefList->object(aSize - 1, false);
164   FeaturePtr aLastFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aLastObject);
165   document()->setCurrentFeature(aLastFeature, false);
166
167   // add new feature
168   std::shared_ptr<ModelAPI_Feature> aNew = document()->addFeature(theID, false);
169   if (aNew) {
170     // the sketch cannot be specified for the macro-features defined in python
171     // like SketchRectangle, so we need to check the type of new feature
172     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
173         std::dynamic_pointer_cast<SketchPlugin_Feature>(aNew);
174     if (aSketchFeature)
175       aSketchFeature->setSketch(this);
176     data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->append(aNew);
177   }
178    // set as current also after it becomes sub to set correctly enabled for other sketch subs
179   document()->setCurrentFeature(aNew, false);
180
181   return aNew;
182 }
183
184 void SketchPlugin_Sketch::removeFeature(std::shared_ptr<ModelAPI_Feature> theFeature)
185 {
186   if (!data()->isValid()) // sketch is already removed (case on undo of sketch), sync is not needed
187     return;
188   AttributeRefListPtr aList = reflist(SketchPlugin_Sketch::FEATURES_ID());
189   // if the object is last, remove it from the list
190   // (needed to skip empty transaction on edit of sketch feature)
191   if (aList->object(aList->size(true) - 1, true) == theFeature) {
192     aList->remove(theFeature);
193   } else {
194     // to keep the persistent sub-elements indexing, do not remove elements from list,
195     // but substitute by nulls
196     aList->substitute(theFeature, ObjectPtr());
197   }
198 }
199
200 int SketchPlugin_Sketch::numberOfSubs(bool forTree) const
201 {
202   if (forTree)
203     return 0;
204   return data()->reflist(FEATURES_ID())->size(false);
205 }
206
207 std::shared_ptr<ModelAPI_Feature> SketchPlugin_Sketch::subFeature(
208   const int theIndex, bool forTree)
209 {
210   if (forTree)
211     return FeaturePtr();
212
213   ObjectPtr anObj = data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->object(theIndex, false);
214   FeaturePtr aRes = std::dynamic_pointer_cast<ModelAPI_Feature>(anObj);
215   return aRes;
216 }
217
218 int SketchPlugin_Sketch::subFeatureId(const int theIndex) const
219 {
220   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
221       ModelAPI_AttributeRefList>(data()->attribute(SketchPlugin_Sketch::FEATURES_ID()));
222   std::list<ObjectPtr> aFeatures = aRefList->list();
223   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin();
224   int aResultIndex = 1; // number of the counted (created) features, started from 1
225   int aFeatureIndex = -1; // number of the not-empty features in the list
226   for (; anIt != aFeatures.end(); anIt++) {
227     if (anIt->get())
228       aFeatureIndex++;
229     if (aFeatureIndex == theIndex)
230       break;
231     aResultIndex++;
232   }
233   return aResultIndex;
234 }
235
236 bool SketchPlugin_Sketch::isSub(ObjectPtr theObject) const
237 {
238   // check is this feature of result
239   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
240   if (!aFeature) {
241     ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
242     if (aRes)
243       aFeature = document()->feature(aRes);
244   }
245   if (aFeature) {
246     return data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->isInList(aFeature);
247   }
248   return false;
249 }
250
251
252 void SketchPlugin_Sketch::attributeChanged(const std::string& theID) {
253   if (theID == SketchPlugin_SketchEntity::EXTERNAL_ID()) {
254     AttributeSelectionPtr aSelAttr = selection(SketchPlugin_SketchEntity::EXTERNAL_ID());
255     if (aSelAttr->context().get()) { // update arguments due to the selection value
256       std::shared_ptr<GeomAPI_Shape> aSelection = aSelAttr->value();
257       if (!aSelection.get()) aSelection = aSelAttr->context()->shape();
258       // update the sketch plane
259       std::shared_ptr<GeomAPI_Face> aFace;
260       if (aSelection->isFace()) {
261         aFace = aSelection->face();
262       } else if (aSelection->isCompound()) {
263         GeomAPI_ShapeIterator anIt(aSelection);
264         aFace = anIt.current()->face();
265       }
266       if (aFace.get()) {
267         std::shared_ptr<GeomAPI_Pln> aPlane = aFace->getPlane();
268         if (aPlane.get()) {
269           double anA, aB, aC, aD;
270           aPlane->coefficients(anA, aB, aC, aD);
271
272           // calculate attributes of the sketch
273           std::shared_ptr<GeomAPI_Dir> aNormDir(new GeomAPI_Dir(anA, aB, aC));
274           std::shared_ptr<GeomAPI_XYZ> aCoords = aNormDir->xyz();
275           std::shared_ptr<GeomAPI_XYZ> aZero(new GeomAPI_XYZ(0, 0, 0));
276           aCoords = aCoords->multiplied(-aD * aCoords->distance(aZero));
277           std::shared_ptr<GeomAPI_Pnt> anOrigPnt(new GeomAPI_Pnt(aCoords));
278           // X axis is preferable to be dirX on the sketch
279           // here can not be very small value to avoid very close to X normal axis (issue 595)
280           static const double tol = 0.1;
281           bool isX = fabs(anA) - 1.0 < tol && fabs(aB) < tol && fabs(aC) < tol;
282           std::shared_ptr<GeomAPI_Dir> aTempDir(
283             isX ? new GeomAPI_Dir(0, 1, 0) : new GeomAPI_Dir(1, 0, 0));
284           std::shared_ptr<GeomAPI_Dir> aYDir(new GeomAPI_Dir(aNormDir->cross(aTempDir)));
285           std::shared_ptr<GeomAPI_Dir> aXDir(new GeomAPI_Dir(aYDir->cross(aNormDir)));
286
287           // update position of the sketch
288           std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast
289             <GeomDataAPI_Point>(data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
290           anOrigin->setValue(anOrigPnt);
291           std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
292             data()->attribute(SketchPlugin_Sketch::NORM_ID()));
293           aNormal->setValue(aNormDir);
294           std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
295             data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
296           aDirX->setValue(aXDir);
297           std::shared_ptr<GeomAPI_Dir> aDir = aPlane->direction();
298         }
299       }
300     }
301   } else if (theID == NORM_ID() || theID == DIRX_ID() || theID == ORIGIN_ID()) {
302     // send all sub-elements are also updated: all entities become created on different plane
303     static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
304     std::list<ObjectPtr> aSubs = data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->list();
305     std::list<ObjectPtr>::iterator aSub = aSubs.begin();
306     for(; aSub != aSubs.end(); aSub++) {
307       if (aSub->get())
308         ModelAPI_EventCreator::get()->sendUpdated(*aSub, anUpdateEvent);
309     }
310   }
311 }
312
313 void SketchPlugin_Sketch::createPoint2DResult(ModelAPI_Feature* theFeature,
314                                               SketchPlugin_Sketch* theSketch,
315                                               const std::string& theAttributeID, const int theIndex)
316 {
317   std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
318     theFeature->attribute(theAttributeID));
319
320   if (!aPoint || !aPoint->isInitialized())
321     return;
322
323   std::shared_ptr<GeomAPI_Pnt> aCenter(theSketch->to3D(aPoint->x(), aPoint->y()));
324   //std::cout<<"Execute circle "<<aCenter->x()<<" "<<aCenter->y()<<" "<<aCenter->z()<<std::endl;
325   // make a visible point
326   std::shared_ptr<GeomAPI_Shape> aCenterPointShape = GeomAlgoAPI_PointBuilder::vertex(aCenter);
327   std::shared_ptr<ModelAPI_ResultConstruction> aResult = theFeature->document()->createConstruction(
328                      theFeature->data(), theIndex);
329   aResult->setShape(aCenterPointShape);
330   aResult->setIsInHistory(false);
331
332   theFeature->setResult(aResult, theIndex);
333 }
334
335 FeaturePtr SketchPlugin_Sketch::addUniqueNamedCopiedFeature(FeaturePtr theFeature,
336                                                             SketchPlugin_Sketch* theSketch,
337                                                             const bool theIsCopy)
338 {
339   FeaturePtr aNewFeature = theSketch->addFeature(theFeature->getKind());
340   // addFeature generates a unique name for the feature, it caches the name
341   std::string aUniqueFeatureName = aNewFeature->data()->name();
342   // all attribute values are copied\pasted to the new feature, name is not an exception
343   theFeature->data()->copyTo(aNewFeature->data());
344   // external state should not be copied as a new object is an object of the current sketch
345   if (theFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID()).get())
346     aNewFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->setValue(ResultPtr(),
347                                                                                GeomShapePtr());
348   aNewFeature->data()->setName(aUniqueFeatureName);
349   // text expressions could block setValue of some attributes
350   SketchPlugin_Tools::clearExpressions(aNewFeature);
351   // Set copy attribute
352   AttributeBooleanPtr anAttr = aNewFeature->data()->boolean(SketchPlugin_SketchEntity::COPY_ID());
353   if(anAttr.get()) {
354     anAttr->setValue(theIsCopy);
355   }
356
357   return aNewFeature;
358 }
359
360 std::shared_ptr<GeomAPI_Ax3> SketchPlugin_Sketch::plane(SketchPlugin_Sketch* theSketch)
361 {
362   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
363
364   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
365       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
366   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
367       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
368   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
369       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
370
371   return std::shared_ptr<GeomAPI_Ax3>(new GeomAPI_Ax3(anOrigin->pnt(), aDirX->dir(), aNorm->dir()));
372 }
373
374 bool SketchPlugin_Sketch::customAction(const std::string& theActionId)
375 {
376   bool isOk = false;
377   if (theActionId == ACTION_REMOVE_EXTERNAL())
378     isOk = removeLinksToExternal();
379   else {
380     std::string aMsg = "Error: Feature \"%1\" does not support action \"%2\".";
381     Events_InfoMessage("SketchPlugin_Sketch", aMsg).arg(getKind()).arg(theActionId).send();
382   }
383   return isOk;
384 }
385
386 static bool isExternalBased(const FeaturePtr theFeature)
387 {
388   return theFeature->getKind() == SketchPlugin_Projection::ID() ||
389          theFeature->getKind() == SketchPlugin_IntersectionPoint::ID();
390 }
391
392 bool SketchPlugin_Sketch::removeLinksToExternal()
393 {
394   std::list<FeaturePtr> aRemove;
395   std::list<ObjectPtr> aSubs = reflist(FEATURES_ID())->list();
396   for (std::list<ObjectPtr>::iterator anIt = aSubs.begin(); anIt != aSubs.end(); ++anIt) {
397     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
398     if (!aFeature)
399       continue;
400     if (isExternalBased(aFeature)) {
401       // mark feature as to be removed
402       aRemove.push_back(aFeature);
403     }
404     else {
405       AttributeSelectionPtr anExtAttr =
406           aFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID());
407       ResultPtr anExternal = anExtAttr ? anExtAttr->context() : ResultPtr();
408       if (anExternal) {
409         FeaturePtr anExtFeature = ModelAPI_Feature::feature(anExternal);
410         if (anExtFeature && isExternalBased(anExtFeature)) {
411           // make result of projection/intersection as non-external,
412           aFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->setValue(
413             ObjectPtr(), GeomShapePtr());
414           // set feature auxiliary if the parent is not included into sketch result
415           bool isIncludedToSketchResult = false;
416           if (anExtFeature->getKind() == SketchPlugin_Projection::ID()) {
417             isIncludedToSketchResult = anExtFeature->boolean(
418                 SketchPlugin_Projection::INCLUDE_INTO_RESULT())->value();
419           }
420           if (anExtFeature->getKind() == SketchPlugin_IntersectionPoint::ID()) {
421             isIncludedToSketchResult = anExtFeature->boolean(
422                 SketchPlugin_IntersectionPoint::INCLUDE_INTO_RESULT())->value();
423           }
424
425           aFeature->boolean(SketchPlugin_SketchEntity::COPY_ID())->setValue(false);
426           aFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(
427               !isIncludedToSketchResult);
428         }
429       }
430     }
431   }
432   for (std::list<FeaturePtr>::iterator anIt = aRemove.begin(); anIt != aRemove.end(); ++anIt)
433     document()->removeFeature(*anIt);
434   return true;
435 }