1 // File: SketchSolver_ConstraintGroup.cpp
2 // Created: 27 May 2014
3 // Author: Artem ZHIDKOV
5 #include "SketchSolver_ConstraintGroup.h"
7 #include <SketchSolver_Constraint.h>
9 #include <Events_Error.h>
10 #include <Events_Loop.h>
11 #include <GeomDataAPI_Dir.h>
12 #include <GeomDataAPI_Point.h>
13 #include <GeomDataAPI_Point2D.h>
14 #include <ModelAPI_AttributeDouble.h>
15 #include <ModelAPI_AttributeRefList.h>
16 #include <Model_Events.h>
18 #include <SketchPlugin_Constraint.h>
19 #include <SketchPlugin_ConstraintLength.h>
20 #include <SketchPlugin_ConstraintCoincidence.h>
22 #include <SketchPlugin_Arc.h>
23 #include <SketchPlugin_Circle.h>
24 #include <SketchPlugin_Line.h>
25 #include <SketchPlugin_Point.h>
26 #include <SketchPlugin_Sketch.h>
31 /// Tolerance for value of parameters
32 const double tolerance = 1.e-10;
34 const std::string ERROR_SOLVE_CONSTRAINTS = "Conflicting constraints";
36 /// This value is used to give unique index to the groups
37 static Slvs_hGroup myGroupIndexer = 0;
39 /** \brief Search the entity/parameter with specified ID in the list of elements
40 * \param[in] theEntityID unique ID of the element
41 * \param[in] theEntities list of elements
42 * \return position of the found element or -1 if the element is not found
45 static int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities);
48 // ========================================================
49 // ========= SketchSolver_ConstraintGroup ===============
50 // ========================================================
52 SketchSolver_ConstraintGroup::
53 SketchSolver_ConstraintGroup(boost::shared_ptr<SketchPlugin_Feature> theWorkplane)
54 : myID(++myGroupIndexer),
64 myConstraints.clear();
66 myTempConstraints.clear();
67 myTempPointWhereDragged.clear();
68 myTempPointWDrgdID = 0;
70 // Initialize workplane
71 myWorkplane.h = SLVS_E_UNKNOWN;
73 assert(addWorkplane(theWorkplane));
75 addWorkplane(theWorkplane);
79 SketchSolver_ConstraintGroup::~SketchSolver_ConstraintGroup()
83 myConstraints.clear();
84 myConstraintMap.clear();
85 myTempConstraints.clear();
86 myTempPointWhereDragged.clear();
88 // If the group with maximal identifier is deleted, decrease the indexer
89 if (myID == myGroupIndexer)
93 // ============================================================================
94 // Function: isBaseWorkplane
95 // Class: SketchSolver_ConstraintGroup
96 // Purpose: verify the group is based on the given workplane
97 // ============================================================================
98 bool SketchSolver_ConstraintGroup::isBaseWorkplane(
99 boost::shared_ptr<SketchPlugin_Feature> theWorkplane) const
101 return theWorkplane == mySketch;
104 // ============================================================================
105 // Function: isInteract
106 // Class: SketchSolver_ConstraintGroup
107 // Purpose: verify are there any entities in the group used by given constraint
108 // ============================================================================
109 bool SketchSolver_ConstraintGroup::isInteract(
110 boost::shared_ptr<SketchPlugin_Constraint> theConstraint) const
112 // Check the group is empty
113 if (myWorkplane.h != SLVS_E_UNKNOWN && myConstraints.empty())
116 // Go through constraint entities and verify if some of them already in the group
117 for (int i = 0; i < CONSTRAINT_ATTR_SIZE; i++)
119 boost::shared_ptr<ModelAPI_AttributeRefAttr> aCAttrRef =
120 boost::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
121 theConstraint->data()->attribute(CONSTRAINT_ATTRIBUTES[i])
123 if (!aCAttrRef) continue;
124 if (!aCAttrRef->isFeature() &&
125 myEntityAttrMap.find(aCAttrRef->attr()) != myEntityAttrMap.end())
127 if (aCAttrRef->isFeature() &&
128 myEntityFeatMap.find(aCAttrRef->feature()) != myEntityFeatMap.end())
132 // Entities did not found
136 // ============================================================================
137 // Function: changeConstraint
138 // Class: SketchSolver_ConstraintGroup
139 // Purpose: create/update the constraint in the group
140 // ============================================================================
141 bool SketchSolver_ConstraintGroup::changeConstraint(
142 boost::shared_ptr<SketchPlugin_Constraint> theConstraint)
144 // There is no workplane yet, something wrong
145 if (myWorkplane.h == SLVS_E_UNKNOWN)
148 // Search this constraint in the current group to update it
149 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
150 aConstrMapIter = myConstraintMap.find(theConstraint);
151 std::vector<Slvs_Constraint>::iterator aConstrIter;
152 if (aConstrMapIter != myConstraintMap.end())
154 int aConstrPos = Search(aConstrMapIter->second, myConstraints);
155 aConstrIter = myConstraints.begin() + aConstrPos;
158 // Get constraint type and verify the constraint parameters are correct
159 SketchSolver_Constraint aConstraint(theConstraint);
160 int aConstrType = aConstraint.getType();
161 if (aConstrType == SLVS_C_UNKNOWN ||
162 (aConstrMapIter != myConstraintMap.end() && aConstrIter->type != aConstrType))
164 const std::vector<std::string>& aConstraintAttributes = aConstraint.getAttributes();
166 // Create constraint parameters
167 double aDistance = 0.0; // scalar value of the constraint
168 AttributeDoublePtr aDistAttr =
169 boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theConstraint->data()->attribute(CONSTRAINT_ATTR_VALUE));
172 aDistance = aDistAttr->value();
173 // SketchPlugin circle defined by its radius, but SolveSpace uses constraint for diameter
174 if (aConstrType == SLVS_C_DIAMETER)
176 if (aConstrMapIter != myConstraintMap.end() && fabs(aConstrIter->valA - aDistance) > tolerance)
178 myNeedToSolve = true;
179 aConstrIter->valA = aDistance;
183 Slvs_hEntity aConstrEnt[CONSTRAINT_ATTR_SIZE]; // parameters of the constraint
184 for (unsigned int indAttr = 0; indAttr < CONSTRAINT_ATTR_SIZE; indAttr++)
186 aConstrEnt[indAttr] = SLVS_E_UNKNOWN;
187 boost::shared_ptr<ModelAPI_AttributeRefAttr> aConstrAttr =
188 boost::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
189 theConstraint->data()->attribute(aConstraintAttributes[indAttr])
191 if (!aConstrAttr) continue;
193 // For the length constraint the start and end points of the line should be added to the entities list instead of line
194 if (aConstrType == SLVS_C_PT_PT_DISTANCE && theConstraint->getKind().compare(SKETCH_CONSTRAINT_LENGTH_KIND) == 0)
196 boost::shared_ptr<ModelAPI_Data> aData = aConstrAttr->feature()->data();
197 aConstrEnt[indAttr] = changeEntity(aData->attribute(LINE_ATTR_START));
198 aConstrEnt[indAttr+1] = changeEntity(aData->attribute(LINE_ATTR_END));
199 myEntityFeatMap[aConstrAttr->feature()] = 0; // measured object is added into the map of objects to avoid problems with interaction betwee constraint and group
200 break; // there should be no other entities
202 else if (aConstrAttr->isFeature())
203 aConstrEnt[indAttr] = changeEntity(aConstrAttr->feature());
205 aConstrEnt[indAttr] = changeEntity(aConstrAttr->attr());
208 if (aConstrMapIter == myConstraintMap.end())
210 // Several points may be coincident, it is not necessary to store all constraints between them.
211 // Try to find sequence of coincident points which connects the points of new constraint
212 if (aConstrType == SLVS_C_POINTS_COINCIDENT &&
213 !addCoincidentPoints(aConstrEnt[0], aConstrEnt[1]))
215 myExtraCoincidence.insert(theConstraint); // the constraint is stored for further purposes
219 // Create SolveSpace constraint structure
220 Slvs_Constraint aConstraint =
221 Slvs_MakeConstraint(++myConstrMaxID, myID, aConstrType, myWorkplane.h,
222 aDistance, aConstrEnt[0], aConstrEnt[1], aConstrEnt[2], aConstrEnt[3]);
223 myConstraints.push_back(aConstraint);
224 myConstraintMap[theConstraint] = aConstraint.h;
229 // ============================================================================
230 // Function: changeEntity
231 // Class: SketchSolver_ConstraintGroup
232 // Purpose: create/update the element affected by any constraint
233 // ============================================================================
234 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntity(
235 boost::shared_ptr<ModelAPI_Attribute> theEntity)
237 // If the entity is already in the group, try to find it
238 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
239 aEntIter = myEntityAttrMap.find(theEntity);
240 std::vector<Slvs_Param>::const_iterator aParamIter; // looks at first parameter of already existent entity or at the end of vector otherwise
241 if (aEntIter == myEntityAttrMap.end()) // no such entity => should be created
242 aParamIter = myParams.end();
244 { // the entity already exists
245 int aEntPos = Search(aEntIter->second, myEntities);
246 int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
247 aParamIter = myParams.begin() + aParamPos;
249 const bool isEntExists = (aEntIter != myEntityAttrMap.end()); // defines that the entity already exists
251 // Look over supported types of entities
254 boost::shared_ptr<GeomDataAPI_Point> aPoint =
255 boost::dynamic_pointer_cast<GeomDataAPI_Point>(theEntity);
258 Slvs_hParam aX = changeParameter(aPoint->x(), aParamIter);
259 Slvs_hParam aY = changeParameter(aPoint->y(), aParamIter);
260 Slvs_hParam aZ = changeParameter(aPoint->z(), aParamIter);
263 return aEntIter->second;
266 Slvs_Entity aPtEntity = Slvs_MakePoint3d(++myEntityMaxID, myID, aX, aY, aZ);
267 myEntities.push_back(aPtEntity);
268 myEntityAttrMap[theEntity] = aPtEntity.h;
272 // All entities except 3D points are created on workplane. So, if there is no workplane yet, then error
273 if (myWorkplane.h == SLVS_E_UNKNOWN)
274 return SLVS_E_UNKNOWN;
277 boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
278 boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theEntity);
281 Slvs_hParam aU = changeParameter(aPoint2D->x(), aParamIter);
282 Slvs_hParam aV = changeParameter(aPoint2D->y(), aParamIter);
285 return aEntIter->second;
288 Slvs_Entity aPt2DEntity = Slvs_MakePoint2d(++myEntityMaxID, myID, myWorkplane.h, aU, aV);
289 myEntities.push_back(aPt2DEntity);
290 myEntityAttrMap[theEntity] = aPt2DEntity.h;
291 return aPt2DEntity.h;
294 // Scalar value (used for the distance entities)
295 AttributeDoublePtr aScalar =
296 boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theEntity);
299 Slvs_hParam aValue = changeParameter(aScalar->value(), aParamIter);
302 return aEntIter->second;
305 Slvs_Entity aDistance = Slvs_MakeDistance(++myEntityMaxID, myID, myWorkplane.h, aValue);
306 myEntities.push_back(aDistance);
307 myEntityAttrMap[theEntity] = aDistance.h;
311 /// \todo Other types of entities
313 // Unsupported or wrong entity type
314 return SLVS_E_UNKNOWN;
318 // ============================================================================
319 // Function: changeEntity
320 // Class: SketchSolver_ConstraintGroup
321 // Purpose: create/update the element defined by the feature affected by any constraint
322 // ============================================================================
323 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntity(
324 FeaturePtr theEntity)
326 // If the entity is already in the group, try to find it
327 std::map<FeaturePtr, Slvs_hEntity>::const_iterator
328 aEntIter = myEntityFeatMap.find(theEntity);
329 // defines that the entity already exists
330 const bool isEntExists = (myEntityFeatMap.find(theEntity) != myEntityFeatMap.end());
332 // SketchPlugin features
333 boost::shared_ptr<SketchPlugin_Feature> aFeature =
334 boost::dynamic_pointer_cast<SketchPlugin_Feature>(theEntity);
336 { // Verify the feature by its kind
337 const std::string& aFeatureKind = aFeature->getKind();
340 if (aFeatureKind.compare(SKETCH_LINE_KIND) == 0)
342 Slvs_hEntity aStart = changeEntity(aFeature->data()->attribute(LINE_ATTR_START));
343 Slvs_hEntity aEnd = changeEntity(aFeature->data()->attribute(LINE_ATTR_END));
346 return aEntIter->second;
349 Slvs_Entity aLineEntity = Slvs_MakeLineSegment(++myEntityMaxID, myID, myWorkplane.h, aStart, aEnd);
350 myEntities.push_back(aLineEntity);
351 myEntityFeatMap[theEntity] = aLineEntity.h;
352 return aLineEntity.h;
355 else if (aFeatureKind.compare(SKETCH_CIRCLE_KIND) == 0)
357 Slvs_hEntity aCenter = changeEntity(aFeature->data()->attribute(CIRCLE_ATTR_CENTER));
358 Slvs_hEntity aRadius = changeEntity(aFeature->data()->attribute(CIRCLE_ATTR_RADIUS));
361 return aEntIter->second;
364 Slvs_Entity aCircleEntity =
365 Slvs_MakeCircle(++myEntityMaxID, myID, myWorkplane.h, aCenter, myWorkplane.normal, aRadius);
366 myEntities.push_back(aCircleEntity);
367 myEntityFeatMap[theEntity] = aCircleEntity.h;
368 return aCircleEntity.h;
371 else if (aFeatureKind.compare(SKETCH_ARC_KIND) == 0)
373 Slvs_hEntity aCenter = changeEntity(aFeature->data()->attribute(ARC_ATTR_CENTER));
374 Slvs_hEntity aStart = changeEntity(aFeature->data()->attribute(ARC_ATTR_START));
375 Slvs_hEntity aEnd = changeEntity(aFeature->data()->attribute(ARC_ATTR_END));
378 return aEntIter->second;
380 Slvs_Entity anArcEntity = Slvs_MakeArcOfCircle(++myEntityMaxID, myID,
381 myWorkplane.h, myWorkplane.normal, aCenter, aStart, aEnd);
382 myEntities.push_back(anArcEntity);
383 myEntityFeatMap[theEntity] = anArcEntity.h;
384 return anArcEntity.h;
386 // Point (it has low probability to be an attribute of constraint, so it is checked at the end)
387 else if (aFeatureKind.compare(SKETCH_POINT_KIND) == 0)
389 Slvs_hEntity aPoint = changeEntity(aFeature->data()->attribute(POINT_ATTR_COORD));
392 return aEntIter->second;
394 // Both the sketch point and its attribute (coordinates) link to the same SolveSpace point identifier
395 myEntityFeatMap[theEntity] = aPoint;
400 /// \todo Other types of features
402 // Unsupported or wrong entity type
403 return SLVS_E_UNKNOWN;
406 // ============================================================================
407 // Function: changeNormal
408 // Class: SketchSolver_ConstraintGroup
409 // Purpose: create/update the normal of workplane
410 // ============================================================================
411 Slvs_hEntity SketchSolver_ConstraintGroup::changeNormal(
412 boost::shared_ptr<ModelAPI_Attribute> theDirX,
413 boost::shared_ptr<ModelAPI_Attribute> theDirY,
414 boost::shared_ptr<ModelAPI_Attribute> theNorm)
416 boost::shared_ptr<GeomDataAPI_Dir> aDirX =
417 boost::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirX);
418 boost::shared_ptr<GeomDataAPI_Dir> aDirY =
419 boost::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirY);
420 if (!aDirX || !aDirY ||
421 (fabs(aDirX->x()) + fabs(aDirX->y()) + fabs(aDirX->z()) < tolerance) ||
422 (fabs(aDirY->x()) + fabs(aDirY->y()) + fabs(aDirY->z()) < tolerance))
423 return SLVS_E_UNKNOWN;
425 // quaternion parameters of normal vector
426 double qw, qx, qy, qz;
427 Slvs_MakeQuaternion(aDirX->x(), aDirX->y(), aDirX->z(),
428 aDirY->x(), aDirY->y(), aDirY->z(),
430 double aNormCoord[4] = {qw, qx, qy, qz};
432 // Try to find existent normal
433 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
434 aEntIter = myEntityAttrMap.find(theNorm);
435 std::vector<Slvs_Param>::const_iterator aParamIter; // looks to the first parameter of already existent entity or to the end of vector otherwise
436 if (aEntIter == myEntityAttrMap.end()) // no such entity => should be created
437 aParamIter = myParams.end();
439 { // the entity already exists, update it
440 int aEntPos = Search(aEntIter->second, myEntities);
441 int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
442 aParamIter = myParams.begin() + aParamPos;
445 // Change parameters of the normal
446 Slvs_hParam aNormParams[4];
447 for (int i = 0; i < 4; i++)
448 aNormParams[i] = changeParameter(aNormCoord[i], aParamIter);
450 if (aEntIter != myEntityAttrMap.end()) // the entity already exists
451 return aEntIter->second;
454 Slvs_Entity aNormal = Slvs_MakeNormal3d(++myEntityMaxID, myID,
455 aNormParams[0], aNormParams[1], aNormParams[2], aNormParams[3]);
456 myEntities.push_back(aNormal);
457 myEntityAttrMap[theNorm] = aNormal.h;
462 // ============================================================================
463 // Function: addWorkplane
464 // Class: SketchSolver_ConstraintGroup
465 // Purpose: create workplane for the group
466 // ============================================================================
467 bool SketchSolver_ConstraintGroup::addWorkplane(
468 boost::shared_ptr<SketchPlugin_Feature> theSketch)
470 if (myWorkplane.h || theSketch->getKind().compare(SKETCH_KIND) != 0)
471 return false; // the workplane already exists or the function parameter is not Sketch
473 mySketch = theSketch;
478 // ============================================================================
479 // Function: updateWorkplane
480 // Class: SketchSolver_ConstraintGroup
481 // Purpose: update parameters of workplane
482 // ============================================================================
483 bool SketchSolver_ConstraintGroup::updateWorkplane()
485 // Get parameters of workplane
486 boost::shared_ptr<ModelAPI_Attribute> aDirX = mySketch->data()->attribute(SKETCH_ATTR_DIRX);
487 boost::shared_ptr<ModelAPI_Attribute> aDirY = mySketch->data()->attribute(SKETCH_ATTR_DIRY);
488 boost::shared_ptr<ModelAPI_Attribute> aNorm = mySketch->data()->attribute(SKETCH_ATTR_NORM);
489 boost::shared_ptr<ModelAPI_Attribute> anOrigin = mySketch->data()->attribute(SKETCH_ATTR_ORIGIN);
490 // Transform them into SolveSpace format
491 Slvs_hEntity aNormalWP = changeNormal(aDirX, aDirY, aNorm);
492 if (!aNormalWP) return false;
493 Slvs_hEntity anOriginWP = changeEntity(anOrigin);
494 if (!anOriginWP) return false;
499 myWorkplane = Slvs_MakeWorkplane(++myEntityMaxID, myID, anOriginWP, aNormalWP);
500 // Workplane should be added to the list of entities
501 myEntities.push_back(myWorkplane);
506 // ============================================================================
507 // Function: changeParameter
508 // Class: SketchSolver_ConstraintGroup
509 // Purpose: create/update value of parameter
510 // ============================================================================
511 Slvs_hParam SketchSolver_ConstraintGroup::changeParameter(
512 const double& theParam,
513 std::vector<Slvs_Param>::const_iterator& thePrmIter)
515 if (thePrmIter != myParams.end())
516 { // Parameter should be updated
517 int aParamPos = thePrmIter - myParams.begin();
518 if (fabs(thePrmIter->val - theParam) > tolerance)
520 myNeedToSolve = true; // parameter is changed, need to resolve constraints
521 myParams[aParamPos].val = theParam;
524 return myParams[aParamPos].h;
527 // Newly created parameter
528 Slvs_Param aParam = Slvs_MakeParam(++myParamMaxID, myID, theParam);
529 myParams.push_back(aParam);
530 myNeedToSolve = true;
531 // The list of parameters is changed, move iterator to the end of the list to avoid problems
532 thePrmIter = myParams.end();
536 // ============================================================================
537 // Function: resolveConstraints
538 // Class: SketchSolver_ConstraintGroup
539 // Purpose: solve the set of constraints for the current group
540 // ============================================================================
541 void SketchSolver_ConstraintGroup::resolveConstraints()
546 myConstrSolver.setGroupID(myID);
547 myConstrSolver.setParameters(myParams);
548 myConstrSolver.setEntities(myEntities);
549 myConstrSolver.setConstraints(myConstraints);
550 myConstrSolver.setDraggedParameters(myTempPointWhereDragged);
552 int aResult = myConstrSolver.solve();
553 if (aResult == SLVS_RESULT_OKAY)
554 { // solution succeeded, store results into correspondent attributes
555 // Obtain result into the same list of parameters
556 if (!myConstrSolver.getResult(myParams))
559 // We should go through the attributes map, because only attributes have valued parameters
560 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
561 anEntIter = myEntityAttrMap.begin();
562 for ( ; anEntIter != myEntityAttrMap.end(); anEntIter++)
563 updateAttribute(anEntIter->first, anEntIter->second);
565 else if (!myConstraints.empty())
566 Events_Error::send(ERROR_SOLVE_CONSTRAINTS, this);
568 removeTemporaryConstraints();
569 myNeedToSolve = false;
572 // ============================================================================
573 // Function: mergeGroups
574 // Class: SketchSolver_ConstraintGroup
575 // Purpose: append specified group to the current group
576 // ============================================================================
577 void SketchSolver_ConstraintGroup::mergeGroups(
578 const SketchSolver_ConstraintGroup& theGroup)
580 // If specified group is empty, no need to merge
581 if (theGroup.myConstraintMap.empty())
584 // Map between old and new indexes of SolveSpace constraints
585 std::map<Slvs_hConstraint, Slvs_hConstraint> aConstrMap;
587 // Add all constraints from theGroup to the current group
588 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
589 aConstrIter = theGroup.myConstraintMap.begin();
590 for ( ; aConstrIter != theGroup.myConstraintMap.end(); aConstrIter++)
591 if (changeConstraint(aConstrIter->first))
592 aConstrMap[aConstrIter->second] = myConstrMaxID; // the constraint was added => store its ID
594 // Add temporary constraints from theGroup
595 std::list<Slvs_hConstraint>::const_iterator aTempConstrIter = theGroup.myTempConstraints.begin();
596 for ( ; aTempConstrIter != theGroup.myTempConstraints.end(); aTempConstrIter++)
598 std::map<Slvs_hConstraint, Slvs_hConstraint>::iterator aFind = aConstrMap.find(*aTempConstrIter);
599 if (aFind != aConstrMap.end())
600 myTempConstraints.push_back(aFind->second);
603 if (myTempPointWhereDragged.empty())
604 myTempPointWhereDragged = theGroup.myTempPointWhereDragged;
605 else if (!theGroup.myTempPointWhereDragged.empty())
606 { // Need to create additional transient constraint
607 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
608 aFeatureIter = theGroup.myEntityAttrMap.begin();
609 for (; aFeatureIter != theGroup.myEntityAttrMap.end(); aFeatureIter++)
610 if (aFeatureIter->second == myTempPointWDrgdID)
612 addTemporaryConstraintWhereDragged(aFeatureIter->first);
617 myNeedToSolve = myNeedToSolve || theGroup.myNeedToSolve;
620 // ============================================================================
621 // Function: splitGroup
622 // Class: SketchSolver_ConstraintGroup
623 // Purpose: divide the group into several subgroups
624 // ============================================================================
625 void SketchSolver_ConstraintGroup::splitGroup(std::vector<SketchSolver_ConstraintGroup*>& theCuts)
627 // Divide constraints and entities into several groups
628 std::vector< std::set<Slvs_hEntity> > aGroupsEntities;
629 std::vector< std::set<Slvs_hConstraint> > aGroupsConstr;
630 int aMaxNbEntities = 0; // index of the group with maximal nuber of elements (this group will be left in the current)
631 std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
632 for ( ; aConstrIter != myConstraints.end(); aConstrIter++)
634 Slvs_hEntity aConstrEnt[] = {
635 aConstrIter->ptA, aConstrIter->ptB,
636 aConstrIter->entityA, aConstrIter->entityB};
637 std::vector<int> anIndexes;
638 // Go through the groupped entities and find even one of entities of current constraint
639 std::vector< std::set<Slvs_hEntity> >::iterator aGrEntIter;
640 for (aGrEntIter = aGroupsEntities.begin(); aGrEntIter != aGroupsEntities.end(); aGrEntIter++)
642 bool isFound = false;
643 for (int i = 0; i < 4 && !isFound; i++)
644 if (aConstrEnt[i] != 0)
645 isFound = (aGrEntIter->find(aConstrEnt[i]) != aGrEntIter->end());
647 anIndexes.push_back(aGrEntIter - aGroupsEntities.begin());
649 // Add new group if no one is found
650 if (anIndexes.empty())
652 std::set<Slvs_hEntity> aNewGrEnt;
653 for (int i = 0; i < 4; i++)
654 if (aConstrEnt[i] != 0)
655 aNewGrEnt.insert(aConstrEnt[i]);
656 std::set<Slvs_hConstraint> aNewGrConstr;
657 aNewGrConstr.insert(aConstrIter->h);
659 aGroupsEntities.push_back(aNewGrEnt);
660 aGroupsConstr.push_back(aNewGrConstr);
661 if (aNewGrEnt.size() > aGroupsEntities[aMaxNbEntities].size())
662 aMaxNbEntities = aGroupsEntities.size() - 1;
664 else if (anIndexes.size() == 1)
665 { // Add entities indexes into the found group
666 aGrEntIter = aGroupsEntities.begin() + anIndexes.front();
667 for (int i = 0; i < 4; i++)
668 if (aConstrEnt[i] != 0)
669 aGrEntIter->insert(aConstrEnt[i]);
670 aGroupsConstr[anIndexes.front()].insert(aConstrIter->h);
671 if (aGrEntIter->size() > aGroupsEntities[aMaxNbEntities].size())
672 aMaxNbEntities = aGrEntIter - aGroupsEntities.begin();
675 { // There are found several connected groups, merge them
676 std::vector< std::set<Slvs_hEntity> >::iterator aFirstGroup =
677 aGroupsEntities.begin() + anIndexes.front();
678 std::vector< std::set<Slvs_hConstraint> >::iterator aFirstConstr =
679 aGroupsConstr.begin() + anIndexes.front();
680 std::vector<int>::iterator anInd = anIndexes.begin();
681 for (++anInd; anInd != anIndexes.end(); anInd++)
683 aFirstGroup->insert(aGroupsEntities[*anInd].begin(), aGroupsEntities[*anInd].end());
684 aFirstConstr->insert(aGroupsConstr[*anInd].begin(), aGroupsConstr[*anInd].end());
686 if (aFirstGroup->size() > aGroupsEntities[aMaxNbEntities].size())
687 aMaxNbEntities = anIndexes.front();
688 // Remove merged groups
689 for (anInd = anIndexes.end() - 1; anInd != anIndexes.begin(); anInd--)
691 aGroupsEntities.erase(aGroupsEntities.begin() + (*anInd));
692 aGroupsConstr.erase(aGroupsConstr.begin() + (*anInd));
697 if (aGroupsEntities.size() <= 1)
700 // Remove the group with maximum elements as it will be left in the current group
701 aGroupsEntities.erase(aGroupsEntities.begin() + aMaxNbEntities);
702 aGroupsConstr.erase(aGroupsConstr.begin() + aMaxNbEntities);
704 // Add new groups of constraints and divide current group
705 std::vector<SketchSolver_ConstraintGroup*> aNewGroups;
706 for (int i = aGroupsEntities.size(); i > 0; i--)
708 SketchSolver_ConstraintGroup* aG = new SketchSolver_ConstraintGroup(mySketch);
709 aNewGroups.push_back(aG);
711 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
712 aConstrMapIter = myConstraintMap.begin();
713 int aConstrMapPos = 0; // position of iterator in the map (used to restore iterator after removing constraint)
714 while (aConstrMapIter != myConstraintMap.end())
716 std::vector< std::set<Slvs_hConstraint> >::const_iterator aGIter = aGroupsConstr.begin();
717 std::vector<SketchSolver_ConstraintGroup*>::iterator aGroup = aNewGroups.begin();
718 for ( ; aGIter != aGroupsConstr.end(); aGIter++, aGroup++)
719 if (aGIter->find(aConstrMapIter->second) != aGIter->end())
721 (*aGroup)->changeConstraint(aConstrMapIter->first);
722 removeConstraint(aConstrMapIter->first);
724 aConstrMapIter = myConstraintMap.begin();
725 for (int i = 0; i < aConstrMapPos; i++)
729 if (aGIter == aGroupsConstr.end())
736 theCuts.insert(theCuts.end(), aNewGroups.begin(), aNewGroups.end());
739 // ============================================================================
740 // Function: updateGroup
741 // Class: SketchSolver_ConstraintGroup
742 // Purpose: search removed entities and constraints
743 // ============================================================================
744 bool SketchSolver_ConstraintGroup::updateGroup()
746 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::reverse_iterator
747 aConstrIter = myConstraintMap.rbegin();
748 bool isAllValid = true;
749 bool isCCRemoved = false; // indicates that at least one of coincidence constraints was removed
750 while (isAllValid && aConstrIter != myConstraintMap.rend())
752 if (!aConstrIter->first->data()->isValid())
754 if (aConstrIter->first->getKind().compare(SKETCH_CONSTRAINT_COINCIDENCE_KIND) == 0)
756 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::reverse_iterator
757 aCopyIter = aConstrIter++;
758 removeConstraint(aCopyIter->first);
764 // Probably, need to update coincidence constraints
765 if (isCCRemoved && !myExtraCoincidence.empty())
767 // Make a copy, because the new list of unused constrtaints will be generated
768 std::set< boost::shared_ptr<SketchPlugin_Constraint> > anExtraCopy = myExtraCoincidence;
769 myExtraCoincidence.clear();
771 std::set< boost::shared_ptr<SketchPlugin_Constraint> >::iterator
772 aCIter = anExtraCopy.begin();
773 for ( ; aCIter != anExtraCopy.end(); aCIter++)
774 if ((*aCIter)->data()->isValid())
775 changeConstraint(*aCIter);
781 // ============================================================================
782 // Function: updateAttribute
783 // Class: SketchSolver_ConstraintGroup
784 // Purpose: update features of sketch after resolving constraints
785 // ============================================================================
786 void SketchSolver_ConstraintGroup::updateAttribute(
787 boost::shared_ptr<ModelAPI_Attribute> theAttribute,
788 const Slvs_hEntity& theEntityID)
790 // Search the position of the first parameter of the entity
791 int anEntPos = Search(theEntityID, myEntities);
792 int aFirstParamPos = Search(myEntities[anEntPos].param[0], myParams);
794 // Look over supported types of entities
797 boost::shared_ptr<GeomDataAPI_Point> aPoint =
798 boost::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
801 aPoint->setValue(myParams[aFirstParamPos].val,
802 myParams[aFirstParamPos+1].val,
803 myParams[aFirstParamPos+2].val);
808 boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
809 boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
812 aPoint2D->setValue(myParams[aFirstParamPos].val,
813 myParams[aFirstParamPos+1].val);
818 AttributeDoublePtr aScalar =
819 boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
822 aScalar->setValue(myParams[aFirstParamPos].val);
826 /// \todo Support other types of entities
829 // ============================================================================
830 // Function: updateEntityIfPossible
831 // Class: SketchSolver_ConstraintGroup
832 // Purpose: search the entity in this group and update it
833 // ============================================================================
834 void SketchSolver_ConstraintGroup::updateEntityIfPossible(
835 boost::shared_ptr<ModelAPI_Attribute> theEntity)
837 if (myEntityAttrMap.find(theEntity) != myEntityAttrMap.end())
839 // If the attribute is a point and it is changed (the group needs to rebuild),
840 // probably user has dragged this point into this position,
841 // so it is necessary to add constraint which will guarantee the point will not change
843 // Store myNeedToSolve flag to verify the entity is really changed
844 bool aNeedToSolveCopy = myNeedToSolve;
845 myNeedToSolve = false;
847 changeEntity(theEntity);
849 if (myNeedToSolve) // the entity is changed
851 // Verify the entity is a point and add temporary constraint of permanency
852 boost::shared_ptr<GeomDataAPI_Point> aPoint =
853 boost::dynamic_pointer_cast<GeomDataAPI_Point>(theEntity);
854 boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
855 boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theEntity);
856 if (aPoint || aPoint2D)
857 addTemporaryConstraintWhereDragged(theEntity);
860 // Restore flag of changes
861 myNeedToSolve = myNeedToSolve || aNeedToSolveCopy;
863 updateRelatedConstraints(theEntity);
867 // ============================================================================
868 // Function: addTemporaryConstraintWhereDragged
869 // Class: SketchSolver_ConstraintGroup
870 // Purpose: add transient constraint SLVS_C_WHERE_DRAGGED for the entity,
871 // which was moved by user
872 // ============================================================================
873 void SketchSolver_ConstraintGroup::addTemporaryConstraintWhereDragged(
874 boost::shared_ptr<ModelAPI_Attribute> theEntity)
876 // Find identifier of the entity
877 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
878 anEntIter = myEntityAttrMap.find(theEntity);
879 if (anEntIter == myEntityAttrMap.end())
882 // If this is a first dragged point, its parameters should be placed
883 // into Slvs_System::dragged field to avoid system inconsistense
884 if (myTempPointWhereDragged.empty())
886 int anEntPos = Search(anEntIter->second, myEntities);
887 Slvs_hParam* aDraggedParam = myEntities[anEntPos].param;
888 for (int i = 0; i < 4; i++, aDraggedParam++)
889 if (*aDraggedParam != 0)
890 myTempPointWhereDragged.push_back(*aDraggedParam);
891 myTempPointWDrgdID = myEntities[anEntPos].h;
895 // Get identifiers of all dragged points
896 std::set<Slvs_hEntity> aDraggedPntID;
897 aDraggedPntID.insert(myTempPointWDrgdID);
898 std::list<Slvs_hConstraint>::iterator aTmpCoIter = myTempConstraints.begin();
899 for ( ; aTmpCoIter != myTempConstraints.end(); aTmpCoIter++)
901 unsigned int aConstrPos = Search(*aTmpCoIter, myConstraints);
902 if (aConstrPos < myConstraints.size())
903 aDraggedPntID.insert(myConstraints[aConstrPos].ptA);
905 // Find whether there is a point coincident with theEntity, which already has SLVS_C_WHERE_DRAGGED
906 std::vector< std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
907 for ( ; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
909 if (aCoPtIter->find(anEntIter->second) == aCoPtIter->end())
910 continue; // the entity was not found in current set
912 // Find one of already created SLVS_C_WHERE_DRAGGED constraints in current set of coincident points
913 std::set<Slvs_hEntity>::const_iterator aDrgIter = aDraggedPntID.begin();
914 for ( ; aDrgIter != aDraggedPntID.end(); aDrgIter++)
915 if (aCoPtIter->find(*aDrgIter) != aCoPtIter->end())
916 return ; // the SLVS_C_WHERE_DRAGGED constraint already exists
919 // Create additional SLVS_C_WHERE_DRAGGED constraint if myTempPointWhereDragged field is not empty
920 Slvs_Constraint aWDConstr = Slvs_MakeConstraint(++myConstrMaxID, myID, SLVS_C_WHERE_DRAGGED,
921 myWorkplane.h, 0.0, anEntIter->second, 0, 0, 0);
922 myConstraints.push_back(aWDConstr);
923 myTempConstraints.push_back(aWDConstr.h);
926 // ============================================================================
927 // Function: removeTemporaryConstraints
928 // Class: SketchSolver_ConstraintGroup
929 // Purpose: remove all transient SLVS_C_WHERE_DRAGGED constraints after
930 // resolving the set of constraints
931 // ============================================================================
932 void SketchSolver_ConstraintGroup::removeTemporaryConstraints()
934 std::list<Slvs_hConstraint>::reverse_iterator aTmpConstrIter;
935 for (aTmpConstrIter = myTempConstraints.rbegin(); aTmpConstrIter != myTempConstraints.rend(); aTmpConstrIter++)
937 unsigned int aConstrPos = Search(*aTmpConstrIter, myConstraints);
938 if (aConstrPos >= myConstraints.size())
940 myConstraints.erase(myConstraints.begin() + aConstrPos);
942 // If the removing constraint has higher index, decrease the indexer
943 if (*aTmpConstrIter == myConstrMaxID)
946 myTempConstraints.clear();
948 // Clear basic dragged point
949 myTempPointWhereDragged.clear();
952 // ============================================================================
953 // Function: removeConstraint
954 // Class: SketchSolver_ConstraintGroup
955 // Purpose: remove constraint and all unused entities
956 // ============================================================================
957 void SketchSolver_ConstraintGroup::removeConstraint(boost::shared_ptr<SketchPlugin_Constraint> theConstraint)
959 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::iterator
960 anIterToRemove = myConstraintMap.find(theConstraint);
961 if (anIterToRemove == myConstraintMap.end())
964 Slvs_hConstraint aCnstrToRemove = anIterToRemove->second;
965 // Remove constraint from the map
966 myConstraintMap.erase(anIterToRemove);
968 // Find unused entities
969 int aConstrPos = Search(aCnstrToRemove, myConstraints);
970 std::set<Slvs_hEntity> anEntToRemove;
971 Slvs_hEntity aCnstEnt[] = {myConstraints[aConstrPos].ptA, myConstraints[aConstrPos].ptB,
972 myConstraints[aConstrPos].entityA, myConstraints[aConstrPos].entityB};
973 for (int i = 0; i < 4; i++)
974 if (aCnstEnt[i] != 0)
975 anEntToRemove.insert(aCnstEnt[i]);
976 myConstraints.erase(myConstraints.begin() + aConstrPos);
977 if (aCnstrToRemove == myConstrMaxID)
979 std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
980 for ( ; aConstrIter != myConstraints.end(); aConstrIter++)
982 Slvs_hEntity aEnts[] = {aConstrIter->ptA, aConstrIter->ptB,
983 aConstrIter->entityA, aConstrIter->entityB};
984 for (int i = 0; i < 4; i++)
985 if (aEnts[i] != 0 && anEntToRemove.find(aEnts[i]) != anEntToRemove.end())
986 anEntToRemove.erase(aEnts[i]);
989 if (anEntToRemove.empty())
992 // Remove unused entities
993 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
994 anEntAttrIter = myEntityAttrMap.begin();
995 while (anEntAttrIter != myEntityAttrMap.end())
997 if (anEntToRemove.find(anEntAttrIter->second) != anEntToRemove.end())
999 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1000 aRemovedIter = anEntAttrIter;
1002 myEntityAttrMap.erase(aRemovedIter);
1004 else anEntAttrIter++;
1006 std::map<FeaturePtr, Slvs_hEntity>::iterator
1007 anEntFeatIter = myEntityFeatMap.begin();
1008 while (anEntFeatIter != myEntityFeatMap.end())
1010 if (anEntToRemove.find(anEntFeatIter->second) != anEntToRemove.end())
1012 std::map<FeaturePtr, Slvs_hEntity>::iterator
1013 aRemovedIter = anEntFeatIter;
1015 myEntityFeatMap.erase(aRemovedIter);
1017 else anEntFeatIter++;
1019 std::set<Slvs_hEntity>::const_reverse_iterator aRemIter = anEntToRemove.rbegin();
1020 for ( ; aRemIter != anEntToRemove.rend(); aRemIter++)
1022 unsigned int anEntPos = Search(*aRemIter, myEntities);
1023 if (anEntPos >= myEntities.size())
1025 unsigned int aParamPos = Search(myEntities[anEntPos].param[0], myParams);
1026 if (aParamPos >= myParams.size())
1029 while (myEntities[anEntPos].param[aNbParams] != 0)
1031 if (myEntities[anEntPos].param[aNbParams-1] == myParamMaxID)
1032 myParamMaxID -= aNbParams;
1033 myParams.erase(myParams.begin() + aParamPos, myParams.begin() + aParamPos + aNbParams);
1034 if (*aRemIter == myEntityMaxID)
1036 myEntities.erase(myEntities.begin() + anEntPos);
1038 // Remove entity's ID from the lists of conincident points
1039 std::vector< std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1040 for ( ; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
1041 aCoPtIter->erase(*aRemIter);
1043 if (myCoincidentPoints.size() == 1 && myCoincidentPoints.front().empty())
1044 myCoincidentPoints.clear();
1048 // ============================================================================
1049 // Function: addCoincidentPoints
1050 // Class: SketchSolver_ConstraintGroup
1051 // Purpose: add coincident point the appropriate list of such points
1052 // ============================================================================
1053 bool SketchSolver_ConstraintGroup::addCoincidentPoints(
1054 const Slvs_hEntity& thePoint1, const Slvs_hEntity& thePoint2)
1056 std::vector< std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1057 std::vector< std::set<Slvs_hEntity> >::iterator aFirstFound = myCoincidentPoints.end();
1058 while (aCoPtIter != myCoincidentPoints.end())
1060 bool isFound[2] = { // indicate which point ID was already in coincidence constraint
1061 aCoPtIter->find(thePoint1) != aCoPtIter->end(),
1062 aCoPtIter->find(thePoint2) != aCoPtIter->end(),
1064 if (isFound[0] && isFound[1]) // points are already connected by coincidence constraints => no need additional one
1066 if ((isFound[0] && !isFound[1]) || (!isFound[0] && isFound[1]))
1068 if (aFirstFound != myCoincidentPoints.end())
1069 { // there are two groups of coincident points connected by created constraint => merge them
1070 int aFirstFoundShift = aFirstFound - myCoincidentPoints.begin();
1071 int aCurrentShift = aCoPtIter - myCoincidentPoints.begin();
1072 aFirstFound->insert(aCoPtIter->begin(), aCoPtIter->end());
1073 myCoincidentPoints.erase(aCoPtIter);
1074 aFirstFound = myCoincidentPoints.begin() + aFirstFoundShift;
1075 aCoPtIter = myCoincidentPoints.begin() + aCurrentShift;
1080 aCoPtIter->insert(isFound[0] ? thePoint2 : thePoint1);
1081 aFirstFound = aCoPtIter;
1086 // No points were found, need to create new set
1087 if (aFirstFound == myCoincidentPoints.end())
1089 std::set<Slvs_hEntity> aNewSet;
1090 aNewSet.insert(thePoint1);
1091 aNewSet.insert(thePoint2);
1092 myCoincidentPoints.push_back(aNewSet);
1099 // ============================================================================
1100 // Function: updateRelatedConstraints
1101 // Class: SketchSolver_ConstraintGroup
1102 // Purpose: emit the signal to update constraints
1103 // ============================================================================
1104 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1105 boost::shared_ptr<ModelAPI_Attribute> theEntity) const
1107 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
1108 aConstrIter = myConstraintMap.begin();
1109 for ( ; aConstrIter != myConstraintMap.end(); aConstrIter++)
1111 std::list< boost::shared_ptr<ModelAPI_Attribute> > anAttributes =
1112 aConstrIter->first->data()->attributes(theEntity->attributeType());
1114 std::list< boost::shared_ptr<ModelAPI_Attribute> >::iterator
1115 anAttrIter = anAttributes.begin();
1116 for ( ; anAttrIter != anAttributes.end(); anAttrIter++)
1117 if (*anAttrIter == theEntity)
1119 static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_UPDATED);
1120 Model_FeatureUpdatedMessage aMsg(aConstrIter->first, anEvent);
1121 Events_Loop::loop()->send(aMsg, true);
1127 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1128 boost::shared_ptr<ModelAPI_Feature> theFeature) const
1130 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
1131 aConstrIter = myConstraintMap.begin();
1132 for ( ; aConstrIter != myConstraintMap.end(); aConstrIter++)
1134 std::list< boost::shared_ptr<ModelAPI_Attribute> > anAttributes =
1135 aConstrIter->first->data()->attributes(std::string());
1137 std::list< boost::shared_ptr<ModelAPI_Attribute> >::iterator
1138 anAttrIter = anAttributes.begin();
1139 for ( ; anAttrIter != anAttributes.end(); anAttrIter++)
1141 boost::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr =
1142 boost::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
1143 if (aRefAttr && aRefAttr->isFeature() && aRefAttr->feature() == theFeature)
1145 static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_UPDATED);
1146 Model_FeatureUpdatedMessage aMsg(aConstrIter->first, anEvent);
1147 Events_Loop::loop()->send(aMsg, true);
1156 // ========================================================
1157 // ========= Auxiliary functions ===============
1158 // ========================================================
1160 template <typename T>
1161 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1163 int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1164 int aVecSize = theEntities.size();
1165 while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1167 while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1169 if (aResIndex == -1)
1170 aResIndex = aVecSize;