Salome HOME
updated copyright message
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Sketch.cpp
1 // Copyright (C) 2014-2023  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_EdgeBuilder.h>
24 #include <GeomAlgoAPI_FaceBuilder.h>
25
26 #include <GeomAPI_Dir.h>
27 #include <GeomAPI_Lin.h>
28 #include <GeomAPI_PlanarEdges.h>
29 #include <GeomAPI_ShapeIterator.h>
30 #include <GeomAPI_Vertex.h>
31
32 #include <GeomDataAPI_Point2D.h>
33 #include <GeomAlgoAPI_PointBuilder.h>
34
35 #include <ModelAPI_AttributeRefList.h>
36 #include <ModelAPI_AttributeString.h>
37 #include <ModelAPI_Data.h>
38 #include <ModelAPI_Document.h>
39 #include <ModelAPI_Feature.h>
40 #include <ModelAPI_Object.h>
41 #include <ModelAPI_ResultConstruction.h>
42 #include <ModelAPI_Validator.h>
43 #include <ModelAPI_Session.h>
44 #include <ModelAPI_Events.h>
45
46 #include <SketchPlugin_Sketch.h>
47 #include <SketchPlugin_Feature.h>
48 #include <SketchPlugin_IntersectionPoint.h>
49 #include <SketchPlugin_Projection.h>
50 #include <SketchPlugin_SketchEntity.h>
51 #include <SketchPlugin_Tools.h>
52
53 #include <Events_InfoMessage.h>
54 #include <Events_Loop.h>
55
56 #include <memory>
57
58 #include <math.h>
59 #include <vector>
60
61 SketchPlugin_Sketch::SketchPlugin_Sketch()
62 {
63 }
64
65 void SketchPlugin_Sketch::initAttributes()
66 {
67   data()->addAttribute(SketchPlugin_Sketch::ORIGIN_ID(), GeomDataAPI_Point::typeId());
68   data()->addAttribute(SketchPlugin_Sketch::DIRX_ID(), GeomDataAPI_Dir::typeId());
69   data()->addAttribute(SketchPlugin_Sketch::NORM_ID(), GeomDataAPI_Dir::typeId());
70   data()->addAttribute(SketchPlugin_Sketch::FEATURES_ID(), ModelAPI_AttributeRefList::typeId());
71   // the selected face, base for the sketcher plane, not obligatory
72   data()->addAttribute(SketchPlugin_SketchEntity::EXTERNAL_ID(),
73     ModelAPI_AttributeSelection::typeId());
74   ModelAPI_Session::get()->validators()->registerNotObligatory(
75     getKind(), SketchPlugin_SketchEntity::EXTERNAL_ID());
76   data()->addAttribute(SketchPlugin_Sketch::SOLVER_ERROR(), ModelAPI_AttributeString::typeId());
77   ModelAPI_Session::get()->validators()->registerNotObligatory(
78     getKind(), SketchPlugin_Sketch::SOLVER_ERROR());
79   data()->addAttribute(SketchPlugin_Sketch::SOLVER_DOF(), ModelAPI_AttributeString::typeId());
80   ModelAPI_Session::get()->validators()->registerNotObligatory(
81     getKind(), SketchPlugin_Sketch::SOLVER_DOF());
82 }
83
84 void SketchPlugin_Sketch::execute()
85 {
86   if (!data()->isValid())
87     return;
88   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
89       ModelAPI_AttributeRefList>(data()->attribute(SketchPlugin_Sketch::FEATURES_ID()));
90
91   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
92       data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
93   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
94       data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
95   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
96       data()->attribute(SketchPlugin_Sketch::NORM_ID()));
97
98   std::list<ObjectPtr> aFeatures = aRefList->list();
99   if (aFeatures.empty()) // actually, this must be avoided by the validators
100     return;
101
102   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
103   std::shared_ptr<SketchPlugin_Feature> aFeature;
104   std::list<std::shared_ptr<GeomAPI_Shape> > aFeaturesPreview;
105   for (; anIt != aLast; anIt++) {
106     aFeature = std::dynamic_pointer_cast<SketchPlugin_Feature>(*anIt);
107     if (aFeature) {
108       if (!aFeature->sketch()) // on load document the back references are missed
109         aFeature->setSketch(this);
110       // do not include into the result the external edges with disabled flag "Include into result"
111       if (aFeature->data()->attribute(SketchPlugin_SketchEntity::EXTERNAL_ID())) {
112         if (aFeature->data()->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->context()) {
113           const std::string& anAttrName =
114               aFeature->getKind() == SketchPlugin_Projection::ID() ?
115               SketchPlugin_Projection::INCLUDE_INTO_RESULT() :
116               SketchPlugin_IntersectionPoint::INCLUDE_INTO_RESULT();
117           AttributeBooleanPtr aKeepResult = aFeature->boolean(anAttrName);
118           if (!aKeepResult || !aKeepResult->value())
119             continue;
120         }
121       }
122       // do not include the construction entities in the result
123       if (aFeature->data()->attribute(SketchPlugin_SketchEntity::AUXILIARY_ID())) {
124         if (aFeature->data()->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value())
125           continue;
126       }
127
128       const std::list<std::shared_ptr<ModelAPI_Result> >& aRes = aFeature->results();
129       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter = aRes.cbegin();
130       for (; aResIter != aRes.cend(); aResIter++) {
131         std::shared_ptr<ModelAPI_ResultConstruction> aConstr = std::dynamic_pointer_cast<
132             ModelAPI_ResultConstruction>(*aResIter);
133         if (aConstr) {
134           std::shared_ptr<GeomAPI_Shape> aShape = aConstr->shape();
135           if (aShape)
136             aFeaturesPreview.push_back(aShape);
137         }
138       }
139     }
140   }
141
142   // Collect all edges as one big wire
143   std::shared_ptr<GeomAPI_PlanarEdges> aBigWire(new GeomAPI_PlanarEdges);
144   std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator aShapeIt = aFeaturesPreview.begin();
145   for (; aShapeIt != aFeaturesPreview.end(); ++aShapeIt) {
146     aBigWire->addEdge(*aShapeIt);
147   }
148   aBigWire->setPlane(anOrigin->pnt(), aDirX->dir(), aNorm->dir());
149   std::shared_ptr<ModelAPI_ResultConstruction> aConstr = document()->createConstruction(data());
150   aConstr->setShape(aBigWire);
151   setResult(aConstr);
152 }
153
154 std::shared_ptr<ModelAPI_Feature> SketchPlugin_Sketch::addFeature(std::string theID)
155 {
156   // It is necessary to keep and restore the current feature in the document,
157   // if the sketch is updated from Python API. Because in that case, the current feature
158   // may be a non-sketch feature, so it is required to set it back, after adding a sketch feature,
159   // to keep the sequence of non-sketch features within the document.
160   FeaturePtr aCurFeature = document()->currentFeature(false);
161   std::shared_ptr<SketchPlugin_Feature> aCurSketchFeature =
162       std::dynamic_pointer_cast<SketchPlugin_Feature>(aCurFeature);
163   std::shared_ptr<SketchPlugin_Sketch> aCurSketch =
164       std::dynamic_pointer_cast<SketchPlugin_Sketch>(aCurFeature);
165   if ((aCurSketch && aCurSketch.get() == this) ||
166       (aCurSketchFeature && aCurSketchFeature->sketch() == this))
167     aCurFeature = FeaturePtr(); // no need to restore feature if it is from the current sketch
168
169   // Set last feature of the sketch as current feature.
170   // Reason: Changing of parameter through Python API may lead to creation of new features
171   //         (e.g. changing number of copies in MultiRotation). If the sketch is not the last
172   //         feature in the Object Browser, then new features will be added to the end feature.
173   //         Therefore, setting any feature below the sketch as a current feature will disable
174   //         these newly created features.
175   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
176       ModelAPI_AttributeRefList>(data()->attribute(SketchPlugin_Sketch::FEATURES_ID()));
177   int aSize = aRefList->size(false);
178   ObjectPtr aLastObject = aSize == 0 ? data()->owner() : aRefList->object(aSize - 1, false);
179   FeaturePtr aLastFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aLastObject);
180   document()->setCurrentFeature(aLastFeature, false);
181
182   // add new feature
183   std::shared_ptr<ModelAPI_Feature> aNew = document()->addFeature(theID, false);
184   if (aNew) {
185     // the sketch cannot be specified for the macro-features defined in python
186     // like SketchRectangle, so we need to check the type of new feature
187     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
188         std::dynamic_pointer_cast<SketchPlugin_Feature>(aNew);
189     if (aSketchFeature)
190       aSketchFeature->setSketch(this);
191     data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->append(aNew);
192   }
193
194   // set as current also after it becomes sub to set correctly enabled for other sketch subs
195   // or restore the previous current feature
196   document()->setCurrentFeature(aCurFeature ? aCurFeature : aNew, false);
197
198   return aNew;
199 }
200
201 void SketchPlugin_Sketch::removeFeature(std::shared_ptr<ModelAPI_Feature> theFeature)
202 {
203   if (!data()->isValid()) // sketch is already removed (case on undo of sketch), sync is not needed
204     return;
205   AttributeRefListPtr aList = reflist(SketchPlugin_Sketch::FEATURES_ID());
206   // if the object is last, remove it from the list
207   // (needed to skip empty transaction on edit of sketch feature)
208   if (aList->object(aList->size(true) - 1, true) == theFeature) {
209     aList->remove(theFeature);
210   } else {
211     // to keep the persistent sub-elements indexing, do not remove elements from list,
212     // but substitute by nulls
213     aList->substitute(theFeature, ObjectPtr());
214   }
215 }
216
217 int SketchPlugin_Sketch::numberOfSubs(bool forTree) const
218 {
219   if (forTree)
220     return 0;
221   return data()->reflist(FEATURES_ID())->size(false);
222 }
223
224 std::shared_ptr<ModelAPI_Feature> SketchPlugin_Sketch::subFeature(
225   const int theIndex, bool forTree)
226 {
227   if (forTree)
228     return FeaturePtr();
229
230   ObjectPtr anObj = data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->object(theIndex, false);
231   FeaturePtr aRes = std::dynamic_pointer_cast<ModelAPI_Feature>(anObj);
232   return aRes;
233 }
234
235 int SketchPlugin_Sketch::subFeatureId(const int theIndex) const
236 {
237   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
238       ModelAPI_AttributeRefList>(data()->attribute(SketchPlugin_Sketch::FEATURES_ID()));
239   std::list<ObjectPtr> aFeatures = aRefList->list();
240   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin();
241   int aResultIndex = 1; // number of the counted (created) features, started from 1
242   int aFeatureIndex = -1; // number of the not-empty features in the list
243   for (; anIt != aFeatures.end(); anIt++) {
244     if (anIt->get())
245       aFeatureIndex++;
246     if (aFeatureIndex == theIndex)
247       break;
248     aResultIndex++;
249   }
250   return aResultIndex;
251 }
252
253 bool SketchPlugin_Sketch::isSub(ObjectPtr theObject) const
254 {
255   // check is this feature of result
256   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
257   if (!aFeature) {
258     ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
259     if (aRes)
260       aFeature = document()->feature(aRes);
261   }
262   if (aFeature) {
263     return data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->isInList(aFeature);
264   }
265   return false;
266 }
267
268
269 static bool isOrigin(const GeomPointPtr& thePoint, const double theTolerance)
270 {
271   return fabs(thePoint->x()) < theTolerance &&
272          fabs(thePoint->y()) < theTolerance &&
273          fabs(thePoint->z()) < theTolerance;
274 }
275
276 static bool isCoordinateAxis(const GeomDirPtr& theDir, const double theTolerance)
277 {
278   return fabs(theDir->x() - 1.0) < theTolerance || fabs(theDir->x() + 1.0) < theTolerance ||
279          fabs(theDir->y() - 1.0) < theTolerance || fabs(theDir->y() + 1.0) < theTolerance ||
280          fabs(theDir->z() - 1.0) < theTolerance || fabs(theDir->z() + 1.0) < theTolerance;
281 }
282
283 static bool isCoordinatePlane(const GeomAx3Ptr& thePlane)
284 {
285   static const double THE_TOLERANCE = 1.e-7;
286   if (!thePlane)
287     return false;
288
289   GeomPointPtr anOrigin = thePlane->origin();
290   GeomDirPtr aNormal = thePlane->normal();
291   GeomDirPtr aDirX = thePlane->dirX();
292
293   return isOrigin(anOrigin, THE_TOLERANCE) &&
294          isCoordinateAxis(aNormal, THE_TOLERANCE) &&
295          isCoordinateAxis(aDirX, THE_TOLERANCE);
296 }
297
298 void SketchPlugin_Sketch::attributeChanged(const std::string& theID) {
299   if (theID == SketchPlugin_SketchEntity::EXTERNAL_ID()) {
300     AttributeSelectionPtr aSelAttr = selection(SketchPlugin_SketchEntity::EXTERNAL_ID());
301     if (aSelAttr->context().get()) { // update arguments due to the selection value
302       std::shared_ptr<GeomAPI_Shape> aSelection = aSelAttr->value();
303       if (!aSelection.get()) aSelection = aSelAttr->context()->shape();
304       // update the sketch plane
305       std::shared_ptr<GeomAPI_Face> aFace;
306       if (aSelection->isFace()) {
307         aFace = aSelection->face();
308       } else if (aSelection->isCompound()) {
309         GeomAPI_ShapeIterator anIt(aSelection);
310         aFace = anIt.current()->face();
311       }
312       if (aFace.get()) {
313         std::shared_ptr<GeomAPI_Pln> aPlane = aFace->getPlane();
314         if (aPlane.get()) {
315           double anA, aB, aC, aD;
316           aPlane->coefficients(anA, aB, aC, aD);
317
318           // calculate attributes of the sketch
319           std::shared_ptr<GeomAPI_Dir> aNormDir(new GeomAPI_Dir(anA, aB, aC));
320           std::shared_ptr<GeomAPI_XYZ> aCoords = aNormDir->xyz();
321           std::shared_ptr<GeomAPI_XYZ> aZero(new GeomAPI_XYZ(0, 0, 0));
322           aCoords = aCoords->multiplied(-aD * aCoords->distance(aZero));
323           std::shared_ptr<GeomAPI_Pnt> anOrigPnt(new GeomAPI_Pnt(aCoords));
324           // X axis is preferable to be dirX on the sketch
325           // here can not be very small value to avoid very close to X normal axis (issue 595)
326           static const double tol = 0.1;
327           bool isX = fabs(anA) - 1.0 < tol && fabs(aB) < tol && fabs(aC) < tol;
328           std::shared_ptr<GeomAPI_Dir> aTempDir(
329             isX ? new GeomAPI_Dir(0, 1, 0) : new GeomAPI_Dir(1, 0, 0));
330           std::shared_ptr<GeomAPI_Dir> aYDir(new GeomAPI_Dir(aNormDir->cross(aTempDir)));
331           std::shared_ptr<GeomAPI_Dir> aXDir(new GeomAPI_Dir(aYDir->cross(aNormDir)));
332
333           bool aWasBlocked = data()->blockSendAttributeUpdated(true);
334           // update position of the sketch
335           std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast
336             <GeomDataAPI_Point>(data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
337           anOrigin->setValue(anOrigPnt);
338           std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
339             data()->attribute(SketchPlugin_Sketch::NORM_ID()));
340           aNormal->setValue(aNormDir);
341           std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
342             data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
343           aDirX->setValue(aXDir);
344           data()->blockSendAttributeUpdated(aWasBlocked, true);
345         }
346       }
347     }
348   } else if (theID == NORM_ID() || theID == DIRX_ID() || theID == ORIGIN_ID()) {
349     // check if current and previous sketch planes are coordinate planes and they are different
350     GeomAx3Ptr aCurPlane;
351     bool areCoordPlanes = false;
352     if (isPlaneSet()) {
353       aCurPlane = coordinatePlane();
354       areCoordPlanes = isCoordinatePlane(aCurPlane) && isCoordinatePlane(myPlane);
355     }
356
357     // send all sub-elements are also updated: all entities become created on different plane
358     static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
359     std::list<ObjectPtr> aSubs = data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->list();
360     std::list<ObjectPtr>::iterator aSub = aSubs.begin();
361     for(; aSub != aSubs.end(); aSub++) {
362       if (aSub->get()) {
363         if (areCoordPlanes)
364           updateCoordinateAxis(*aSub, aCurPlane);
365
366         ModelAPI_EventCreator::get()->sendUpdated(*aSub, anUpdateEvent);
367       }
368     }
369     if (aCurPlane)
370       myPlane = aCurPlane;
371   }
372 }
373
374 void SketchPlugin_Sketch::createPoint2DResult(ModelAPI_Feature* theFeature,
375                                               SketchPlugin_Sketch* theSketch,
376                                               const std::string& theAttributeID, const int theIndex)
377 {
378   std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
379     theFeature->attribute(theAttributeID));
380
381   if (!aPoint || !aPoint->isInitialized())
382     return;
383
384   std::shared_ptr<GeomAPI_Pnt> aCenter(theSketch->to3D(aPoint->x(), aPoint->y()));
385   //std::cout<<"Execute circle "<<aCenter->x()<<" "<<aCenter->y()<<" "<<aCenter->z()<<std::endl;
386   // make a visible point
387   std::shared_ptr<GeomAPI_Shape> aCenterPointShape = GeomAlgoAPI_PointBuilder::vertex(aCenter);
388   std::shared_ptr<ModelAPI_ResultConstruction> aResult = theFeature->document()->createConstruction(
389                      theFeature->data(), theIndex);
390   aResult->setShape(aCenterPointShape);
391   aResult->setIsInHistory(false);
392
393   theFeature->setResult(aResult, theIndex);
394 }
395
396 void SketchPlugin_Sketch::createLine2DResult(ModelAPI_Feature* theFeature,
397                                              SketchPlugin_Sketch* theSketch,
398                                              const std::string& theStartAttrID,
399                                              const std::string& theEndAttrID,
400                                              const int theIndex)
401 {
402   std::shared_ptr<GeomDataAPI_Point2D> aStartAttr =
403       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theFeature->attribute(theStartAttrID));
404   std::shared_ptr<GeomDataAPI_Point2D> anEndAttr =
405       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theFeature->attribute(theEndAttrID));
406
407   if (!aStartAttr || !aStartAttr->isInitialized() ||
408       !anEndAttr || !anEndAttr->isInitialized())
409     return;
410
411   std::shared_ptr<GeomAPI_Pnt> aStart(theSketch->to3D(aStartAttr->x(), aStartAttr->y()));
412   std::shared_ptr<GeomAPI_Pnt> anEnd(theSketch->to3D(anEndAttr->x(), anEndAttr->y()));
413   //std::cout<<"Execute line "<<aStart->x()<<" "<<aStart->y()<<" "<<aStart->z()<<" - "
414   //  <<anEnd->x()<<" "<<anEnd->y()<<" "<<anEnd->z()<<std::endl;
415   // make linear edge
416   std::shared_ptr<GeomAPI_Edge> anEdge = GeomAlgoAPI_EdgeBuilder::line(aStart, anEnd);
417   // store the result
418   std::shared_ptr<ModelAPI_ResultConstruction> aResult =
419       theFeature->document()->createConstruction(theFeature->data(), theIndex);
420   aResult->setShape(anEdge);
421   aResult->setIsInHistory(false);
422   theFeature->setResult(aResult, theIndex);
423 }
424
425 FeaturePtr SketchPlugin_Sketch::addUniqueNamedCopiedFeature(FeaturePtr theFeature,
426                                                             SketchPlugin_Sketch* theSketch,
427                                                             const bool theIsCopy)
428 {
429   FeaturePtr aNewFeature = theSketch->addFeature(theFeature->getKind());
430   // addFeature generates a unique name for the feature, it caches the name
431   std::wstring aUniqueFeatureName = aNewFeature->data()->name();
432   // all attribute values are copied\pasted to the new feature, name is not an exception
433   theFeature->data()->copyTo(aNewFeature->data());
434   // external state should not be copied as a new object is an object of the current sketch
435   if (theFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID()).get())
436     aNewFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->setValue(ResultPtr(),
437                                                                                GeomShapePtr());
438   aNewFeature->data()->setName(aUniqueFeatureName);
439   // text expressions could block setValue of some attributes
440   SketchPlugin_Tools::clearExpressions(aNewFeature);
441   // Set copy attribute
442   AttributeBooleanPtr anAttr = aNewFeature->data()->boolean(SketchPlugin_SketchEntity::COPY_ID());
443   if(anAttr.get()) {
444     anAttr->setValue(theIsCopy);
445   }
446
447   return aNewFeature;
448 }
449
450 std::shared_ptr<GeomAPI_Ax3> SketchPlugin_Sketch::plane(SketchPlugin_Sketch* theSketch)
451 {
452   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
453
454   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
455       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
456   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
457       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
458   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
459       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
460
461   if (aNorm.get() && aNorm->isInitialized() && anOrigin.get() && anOrigin->isInitialized())
462     return std::shared_ptr<GeomAPI_Ax3>(
463       new GeomAPI_Ax3(anOrigin->pnt(), aDirX->dir(), aNorm->dir()));
464
465   return std::shared_ptr<GeomAPI_Ax3>();
466 }
467
468 bool SketchPlugin_Sketch::customAction(const std::string& theActionId)
469 {
470   bool isOk = false;
471   if (theActionId == ACTION_REMOVE_EXTERNAL())
472     isOk = removeLinksToExternal();
473   else {
474     std::string aMsg = "Error: Feature \"%1\" does not support action \"%2\".";
475     Events_InfoMessage("SketchPlugin_Sketch", aMsg).arg(getKind()).arg(theActionId).send();
476   }
477   return isOk;
478 }
479
480 static bool isExternalBased(const FeaturePtr theFeature)
481 {
482   return theFeature->getKind() == SketchPlugin_Projection::ID() ||
483          theFeature->getKind() == SketchPlugin_IntersectionPoint::ID();
484 }
485
486 bool SketchPlugin_Sketch::removeLinksToExternal()
487 {
488   std::list<FeaturePtr> aRemove;
489   std::list<ObjectPtr> aSubs = reflist(FEATURES_ID())->list();
490   for (std::list<ObjectPtr>::iterator anIt = aSubs.begin(); anIt != aSubs.end(); ++anIt) {
491     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
492     if (!aFeature)
493       continue;
494     if (isExternalBased(aFeature)) {
495       // mark feature as to be removed
496       aRemove.push_back(aFeature);
497     }
498     else {
499       AttributeSelectionPtr anExtAttr =
500           aFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID());
501       ResultPtr anExternal = anExtAttr ? anExtAttr->context() : ResultPtr();
502       if (anExternal) {
503         FeaturePtr anExtFeature = ModelAPI_Feature::feature(anExternal);
504         if (anExtFeature && isExternalBased(anExtFeature)) {
505           // make result of projection/intersection as non-external,
506           aFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->setValue(
507             ObjectPtr(), GeomShapePtr());
508           // set feature auxiliary if the parent is not included into sketch result
509           bool isIncludedToSketchResult = false;
510           if (anExtFeature->getKind() == SketchPlugin_Projection::ID()) {
511             isIncludedToSketchResult = anExtFeature->boolean(
512                 SketchPlugin_Projection::INCLUDE_INTO_RESULT())->value();
513           }
514           if (anExtFeature->getKind() == SketchPlugin_IntersectionPoint::ID()) {
515             isIncludedToSketchResult = anExtFeature->boolean(
516                 SketchPlugin_IntersectionPoint::INCLUDE_INTO_RESULT())->value();
517           }
518
519           aFeature->boolean(SketchPlugin_SketchEntity::COPY_ID())->setValue(false);
520           aFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(
521               !isIncludedToSketchResult);
522         }
523       }
524     }
525   }
526   for (std::list<FeaturePtr>::iterator anIt = aRemove.begin(); anIt != aRemove.end(); ++anIt)
527     document()->removeFeature(*anIt);
528   return true;
529 }
530
531
532 static ObjectPtr findAxis(GeomShapePtr theAxisToCompare,
533                           ObjectPtr theOX,
534                           ObjectPtr theOY,
535                           ObjectPtr theOZ)
536 {
537   if (theAxisToCompare) {
538     ObjectPtr anAxes[] = { theOX, theOY, theOZ };
539     for (int i = 0; i < 3; ++i) {
540       ResultPtr anAx = std::dynamic_pointer_cast<ModelAPI_Result>(anAxes[i]);
541       if (anAx && theAxisToCompare->isEqual(anAx->shape()))
542         return anAxes[i];
543     }
544   }
545   return ObjectPtr();
546 }
547
548 static ObjectPtr findAxis(ObjectPtr theAxisToCompare,
549                           ObjectPtr theOX,
550                           ObjectPtr theOY,
551                           ObjectPtr theOZ)
552 {
553   if (theAxisToCompare == theOX)
554     return theOX;
555   else if (theAxisToCompare == theOY)
556     return theOY;
557   else if (theAxisToCompare == theOZ)
558     return theOZ;
559   // nothing helped, search by shape
560   ResultPtr anAxis = std::dynamic_pointer_cast<ModelAPI_Result>(theAxisToCompare);
561   return findAxis(anAxis ? anAxis->shape() : GeomShapePtr(), theOX, theOY, theOZ);
562 }
563
564 GeomShapePtr axisOnNewPlane(ObjectPtr theAxis, GeomAx3Ptr theOldPlane, GeomAx3Ptr theNewPlane)
565 {
566   ResultPtr anAxis = std::dynamic_pointer_cast<ModelAPI_Result>(theAxis);
567   if (!anAxis)
568     return GeomShapePtr();
569
570   GeomEdgePtr anAxisEdge = anAxis->shape()->edge();
571   GeomLinePtr anAxisLine = anAxisEdge->line();
572   GeomDirPtr anAxisDir = anAxisLine->direction();
573
574   double aFirstParam, aLastParam;
575   anAxisEdge->getRange(aFirstParam, aLastParam);
576
577   if (theOldPlane->dirX()->isParallel(anAxisDir))
578     anAxisDir = theNewPlane->dirX();
579   else if (theOldPlane->dirY()->isParallel(anAxisDir))
580     anAxisDir = theNewPlane->dirY();
581   else if (theOldPlane->normal()->isParallel(anAxisDir))
582     anAxisDir = theNewPlane->normal();
583
584   GeomPointPtr aFirstPoint(new GeomAPI_Pnt(aFirstParam * anAxisDir->x(),
585                                            aFirstParam * anAxisDir->y(),
586                                            aFirstParam * anAxisDir->z()));
587   GeomPointPtr aLastPoint(new GeomAPI_Pnt(aLastParam * anAxisDir->x(),
588                                           aLastParam * anAxisDir->y(),
589                                           aLastParam * anAxisDir->z()));
590   return GeomAlgoAPI_EdgeBuilder::line(aFirstPoint, aLastPoint);
591 }
592
593 void  SketchPlugin_Sketch::updateCoordinateAxis(ObjectPtr theSub, GeomAx3Ptr thePlane)
594 {
595   FeaturePtr aFeature = ModelAPI_Feature::feature(theSub);
596   if (!aFeature)
597     return;
598
599   DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
600   ObjectPtr anOX = aRootDoc->objectByName(ModelAPI_ResultConstruction::group(), L"OX");
601   ObjectPtr anOY = aRootDoc->objectByName(ModelAPI_ResultConstruction::group(), L"OY");
602   ObjectPtr anOZ = aRootDoc->objectByName(ModelAPI_ResultConstruction::group(), L"OZ");
603
604   AttributeSelectionPtr anExtFeature;
605   if (aFeature->getKind() == SketchPlugin_Projection::ID())
606     anExtFeature = aFeature->selection(SketchPlugin_Projection::EXTERNAL_FEATURE_ID());
607   else if (aFeature->getKind() == SketchPlugin_IntersectionPoint::ID())
608     anExtFeature = aFeature->selection(SketchPlugin_IntersectionPoint::EXTERNAL_FEATURE_ID());
609   else
610     return;
611
612   ObjectPtr aContext = anExtFeature->context();
613   GeomShapePtr aShape = anExtFeature->value();
614   if (!aShape) { // selected object is a construction
615     ObjectPtr anAxis = findAxis(aContext, anOX, anOY, anOZ);
616     GeomShapePtr aNewAxis = axisOnNewPlane(anAxis, myPlane, thePlane);
617     anAxis = findAxis(aNewAxis, anOX, anOY, anOZ);
618     if (anAxis)
619       anExtFeature->setValue(anAxis, aShape);
620   }
621 }