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)
214 if (aConstrEnt[0] == aConstrEnt[1]) // no need to add self coincidence
218 if (!addCoincidentPoints(aConstrEnt[0], aConstrEnt[1]))
220 myExtraCoincidence.insert(theConstraint); // the constraint is stored for further purposes
225 // Create SolveSpace constraint structure
226 Slvs_Constraint aConstraint =
227 Slvs_MakeConstraint(++myConstrMaxID, myID, aConstrType, myWorkplane.h,
228 aDistance, aConstrEnt[0], aConstrEnt[1], aConstrEnt[2], aConstrEnt[3]);
229 myConstraints.push_back(aConstraint);
230 myConstraintMap[theConstraint] = aConstraint.h;
235 // ============================================================================
236 // Function: changeEntity
237 // Class: SketchSolver_ConstraintGroup
238 // Purpose: create/update the element affected by any constraint
239 // ============================================================================
240 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntity(
241 boost::shared_ptr<ModelAPI_Attribute> theEntity)
243 // If the entity is already in the group, try to find it
244 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
245 aEntIter = myEntityAttrMap.find(theEntity);
246 std::vector<Slvs_Param>::const_iterator aParamIter; // looks at first parameter of already existent entity or at the end of vector otherwise
247 if (aEntIter == myEntityAttrMap.end()) // no such entity => should be created
248 aParamIter = myParams.end();
250 { // the entity already exists
251 int aEntPos = Search(aEntIter->second, myEntities);
252 int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
253 aParamIter = myParams.begin() + aParamPos;
255 const bool isEntExists = (aEntIter != myEntityAttrMap.end()); // defines that the entity already exists
257 // Look over supported types of entities
260 boost::shared_ptr<GeomDataAPI_Point> aPoint =
261 boost::dynamic_pointer_cast<GeomDataAPI_Point>(theEntity);
264 Slvs_hParam aX = changeParameter(aPoint->x(), aParamIter);
265 Slvs_hParam aY = changeParameter(aPoint->y(), aParamIter);
266 Slvs_hParam aZ = changeParameter(aPoint->z(), aParamIter);
269 return aEntIter->second;
272 Slvs_Entity aPtEntity = Slvs_MakePoint3d(++myEntityMaxID, myID, aX, aY, aZ);
273 myEntities.push_back(aPtEntity);
274 myEntityAttrMap[theEntity] = aPtEntity.h;
278 // All entities except 3D points are created on workplane. So, if there is no workplane yet, then error
279 if (myWorkplane.h == SLVS_E_UNKNOWN)
280 return SLVS_E_UNKNOWN;
283 boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
284 boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theEntity);
287 Slvs_hParam aU = changeParameter(aPoint2D->x(), aParamIter);
288 Slvs_hParam aV = changeParameter(aPoint2D->y(), aParamIter);
291 return aEntIter->second;
294 Slvs_Entity aPt2DEntity = Slvs_MakePoint2d(++myEntityMaxID, myID, myWorkplane.h, aU, aV);
295 myEntities.push_back(aPt2DEntity);
296 myEntityAttrMap[theEntity] = aPt2DEntity.h;
297 return aPt2DEntity.h;
300 // Scalar value (used for the distance entities)
301 AttributeDoublePtr aScalar =
302 boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theEntity);
305 Slvs_hParam aValue = changeParameter(aScalar->value(), aParamIter);
308 return aEntIter->second;
311 Slvs_Entity aDistance = Slvs_MakeDistance(++myEntityMaxID, myID, myWorkplane.h, aValue);
312 myEntities.push_back(aDistance);
313 myEntityAttrMap[theEntity] = aDistance.h;
317 /// \todo Other types of entities
319 // Unsupported or wrong entity type
320 return SLVS_E_UNKNOWN;
324 // ============================================================================
325 // Function: changeEntity
326 // Class: SketchSolver_ConstraintGroup
327 // Purpose: create/update the element defined by the feature affected by any constraint
328 // ============================================================================
329 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntity(
330 FeaturePtr theEntity)
332 // If the entity is already in the group, try to find it
333 std::map<FeaturePtr, Slvs_hEntity>::const_iterator
334 aEntIter = myEntityFeatMap.find(theEntity);
335 // defines that the entity already exists
336 const bool isEntExists = (myEntityFeatMap.find(theEntity) != myEntityFeatMap.end());
338 // SketchPlugin features
339 boost::shared_ptr<SketchPlugin_Feature> aFeature =
340 boost::dynamic_pointer_cast<SketchPlugin_Feature>(theEntity);
342 { // Verify the feature by its kind
343 const std::string& aFeatureKind = aFeature->getKind();
346 if (aFeatureKind.compare(SKETCH_LINE_KIND) == 0)
348 Slvs_hEntity aStart = changeEntity(aFeature->data()->attribute(LINE_ATTR_START));
349 Slvs_hEntity aEnd = changeEntity(aFeature->data()->attribute(LINE_ATTR_END));
352 return aEntIter->second;
355 Slvs_Entity aLineEntity = Slvs_MakeLineSegment(++myEntityMaxID, myID, myWorkplane.h, aStart, aEnd);
356 myEntities.push_back(aLineEntity);
357 myEntityFeatMap[theEntity] = aLineEntity.h;
358 return aLineEntity.h;
361 else if (aFeatureKind.compare(SKETCH_CIRCLE_KIND) == 0)
363 Slvs_hEntity aCenter = changeEntity(aFeature->data()->attribute(CIRCLE_ATTR_CENTER));
364 Slvs_hEntity aRadius = changeEntity(aFeature->data()->attribute(CIRCLE_ATTR_RADIUS));
367 return aEntIter->second;
370 Slvs_Entity aCircleEntity =
371 Slvs_MakeCircle(++myEntityMaxID, myID, myWorkplane.h, aCenter, myWorkplane.normal, aRadius);
372 myEntities.push_back(aCircleEntity);
373 myEntityFeatMap[theEntity] = aCircleEntity.h;
374 return aCircleEntity.h;
377 else if (aFeatureKind.compare(SKETCH_ARC_KIND) == 0)
379 Slvs_hEntity aCenter = changeEntity(aFeature->data()->attribute(ARC_ATTR_CENTER));
380 Slvs_hEntity aStart = changeEntity(aFeature->data()->attribute(ARC_ATTR_START));
381 Slvs_hEntity aEnd = changeEntity(aFeature->data()->attribute(ARC_ATTR_END));
384 return aEntIter->second;
386 Slvs_Entity anArcEntity = Slvs_MakeArcOfCircle(++myEntityMaxID, myID,
387 myWorkplane.h, myWorkplane.normal, aCenter, aStart, aEnd);
388 myEntities.push_back(anArcEntity);
389 myEntityFeatMap[theEntity] = anArcEntity.h;
390 return anArcEntity.h;
392 // Point (it has low probability to be an attribute of constraint, so it is checked at the end)
393 else if (aFeatureKind.compare(SKETCH_POINT_KIND) == 0)
395 Slvs_hEntity aPoint = changeEntity(aFeature->data()->attribute(POINT_ATTR_COORD));
398 return aEntIter->second;
400 // Both the sketch point and its attribute (coordinates) link to the same SolveSpace point identifier
401 myEntityFeatMap[theEntity] = aPoint;
406 /// \todo Other types of features
408 // Unsupported or wrong entity type
409 return SLVS_E_UNKNOWN;
412 // ============================================================================
413 // Function: changeNormal
414 // Class: SketchSolver_ConstraintGroup
415 // Purpose: create/update the normal of workplane
416 // ============================================================================
417 Slvs_hEntity SketchSolver_ConstraintGroup::changeNormal(
418 boost::shared_ptr<ModelAPI_Attribute> theDirX,
419 boost::shared_ptr<ModelAPI_Attribute> theDirY,
420 boost::shared_ptr<ModelAPI_Attribute> theNorm)
422 boost::shared_ptr<GeomDataAPI_Dir> aDirX =
423 boost::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirX);
424 boost::shared_ptr<GeomDataAPI_Dir> aDirY =
425 boost::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirY);
426 if (!aDirX || !aDirY ||
427 (fabs(aDirX->x()) + fabs(aDirX->y()) + fabs(aDirX->z()) < tolerance) ||
428 (fabs(aDirY->x()) + fabs(aDirY->y()) + fabs(aDirY->z()) < tolerance))
429 return SLVS_E_UNKNOWN;
431 // quaternion parameters of normal vector
432 double qw, qx, qy, qz;
433 Slvs_MakeQuaternion(aDirX->x(), aDirX->y(), aDirX->z(),
434 aDirY->x(), aDirY->y(), aDirY->z(),
436 double aNormCoord[4] = {qw, qx, qy, qz};
438 // Try to find existent normal
439 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
440 aEntIter = myEntityAttrMap.find(theNorm);
441 std::vector<Slvs_Param>::const_iterator aParamIter; // looks to the first parameter of already existent entity or to the end of vector otherwise
442 if (aEntIter == myEntityAttrMap.end()) // no such entity => should be created
443 aParamIter = myParams.end();
445 { // the entity already exists, update it
446 int aEntPos = Search(aEntIter->second, myEntities);
447 int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
448 aParamIter = myParams.begin() + aParamPos;
451 // Change parameters of the normal
452 Slvs_hParam aNormParams[4];
453 for (int i = 0; i < 4; i++)
454 aNormParams[i] = changeParameter(aNormCoord[i], aParamIter);
456 if (aEntIter != myEntityAttrMap.end()) // the entity already exists
457 return aEntIter->second;
460 Slvs_Entity aNormal = Slvs_MakeNormal3d(++myEntityMaxID, myID,
461 aNormParams[0], aNormParams[1], aNormParams[2], aNormParams[3]);
462 myEntities.push_back(aNormal);
463 myEntityAttrMap[theNorm] = aNormal.h;
468 // ============================================================================
469 // Function: addWorkplane
470 // Class: SketchSolver_ConstraintGroup
471 // Purpose: create workplane for the group
472 // ============================================================================
473 bool SketchSolver_ConstraintGroup::addWorkplane(
474 boost::shared_ptr<SketchPlugin_Feature> theSketch)
476 if (myWorkplane.h || theSketch->getKind().compare(SKETCH_KIND) != 0)
477 return false; // the workplane already exists or the function parameter is not Sketch
479 mySketch = theSketch;
484 // ============================================================================
485 // Function: updateWorkplane
486 // Class: SketchSolver_ConstraintGroup
487 // Purpose: update parameters of workplane
488 // ============================================================================
489 bool SketchSolver_ConstraintGroup::updateWorkplane()
491 // Get parameters of workplane
492 boost::shared_ptr<ModelAPI_Attribute> aDirX = mySketch->data()->attribute(SKETCH_ATTR_DIRX);
493 boost::shared_ptr<ModelAPI_Attribute> aDirY = mySketch->data()->attribute(SKETCH_ATTR_DIRY);
494 boost::shared_ptr<ModelAPI_Attribute> aNorm = mySketch->data()->attribute(SKETCH_ATTR_NORM);
495 boost::shared_ptr<ModelAPI_Attribute> anOrigin = mySketch->data()->attribute(SKETCH_ATTR_ORIGIN);
496 // Transform them into SolveSpace format
497 Slvs_hEntity aNormalWP = changeNormal(aDirX, aDirY, aNorm);
498 if (!aNormalWP) return false;
499 Slvs_hEntity anOriginWP = changeEntity(anOrigin);
500 if (!anOriginWP) return false;
505 myWorkplane = Slvs_MakeWorkplane(++myEntityMaxID, myID, anOriginWP, aNormalWP);
506 // Workplane should be added to the list of entities
507 myEntities.push_back(myWorkplane);
512 // ============================================================================
513 // Function: changeParameter
514 // Class: SketchSolver_ConstraintGroup
515 // Purpose: create/update value of parameter
516 // ============================================================================
517 Slvs_hParam SketchSolver_ConstraintGroup::changeParameter(
518 const double& theParam,
519 std::vector<Slvs_Param>::const_iterator& thePrmIter)
521 if (thePrmIter != myParams.end())
522 { // Parameter should be updated
523 int aParamPos = thePrmIter - myParams.begin();
524 if (fabs(thePrmIter->val - theParam) > tolerance)
526 myNeedToSolve = true; // parameter is changed, need to resolve constraints
527 myParams[aParamPos].val = theParam;
530 return myParams[aParamPos].h;
533 // Newly created parameter
534 Slvs_Param aParam = Slvs_MakeParam(++myParamMaxID, myID, theParam);
535 myParams.push_back(aParam);
536 myNeedToSolve = true;
537 // The list of parameters is changed, move iterator to the end of the list to avoid problems
538 thePrmIter = myParams.end();
542 // ============================================================================
543 // Function: resolveConstraints
544 // Class: SketchSolver_ConstraintGroup
545 // Purpose: solve the set of constraints for the current group
546 // ============================================================================
547 void SketchSolver_ConstraintGroup::resolveConstraints()
552 myConstrSolver.setGroupID(myID);
553 myConstrSolver.setParameters(myParams);
554 myConstrSolver.setEntities(myEntities);
555 myConstrSolver.setConstraints(myConstraints);
556 myConstrSolver.setDraggedParameters(myTempPointWhereDragged);
558 int aResult = myConstrSolver.solve();
559 if (aResult == SLVS_RESULT_OKAY)
560 { // solution succeeded, store results into correspondent attributes
561 // Obtain result into the same list of parameters
562 if (!myConstrSolver.getResult(myParams))
565 // We should go through the attributes map, because only attributes have valued parameters
566 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
567 anEntIter = myEntityAttrMap.begin();
568 for ( ; anEntIter != myEntityAttrMap.end(); anEntIter++)
569 updateAttribute(anEntIter->first, anEntIter->second);
571 else if (!myConstraints.empty())
572 Events_Error::send(ERROR_SOLVE_CONSTRAINTS, this);
574 removeTemporaryConstraints();
575 myNeedToSolve = false;
578 // ============================================================================
579 // Function: mergeGroups
580 // Class: SketchSolver_ConstraintGroup
581 // Purpose: append specified group to the current group
582 // ============================================================================
583 void SketchSolver_ConstraintGroup::mergeGroups(
584 const SketchSolver_ConstraintGroup& theGroup)
586 // If specified group is empty, no need to merge
587 if (theGroup.myConstraintMap.empty())
590 // Map between old and new indexes of SolveSpace constraints
591 std::map<Slvs_hConstraint, Slvs_hConstraint> aConstrMap;
593 // Add all constraints from theGroup to the current group
594 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
595 aConstrIter = theGroup.myConstraintMap.begin();
596 for ( ; aConstrIter != theGroup.myConstraintMap.end(); aConstrIter++)
597 if (changeConstraint(aConstrIter->first))
598 aConstrMap[aConstrIter->second] = myConstrMaxID; // the constraint was added => store its ID
600 // Add temporary constraints from theGroup
601 std::list<Slvs_hConstraint>::const_iterator aTempConstrIter = theGroup.myTempConstraints.begin();
602 for ( ; aTempConstrIter != theGroup.myTempConstraints.end(); aTempConstrIter++)
604 std::map<Slvs_hConstraint, Slvs_hConstraint>::iterator aFind = aConstrMap.find(*aTempConstrIter);
605 if (aFind != aConstrMap.end())
606 myTempConstraints.push_back(aFind->second);
609 if (myTempPointWhereDragged.empty())
610 myTempPointWhereDragged = theGroup.myTempPointWhereDragged;
611 else if (!theGroup.myTempPointWhereDragged.empty())
612 { // Need to create additional transient constraint
613 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
614 aFeatureIter = theGroup.myEntityAttrMap.begin();
615 for (; aFeatureIter != theGroup.myEntityAttrMap.end(); aFeatureIter++)
616 if (aFeatureIter->second == myTempPointWDrgdID)
618 addTemporaryConstraintWhereDragged(aFeatureIter->first);
623 myNeedToSolve = myNeedToSolve || theGroup.myNeedToSolve;
626 // ============================================================================
627 // Function: splitGroup
628 // Class: SketchSolver_ConstraintGroup
629 // Purpose: divide the group into several subgroups
630 // ============================================================================
631 void SketchSolver_ConstraintGroup::splitGroup(std::vector<SketchSolver_ConstraintGroup*>& theCuts)
633 // Divide constraints and entities into several groups
634 std::vector< std::set<Slvs_hEntity> > aGroupsEntities;
635 std::vector< std::set<Slvs_hConstraint> > aGroupsConstr;
636 int aMaxNbEntities = 0; // index of the group with maximal nuber of elements (this group will be left in the current)
637 std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
638 for ( ; aConstrIter != myConstraints.end(); aConstrIter++)
640 Slvs_hEntity aConstrEnt[] = {
641 aConstrIter->ptA, aConstrIter->ptB,
642 aConstrIter->entityA, aConstrIter->entityB};
643 std::vector<int> anIndexes;
644 // Go through the groupped entities and find even one of entities of current constraint
645 std::vector< std::set<Slvs_hEntity> >::iterator aGrEntIter;
646 for (aGrEntIter = aGroupsEntities.begin(); aGrEntIter != aGroupsEntities.end(); aGrEntIter++)
648 bool isFound = false;
649 for (int i = 0; i < 4 && !isFound; i++)
650 if (aConstrEnt[i] != 0)
651 isFound = (aGrEntIter->find(aConstrEnt[i]) != aGrEntIter->end());
653 anIndexes.push_back(aGrEntIter - aGroupsEntities.begin());
655 // Add new group if no one is found
656 if (anIndexes.empty())
658 std::set<Slvs_hEntity> aNewGrEnt;
659 for (int i = 0; i < 4; i++)
660 if (aConstrEnt[i] != 0)
661 aNewGrEnt.insert(aConstrEnt[i]);
662 std::set<Slvs_hConstraint> aNewGrConstr;
663 aNewGrConstr.insert(aConstrIter->h);
665 aGroupsEntities.push_back(aNewGrEnt);
666 aGroupsConstr.push_back(aNewGrConstr);
667 if (aNewGrEnt.size() > aGroupsEntities[aMaxNbEntities].size())
668 aMaxNbEntities = aGroupsEntities.size() - 1;
670 else if (anIndexes.size() == 1)
671 { // Add entities indexes into the found group
672 aGrEntIter = aGroupsEntities.begin() + anIndexes.front();
673 for (int i = 0; i < 4; i++)
674 if (aConstrEnt[i] != 0)
675 aGrEntIter->insert(aConstrEnt[i]);
676 aGroupsConstr[anIndexes.front()].insert(aConstrIter->h);
677 if (aGrEntIter->size() > aGroupsEntities[aMaxNbEntities].size())
678 aMaxNbEntities = aGrEntIter - aGroupsEntities.begin();
681 { // There are found several connected groups, merge them
682 std::vector< std::set<Slvs_hEntity> >::iterator aFirstGroup =
683 aGroupsEntities.begin() + anIndexes.front();
684 std::vector< std::set<Slvs_hConstraint> >::iterator aFirstConstr =
685 aGroupsConstr.begin() + anIndexes.front();
686 std::vector<int>::iterator anInd = anIndexes.begin();
687 for (++anInd; anInd != anIndexes.end(); anInd++)
689 aFirstGroup->insert(aGroupsEntities[*anInd].begin(), aGroupsEntities[*anInd].end());
690 aFirstConstr->insert(aGroupsConstr[*anInd].begin(), aGroupsConstr[*anInd].end());
692 if (aFirstGroup->size() > aGroupsEntities[aMaxNbEntities].size())
693 aMaxNbEntities = anIndexes.front();
694 // Remove merged groups
695 for (anInd = anIndexes.end() - 1; anInd != anIndexes.begin(); anInd--)
697 aGroupsEntities.erase(aGroupsEntities.begin() + (*anInd));
698 aGroupsConstr.erase(aGroupsConstr.begin() + (*anInd));
703 if (aGroupsEntities.size() <= 1)
706 // Remove the group with maximum elements as it will be left in the current group
707 aGroupsEntities.erase(aGroupsEntities.begin() + aMaxNbEntities);
708 aGroupsConstr.erase(aGroupsConstr.begin() + aMaxNbEntities);
710 // Add new groups of constraints and divide current group
711 std::vector<SketchSolver_ConstraintGroup*> aNewGroups;
712 for (int i = aGroupsEntities.size(); i > 0; i--)
714 SketchSolver_ConstraintGroup* aG = new SketchSolver_ConstraintGroup(mySketch);
715 aNewGroups.push_back(aG);
717 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
718 aConstrMapIter = myConstraintMap.begin();
719 int aConstrMapPos = 0; // position of iterator in the map (used to restore iterator after removing constraint)
720 while (aConstrMapIter != myConstraintMap.end())
722 std::vector< std::set<Slvs_hConstraint> >::const_iterator aGIter = aGroupsConstr.begin();
723 std::vector<SketchSolver_ConstraintGroup*>::iterator aGroup = aNewGroups.begin();
724 for ( ; aGIter != aGroupsConstr.end(); aGIter++, aGroup++)
725 if (aGIter->find(aConstrMapIter->second) != aGIter->end())
727 (*aGroup)->changeConstraint(aConstrMapIter->first);
728 removeConstraint(aConstrMapIter->first);
730 aConstrMapIter = myConstraintMap.begin();
731 for (int i = 0; i < aConstrMapPos; i++)
735 if (aGIter == aGroupsConstr.end())
742 theCuts.insert(theCuts.end(), aNewGroups.begin(), aNewGroups.end());
745 // ============================================================================
746 // Function: updateGroup
747 // Class: SketchSolver_ConstraintGroup
748 // Purpose: search removed entities and constraints
749 // ============================================================================
750 bool SketchSolver_ConstraintGroup::updateGroup()
752 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::reverse_iterator
753 aConstrIter = myConstraintMap.rbegin();
754 bool isAllValid = true;
755 bool isCCRemoved = false; // indicates that at least one of coincidence constraints was removed
756 while (isAllValid && aConstrIter != myConstraintMap.rend())
758 if (!aConstrIter->first->data()->isValid())
760 if (aConstrIter->first->getKind().compare(SKETCH_CONSTRAINT_COINCIDENCE_KIND) == 0)
762 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::reverse_iterator
763 aCopyIter = aConstrIter++;
764 removeConstraint(aCopyIter->first);
770 // Probably, need to update coincidence constraints
771 if (isCCRemoved && !myExtraCoincidence.empty())
773 // Make a copy, because the new list of unused constrtaints will be generated
774 std::set< boost::shared_ptr<SketchPlugin_Constraint> > anExtraCopy = myExtraCoincidence;
775 myExtraCoincidence.clear();
777 std::set< boost::shared_ptr<SketchPlugin_Constraint> >::iterator
778 aCIter = anExtraCopy.begin();
779 for ( ; aCIter != anExtraCopy.end(); aCIter++)
780 if ((*aCIter)->data()->isValid())
781 changeConstraint(*aCIter);
787 // ============================================================================
788 // Function: updateAttribute
789 // Class: SketchSolver_ConstraintGroup
790 // Purpose: update features of sketch after resolving constraints
791 // ============================================================================
792 void SketchSolver_ConstraintGroup::updateAttribute(
793 boost::shared_ptr<ModelAPI_Attribute> theAttribute,
794 const Slvs_hEntity& theEntityID)
796 // Search the position of the first parameter of the entity
797 int anEntPos = Search(theEntityID, myEntities);
798 int aFirstParamPos = Search(myEntities[anEntPos].param[0], myParams);
800 // Look over supported types of entities
803 boost::shared_ptr<GeomDataAPI_Point> aPoint =
804 boost::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
807 aPoint->setValue(myParams[aFirstParamPos].val,
808 myParams[aFirstParamPos+1].val,
809 myParams[aFirstParamPos+2].val);
814 boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
815 boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
818 aPoint2D->setValue(myParams[aFirstParamPos].val,
819 myParams[aFirstParamPos+1].val);
824 AttributeDoublePtr aScalar =
825 boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
828 aScalar->setValue(myParams[aFirstParamPos].val);
832 /// \todo Support other types of entities
835 // ============================================================================
836 // Function: updateEntityIfPossible
837 // Class: SketchSolver_ConstraintGroup
838 // Purpose: search the entity in this group and update it
839 // ============================================================================
840 void SketchSolver_ConstraintGroup::updateEntityIfPossible(
841 boost::shared_ptr<ModelAPI_Attribute> theEntity)
843 if (myEntityAttrMap.find(theEntity) != myEntityAttrMap.end())
845 // If the attribute is a point and it is changed (the group needs to rebuild),
846 // probably user has dragged this point into this position,
847 // so it is necessary to add constraint which will guarantee the point will not change
849 // Store myNeedToSolve flag to verify the entity is really changed
850 bool aNeedToSolveCopy = myNeedToSolve;
851 myNeedToSolve = false;
853 changeEntity(theEntity);
855 if (myNeedToSolve) // the entity is changed
857 // Verify the entity is a point and add temporary constraint of permanency
858 boost::shared_ptr<GeomDataAPI_Point> aPoint =
859 boost::dynamic_pointer_cast<GeomDataAPI_Point>(theEntity);
860 boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
861 boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theEntity);
862 if (aPoint || aPoint2D)
863 addTemporaryConstraintWhereDragged(theEntity);
866 // Restore flag of changes
867 myNeedToSolve = myNeedToSolve || aNeedToSolveCopy;
869 updateRelatedConstraints(theEntity);
873 // ============================================================================
874 // Function: addTemporaryConstraintWhereDragged
875 // Class: SketchSolver_ConstraintGroup
876 // Purpose: add transient constraint SLVS_C_WHERE_DRAGGED for the entity,
877 // which was moved by user
878 // ============================================================================
879 void SketchSolver_ConstraintGroup::addTemporaryConstraintWhereDragged(
880 boost::shared_ptr<ModelAPI_Attribute> theEntity)
882 // Find identifier of the entity
883 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator
884 anEntIter = myEntityAttrMap.find(theEntity);
885 if (anEntIter == myEntityAttrMap.end())
888 // If this is a first dragged point, its parameters should be placed
889 // into Slvs_System::dragged field to avoid system inconsistense
890 if (myTempPointWhereDragged.empty())
892 int anEntPos = Search(anEntIter->second, myEntities);
893 Slvs_hParam* aDraggedParam = myEntities[anEntPos].param;
894 for (int i = 0; i < 4; i++, aDraggedParam++)
895 if (*aDraggedParam != 0)
896 myTempPointWhereDragged.push_back(*aDraggedParam);
897 myTempPointWDrgdID = myEntities[anEntPos].h;
901 // Get identifiers of all dragged points
902 std::set<Slvs_hEntity> aDraggedPntID;
903 aDraggedPntID.insert(myTempPointWDrgdID);
904 std::list<Slvs_hConstraint>::iterator aTmpCoIter = myTempConstraints.begin();
905 for ( ; aTmpCoIter != myTempConstraints.end(); aTmpCoIter++)
907 unsigned int aConstrPos = Search(*aTmpCoIter, myConstraints);
908 if (aConstrPos < myConstraints.size())
909 aDraggedPntID.insert(myConstraints[aConstrPos].ptA);
911 // Find whether there is a point coincident with theEntity, which already has SLVS_C_WHERE_DRAGGED
912 std::vector< std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
913 for ( ; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
915 if (aCoPtIter->find(anEntIter->second) == aCoPtIter->end())
916 continue; // the entity was not found in current set
918 // Find one of already created SLVS_C_WHERE_DRAGGED constraints in current set of coincident points
919 std::set<Slvs_hEntity>::const_iterator aDrgIter = aDraggedPntID.begin();
920 for ( ; aDrgIter != aDraggedPntID.end(); aDrgIter++)
921 if (aCoPtIter->find(*aDrgIter) != aCoPtIter->end())
922 return ; // the SLVS_C_WHERE_DRAGGED constraint already exists
925 // Create additional SLVS_C_WHERE_DRAGGED constraint if myTempPointWhereDragged field is not empty
926 Slvs_Constraint aWDConstr = Slvs_MakeConstraint(++myConstrMaxID, myID, SLVS_C_WHERE_DRAGGED,
927 myWorkplane.h, 0.0, anEntIter->second, 0, 0, 0);
928 myConstraints.push_back(aWDConstr);
929 myTempConstraints.push_back(aWDConstr.h);
932 // ============================================================================
933 // Function: removeTemporaryConstraints
934 // Class: SketchSolver_ConstraintGroup
935 // Purpose: remove all transient SLVS_C_WHERE_DRAGGED constraints after
936 // resolving the set of constraints
937 // ============================================================================
938 void SketchSolver_ConstraintGroup::removeTemporaryConstraints()
940 std::list<Slvs_hConstraint>::reverse_iterator aTmpConstrIter;
941 for (aTmpConstrIter = myTempConstraints.rbegin(); aTmpConstrIter != myTempConstraints.rend(); aTmpConstrIter++)
943 unsigned int aConstrPos = Search(*aTmpConstrIter, myConstraints);
944 if (aConstrPos >= myConstraints.size())
946 myConstraints.erase(myConstraints.begin() + aConstrPos);
948 // If the removing constraint has higher index, decrease the indexer
949 if (*aTmpConstrIter == myConstrMaxID)
952 myTempConstraints.clear();
954 // Clear basic dragged point
955 myTempPointWhereDragged.clear();
958 // ============================================================================
959 // Function: removeConstraint
960 // Class: SketchSolver_ConstraintGroup
961 // Purpose: remove constraint and all unused entities
962 // ============================================================================
963 void SketchSolver_ConstraintGroup::removeConstraint(boost::shared_ptr<SketchPlugin_Constraint> theConstraint)
965 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::iterator
966 anIterToRemove = myConstraintMap.find(theConstraint);
967 if (anIterToRemove == myConstraintMap.end())
970 Slvs_hConstraint aCnstrToRemove = anIterToRemove->second;
971 // Remove constraint from the map
972 myConstraintMap.erase(anIterToRemove);
974 // Find unused entities
975 int aConstrPos = Search(aCnstrToRemove, myConstraints);
976 std::set<Slvs_hEntity> anEntToRemove;
977 Slvs_hEntity aCnstEnt[] = {myConstraints[aConstrPos].ptA, myConstraints[aConstrPos].ptB,
978 myConstraints[aConstrPos].entityA, myConstraints[aConstrPos].entityB};
979 for (int i = 0; i < 4; i++)
980 if (aCnstEnt[i] != 0)
981 anEntToRemove.insert(aCnstEnt[i]);
982 myConstraints.erase(myConstraints.begin() + aConstrPos);
983 if (aCnstrToRemove == myConstrMaxID)
985 std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
986 for ( ; aConstrIter != myConstraints.end(); aConstrIter++)
988 Slvs_hEntity aEnts[] = {aConstrIter->ptA, aConstrIter->ptB,
989 aConstrIter->entityA, aConstrIter->entityB};
990 for (int i = 0; i < 4; i++)
991 if (aEnts[i] != 0 && anEntToRemove.find(aEnts[i]) != anEntToRemove.end())
992 anEntToRemove.erase(aEnts[i]);
995 if (anEntToRemove.empty())
998 // Remove unused entities
999 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1000 anEntAttrIter = myEntityAttrMap.begin();
1001 while (anEntAttrIter != myEntityAttrMap.end())
1003 if (anEntToRemove.find(anEntAttrIter->second) != anEntToRemove.end())
1005 std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1006 aRemovedIter = anEntAttrIter;
1008 myEntityAttrMap.erase(aRemovedIter);
1010 else anEntAttrIter++;
1012 std::map<FeaturePtr, Slvs_hEntity>::iterator
1013 anEntFeatIter = myEntityFeatMap.begin();
1014 while (anEntFeatIter != myEntityFeatMap.end())
1016 if (anEntToRemove.find(anEntFeatIter->second) != anEntToRemove.end())
1018 std::map<FeaturePtr, Slvs_hEntity>::iterator
1019 aRemovedIter = anEntFeatIter;
1021 myEntityFeatMap.erase(aRemovedIter);
1023 else anEntFeatIter++;
1025 std::set<Slvs_hEntity>::const_reverse_iterator aRemIter = anEntToRemove.rbegin();
1026 for ( ; aRemIter != anEntToRemove.rend(); aRemIter++)
1028 unsigned int anEntPos = Search(*aRemIter, myEntities);
1029 if (anEntPos >= myEntities.size())
1031 unsigned int aParamPos = Search(myEntities[anEntPos].param[0], myParams);
1032 if (aParamPos >= myParams.size())
1035 while (myEntities[anEntPos].param[aNbParams] != 0)
1037 if (myEntities[anEntPos].param[aNbParams-1] == myParamMaxID)
1038 myParamMaxID -= aNbParams;
1039 myParams.erase(myParams.begin() + aParamPos, myParams.begin() + aParamPos + aNbParams);
1040 if (*aRemIter == myEntityMaxID)
1042 myEntities.erase(myEntities.begin() + anEntPos);
1044 // Remove entity's ID from the lists of conincident points
1045 std::vector< std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1046 for ( ; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
1047 aCoPtIter->erase(*aRemIter);
1049 if (myCoincidentPoints.size() == 1 && myCoincidentPoints.front().empty())
1050 myCoincidentPoints.clear();
1054 // ============================================================================
1055 // Function: addCoincidentPoints
1056 // Class: SketchSolver_ConstraintGroup
1057 // Purpose: add coincident point the appropriate list of such points
1058 // ============================================================================
1059 bool SketchSolver_ConstraintGroup::addCoincidentPoints(
1060 const Slvs_hEntity& thePoint1, const Slvs_hEntity& thePoint2)
1062 std::vector< std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1063 std::vector< std::set<Slvs_hEntity> >::iterator aFirstFound = myCoincidentPoints.end();
1064 while (aCoPtIter != myCoincidentPoints.end())
1066 bool isFound[2] = { // indicate which point ID was already in coincidence constraint
1067 aCoPtIter->find(thePoint1) != aCoPtIter->end(),
1068 aCoPtIter->find(thePoint2) != aCoPtIter->end(),
1070 if (isFound[0] && isFound[1]) // points are already connected by coincidence constraints => no need additional one
1072 if ((isFound[0] && !isFound[1]) || (!isFound[0] && isFound[1]))
1074 if (aFirstFound != myCoincidentPoints.end())
1075 { // there are two groups of coincident points connected by created constraint => merge them
1076 int aFirstFoundShift = aFirstFound - myCoincidentPoints.begin();
1077 int aCurrentShift = aCoPtIter - myCoincidentPoints.begin();
1078 aFirstFound->insert(aCoPtIter->begin(), aCoPtIter->end());
1079 myCoincidentPoints.erase(aCoPtIter);
1080 aFirstFound = myCoincidentPoints.begin() + aFirstFoundShift;
1081 aCoPtIter = myCoincidentPoints.begin() + aCurrentShift;
1086 aCoPtIter->insert(isFound[0] ? thePoint2 : thePoint1);
1087 aFirstFound = aCoPtIter;
1092 // No points were found, need to create new set
1093 if (aFirstFound == myCoincidentPoints.end())
1095 std::set<Slvs_hEntity> aNewSet;
1096 aNewSet.insert(thePoint1);
1097 aNewSet.insert(thePoint2);
1098 myCoincidentPoints.push_back(aNewSet);
1105 // ============================================================================
1106 // Function: updateRelatedConstraints
1107 // Class: SketchSolver_ConstraintGroup
1108 // Purpose: emit the signal to update constraints
1109 // ============================================================================
1110 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1111 boost::shared_ptr<ModelAPI_Attribute> theEntity) const
1113 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
1114 aConstrIter = myConstraintMap.begin();
1115 for ( ; aConstrIter != myConstraintMap.end(); aConstrIter++)
1117 std::list< boost::shared_ptr<ModelAPI_Attribute> > anAttributes =
1118 aConstrIter->first->data()->attributes(theEntity->attributeType());
1120 std::list< boost::shared_ptr<ModelAPI_Attribute> >::iterator
1121 anAttrIter = anAttributes.begin();
1122 for ( ; anAttrIter != anAttributes.end(); anAttrIter++)
1123 if (*anAttrIter == theEntity)
1125 static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_UPDATED);
1126 Model_FeatureUpdatedMessage aMsg(aConstrIter->first, anEvent);
1127 Events_Loop::loop()->send(aMsg, true);
1133 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1134 boost::shared_ptr<ModelAPI_Feature> theFeature) const
1136 std::map<boost::shared_ptr<SketchPlugin_Constraint>, Slvs_hConstraint>::const_iterator
1137 aConstrIter = myConstraintMap.begin();
1138 for ( ; aConstrIter != myConstraintMap.end(); aConstrIter++)
1140 std::list< boost::shared_ptr<ModelAPI_Attribute> > anAttributes =
1141 aConstrIter->first->data()->attributes(std::string());
1143 std::list< boost::shared_ptr<ModelAPI_Attribute> >::iterator
1144 anAttrIter = anAttributes.begin();
1145 for ( ; anAttrIter != anAttributes.end(); anAttrIter++)
1147 boost::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr =
1148 boost::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
1149 if (aRefAttr && aRefAttr->isFeature() && aRefAttr->feature() == theFeature)
1151 static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_UPDATED);
1152 Model_FeatureUpdatedMessage aMsg(aConstrIter->first, anEvent);
1153 Events_Loop::loop()->send(aMsg, true);
1162 // ========================================================
1163 // ========= Auxiliary functions ===============
1164 // ========================================================
1166 template <typename T>
1167 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1169 int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1170 int aVecSize = theEntities.size();
1171 while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1173 while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1175 if (aResIndex == -1)
1176 aResIndex = aVecSize;