Salome HOME
6a9a1596eab33ba9ae5e7525cc7c06ed1fd81686
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_MultiRotation.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 "SketchPlugin_MultiRotation.h"
22 #include "SketchPlugin_Tools.h"
23
24 #include <GeomDataAPI_Point2D.h>
25 #include <ModelAPI_AttributeRefAttr.h>
26 #include <ModelAPI_AttributeBoolean.h>
27 #include <ModelAPI_AttributeDouble.h>
28 #include <ModelAPI_AttributeString.h>
29 #include <ModelAPI_AttributeInteger.h>
30 #include <ModelAPI_Data.h>
31 #include <ModelAPI_ResultConstruction.h>
32 #include <ModelAPI_AttributeRefList.h>
33 #include <ModelAPI_Events.h>
34 #include <ModelAPI_Session.h>
35 #include <ModelAPI_Validator.h>
36 #include <ModelAPI_Tools.h>
37
38 #include <SketchPlugin_SketchEntity.h>
39
40 #include <GeomAPI_Pnt2d.h>
41 #include <GeomAPI_XY.h>
42
43 #include <SketcherPrs_Factory.h>
44
45 #include <cmath>
46
47 static const double PI = 3.1415926535897932;
48 static const double PERIOD = 360.0;
49 static const double ANGLETOL = 1.e-7;
50
51 SketchPlugin_MultiRotation::SketchPlugin_MultiRotation()
52   : isUpdatingAngle(false)
53 {
54 }
55
56 void SketchPlugin_MultiRotation::initAttributes()
57 {
58   data()->addAttribute(CENTER_ID(), ModelAPI_AttributeRefAttr::typeId());
59
60   data()->addAttribute(ANGLE_TYPE(),   ModelAPI_AttributeString::typeId());
61   data()->addAttribute(ANGLE_ID(), ModelAPI_AttributeDouble::typeId());
62   data()->addAttribute(NUMBER_OF_OBJECTS_ID(), ModelAPI_AttributeInteger::typeId());
63   data()->addAttribute(SketchPlugin_Constraint::ENTITY_A(), ModelAPI_AttributeRefList::typeId());
64   data()->addAttribute(SketchPlugin_Constraint::ENTITY_B(), ModelAPI_AttributeRefList::typeId());
65   data()->addAttribute(ROTATION_LIST_ID(), ModelAPI_AttributeRefList::typeId());
66   data()->addAttribute(REVERSED_ID(), ModelAPI_AttributeBoolean::typeId());
67
68   ModelAPI_Session::get()->validators()->
69     registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_A());
70   ModelAPI_Session::get()->validators()->
71     registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_B());
72 }
73
74 void SketchPlugin_MultiRotation::execute()
75 {
76   if (!sketch()) {
77     // it is possible, that this method is called before this feature has back reference to sketch
78     // in this case, the execute is performed after this is done
79     return;
80   }
81
82   AttributeRefListPtr aRotationObjectRefs = reflist(ROTATION_LIST_ID());
83   int aNbCopies = integer(NUMBER_OF_OBJECTS_ID())->value() - 1;
84   if (aNbCopies <= 0)
85     return;
86
87   // Obtain center and angle of rotation
88   AttributeRefAttrPtr aCenter = data()->refattr(CENTER_ID());
89   if (!aCenter || !aCenter->isInitialized())
90     return;
91
92   //double anAngle = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
93   //                                                           attribute(ANGLE_ID()))->value();
94
95   // Convert angle to radians
96   //anAngle *= PI / 180.0;
97
98   // Wait all objects being created, then send update events
99   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
100   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
101   if (isUpdateFlushed)
102     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
103
104   std::shared_ptr<ModelAPI_Data> aData = data();
105   AttributeRefListPtr aRefListOfShapes = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
106       aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
107   AttributeRefListPtr aRefListOfRotated = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
108       aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
109   int aCurrentNbCopies = aRefListOfShapes->size() ?
110       aRefListOfRotated->size() / aRefListOfShapes->size() - 1 : 0;
111   std::list<ObjectPtr> anInitialList = aRefListOfShapes->list();
112   std::list<ObjectPtr> aTargetList = aRefListOfRotated->list();
113   std::list<ObjectPtr> anAddition;
114   std::vector<bool> isUsed(anInitialList.size(), false);
115   // collect new items and check the items to remove
116   for(int anInd = 0; anInd < aRotationObjectRefs->size(); anInd++) {
117     ObjectPtr anObject = aRotationObjectRefs->object(anInd);
118     std::list<ObjectPtr>::const_iterator anIt = anInitialList.begin();
119     std::vector<bool>::iterator aUsedIt = isUsed.begin();
120     for (; anIt != anInitialList.end(); anIt++, aUsedIt++)
121       if (*anIt == anObject) {
122         *aUsedIt = true;
123         break;
124       }
125     if (anIt == anInitialList.end())
126       anAddition.push_back(anObject);
127   }
128   // remove unused items
129   std::list<ObjectPtr>::iterator anInitIter = anInitialList.begin();
130   std::list<ObjectPtr>::iterator aTargetIter = aTargetList.begin();
131   std::vector<bool>::iterator aUsedIter = isUsed.begin();
132   std::set<FeaturePtr> aFeaturesToBeRemoved;
133   for (; aUsedIter != isUsed.end(); aUsedIter++) {
134     if (!(*aUsedIter)) {
135       aRefListOfShapes->remove(*anInitIter);
136       aRefListOfRotated->remove(*aTargetIter++);
137       for (int i = 0; i < aCurrentNbCopies && aTargetIter != aTargetList.end();
138            i++, aTargetIter++) {
139         aRefListOfRotated->remove(*aTargetIter);
140         // remove the corresponding feature from the sketch
141         ResultConstructionPtr aRC =
142             std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aTargetIter);
143         DocumentPtr aDoc = aRC ? aRC->document() : DocumentPtr();
144         FeaturePtr aFeature =  aDoc ? aDoc->feature(aRC) : FeaturePtr();
145         if (aFeature)
146           aFeaturesToBeRemoved.insert(aFeature);
147       }
148     } else {
149       for (int i = 0; i <= aNbCopies && aTargetIter != aTargetList.end(); i++)
150         aTargetIter++;
151     }
152     if (anInitIter != anInitialList.end())
153       anInitIter++;
154   }
155   ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToBeRemoved);
156   // change number of copies
157   if (aCurrentNbCopies != 0 && aNbCopies != aCurrentNbCopies) {
158     bool isAdd = aNbCopies > aCurrentNbCopies;
159     int aMinCopies = isAdd ? aCurrentNbCopies : aNbCopies;
160     int aMaxCopies = isAdd ? aNbCopies : aCurrentNbCopies;
161     int ind = 0;
162
163     aTargetList = aRefListOfRotated->list();
164     aTargetIter = aTargetList.begin();
165     ObjectPtr anObjToCopy = *aTargetIter;
166     std::set<FeaturePtr> aFeaturesToBeRemoved;
167     while (aTargetIter != aTargetList.end()) {
168       aRefListOfRotated->remove(*aTargetIter);
169       aTargetIter++;
170       ind++;
171       if (ind > aMinCopies && ind <=aMaxCopies) {
172         while (ind <= aMaxCopies) {
173           if (isAdd) {
174             // Add new shifted item
175             ObjectPtr anObject = copyFeature(anObjToCopy);
176             aTargetList.insert(aTargetIter, anObject);
177           } else {
178             // remove object
179             std::list<ObjectPtr>::iterator aRemoveIt = aTargetIter++;
180             ObjectPtr anObject = *aRemoveIt;
181             aTargetList.erase(aRemoveIt);
182             aRefListOfRotated->remove(anObject);
183             // remove the corresponding feature from the sketch
184             ResultConstructionPtr aRC =
185                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anObject);
186             DocumentPtr aDoc = aRC ? aRC->document() : DocumentPtr();
187             FeaturePtr aFeature =  aDoc ? aDoc->feature(aRC) : FeaturePtr();
188             if (aFeature)
189               aFeaturesToBeRemoved.insert(aFeature);
190           }
191           ind++;
192         }
193         ind = 0;
194         if (aTargetIter != aTargetList.end())
195           anObjToCopy = *aTargetIter;
196       }
197     }
198     ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToBeRemoved);
199
200     for (aTargetIter = aTargetList.begin(); aTargetIter != aTargetList.end(); aTargetIter++)
201       aRefListOfRotated->append(*aTargetIter);
202   }
203   // add new items
204   std::list<ObjectPtr>::iterator anAddIter = anAddition.begin();
205   for (; anAddIter != anAddition.end(); anAddIter++) {
206     aRefListOfShapes->append(*anAddIter);
207     aRefListOfRotated->append(*anAddIter);
208     for (int i = 0; i < aNbCopies; i++) {
209       ObjectPtr anObject = copyFeature(*anAddIter);
210       aRefListOfRotated->append(anObject);
211     }
212   }
213
214 ////  if (fabs(anAngle) > 1.e-12) {
215 ////    // Recalculate positions of features
216 ////    aTargetList = aRefListOfRotated->list();
217 ////    aTargetIter = aTargetList.begin();
218 ////    while (aTargetIter != aTargetList.end()) {
219 ////      ObjectPtr anInitialObject = *aTargetIter++;
220 ////      for (int i = 0; i < aNbCopies && aTargetIter != aTargetList.end(); i++, aTargetIter++)
221 //// rotateFeature(anInitialObject, *aTargetIter, aCenter->x(), aCenter->y(), anAngle * (i + 1));
222 ////    }
223 ////  }
224
225   // send events to update the sub-features by the solver
226   if (isUpdateFlushed)
227     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
228 }
229
230 AISObjectPtr SketchPlugin_MultiRotation::getAISObject(AISObjectPtr thePrevious)
231 {
232   if (!sketch())
233     return thePrevious;
234
235   AISObjectPtr anAIS = SketcherPrs_Factory::rotateConstraint(this, sketch(),
236                                                              sketch()->coordinatePlane(),
237                                                              thePrevious);
238   return anAIS;
239 }
240
241 void SketchPlugin_MultiRotation::erase()
242 {
243   static Events_Loop* aLoop = Events_Loop::loop();
244   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
245
246   // Set copy attribute to false on all copied features.
247   AttributeRefListPtr aRefListOfShapes = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
248       data()->attribute(SketchPlugin_Constraint::ENTITY_A()));
249   AttributeRefListPtr aRefListOfRotated = std::dynamic_pointer_cast<ModelAPI_AttributeRefList>(
250       data()->attribute(SketchPlugin_Constraint::ENTITY_B()));
251
252   if(aRefListOfShapes.get() && aRefListOfRotated.get()) {
253     for(int anIndex = 0; anIndex < aRefListOfRotated->size(); anIndex++) {
254       ObjectPtr anObject = aRefListOfRotated->object(anIndex);
255       if(aRefListOfShapes->isInList(anObject)) {
256         // Don't modify attribute of original features, just skip.
257         continue;
258       }
259       if(anObject.get()) {
260         ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
261         if(aRes.get()) {
262           FeaturePtr aFeature = aRes->document()->feature(aRes);
263           if(aFeature.get()) {
264             AttributeBooleanPtr aBooleanAttr =
265               aFeature->boolean(SketchPlugin_SketchEntity::COPY_ID());
266             if(aBooleanAttr.get()) {
267               if (ModelAPI_Session::get()->isOperation()) // if this is not undo or redo
268                 aBooleanAttr->setValue(false);
269               // Redisplay object as it is not copy anymore.
270               ModelAPI_EventCreator::get()->sendUpdated(aRes, aRedispEvent);
271             }
272           }
273         }
274       }
275     }
276   }
277
278   SketchPlugin_ConstraintBase::erase();
279 }
280
281 ObjectPtr SketchPlugin_MultiRotation::copyFeature(ObjectPtr theObject)
282 {
283   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theObject);
284   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
285   if (!aFeature || !aResult)
286     return ObjectPtr();
287
288   FeaturePtr aNewFeature =
289     SketchPlugin_Sketch::addUniqueNamedCopiedFeature(aFeature, sketch(), true);
290   aNewFeature->execute();
291
292   static Events_ID aRedisplayEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
293   ModelAPI_EventCreator::get()->sendUpdated(aNewFeature, aRedisplayEvent);
294
295   std::shared_ptr<GeomAPI_Shape> aShapeIn = aResult->shape();
296   const std::list<ResultPtr>& aResults = aNewFeature->results();
297   std::list<ResultPtr>::const_iterator anIt = aResults.begin();
298   for (; anIt != aResults.end(); anIt++) {
299     ResultConstructionPtr aRC = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*anIt);
300     if (!aRC) continue;
301     std::shared_ptr<GeomAPI_Shape> aShapeOut = aRC->shape();
302     if ((aShapeIn->isVertex() && aShapeOut->isVertex()) ||
303         (aShapeIn->isEdge() && aShapeOut->isEdge()) ||
304         (aShapeIn->isFace() && aShapeOut->isFace()))
305       return aRC;
306   }
307   return ObjectPtr();
308 }
309
310 /*void SketchPlugin_MultiRotation::rotateFeature(
311     ObjectPtr theInitial, ObjectPtr theTarget,
312     double theCenterX, double theCenterY, double theAngle)
313 {
314   std::shared_ptr<GeomAPI_Pnt2d> aCenter(new GeomAPI_Pnt2d(theCenterX, theCenterY));
315   double cosA = std::cos(theAngle);
316   double sinA = std::sin(theAngle);
317
318   FeaturePtr anInitialFeature = ModelAPI_Feature::feature(theInitial);
319   FeaturePtr aTargetFeature = ModelAPI_Feature::feature(theTarget);
320
321   // block feature update
322   aTargetFeature->data()->blockSendAttributeUpdated(true);
323
324   std::list<AttributePtr> anInitAttrList =
325       anInitialFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
326   std::list<AttributePtr> aTargetAttrList =
327       aTargetFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
328   std::list<AttributePtr>::iterator anInitIt = anInitAttrList.begin();
329   std::list<AttributePtr>::iterator aTargetIt = aTargetAttrList.begin();
330   for (; anInitIt != anInitAttrList.end(); anInitIt++, aTargetIt++) {
331     std::shared_ptr<GeomDataAPI_Point2D> aPointFrom =
332         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anInitIt);
333     std::shared_ptr<GeomDataAPI_Point2D> aPointTo =
334         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*aTargetIt);
335     std::shared_ptr<GeomAPI_XY> aPnt = aPointFrom->pnt()->xy();
336     if (aPnt->distance(aCenter->xy()) > 1.e-7) {
337       std::shared_ptr<GeomAPI_XY> aDir = aPnt->decreased(aCenter->xy());
338       double dx = cosA * aDir->x() - sinA * aDir->y();
339       double dy = sinA * aDir->x() + cosA * aDir->y();
340       aPnt->setX(aCenter->x() + dx);
341       aPnt->setY(aCenter->y() + dy);
342     }
343     aPointTo->setValue(aPnt->x(), aPnt->y());
344   }
345
346   // unblock feature update
347   aTargetFeature->data()->blockSendAttributeUpdated(false);
348 }*/
349
350
351 void SketchPlugin_MultiRotation::attributeChanged(const std::string& theID)
352 {
353   if (theID == ROTATION_LIST_ID()) {
354     AttributeRefListPtr aRotationObjectRefs = reflist(ROTATION_LIST_ID());
355     if (aRotationObjectRefs->size() == 0) {
356       int aNbCopies = integer(NUMBER_OF_OBJECTS_ID())->value()-1;
357       if (aNbCopies <= 0)
358         return;
359
360       // Clear list of objects
361       AttributeRefListPtr aRefListOfRotated = reflist(SketchPlugin_Constraint::ENTITY_B());
362       std::list<ObjectPtr> aTargetList = aRefListOfRotated->list();
363       std::list<ObjectPtr>::iterator aTargetIter = aTargetList.begin();
364       std::set<FeaturePtr> aFeaturesToBeRemoved;
365       while (aTargetIter != aTargetList.end()) {
366         aTargetIter++;
367         for (int i = 0; i < aNbCopies && aTargetIter != aTargetList.end(); i++, aTargetIter++) {
368           aRefListOfRotated->remove(*aTargetIter);
369           // remove the corresponding feature from the sketch
370           FeaturePtr aFeature = ModelAPI_Feature::feature(*aTargetIter);
371           if (aFeature)
372             aFeaturesToBeRemoved.insert(aFeature);
373         }
374       }
375       ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToBeRemoved);
376
377       aRefListOfRotated->clear();
378       reflist(SketchPlugin_Constraint::ENTITY_A())->clear();
379     }
380   }
381   else if (!isUpdatingAngle && real(ANGLE_ID())->isInitialized())
382   {
383     isUpdatingAngle = true;
384     AttributeDoublePtr anAngle = real(ANGLE_ID());
385     if (theID == ANGLE_TYPE() && integer(NUMBER_OF_OBJECTS_ID())->isInitialized()) {
386       if (string(ANGLE_TYPE())->value() != "SingleAngle")
387         anAngle->setValue(anAngle->value() * (integer(NUMBER_OF_OBJECTS_ID())->value() - 1));
388       else
389       {
390         int aNbSplits = integer(NUMBER_OF_OBJECTS_ID())->value();
391         if (anAngle->value() < PERIOD - ANGLETOL)
392           aNbSplits -= 1;
393         anAngle->setValue(anAngle->value() / aNbSplits);
394       }
395     }
396     else if (theID == ANGLE_ID()) {
397       if (anAngle->value() > PERIOD + ANGLETOL || anAngle->value() < -ANGLETOL)
398         anAngle->setValue(anAngle->value() + PERIOD * ceil(-anAngle->value() / PERIOD));
399       if (fabs(anAngle->value() - PERIOD) < ANGLETOL)
400         anAngle->setValue(PERIOD);
401       else if (fabs(anAngle->value()) < ANGLETOL)
402         anAngle->setValue(0.);
403     }
404     isUpdatingAngle = false;
405   }
406 }