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