Salome HOME
Merge branch 'master' into cgt/devCEA
[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: changeConstraintOrEntity
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: findGroup
228 //  Purpose:  search groups of entities interacting with given feature
229 // ============================================================================
230 SketchGroupPtr SketchSolver_Manager::findGroup(
231     std::shared_ptr<SketchPlugin_Feature> theFeature)
232 {
233   if (!isFeatureValid(theFeature))
234     return SketchGroupPtr(); // do not process wrong features
235
236   // Obtain sketch, containing the feature
237   CompositeFeaturePtr aSketch;
238   const std::set<AttributePtr>& aRefsList = theFeature->data()->refsToMe();
239   std::set<AttributePtr>::const_iterator aRefIt = aRefsList.begin();
240   for (; aRefIt != aRefsList.end(); ++aRefIt) {
241     FeaturePtr anOwner = ModelAPI_Feature::feature((*aRefIt)->owner());
242     if (anOwner && anOwner->getKind() == SketchPlugin_Sketch::ID()) {
243       aSketch = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(anOwner);
244       break;
245     }
246   }
247
248   if (!aSketch)
249     return SketchGroupPtr(); // not a sketch's feature
250
251   std::list<SketchGroupPtr>::const_iterator aGroupIt;
252   for (aGroupIt = myGroups.begin(); aGroupIt != myGroups.end(); ++aGroupIt)
253     if ((*aGroupIt)->getWorkplane() == aSketch)
254       return *aGroupIt;
255
256   // group for the sketch does not created yet
257   SketchGroupPtr aNewGroup = SketchGroupPtr(new SketchSolver_Group(aSketch));
258   myGroups.push_back(aNewGroup);
259   return aNewGroup;
260 }
261
262 // ============================================================================
263 //  Function: resolveConstraints
264 //  Purpose:  change entities according to available constraints
265 // ============================================================================
266 bool SketchSolver_Manager::resolveConstraints()
267 {
268   bool needToUpdate = false;
269   std::list<SketchGroupPtr>::const_iterator aGroupIter = myGroups.begin();
270   for (; aGroupIter != myGroups.end(); ++aGroupIter) {
271     if ((*aGroupIter)->resolveConstraints())
272       needToUpdate = true;
273   }
274   return needToUpdate;
275 }
276
277 void SketchSolver_Manager::releaseFeaturesIfEventsBlocked() const
278 {
279   std::list<SketchGroupPtr>::const_iterator aGroupIter = myGroups.begin();
280   for (; aGroupIter != myGroups.end(); ++aGroupIter)
281     (*aGroupIter)->blockEvents(false);
282 }
283
284 bool SketchSolver_Manager::stopSendUpdate() const
285 {
286 static const Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
287   // to avoid redisplay of each segment on update by solver one by one in the viewer
288   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
289   if (isUpdateFlushed) {
290     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
291   }
292   return isUpdateFlushed;
293 }
294
295 void SketchSolver_Manager::allowSendUpdate() const
296 {
297   Events_Loop::loop()->setFlushed(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), true);
298 }