Salome HOME
Issue #2824: Constraints at wrong positions when editing the sketch
[modules/shaper.git] / src / SketchSolver / SketchSolver_Manager.cpp
1 // Copyright (C) 2014-2017  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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "SketchSolver_Manager.h"
22 #include "SketchSolver_Error.h"
23
24 #include <Events_Loop.h>
25 #include <GeomDataAPI_Point2D.h>
26 #include <ModelAPI_Events.h>
27 #include <ModelAPI_ResultConstruction.h>
28 #include <ModelAPI_Session.h>
29 #include <ModelAPI_Validator.h>
30 #include <SketchPlugin_Sketch.h>
31
32 /// Global constraint manager object
33 static SketchSolver_Manager* myManager = SketchSolver_Manager::instance();
34
35 /// \brief Verifies is the feature valid
36 static bool isFeatureValid(FeaturePtr theFeature)
37 {
38   if (!theFeature || !theFeature->data() || !theFeature->data()->isValid())
39     return false;
40
41   SessionPtr aMgr = ModelAPI_Session::get();
42   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
43   return aFactory->validate(theFeature);
44 }
45
46 typedef std::map<int, std::shared_ptr<SketchPlugin_Feature>> IndexedFeatureMap;
47
48 static void featuresOrderedByCreation(const std::set<ObjectPtr>& theOriginalFeatures,
49                                       IndexedFeatureMap& theOrderedFeatures)
50 {
51   std::set<ObjectPtr>::iterator aFeatIter = theOriginalFeatures.begin();
52   for (; aFeatIter != theOriginalFeatures.end(); aFeatIter++) {
53     std::shared_ptr<SketchPlugin_Feature> aFeature =
54         std::dynamic_pointer_cast<SketchPlugin_Feature>(*aFeatIter);
55     if (aFeature && !aFeature->isMacro() && aFeature->data() && aFeature->data()->isValid()) {
56       theOrderedFeatures[aFeature->data()->featureId()] = aFeature;
57     }
58   }
59 }
60
61 static void featuresOrderedByType(const std::set<ObjectPtr>& theOriginalFeatures,
62                                   IndexedFeatureMap& theOrderedFeatures)
63 {
64   int aFeatureIndex = 0;
65   int aConstraintIndex = (int)theOriginalFeatures.size();
66
67   std::set<ObjectPtr>::iterator aFeatIter = theOriginalFeatures.begin();
68   for (; aFeatIter != theOriginalFeatures.end(); aFeatIter++) {
69     std::shared_ptr<SketchPlugin_Feature> aFeature =
70         std::dynamic_pointer_cast<SketchPlugin_Feature>(*aFeatIter);
71     if (aFeature && !aFeature->isMacro() && aFeature->data() && aFeature->data()->isValid()) {
72       std::shared_ptr<SketchPlugin_Constraint> aConstraint =
73           std::dynamic_pointer_cast<SketchPlugin_Constraint>(aFeature);
74       if (aConstraint)
75         theOrderedFeatures[++aConstraintIndex] = aFeature;
76       else
77         theOrderedFeatures[++aFeatureIndex] = aFeature;
78     }
79   }
80 }
81
82
83
84 // ========================================================
85 // ========= SketchSolver_Manager ===============
86 // ========================================================
87 SketchSolver_Manager* SketchSolver_Manager::instance()
88 {
89   static SketchSolver_Manager* mySelf = 0; // Self pointer to implement singleton functionality
90   if (!mySelf)
91     mySelf = new SketchSolver_Manager();
92   return mySelf;
93 }
94
95 SketchSolver_Manager::SketchSolver_Manager()
96 {
97   myGroups.clear();
98   myIsComputed = false;
99
100   // Register in event loop
101   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_CREATED));
102   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
103   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_DELETED));
104   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_OBJECT_MOVED));
105
106   ////Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SOLVER_FAILED));
107   ////Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SOLVER_REPAIRED));
108   Events_Loop::loop()->registerListener(this, Events_Loop::eventByName(EVENT_SKETCH_PREPARED));
109 }
110
111 SketchSolver_Manager::~SketchSolver_Manager()
112 {
113   myGroups.clear();
114 }
115
116 bool SketchSolver_Manager::groupMessages()
117 {
118   return true;
119 }
120
121 // ============================================================================
122 //  Function: processEvent
123 //  Purpose:  listen the event loop and process the message
124 // ============================================================================
125 void SketchSolver_Manager::processEvent(
126   const std::shared_ptr<Events_Message>& theMessage)
127 {
128   bool needToResolve = false;
129   bool isUpdateFlushed = false;
130   bool isMovedEvt = false;
131
132   static const Events_ID aCreatedEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
133   static const Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
134   static const Events_ID aSketchPreparedEvent = Events_Loop::eventByName(EVENT_SKETCH_PREPARED);
135   // sketch is prepared for resolve: all the needed events
136   // are collected and must be processed by the solver
137   if (theMessage->eventID() == aSketchPreparedEvent) {
138     flushGrouped(anUpdateEvent);
139     needToResolve = true;
140   }
141
142   if (myIsComputed)
143     return;
144   myIsComputed = true;
145
146   if (theMessage->eventID() == aCreatedEvent || theMessage->eventID() == anUpdateEvent) {
147     std::shared_ptr<ModelAPI_ObjectUpdatedMessage> anUpdateMsg =
148         std::dynamic_pointer_cast<ModelAPI_ObjectUpdatedMessage>(theMessage);
149
150     isUpdateFlushed = stopSendUpdate();
151
152     // update sketch features only
153     const std::set<ObjectPtr>& aFeatures = anUpdateMsg->objects();
154     IndexedFeatureMap anOrderedFeatures;
155     // try to keep order as features were created if there are several created features: #2229
156     if (theMessage->eventID() == aCreatedEvent && aFeatures.size() > 1) {
157       featuresOrderedByCreation(aFeatures, anOrderedFeatures);
158     } else { // order is not important, just process features before constraints
159       featuresOrderedByType(aFeatures, anOrderedFeatures);
160     }
161
162     IndexedFeatureMap::iterator aFeat;
163     for (aFeat = anOrderedFeatures.begin(); aFeat != anOrderedFeatures.end(); aFeat++) {
164       updateFeature(aFeat->second);
165     }
166
167   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_MOVED)) {
168     std::shared_ptr<ModelAPI_ObjectMovedMessage> aMoveMsg =
169         std::dynamic_pointer_cast<ModelAPI_ObjectMovedMessage>(theMessage);
170
171     ObjectPtr aMovedObject = aMoveMsg->movedObject();
172     std::shared_ptr<GeomDataAPI_Point2D> aMovedPoint =
173         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aMoveMsg->movedAttribute());
174
175     const std::shared_ptr<GeomAPI_Pnt2d>& aFrom = aMoveMsg->originalPosition();
176     const std::shared_ptr<GeomAPI_Pnt2d>& aTo = aMoveMsg->currentPosition();
177
178     if (aMovedObject) {
179       FeaturePtr aMovedFeature = ModelAPI_Feature::feature(aMovedObject);
180       std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
181           std::dynamic_pointer_cast<SketchPlugin_Feature>(aMovedFeature);
182       if (aSketchFeature && !aSketchFeature->isMacro())
183         needToResolve = moveFeature(aSketchFeature, aFrom, aTo);
184     } else if (aMovedPoint)
185       needToResolve = moveAttribute(aMovedPoint, aFrom, aTo);
186
187   } else if (theMessage->eventID() == Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED)) {
188     std::shared_ptr<ModelAPI_ObjectDeletedMessage> aDeleteMsg =
189       std::dynamic_pointer_cast<ModelAPI_ObjectDeletedMessage>(theMessage);
190     const std::list<std::pair<std::shared_ptr<ModelAPI_Document>, std::string>>& aFeatureGroups =
191       aDeleteMsg->groups();
192
193     // Find SketchPlugin_Sketch::ID() in groups.
194     // The constraint groups should be updated when an object removed from Sketch
195     std::list<std::pair<std::shared_ptr<ModelAPI_Document>, std::string>>::const_iterator aFGrIter;
196     for (aFGrIter = aFeatureGroups.begin(); aFGrIter != aFeatureGroups.end(); aFGrIter++)
197       if (aFGrIter->second == ModelAPI_ResultConstruction::group() ||
198         aFGrIter->second == ModelAPI_Feature::group())
199         break;
200
201     if (aFGrIter != aFeatureGroups.end()) {
202       std::list<SketchGroupPtr>::iterator aGroupIter = myGroups.begin();
203       while (aGroupIter != myGroups.end()) {
204         if (!(*aGroupIter)->isWorkplaneValid()) {  // the group should be removed
205           std::list<SketchGroupPtr>::iterator aRemoveIt = aGroupIter++;
206           myGroups.erase(aRemoveIt);
207           continue;
208         }
209
210         (*aGroupIter)->repairConsistency();
211         ++aGroupIter;
212       }
213     }
214     myIsComputed = false;
215   }
216
217   // resolve constraints if needed
218   bool needToUpdate = needToResolve && resolveConstraints();
219   releaseFeaturesIfEventsBlocked();
220
221   // Features may be updated => now send events, but for all changed at once
222   if (isUpdateFlushed)
223     allowSendUpdate();
224
225   myIsComputed = false;
226
227   // send update for movement in any case
228   if (needToUpdate || isMovedEvt)
229     Events_Loop::loop()->flush(anUpdateEvent);
230 }
231
232 // ============================================================================
233 //  Function: updateFeature
234 //  Purpose:  create/update constraint or feature in appropriate group
235 // ============================================================================
236 bool SketchSolver_Manager::updateFeature(const std::shared_ptr<SketchPlugin_Feature>& theFeature)
237 {
238   // Check feature validity and find a group to place it.
239   // If the feature is not valid, the returned group will be empty.
240   // This will protect to deal with wrong (not fully initialized) features.
241   SketchGroupPtr aGroup = findGroup(theFeature);
242   if (!aGroup)
243     return false;
244   aGroup->blockEvents(true);
245
246   std::shared_ptr<SketchPlugin_Constraint> aConstraint =
247       std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
248
249   bool isOk = false;
250   if (aConstraint)
251     isOk = aGroup->changeConstraint(aConstraint);
252   else
253     isOk = aGroup->updateFeature(theFeature);
254   return isOk;
255 }
256
257 // ============================================================================
258 //  Function: moveFeature
259 //  Purpose:  move given feature in appropriate group
260 // ============================================================================
261 bool SketchSolver_Manager::moveFeature(
262     const std::shared_ptr<SketchPlugin_Feature>& theMovedFeature,
263     const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
264     const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
265 {
266   SketchGroupPtr aGroup = findGroup(theMovedFeature);
267   if (!aGroup)
268     return false;
269
270   std::shared_ptr<SketchPlugin_Constraint> aConstraint =
271       std::dynamic_pointer_cast<SketchPlugin_Constraint>(theMovedFeature);
272   if (aConstraint)
273   {
274     std::shared_ptr<GeomDataAPI_Point2D> aPntAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>
275       (aConstraint->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT()));
276     if (aPntAttr)
277     {
278       aPntAttr->setValue(theTo);
279       Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
280     }
281     return true;
282   }
283
284   aGroup->blockEvents(true);
285   return aGroup->moveFeature(theMovedFeature, theFrom, theTo);
286 }
287
288 // ============================================================================
289 //  Function: moveAttribute
290 //  Purpose:  move given attribute in appropriate group
291 // ============================================================================
292 bool SketchSolver_Manager::moveAttribute(
293     const std::shared_ptr<GeomDataAPI_Point2D>& theMovedAttribute,
294     const std::shared_ptr<GeomAPI_Pnt2d>& theFrom,
295     const std::shared_ptr<GeomAPI_Pnt2d>& theTo)
296 {
297   FeaturePtr anOwner = ModelAPI_Feature::feature(theMovedAttribute->owner());
298   std::shared_ptr<SketchPlugin_Constraint> aConstraint =
299       std::dynamic_pointer_cast<SketchPlugin_Constraint>(anOwner);
300   if (aConstraint)
301   {
302     theMovedAttribute->setValue(theTo);
303     Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
304     return true;
305   }
306
307   std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
308       std::dynamic_pointer_cast<SketchPlugin_Feature>(anOwner);
309   SketchGroupPtr aGroup;
310   if (aSketchFeature)
311     aGroup = findGroup(aSketchFeature);
312   if (!aGroup) {
313     theMovedAttribute->setValue(theTo);
314     return false;
315   }
316
317   aGroup->blockEvents(true);
318   return aGroup->movePoint(theMovedAttribute, theFrom, theTo);
319 }
320
321 // ============================================================================
322 //  Function: findGroup
323 //  Purpose:  search groups of entities interacting with given feature
324 // ============================================================================
325 SketchGroupPtr SketchSolver_Manager::findGroup(
326     std::shared_ptr<SketchPlugin_Feature> theFeature)
327 {
328   if (!isFeatureValid(theFeature))
329     return SketchGroupPtr(); // do not process wrong features
330
331   // Obtain sketch, containing the feature
332   CompositeFeaturePtr aSketch;
333   const std::set<AttributePtr>& aRefsList = theFeature->data()->refsToMe();
334   std::set<AttributePtr>::const_iterator aRefIt = aRefsList.begin();
335   for (; aRefIt != aRefsList.end(); ++aRefIt) {
336     FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
337     if (anOwner && anOwner->getKind() == SketchPlugin_Sketch::ID()) {
338       aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(anOwner);
339       break;
340     }
341   }
342
343   if (!aSketch)
344     return SketchGroupPtr(); // not a sketch's feature
345
346   std::list<SketchGroupPtr>::const_iterator aGroupIt;
347   for (aGroupIt = myGroups.begin(); aGroupIt != myGroups.end(); ++aGroupIt)
348     if ((*aGroupIt)->getWorkplane() == aSketch)
349       return *aGroupIt;
350
351   // group for the sketch does not created yet
352   SketchGroupPtr aNewGroup = SketchGroupPtr(new SketchSolver_Group(aSketch));
353   myGroups.push_back(aNewGroup);
354   return aNewGroup;
355 }
356
357 // ============================================================================
358 //  Function: resolveConstraints
359 //  Purpose:  change entities according to available constraints
360 // ============================================================================
361 bool SketchSolver_Manager::resolveConstraints()
362 {
363   bool needToUpdate = false;
364   std::list<SketchGroupPtr>::const_iterator aGroupIter = myGroups.begin();
365   for (; aGroupIter != myGroups.end(); ++aGroupIter) {
366     if ((*aGroupIter)->resolveConstraints())
367       needToUpdate = true;
368   }
369   return needToUpdate;
370 }
371
372 void SketchSolver_Manager::releaseFeaturesIfEventsBlocked() const
373 {
374   std::list<SketchGroupPtr>::const_iterator aGroupIter = myGroups.begin();
375   for (; aGroupIter != myGroups.end(); ++aGroupIter)
376     (*aGroupIter)->blockEvents(false);
377 }
378
379 bool SketchSolver_Manager::stopSendUpdate() const
380 {
381 static const Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
382   // to avoid redisplay of each segment on update by solver one by one in the viewer
383   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
384   if (isUpdateFlushed) {
385     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
386   }
387   return isUpdateFlushed;
388 }
389
390 void SketchSolver_Manager::allowSendUpdate() const
391 {
392   Events_Loop::loop()->setFlushed(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), true);
393 }