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