]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchPlugin/SketchPlugin_Offset.cpp
Salome HOME
f7f7b75e8b3ed805588ee61e35420f94e2de987e
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Offset.cpp
1 // Copyright (C) 2020  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 <SketchPlugin_Offset.h>
21
22 #include <SketchPlugin_Sketch.h>
23 #include <SketchPlugin_Line.h>
24 #include <SketchPlugin_Point.h>
25 #include <SketchPlugin_Arc.h>
26 #include <SketchPlugin_Circle.h>
27 #include <SketchPlugin_Ellipse.h>
28 #include <SketchPlugin_EllipticArc.h>
29 #include <SketchPlugin_BSpline.h>
30 #include <SketchPlugin_BSplinePeriodic.h>
31 #include <SketchPlugin_Tools.h>
32
33 #include <SketcherPrs_Factory.h>
34
35 #include <Events_InfoMessage.h>
36
37 #include <ModelAPI_AttributeBoolean.h>
38 #include <ModelAPI_AttributeDouble.h>
39 #include <ModelAPI_AttributeDoubleArray.h>
40 #include <ModelAPI_AttributeInteger.h>
41 #include <ModelAPI_AttributeIntArray.h>
42 #include <ModelAPI_AttributeRefList.h>
43 #include <ModelAPI_Events.h>
44 #include <ModelAPI_ResultConstruction.h>
45 #include <ModelAPI_Tools.h>
46 #include <ModelAPI_Validator.h>
47
48 #include <GeomAlgoAPI_MakeShapeList.h>
49 #include <GeomAlgoAPI_Offset.h>
50 #include <GeomAlgoAPI_ShapeTools.h>
51 #include <GeomAlgoAPI_WireBuilder.h>
52
53 #include <GeomAPI_BSpline.h>
54 #include <GeomAPI_Circ.h>
55 #include <GeomAPI_Edge.h>
56 #include <GeomAPI_Ellipse.h>
57 #include <GeomAPI_ShapeExplorer.h>
58 #include <GeomAPI_Wire.h>
59 #include <GeomAPI_WireExplorer.h>
60
61 #include <GeomDataAPI_Point2D.h>
62 #include <GeomDataAPI_Point2DArray.h>
63
64 #include <iostream>
65
66 static const double tolerance = 1.e-7;
67
68 SketchPlugin_Offset::SketchPlugin_Offset()
69 {
70 }
71
72 void SketchPlugin_Offset::initAttributes()
73 {
74   data()->addAttribute(EDGES_ID(), ModelAPI_AttributeRefList::typeId());
75   data()->addAttribute(VALUE_ID(), ModelAPI_AttributeDouble::typeId());
76   data()->addAttribute(REVERSED_ID(), ModelAPI_AttributeBoolean::typeId());
77
78   // store original entities
79   data()->addAttribute(SketchPlugin_Constraint::ENTITY_A(), ModelAPI_AttributeRefList::typeId());
80   // store offset entities
81   data()->addAttribute(SketchPlugin_Constraint::ENTITY_B(), ModelAPI_AttributeRefList::typeId());
82   // store mapping between original entity and index of the corresponding offset entity
83   data()->addAttribute(SketchPlugin_Constraint::ENTITY_C(), ModelAPI_AttributeIntArray::typeId());
84
85   ModelAPI_Session::get()->validators()->
86       registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_A());
87   ModelAPI_Session::get()->validators()->
88       registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_B());
89   ModelAPI_Session::get()->validators()->
90       registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_C());
91 }
92
93 void SketchPlugin_Offset::execute()
94 {
95   SketchPlugin_Sketch* aSketch = sketch();
96   if (!aSketch) return;
97
98   // 1. Sketch plane
99   std::shared_ptr<GeomAPI_Pln> aPlane = aSketch->plane();
100
101   // 2. Offset value
102   AttributeDoublePtr aValueAttr = real(VALUE_ID());
103   if (!aValueAttr->isInitialized()) return;
104   double aValue = aValueAttr->value();
105   if (aValue < tolerance) return;
106
107   // 2.a. Reversed?
108   AttributeBooleanPtr aReversedAttr = boolean(REVERSED_ID());
109   if (!aReversedAttr->isInitialized()) return;
110   if (aReversedAttr->value()) aValue = -aValue; // reverse offset direction
111
112   // 3. List of all selected edges
113   AttributeRefListPtr aSelectedEdges = reflist(EDGES_ID());
114   std::list<ObjectPtr> anEdgesList = aSelectedEdges->list();
115
116   // 4. Put all selected edges in a set to pass them into findWireOneWay() below
117   std::set<FeaturePtr> anEdgesSet;
118   std::list<ObjectPtr>::const_iterator anEdgesIt = anEdgesList.begin();
119   for (; anEdgesIt != anEdgesList.end(); anEdgesIt++) {
120     FeaturePtr aFeature = ModelAPI_Feature::feature(*anEdgesIt);
121     if (aFeature) {
122       anEdgesSet.insert(aFeature);
123     }
124   }
125
126   // Wait all objects being created, then send update events
127   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
128   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
129   if (isUpdateFlushed)
130     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
131
132   // 5. Gather wires and make offset for each wire
133   ListOfMakeShape anOffsetAlgos;
134   for (anEdgesIt = anEdgesList.begin(); anEdgesIt != anEdgesList.end(); anEdgesIt++) {
135     FeaturePtr aFeature = ModelAPI_Feature::feature(*anEdgesIt);
136     if (aFeature.get()) {
137       if (anEdgesSet.find(aFeature) == anEdgesSet.end())
138         continue;
139
140       // 5.a. End points (if any)
141       std::shared_ptr<GeomDataAPI_Point2D> aStartPoint, anEndPoint;
142       SketchPlugin_SegmentationTools::getFeaturePoints(aFeature, aStartPoint, anEndPoint);
143
144       // 5.b. Find a chain of edges
145       std::list<FeaturePtr> aChain;
146       aChain.push_back(aFeature);
147       if (aStartPoint && anEndPoint) { // not closed edge
148         bool isClosed = findWireOneWay(aFeature, aFeature, aStartPoint, anEdgesSet, aChain, true);
149         if (!isClosed)
150           findWireOneWay(aFeature, aFeature, anEndPoint, anEdgesSet, aChain, false);
151       }
152       std::set<FeaturePtr>::iterator aPos = anEdgesSet.find(aFeature);
153       if (aPos != anEdgesSet.end())
154         anEdgesSet.erase(aPos);
155
156       // 5.c. Make wire
157       ListOfShape aTopoChain;
158       std::list<FeaturePtr>::iterator aChainIt = aChain.begin();
159       for (; aChainIt != aChain.end(); ++aChainIt) {
160         FeaturePtr aChainFeature = (*aChainIt);
161         GeomShapePtr aTopoEdge = aChainFeature->lastResult()->shape();
162         if (aTopoEdge->shapeType() == GeomAPI_Shape::EDGE) {
163           aTopoChain.push_back(aTopoEdge);
164         }
165       }
166       std::shared_ptr<GeomAlgoAPI_WireBuilder> aWireBuilder(
167           new GeomAlgoAPI_WireBuilder(aTopoChain));
168
169       GeomShapePtr aWireShape = aWireBuilder->shape();
170       GeomWirePtr aWire (new GeomAPI_Wire (aWireShape));
171
172       // Fix for a problem of offset side change with selection change.
173       // Wire direction is defined by the first selected edge of this wire.
174       if (!aWire->isClosed()) {
175         ListOfShape aModified;
176         // First selected edge of current chain
177         GeomShapePtr aFirstSel = aFeature->lastResult()->shape();
178         aWireBuilder->modified(aFirstSel, aModified);
179         GeomShapePtr aModFS = aModified.front();
180         if (aModFS->orientation() != aFirstSel->orientation())
181           aValue = -aValue;
182       }
183
184       // 5.d. Make offset for the wire
185       std::shared_ptr<GeomAlgoAPI_Offset> anOffsetShape(
186           new GeomAlgoAPI_Offset(aPlane, aWireShape, aValue));
187
188       std::shared_ptr<GeomAlgoAPI_MakeShapeList> aMakeList(new GeomAlgoAPI_MakeShapeList);
189       aMakeList->appendAlgo(aWireBuilder);
190       aMakeList->appendAlgo(anOffsetShape);
191       anOffsetAlgos.push_back(aMakeList);
192     }
193   }
194
195   // 6. Store offset results.
196   //    Create sketch feature for each edge of anOffsetShape, and also store
197   //    created features in CREATED_ID() to remove them on next execute()
198   addToSketch(anOffsetAlgos);
199
200   // send events to update the sub-features by the solver
201   if (isUpdateFlushed)
202     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
203 }
204
205 bool SketchPlugin_Offset::findWireOneWay (const FeaturePtr& theFirstEdge,
206                                           const FeaturePtr& theEdge,
207                                           const std::shared_ptr<GeomDataAPI_Point2D>& theEndPoint,
208                                           std::set<FeaturePtr>& theEdgesSet,
209                                           std::list<FeaturePtr>& theChain,
210                                           const bool isPrepend)
211 {
212   // 1. Find a single edge, coincident to theEndPoint by one of its ends
213   if (!theEndPoint) return false;
214
215   FeaturePtr aNextEdgeFeature;
216   int nbFound = 0;
217
218   std::set<AttributePoint2DPtr> aCoincPoints;
219   std::map<AttributePoint2DArrayPtr, int> aCoincPointsInArray;
220   SketchPlugin_Tools::findPointsCoincidentToPoint(theEndPoint, aCoincPoints, aCoincPointsInArray);
221
222   // store all found attributes to a single array
223   std::set<AttributePtr> anAllCoincPoints;
224   anAllCoincPoints.insert(aCoincPoints.begin(), aCoincPoints.end());
225   for (auto it = aCoincPointsInArray.begin(); it != aCoincPointsInArray.end(); ++it)
226     anAllCoincPoints.insert(it->first);
227
228   std::set<AttributePtr>::iterator aPointsIt = anAllCoincPoints.begin();
229   for (; aPointsIt != anAllCoincPoints.end(); aPointsIt++) {
230     AttributePtr aP = (*aPointsIt);
231     FeaturePtr aCoincFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aP->owner());
232     bool isInSet = (theEdgesSet.find(aCoincFeature) != theEdgesSet.end());
233
234     // Condition 0: not auxiliary
235     if (!isInSet && aCoincFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value())
236       continue;
237
238     // Condition 1: not a point feature
239     if (aCoincFeature->getKind() != SketchPlugin_Point::ID()) {
240       // Condition 2: it is not the current edge
241       if (aCoincFeature != theEdge) {
242         // Condition 3: it is in the set of interest.
243         //              Empty set means all sketch edges.
244         if (isInSet || theEdgesSet.empty()) {
245           // Condition 4: consider only features with two end points
246           std::shared_ptr<GeomDataAPI_Point2D> aP1, aP2;
247           SketchPlugin_SegmentationTools::getFeaturePoints(aCoincFeature, aP1, aP2);
248           if (aP1 && aP2) {
249             // Condition 5: consider only features, that have aP as one of they ends.
250             //              For example, we do not need an arc, coincident to aP by its center.
251             if (theEndPoint->pnt()->isEqual(aP1->pnt()) ||
252                 theEndPoint->pnt()->isEqual(aP2->pnt())) {
253               // Condition 6: only one edge can prolongate the chain. If several, we stop here.
254               nbFound++;
255               if (nbFound > 1)
256                 return false;
257
258               // One found
259               aNextEdgeFeature = aCoincFeature;
260             }
261           }
262         }
263       }
264     }
265   }
266
267   // Only one edge can prolongate the chain. If several or none, we stop here.
268   if (nbFound != 1)
269     return false;
270
271   // 2. So, we have the single edge, that prolongate the chain
272
273   // Condition 7: if we reached the very first edge of the chain
274   if (aNextEdgeFeature == theFirstEdge)
275     // Closed chain found
276     return true;
277
278   // 3. Add the found edge to the chain
279   if (isPrepend)
280     theChain.push_front(aNextEdgeFeature);
281   else
282     theChain.push_back(aNextEdgeFeature);
283   // remove from the set, if the set is used
284   if (theEdgesSet.size()) {
285     std::set<FeaturePtr>::iterator aPos = theEdgesSet.find(aNextEdgeFeature);
286     if (aPos != theEdgesSet.end())
287       theEdgesSet.erase(aPos);
288   }
289
290   // 4. Which end of aNextEdgeFeature we need to proceed
291   std::shared_ptr<GeomDataAPI_Point2D> aP1, aP2;
292   SketchPlugin_SegmentationTools::getFeaturePoints(aNextEdgeFeature, aP1, aP2);
293   if (aP2->pnt()->isEqual(theEndPoint->pnt())) {
294     // reversed
295     aP2 = aP1;
296   }
297
298   // 5. Continue gathering the chain (recursive)
299   return findWireOneWay (theFirstEdge, aNextEdgeFeature, aP2, theEdgesSet, theChain, isPrepend);
300 }
301
302 static void setRefListValue(AttributeRefListPtr theList, int theListSize,
303                             ObjectPtr theValue, int theIndex)
304 {
305   if (theIndex < theListSize) {
306     ObjectPtr aCur = theList->object(theIndex);
307     if (aCur != theValue)
308       theList->substitute(aCur, theValue);
309   }
310   else
311     theList->append(theValue);
312 }
313
314 // Reorder shapes according to the wire's order
315 static void reorderShapes(ListOfShape& theShapes, GeomShapePtr theWire)
316 {
317   std::set<GeomShapePtr, GeomAPI_Shape::Comparator> aShapes;
318   aShapes.insert(theShapes.begin(), theShapes.end());
319   theShapes.clear();
320
321   GeomWirePtr aWire(new GeomAPI_Wire(theWire));
322   GeomAPI_WireExplorer anExp(aWire);
323   for (; anExp.more(); anExp.next()) {
324     GeomShapePtr aCurEdge = anExp.current();
325     auto aFound = aShapes.find(aCurEdge);
326     if (aFound != aShapes.end()) {
327       theShapes.push_back(aCurEdge);
328       aShapes.erase(aFound);
329     }
330   }
331 }
332
333 static void removeLastFromIndex(AttributeRefListPtr theList, int theListSize, int& theLastIndex)
334 {
335   if (theLastIndex < theListSize) {
336     std::set<int> anIndicesToRemove;
337     for (; theLastIndex < theListSize; ++theLastIndex)
338       anIndicesToRemove.insert(theLastIndex);
339     theList->remove(anIndicesToRemove);
340   }
341 }
342
343 void SketchPlugin_Offset::addToSketch(const ListOfMakeShape& theOffsetAlgos)
344 {
345   AttributeRefListPtr aSelectedRefList = reflist(EDGES_ID());
346   AttributeRefListPtr aBaseRefList = reflist(ENTITY_A());
347   AttributeRefListPtr anOffsetRefList = reflist(ENTITY_B());
348   AttributeIntArrayPtr anOffsetToBaseMap = intArray(ENTITY_C());
349
350   // compare the list of selected edges and the previously stored,
351   // and store maping between them
352   std::map<ObjectPtr, std::list<ObjectPtr> > aMapExistent;
353   std::list<ObjectPtr> anObjectsToRemove;
354   std::list<ObjectPtr> aSelectedList = aSelectedRefList->list();
355   for (std::list<ObjectPtr>::iterator aSIt = aSelectedList.begin();
356        aSIt != aSelectedList.end(); ++aSIt) {
357     aMapExistent[*aSIt] = std::list<ObjectPtr>();
358   }
359   for (int anIndex = 0, aSize = anOffsetRefList->size(); anIndex < aSize; ++anIndex) {
360     ObjectPtr aCurrent = anOffsetRefList->object(anIndex);
361     int aBaseIndex = anOffsetToBaseMap->value(anIndex);
362     if (aBaseIndex >= 0) {
363       ObjectPtr aBaseObj = aBaseRefList->object(aBaseIndex);
364       std::map<ObjectPtr, std::list<ObjectPtr> >::iterator aFound = aMapExistent.find(aBaseObj);
365       if (aFound != aMapExistent.end())
366         aFound->second.push_back(aCurrent);
367       else
368         anObjectsToRemove.push_back(aCurrent);
369     }
370     else
371       anObjectsToRemove.push_back(aCurrent);
372   }
373
374   // update lists of base shapes and of offset shapes
375   int aBaseListSize = aBaseRefList->size();
376   int anOffsetListSize = anOffsetRefList->size();
377   int aBaseListIndex = 0, anOffsetListIndex = 0;
378   std::list<int> anOffsetBaseBackRefs;
379   std::set<GeomShapePtr, GeomAPI_Shape::ComparatorWithOri> aProcessedOffsets;
380   for (std::list<ObjectPtr>::iterator aSIt = aSelectedList.begin();
381        aSIt != aSelectedList.end(); ++aSIt) {
382     // find an offseted edge
383     FeaturePtr aBaseFeature = ModelAPI_Feature::feature(*aSIt);
384     GeomShapePtr aBaseShape = aBaseFeature->lastResult()->shape();
385     ListOfShape aNewShapes;
386     for (ListOfMakeShape::const_iterator anAlgoIt = theOffsetAlgos.begin();
387          anAlgoIt != theOffsetAlgos.end(); ++anAlgoIt) {
388       (*anAlgoIt)->generated(aBaseShape, aNewShapes);
389       if (!aNewShapes.empty()) {
390         reorderShapes(aNewShapes, (*anAlgoIt)->shape());
391         break;
392       }
393     }
394
395     // store base feature
396     setRefListValue(aBaseRefList, aBaseListSize, *aSIt, aBaseListIndex);
397
398     // create or update an offseted feature
399     const std::list<ObjectPtr>& anImages = aMapExistent[*aSIt];
400     std::list<ObjectPtr>::const_iterator anImgIt = anImages.begin();
401     for (ListOfShape::iterator aNewIt = aNewShapes.begin(); aNewIt != aNewShapes.end(); ++aNewIt) {
402       FeaturePtr aNewFeature;
403       if (anImgIt != anImages.end())
404         aNewFeature = ModelAPI_Feature::feature(*anImgIt++);
405       updateExistentOrCreateNew(*aNewIt, aNewFeature, anObjectsToRemove);
406       aProcessedOffsets.insert(*aNewIt);
407
408       // store an offseted feature
409       setRefListValue(anOffsetRefList, anOffsetListSize, aNewFeature, anOffsetListIndex);
410
411       anOffsetBaseBackRefs.push_back(aBaseListIndex);
412       ++anOffsetListIndex;
413     }
414     ++aBaseListIndex;
415     anObjectsToRemove.insert(anObjectsToRemove.end(), anImgIt, anImages.end());
416   }
417   // create arcs generated from vertices
418   for (ListOfMakeShape::const_iterator anAlgoIt = theOffsetAlgos.begin();
419        anAlgoIt != theOffsetAlgos.end(); ++anAlgoIt) {
420     GeomShapePtr aCurWire = (*anAlgoIt)->shape();
421     GeomAPI_ShapeExplorer anExp(aCurWire, GeomAPI_Shape::EDGE);
422     for (; anExp.more(); anExp.next()) {
423       GeomShapePtr aCurEdge = anExp.current();
424       if (aProcessedOffsets.find(aCurEdge) == aProcessedOffsets.end()) {
425         FeaturePtr aNewFeature;
426         updateExistentOrCreateNew(aCurEdge, aNewFeature, anObjectsToRemove);
427         aProcessedOffsets.insert(aCurEdge);
428
429         // store an offseted feature
430         setRefListValue(anOffsetRefList, anOffsetListSize, aNewFeature, anOffsetListIndex);
431
432         anOffsetBaseBackRefs.push_back(-1);
433         ++anOffsetListIndex;
434       }
435     }
436   }
437
438   removeLastFromIndex(aBaseRefList, aBaseListSize, aBaseListIndex);
439   removeLastFromIndex(anOffsetRefList, anOffsetListSize, anOffsetListIndex);
440
441   anOffsetToBaseMap->setSize((int)anOffsetBaseBackRefs.size(), false);
442   int anIndex = 0;
443   for (std::list<int>::iterator anIt = anOffsetBaseBackRefs.begin();
444        anIt != anOffsetBaseBackRefs.end(); ++anIt) {
445     anOffsetToBaseMap->setValue(anIndex++, *anIt, false);
446   }
447
448   // remove unused objects
449   std::set<FeaturePtr> aSet;
450   for (std::list<ObjectPtr>::iterator anIt = anObjectsToRemove.begin();
451        anIt != anObjectsToRemove.end(); ++anIt) {
452     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
453     if (aFeature)
454       aSet.insert(aFeature);
455   }
456   ModelAPI_Tools::removeFeaturesAndReferences(aSet);
457 }
458
459 static void findOrCreateFeatureByKind(SketchPlugin_Sketch* theSketch,
460                                       const std::string& theFeatureKind,
461                                       FeaturePtr& theFeature,
462                                       std::list<ObjectPtr>& thePoolOfFeatures)
463 {
464   if (theFeature) {
465     // check the feature type is the same as required
466     if (theFeature->getKind() != theFeatureKind) {
467       // return feature to the pool and try to find the most appropriate
468       thePoolOfFeatures.push_back(theFeature);
469       theFeature = FeaturePtr();
470     }
471   }
472   if (!theFeature) {
473     // try to find appropriate feature in the pool
474     for (std::list<ObjectPtr>::iterator it = thePoolOfFeatures.begin();
475          it != thePoolOfFeatures.end(); ++it) {
476       FeaturePtr aCurFeature = ModelAPI_Feature::feature(*it);
477       if (aCurFeature->getKind() == theFeatureKind) {
478         theFeature = aCurFeature;
479         thePoolOfFeatures.erase(it);
480         break;
481       }
482     }
483     // feature not found, create new
484     if (!theFeature)
485       theFeature = theSketch->addFeature(theFeatureKind);
486   }
487 }
488
489 void SketchPlugin_Offset::updateExistentOrCreateNew(const GeomShapePtr& theShape,
490                                                     FeaturePtr& theFeature,
491                                                     std::list<ObjectPtr>& thePoolOfFeatures)
492 {
493   if (theShape->shapeType() != GeomAPI_Shape::EDGE)
494     return;
495
496   std::shared_ptr<GeomAPI_Edge> aResEdge(new GeomAPI_Edge(theShape));
497
498   std::shared_ptr<GeomAPI_Pnt2d> aFP, aLP;
499   std::shared_ptr<GeomAPI_Pnt> aFP3d = aResEdge->firstPoint();
500   std::shared_ptr<GeomAPI_Pnt> aLP3d = aResEdge->lastPoint();
501   if (aFP3d && aLP3d) {
502     aFP = sketch()->to2D(aFP3d);
503     aLP = sketch()->to2D(aLP3d);
504   }
505
506   if (aResEdge->isLine()) {
507     findOrCreateFeatureByKind(sketch(), SketchPlugin_Line::ID(), theFeature, thePoolOfFeatures);
508
509     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
510       (theFeature->attribute(SketchPlugin_Line::START_ID()))->setValue(aFP);
511     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
512       (theFeature->attribute(SketchPlugin_Line::END_ID()))->setValue(aLP);
513   }
514   else if (aResEdge->isArc()) {
515     std::shared_ptr<GeomAPI_Circ> aCircEdge = aResEdge->circle();
516     std::shared_ptr<GeomAPI_Pnt> aCP3d = aCircEdge->center();
517     std::shared_ptr<GeomAPI_Pnt2d> aCP = sketch()->to2D(aCP3d);
518
519     findOrCreateFeatureByKind(sketch(), SketchPlugin_Arc::ID(), theFeature, thePoolOfFeatures);
520
521     GeomDirPtr aCircNormal = aCircEdge->normal();
522     GeomDirPtr aSketchNormal = sketch()->coordinatePlane()->normal();
523     if (aSketchNormal->dot(aCircNormal) < -tolerance)
524       std::swap(aFP, aLP);
525
526     bool aWasBlocked = theFeature->data()->blockSendAttributeUpdated(true);
527     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
528       (theFeature->attribute(SketchPlugin_Arc::END_ID()))->setValue(aLP);
529     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
530       (theFeature->attribute(SketchPlugin_Arc::START_ID()))->setValue(aFP);
531     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
532       (theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->setValue(aCP);
533     theFeature->data()->blockSendAttributeUpdated(aWasBlocked);
534   }
535   else if (aResEdge->isCircle()) {
536     std::shared_ptr<GeomAPI_Circ> aCircEdge = aResEdge->circle();
537     std::shared_ptr<GeomAPI_Pnt> aCP3d = aCircEdge->center();
538     std::shared_ptr<GeomAPI_Pnt2d> aCP = sketch()->to2D(aCP3d);
539
540     findOrCreateFeatureByKind(sketch(), SketchPlugin_Circle::ID(), theFeature, thePoolOfFeatures);
541
542     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
543       (theFeature->attribute(SketchPlugin_Circle::CENTER_ID()))->setValue(aCP);
544     theFeature->real(SketchPlugin_Circle::RADIUS_ID())->setValue(aCircEdge->radius());
545   }
546   else if (aResEdge->isEllipse()) {
547     std::shared_ptr<GeomAPI_Ellipse> anEllipseEdge = aResEdge->ellipse();
548
549     GeomPointPtr aCP3d = anEllipseEdge->center();
550     GeomPnt2dPtr aCP = sketch()->to2D(aCP3d);
551
552     GeomPointPtr aFocus3d = anEllipseEdge->firstFocus();
553     GeomPnt2dPtr aFocus = sketch()->to2D(aFocus3d);
554
555     if (aFP3d && aLP3d) {
556       // Elliptic arc
557       findOrCreateFeatureByKind(sketch(), SketchPlugin_EllipticArc::ID(),
558                                 theFeature, thePoolOfFeatures);
559
560       bool aWasBlocked = theFeature->data()->blockSendAttributeUpdated(true);
561       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
562         (theFeature->attribute(SketchPlugin_EllipticArc::CENTER_ID()))->setValue(aCP);
563       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
564         (theFeature->attribute(SketchPlugin_EllipticArc::FIRST_FOCUS_ID()))->setValue(aFocus);
565       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
566         (theFeature->attribute(SketchPlugin_EllipticArc::START_POINT_ID()))->setValue(aFP);
567       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
568         (theFeature->attribute(SketchPlugin_EllipticArc::END_POINT_ID()))->setValue(aLP);
569       theFeature->data()->blockSendAttributeUpdated(aWasBlocked);
570     }
571     else {
572       // Ellipse
573       findOrCreateFeatureByKind(sketch(), SketchPlugin_Ellipse::ID(),
574                                 theFeature, thePoolOfFeatures);
575
576       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
577         (theFeature->attribute(SketchPlugin_Ellipse::CENTER_ID()))->setValue(aCP);
578       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
579         (theFeature->attribute(SketchPlugin_Ellipse::FIRST_FOCUS_ID()))->setValue(aFocus);
580       theFeature->real(SketchPlugin_Ellipse::MINOR_RADIUS_ID())->setValue(
581         anEllipseEdge->minorRadius());
582     }
583   }
584   else {
585     // convert to b-spline
586     mkBSpline(theFeature, aResEdge, thePoolOfFeatures);
587   }
588
589   if (theFeature.get()) {
590     theFeature->boolean(SketchPlugin_SketchEntity::COPY_ID())->setValue(true);
591     theFeature->execute();
592
593     static Events_ID aRedisplayEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
594     ModelAPI_EventCreator::get()->sendUpdated(theFeature, aRedisplayEvent);
595     const std::list<ResultPtr>& aResults = theFeature->results();
596     for (std::list<ResultPtr>::const_iterator anIt = aResults.begin();
597          anIt != aResults.end(); ++anIt)
598       ModelAPI_EventCreator::get()->sendUpdated(*anIt, aRedisplayEvent);
599   }
600 }
601
602 void SketchPlugin_Offset::mkBSpline (FeaturePtr& theResult,
603                                      const GeomEdgePtr& theEdge,
604                                      std::list<ObjectPtr>& thePoolOfFeatures)
605 {
606   GeomCurvePtr aCurve (new GeomAPI_Curve (theEdge));
607   // Forced conversion to b-spline, if aCurve is not b-spline
608   GeomBSplinePtr aBSpline = GeomAPI_BSpline::convertToBSpline(aCurve);
609
610   const std::string& aBSplineKind = aBSpline->isPeriodic() ? SketchPlugin_BSplinePeriodic::ID()
611                                                            : SketchPlugin_BSpline::ID();
612   findOrCreateFeatureByKind(sketch(), aBSplineKind, theResult, thePoolOfFeatures);
613
614   theResult->integer(SketchPlugin_BSpline::DEGREE_ID())->setValue(aBSpline->degree());
615
616   AttributePoint2DArrayPtr aPolesAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2DArray>
617     (theResult->attribute(SketchPlugin_BSpline::POLES_ID()));
618   std::list<GeomPointPtr> aPoles = aBSpline->poles();
619   aPolesAttr->setSize((int)aPoles.size());
620   std::list<GeomPointPtr>::iterator anIt = aPoles.begin();
621   for (int anIndex = 0; anIt != aPoles.end(); ++anIt, ++anIndex) {
622     GeomPnt2dPtr aPoleInSketch = sketch()->to2D(*anIt);
623     aPolesAttr->setPnt(anIndex, aPoleInSketch);
624   }
625
626   AttributeDoubleArrayPtr aWeightsAttr =
627       theResult->data()->realArray(SketchPlugin_BSpline::WEIGHTS_ID());
628   std::list<double> aWeights = aBSpline->weights();
629   if (aWeights.empty()) { // rational B-spline
630     int aSize = (int)aPoles.size();
631     aWeightsAttr->setSize(aSize);
632     for (int anIndex = 0; anIndex < aSize; ++anIndex)
633       aWeightsAttr->setValue(anIndex, 1.0);
634   }
635   else { // non-rational B-spline
636     aWeightsAttr->setSize((int)aWeights.size());
637     std::list<double>::iterator anIt = aWeights.begin();
638     for (int anIndex = 0; anIt != aWeights.end(); ++anIt, ++anIndex)
639       aWeightsAttr->setValue(anIndex, *anIt);
640   }
641
642   AttributeDoubleArrayPtr aKnotsAttr =
643       theResult->data()->realArray(SketchPlugin_BSpline::KNOTS_ID());
644   std::list<double> aKnots = aBSpline->knots();
645   int aSize = (int)aKnots.size();
646   aKnotsAttr->setSize(aSize);
647   std::list<double>::iterator aKIt = aKnots.begin();
648   for (int index = 0; index < aSize; ++index, ++aKIt)
649     aKnotsAttr->setValue(index, *aKIt);
650
651   AttributeIntArrayPtr aMultsAttr =
652       theResult->data()->intArray(SketchPlugin_BSpline::MULTS_ID());
653   std::list<int> aMultiplicities = aBSpline->mults();
654   aSize = (int)aMultiplicities.size();
655   aMultsAttr->setSize(aSize);
656   std::list<int>::iterator aMIt = aMultiplicities.begin();
657   for (int index = 0; index < aSize; ++index, ++aMIt)
658     aMultsAttr->setValue(index, *aMIt);
659 }
660
661 void SketchPlugin_Offset::attributeChanged(const std::string& theID)
662 {
663 ////  if (theID == EDGES_ID())
664 ////    removeCreated();
665 }
666
667 bool SketchPlugin_Offset::customAction(const std::string& theActionId)
668 {
669   bool isOk = false;
670   if (theActionId == ADD_WIRE_ACTION_ID()) {
671     isOk = findWires();
672   }
673   else {
674     std::string aMsg = "Error: Feature \"%1\" does not support action \"%2\".";
675     Events_InfoMessage("SketchPlugin_Offset", aMsg).arg(getKind()).arg(theActionId).send();
676   }
677   return isOk;
678 }
679
680 bool SketchPlugin_Offset::findWires()
681 {
682   AttributeRefListPtr aSelectedEdges = reflist(EDGES_ID());
683   std::list<ObjectPtr> anEdgesList = aSelectedEdges->list();
684
685   // Empty set
686   std::set<FeaturePtr> anEdgesSet;
687
688   // Processed set
689   std::set<FeaturePtr> aProcessedSet;
690
691   // Put all selected edges in a set to avoid adding them in reflist(EDGES_ID())
692   std::set<FeaturePtr> aSelectedSet;
693   std::list<ObjectPtr>::const_iterator anEdgesIt = anEdgesList.begin();
694   for (; anEdgesIt != anEdgesList.end(); anEdgesIt++) {
695     FeaturePtr aFeature = ModelAPI_Feature::feature(*anEdgesIt);
696     if (aFeature) {
697       aSelectedSet.insert(aFeature);
698     }
699   }
700
701   bool aWasBlocked = data()->blockSendAttributeUpdated(true);
702
703   // Gather chains of edges
704   for (anEdgesIt = anEdgesList.begin(); anEdgesIt != anEdgesList.end(); anEdgesIt++) {
705     FeaturePtr aFeature = ModelAPI_Feature::feature(*anEdgesIt);
706     if (aFeature.get()) {
707       if (aProcessedSet.find(aFeature) != aProcessedSet.end())
708         continue;
709       aProcessedSet.insert(aFeature);
710
711       // End points (if any)
712       std::shared_ptr<GeomDataAPI_Point2D> aStartPoint, anEndPoint;
713       SketchPlugin_SegmentationTools::getFeaturePoints(aFeature, aStartPoint, anEndPoint);
714
715       std::list<FeaturePtr> aChain;
716       aChain.push_back(aFeature);
717       bool isClosed = findWireOneWay(aFeature, aFeature, aStartPoint, anEdgesSet, aChain, true);
718       if (!isClosed)
719         findWireOneWay(aFeature, aFeature, anEndPoint, anEdgesSet, aChain, false);
720
721       std::list<FeaturePtr>::iterator aChainIt = aChain.begin();
722       for (; aChainIt != aChain.end(); ++aChainIt) {
723         FeaturePtr aChainFeature = (*aChainIt);
724         aProcessedSet.insert(aChainFeature);
725         if (aSelectedSet.find(aChainFeature) == aSelectedSet.end()) {
726           aSelectedEdges->append(aChainFeature->lastResult());
727         }
728       }
729     }
730   }
731   // TODO: hilight selection in the viewer
732
733   data()->blockSendAttributeUpdated(aWasBlocked);
734   return true;
735 }
736
737
738 AISObjectPtr SketchPlugin_Offset::getAISObject(AISObjectPtr thePrevious)
739 {
740   if (!sketch())
741     return thePrevious;
742
743   AISObjectPtr anAIS = SketcherPrs_Factory::offsetObject(this, sketch(),
744     thePrevious);
745   return anAIS;
746 }