Salome HOME
Copyright update 2022
[modules/shaper.git] / src / SketcherPrs / SketcherPrs_PositionMgr.cpp
1 // Copyright (C) 2014-2022  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 "SketcherPrs_PositionMgr.h"
21 #include "SketcherPrs_Tools.h"
22
23 #include <GeomAPI_Ax3.h>
24 #include <GeomAPI_Circ.h>
25 #include <GeomAPI_Curve.h>
26 #include <GeomAPI_Edge.h>
27 #include <GeomAPI_Ellipse.h>
28 #include <GeomAPI_Dir.h>
29 #include <GeomAPI_Lin2d.h>
30 #include <GeomAPI_Vertex.h>
31
32 #include <GeomDataAPI_Point2D.h>
33
34 #include <SketchPlugin_Arc.h>
35 #include <SketchPlugin_Circle.h>
36 #include <SketchPlugin_Ellipse.h>
37 #include <SketchPlugin_Line.h>
38 #include <SketchPlugin_ConstraintPerpendicular.h>
39 #include <SketchPlugin_ConstraintTangent.h>
40
41 #include <TopoDS_Vertex.hxx>
42 #include <Geom_Curve.hxx>
43 #include <GeomAPI_ProjectPointOnCurve.hxx>
44 #include <TColGeom_SequenceOfCurve.hxx>
45 #include <gp_Dir.hxx>
46
47 #include <array>
48
49 static SketcherPrs_PositionMgr* MyPosMgr = NULL;
50
51 #define PI 3.1415926535897932
52
53 // The class is implemented as a singlton
54 SketcherPrs_PositionMgr* SketcherPrs_PositionMgr::get()
55 {
56   if (MyPosMgr == NULL)
57     MyPosMgr = new SketcherPrs_PositionMgr();
58   return MyPosMgr;
59 }
60
61 SketcherPrs_PositionMgr::SketcherPrs_PositionMgr()
62 {
63 }
64
65 int SketcherPrs_PositionMgr::getPositionIndex(ObjectPtr theLine,
66                                               const SketcherPrs_SymbolPrs* thePrs)
67 {
68   if (myShapes.count(theLine) == 1) {
69     // Find the map and add new [Presentation - Index] pair
70     PositionsMap& aPosMap = myShapes[theLine];
71     if (aPosMap.count(thePrs) == 1) {
72       // return existing index
73       return aPosMap[thePrs];
74     } else {
75       // Add a new [Presentation - Index] pair
76       int aInd = int(aPosMap.size());
77       aPosMap[thePrs] = aInd;
78       return aInd;
79     }
80   } else {
81     // Create a new map with initial index
82     PositionsMap aPosMap;
83     aPosMap[thePrs] = 0;
84     myShapes[theLine] = aPosMap;
85     return 0;
86   }
87 }
88
89
90 bool SketcherPrs_PositionMgr::isPntConstraint(const std::string& theName)
91 {
92   return ((theName == SketchPlugin_ConstraintTangent::ID()) ||
93     (theName == SketchPlugin_ConstraintPerpendicular::ID()));
94 }
95
96 bool containsPoint(const FeaturePtr& theFeature, GeomPnt2dPtr thePnt2d, GeomPointPtr thePos)
97 {
98   if (theFeature->getKind() == SketchPlugin_Line::ID()) {
99     AttributePoint2DPtr aSPnt1 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
100       theFeature->data()->attribute(SketchPlugin_Line::START_ID()));
101     AttributePoint2DPtr aSPnt2 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
102       theFeature->data()->attribute(SketchPlugin_Line::END_ID()));
103
104     GeomPnt2dPtr aPnt1 = aSPnt1->pnt();
105     GeomPnt2dPtr aPnt2 = aSPnt2->pnt();
106
107     if (aPnt1->isEqual(thePnt2d) || aPnt2->isEqual(thePnt2d))
108       return true;
109   } else if ((theFeature->getKind() == SketchPlugin_Circle::ID()) ||
110              (theFeature->getKind() == SketchPlugin_Arc::ID())) {
111     GeomCurvePtr aCurve;
112     ObjectPtr aResObj;
113     std::list<ResultPtr> aResults = theFeature->results();
114     std::list<ResultPtr>::const_iterator aIt;
115     for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
116       GeomShapePtr aShp = SketcherPrs_Tools::getShape((*aIt));
117       if (aShp->isEdge()) {
118         aResObj = (*aIt);
119         aCurve = std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(aShp));
120         break;
121       }
122     }
123     if (aCurve.get()) {
124       double aStart = aCurve->startParam();
125       double aEnd = aCurve->endParam();
126       GeomCirclePtr  aCircle = GeomCirclePtr(new GeomAPI_Circ(aCurve));
127       double aParam;
128       if (aCircle->parameter(thePos, 1.e-4, aParam) && (aParam >= aStart) && (aParam <= aEnd))
129         return true;
130     }
131   }
132   return false;
133 }
134
135 const std::array<int, 2>& SketcherPrs_PositionMgr::getPositionIndex(GeomPointPtr thePos,
136                                               const SketcherPrs_SymbolPrs* thePrs)
137 {
138   if (myPntShapes.count(thePrs->feature()) == 0) {
139     // Renumerate positions around the specified constraint point for all constraints
140     GeomAx3Ptr aAx3 = thePrs->plane();
141     ModelAPI_CompositeFeature* aOwner = thePrs->sketcher();
142     GeomPnt2dPtr aPnt2d = thePos->to2D(aAx3->origin(), aAx3->dirX(), aAx3->dirY());
143
144     int aNbSubs = aOwner->numberOfSubs();
145     int aId = 0;
146     std::list<const ModelAPI_Feature*> aFeaList;
147     for (int i = 0; i < aNbSubs; i++) {
148       FeaturePtr aFeature = aOwner->subFeature(i);
149
150       bool aUseFeature = ((myPntShapes.count(aFeature.get()) == 1) ||
151                          (isPntConstraint(aFeature->getKind())));
152       if (aUseFeature) {
153         DataPtr aData = aFeature->data();
154         AttributeRefAttrPtr aObjRef = aData->refattr(SketchPlugin_Constraint::ENTITY_A());
155         FeaturePtr aObj;
156         if (aObjRef)
157           aObj = ModelAPI_Feature::feature(aObjRef->object());
158         bool aContains = false;
159         if (aObj && containsPoint(aObj, aPnt2d, thePos)) {
160           aContains = true;
161         } else {
162           aObjRef = aData->refattr(SketchPlugin_Constraint::ENTITY_B());
163           if (aObjRef)
164             aObj = ModelAPI_Feature::feature(aObjRef->object());
165           if (aObj && containsPoint(aObj, aPnt2d, thePos)) {
166             aContains = true;
167           }
168         }
169         if (aContains) {
170           myPntShapes[aFeature.get()][0] = aId;
171           aId++;
172           aFeaList.push_back(aFeature.get());
173         }
174       }
175     }
176     int aSize = (int) aFeaList.size();
177     std::list<const ModelAPI_Feature*>::const_iterator aIt;
178     for (aIt = aFeaList.cbegin(); aIt != aFeaList.cend(); aIt++) {
179       myPntShapes[*aIt][1] = aSize;
180     }
181   }
182   return myPntShapes[thePrs->feature()];
183 }
184
185 //*****************************************************************
186 gp_Vec getVector(ObjectPtr theShape, GeomDirPtr theDir, gp_Pnt theP)
187 {
188   gp_Vec aVec;
189   std::shared_ptr<GeomAPI_Shape> aShape = SketcherPrs_Tools::getShape(theShape);
190   if (aShape->isEdge()) {
191     std::shared_ptr<GeomAPI_Edge> anEdge = aShape->edge();
192     std::shared_ptr<GeomAPI_Curve> aCurve =
193       std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(aShape));
194
195     if (anEdge->isClosed()) {
196       double aPeriod = aCurve->endParam() - aCurve->startParam();
197       Handle(Geom_Curve) aCurv = aCurve->impl<Handle_Geom_Curve>();
198       GeomAPI_ProjectPointOnCurve anExtr(theP, aCurv);
199       double aParam = anExtr.LowerDistanceParameter();
200       gp_Pnt aP;
201       aCurv->D1(aParam, aP, aVec);
202       // 2458: check correct orientation of the vector
203       if (aVec.SquareMagnitude() > Precision::Confusion()) {
204         std::shared_ptr<GeomAPI_Edge> aCircEdge(new GeomAPI_Edge(aShape));
205         double aFirstParam, aLastParam;
206         aCircEdge->getRange(aFirstParam, aLastParam);
207         // if parameter is near the LastParam, make the vector go inside (reverse)
208         double aDelta = aLastParam - aParam;
209         while (aDelta < -Precision::Confusion())
210           aDelta += aPeriod;
211         while (aDelta > aPeriod + Precision::Confusion())
212           aDelta -= aPeriod;
213         if (fabs(aDelta) < Precision::Confusion())
214           aVec.Reverse();
215       }
216     } else {
217       GeomPointPtr aPnt1 = aCurve->getPoint(aCurve->endParam());
218       GeomPointPtr aPnt2 = aCurve->getPoint(aCurve->startParam());
219
220       gp_Pnt aPn2 = aPnt2->impl<gp_Pnt>();
221       if (aPn2.IsEqual(theP, Precision::Confusion()))
222         aVec = gp_Vec(aPn2, aPnt1->impl<gp_Pnt>());
223       else
224         aVec = gp_Vec(aPnt1->impl<gp_Pnt>(), aPn2);
225     }
226   } else {
227     aVec = gp_Vec(theDir->impl<gp_Dir>());
228   }
229   return aVec;
230 }
231
232 //*****************************************************************
233 gp_Pnt SketcherPrs_PositionMgr::getPosition(ObjectPtr theShape,
234                                             const SketcherPrs_SymbolPrs* thePrs,
235                                             double theStep, GeomPointPtr thePnt)
236 {
237   std::shared_ptr<GeomAPI_Shape> aShape = SketcherPrs_Tools::getShape(theShape);
238   gp_Pnt aP; // Central point
239
240   if (thePnt.get()) {
241     return getPointPosition(theShape, thePrs, theStep, thePnt);
242   } else {
243     if (aShape->isEdge()) {
244       std::shared_ptr<GeomAPI_Curve> aCurve =
245         std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(aShape));
246       // this is a circle or arc
247       double aMidParam = (aCurve->startParam() + aCurve->endParam()) / 2.;
248       std::shared_ptr<GeomAPI_Pnt> aPnt = aCurve->getPoint(aMidParam);
249       aP = aPnt->impl<gp_Pnt>();
250     } else {
251       // This is a point
252       std::shared_ptr<GeomAPI_Vertex> aVertex =
253         std::shared_ptr<GeomAPI_Vertex>(new GeomAPI_Vertex(aShape));
254       std::shared_ptr<GeomAPI_Pnt> aPnt = aVertex->point();
255       aP = aPnt->impl<gp_Pnt>();
256     }
257   }
258   // main vector
259   gp_Vec aVec1 = getVector(theShape, thePrs->plane()->dirX(), aP);
260
261   // Compute shifting vector for a one symbol
262   gp_Vec aShift = aVec1.Crossed(thePrs->plane()->normal()->impl<gp_Dir>());
263   if (aShift.SquareMagnitude() > Precision::SquareConfusion())
264     aShift.Normalize();
265   aShift.Multiply(theStep * 0.8);
266
267   // Shift the position coordinate according to position index
268   int aPos = getPositionIndex(theShape, thePrs);
269   int aM = 1;
270   if ((aPos % 2) == 0) {
271     // Even position
272     aP.Translate(aShift);
273     if (aPos > 0) {
274       if (aPos % 4 == 0)
275         aM = aPos / 4;
276       else
277         aM = -(aPos + 2) / 4;
278     }
279   } else {
280     // Odd position
281     aP.Translate(-aShift);
282     if (aPos > 1) {
283       if ((aPos - 1) % 4 == 0)
284         aM = (aPos - 1) / 4;
285       else
286         aM = -(aPos + 1) / 4;
287     }
288   }
289   if (aPos > 1) {
290     // Normalize vector along the line
291     aVec1.Normalize();
292     aVec1.Multiply(theStep);
293     aP.Translate(aVec1.Multiplied(aM));
294   }
295   return aP;
296 }
297
298
299 //*****************************************************************
300 //! Returns curves connected to the given point
301 std::list<ObjectPtr> getCurves(const GeomPointPtr& thePnt, const SketcherPrs_SymbolPrs* thePrs)
302 {
303   std::list<ObjectPtr> aList;
304   GeomAx3Ptr aAx3 = thePrs->plane();
305   ModelAPI_CompositeFeature* aOwner = thePrs->sketcher();
306   GeomPnt2dPtr aPnt2d = thePnt->to2D(aAx3->origin(), aAx3->dirX(), aAx3->dirY());
307
308   int aNbSubs = aOwner->numberOfSubs();
309   for (int i = 0; i < aNbSubs; i++) {
310     FeaturePtr aFeature = aOwner->subFeature(i);
311     if (!aFeature->firstResult().get() || aFeature->firstResult()->isDisabled())
312       continue;  // There is no result
313
314     if (aFeature->getKind() == SketchPlugin_Line::ID()) {
315       AttributePoint2DPtr aSPnt1 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
316         aFeature->data()->attribute(SketchPlugin_Line::START_ID()));
317       AttributePoint2DPtr aSPnt2 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
318         aFeature->data()->attribute(SketchPlugin_Line::END_ID()));
319
320       GeomPnt2dPtr aPnt1 = aSPnt1->pnt();
321       GeomPnt2dPtr aPnt2 = aSPnt2->pnt();
322
323       if (aPnt1->distance(aPnt2d) <= Precision::Confusion() ||
324           aPnt2->distance(aPnt2d) <= Precision::Confusion()) {
325         // a point corresponds to one of the line end
326         GeomShapePtr aShp = SketcherPrs_Tools::getShape(aFeature->firstResult());
327         GeomCurvePtr aCurv = std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(aShp));
328         aList.push_back(aFeature->firstResult());
329       } else {
330         // Check that a point belongs to the curve
331         GeomAPI_Lin2d aLin2d(aPnt1, aPnt2);
332         double aDist = aLin2d.distance(aPnt2d);
333         if (aDist <= Precision::Confusion())
334           aList.push_back(aFeature->firstResult());
335       }
336     } else {
337       GeomCurvePtr aCurve;
338       ObjectPtr aResObj;
339       std::list<ResultPtr> aResults = aFeature->results();
340       std::list<ResultPtr>::const_iterator aIt;
341       for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
342         GeomShapePtr aShp = SketcherPrs_Tools::getShape((*aIt));
343         if (aShp->isEdge()) {
344           aResObj = (*aIt);
345           aCurve = std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(aShp));
346           break;
347         }
348       }
349       if (aCurve.get()) {
350         GeomPointPtr aProjPnt;
351         if (aFeature->getKind() == SketchPlugin_Circle::ID() ||
352           aFeature->getKind() == SketchPlugin_Arc::ID()) {
353           GeomCirclePtr aCircle = GeomCirclePtr(new GeomAPI_Circ(aCurve));
354           aProjPnt = aCircle->project(thePnt);
355         }
356         else if (aFeature->getKind() == SketchPlugin_Ellipse::ID()) {
357           GeomEllipsePtr anEllipse = GeomEllipsePtr(new GeomAPI_Ellipse(aCurve));
358           aProjPnt = anEllipse->project(thePnt);
359         }
360         else
361           aProjPnt = aCurve->project(thePnt);
362         if (aProjPnt && thePnt->distance(aProjPnt) <= Precision::Confusion())
363           aList.push_back(aResObj);
364       }
365     }
366   }
367   return aList;
368 }
369
370 //*****************************************************************
371 gp_Pnt SketcherPrs_PositionMgr::getPointPosition(
372   ObjectPtr theLine, const SketcherPrs_SymbolPrs* thePrs,
373   double theStep, GeomPointPtr thePnt)
374 {
375   gp_Pnt aP = thePnt->impl<gp_Pnt>();
376   if (!thePrs->plane().get())
377     return aP;
378   GeomDirPtr aNormal = thePrs->plane()->normal();
379   gp_Dir aNormDir = aNormal->impl<gp_Dir>();
380
381   std::list<ObjectPtr> aCurves = getCurves(thePnt, thePrs);
382   std::list<ObjectPtr>::const_iterator aItCurv;
383   std::list<gp_Vec> aVectorsList;
384   // Calculate all vectors
385   for (aItCurv = aCurves.cbegin(); aItCurv != aCurves.cend(); aItCurv++) {
386     aVectorsList.push_back(getVector((*aItCurv), thePrs->plane()->dirX(), aP));
387   }
388
389   // Position of the symbol
390   const std::array<int, 2>& aPos = getPositionIndex(thePnt, thePrs);
391
392   // Angle size of a symbol
393   //double aAngleStep = PI * 50./180.;
394   double aAngleStep = PI/4.;
395
396   std::list<gp_Vec>::const_iterator aItVec;
397   std::list<double> aAngles;
398   std::list<gp_Vec> aVectors;
399   // Select closest vectors and calculate angles between base vector and closest vector
400   for (aItVec = aVectorsList.cbegin(); aItVec != aVectorsList.cend(); aItVec++) {
401     std::list<gp_Vec>::const_iterator aIt;
402     double aMinAng = 0;
403     gp_Vec aVec = *aItVec;
404     for (aIt = aVectorsList.cbegin(); aIt != aVectorsList.cend(); aIt++) {
405       double aAng = aVec.AngleWithRef(*aIt, aNormDir);
406       if (aAng != 0) {
407         if (aAng < 0)
408           aAng = 2 * PI + aAng;
409
410         if (aMinAng == 0)
411           aMinAng = aAng;
412         else if (aAng < aMinAng) {
413           aMinAng = aAng;
414         }
415       }
416     }
417     if (aMinAng >= aAngleStep) {
418       aVectors.push_back(aVec);
419       aAngles.push_back(aMinAng);
420     }
421   }
422
423   gp_Ax1 aRotAx(aP, aNormDir);
424   gp_Vec aVecPos;
425   // If number of angle less then number of symbols then each symbol can be placed
426   // directly inside of the angle
427   if ((int)aAngles.size() >= aPos[1] && !aVectors.empty()) {
428     int aId = aPos[0];
429     aVecPos = *(std::next(aVectors.begin(), aId));
430
431     gp_Vec aShift = aVecPos.Rotated(aRotAx, aAngleStep);
432     aShift.Normalize();
433     aShift.Multiply(theStep * 1.5);
434     return aP.Translated(aShift);
435   }
436
437   // A case when there are a lot of symbols
438   int aPosCount = 0;
439   double aAng;
440   std::list<double>::const_iterator aItAng;
441
442   bool aHasPlace = false;
443   while (aPosCount < aPos[1]) {
444     for (aItAng = aAngles.cbegin(), aItVec = aVectors.cbegin();
445          aItAng != aAngles.cend(); ++aItAng, ++aItVec) {
446       aAng = (*aItAng);
447       int Nb = int(aAng / aAngleStep);
448       aPosCount += Nb;
449
450       if ((!aHasPlace) && (aPosCount >= (aPos[0] + 1))) {
451         aHasPlace = true;
452         aVecPos = (*aItVec);
453       }
454     }
455     if (aPosCount < aPos[1]) {
456       aAngleStep -= 0.1;
457       aHasPlace = false;
458       aPosCount = 0;
459     }
460     if (aAngleStep <= 0)
461       break;
462   }
463
464   if (aHasPlace) {
465     // rotate base vector on a necessary angle
466     gp_Vec aShift = aVecPos.Rotated(aRotAx, aAngleStep + aAngleStep * aPos[0]);
467     aShift.Normalize();
468     aShift.Multiply(theStep * 1.5);
469     return aP.Translated(aShift);
470   }
471   return aP;
472 }
473
474 //*****************************************************************
475 void SketcherPrs_PositionMgr::deleteConstraint(const SketcherPrs_SymbolPrs* thePrs)
476 {
477   std::map<ObjectPtr, PositionsMap>::iterator aIt;
478   std::list<ObjectPtr> aToDel;
479   // Clear map for deleted presentation
480   for (aIt = myShapes.begin(); aIt != myShapes.end(); ++aIt) {
481     PositionsMap& aPosMap = aIt->second;
482     if (aPosMap.count(thePrs) > 0) {
483       // Erase index
484       aPosMap.erase(aPosMap.find(thePrs));
485       if (aPosMap.size() == 0)
486         // Delete the map
487         aToDel.push_back(aIt->first);
488       else {
489         // Reindex objects positions in order to avoid spaces
490         PositionsMap::iterator aPMIt;
491         int i = 0;
492         for (aPMIt = aPosMap.begin(); aPMIt != aPosMap.end(); aPMIt++, i++)
493           aPMIt->second = i;
494       }
495     }
496   }
497   std::list<ObjectPtr>::const_iterator aListIt;
498   for (aListIt = aToDel.cbegin(); aListIt != aToDel.cend(); ++aListIt) {
499     myShapes.erase(*aListIt);
500   }
501 }