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