Debian Codegraph @

src/Base/Rotation.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2006 Werner Mayer <wmayer[at]users.sourceforge.net> *
5 * *
6 * This file is part of the FreeCAD CAx development system. *
7 * *
8 * This library is free software; you can redistribute it and/or *
9 * modify it under the terms of the GNU Library General Public *
10 * License as published by the Free Software Foundation; either *
11 * version 2 of the License, or (at your option) any later version. *
12 * *
13 * This library is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU Library General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Library General Public *
19 * License along with this library; see the file COPYING.LIB. If not, *
20 * write to the Free Software Foundation, Inc., 59 Temple Place, *
21 * Suite 330, Boston, MA 02111-1307, USA *
22 * *
23 ***************************************************************************/
24
25 #include <limits>
26
27 #include <boost/algorithm/string/predicate.hpp>
28 #include "Base/Exception.h"
29 #include "Base/Tools.h"
30
31 #include "Rotation.h"
32 #include "Matrix.h"
33 #include "Precision.h"
34
35
36 using namespace Base;
37
38 Rotation::Rotation()
39 : quat {0.0, 0.0, 0.0, 1.0}
40 , _axis {0.0, 0.0, 1.0}
41 , _angle {0.0}
42 {}
43
44 /** Construct a rotation by rotation axis and angle */
45 Rotation::Rotation(const Vector3d& axis, const double fAngle)
46 : Rotation()
47 {
48 // set to (0,0,1) as fallback in case the passed axis is the null vector
49 _axis.Set(0.0, 0.0, 1.0);
50 this->setValue(axis, fAngle);
51 }
52
53 Rotation::Rotation(const Matrix4D& matrix)
54 : Rotation()
55 {
56 this->setValue(matrix);
57 }
58
59 /** Construct a rotation initialized with the given quaternion components:
60 * q[0] = x, q[1] = y, q[2] = z and q[3] = w,
61 * where the quaternion is specified by q=w+xi+yj+zk.
62 */
63 Rotation::Rotation(const double q[4])
64 : Rotation()
65 {
66 this->setValue(q);
67 }
68
69 /** Construct a rotation initialized with the given quaternion components:
70 * q0 = x, q1 = y, q2 = z and q3 = w,
71 * where the quaternion is specified by q=w+xi+yj+zk.
72 */
73 Rotation::Rotation(double q0, double q1, double q2, double q3)
74 : Rotation()
75 {
76 this->setValue(q0, q1, q2, q3);
77 }
78
79 Rotation::Rotation(const Vector3d& rotateFrom, const Vector3d& rotateTo)
80 : Rotation()
81 {
82 this->setValue(rotateFrom, rotateTo);
83 }
84
85 Rotation Rotation::fromNormalVector(const Vector3d& normal)
86 {
87 // We rotate Z axis to be aligned with the supplied normal vector
88 return Rotation(Vector3d(0, 0, 1), normal);
89 }
90
91 Rotation Rotation::fromEulerAngles(EulerSequence theOrder, double alpha, double beta, double gamma)
92 {
93 Rotation rotation;
94 rotation.setEulerAngles(theOrder, alpha, beta, gamma);
95 return rotation;
96 }
97
98 const double* Rotation::getValue() const
99 {
100 return &this->quat[0];
101 }
102
103 void Rotation::getValue(double& q0, double& q1, double& q2, double& q3) const
104 {
105 q0 = this->quat[0];
106 q1 = this->quat[1];
107 q2 = this->quat[2];
108 q3 = this->quat[3];
109 }
110
111 void Rotation::evaluateVector()
112 {
113 // Taken from <http://de.wikipedia.org/wiki/Quaternionen>
114 //
115 // Note: -1 < w < +1 (|w| == 1 not allowed, with w:=quat[3])
116 if ((this->quat[3] > -1.0) && (this->quat[3] < 1.0)) {
117 double rfAngle = acos(this->quat[3]) * 2.0;
118 double scale = sin(rfAngle / 2.0);
119 // Get a normalized vector
120 double l = this->_axis.Length();
121 if (l < Base::Vector3d::epsilon()) {
122 l = 1;
123 }
124 this->_axis.x = this->quat[0] * l / scale;
125 this->_axis.y = this->quat[1] * l / scale;
126 this->_axis.z = this->quat[2] * l / scale;
127
128 _angle = rfAngle;
129 }
130 else {
131 _axis.Set(0.0, 0.0, 1.0);
132 _angle = 0.0;
133 }
134 }
135
136 void Rotation::setValue(double q0, double q1, double q2, double q3)
137 {
138 this->quat[0] = q0;
139 this->quat[1] = q1;
140 this->quat[2] = q2;
141 this->quat[3] = q3;
142 this->normalize();
143 this->evaluateVector();
144 }
145
146 void Rotation::getValue(Vector3d& axis, double& rfAngle) const
147 {
148 rfAngle = _angle;
149 axis.x = _axis.x;
150 axis.y = _axis.y;
151 axis.z = _axis.z;
152 axis.Normalize();
153 }
154
155 void Rotation::getRawValue(Vector3d& axis, double& rfAngle) const
156 {
157 rfAngle = _angle;
158 axis.x = _axis.x;
159 axis.y = _axis.y;
160 axis.z = _axis.z;
161 }
162
163 /**
164 * Returns this rotation in form of a matrix.
165 */
166 void Rotation::getValue(Matrix4D& matrix) const
167 {
168 // Taken from <http://de.wikipedia.org/wiki/Quaternionen>
169 //
170 const double l = sqrt(
171 this->quat[0] * this->quat[0] + this->quat[1] * this->quat[1]
172 + this->quat[2] * this->quat[2] + this->quat[3] * this->quat[3]
173 );
174 const double x = this->quat[0] / l;
175 const double y = this->quat[1] / l;
176 const double z = this->quat[2] / l;
177 const double w = this->quat[3] / l;
178
179 matrix[0][0] = 1.0 - 2.0 * (y * y + z * z);
180 matrix[0][1] = 2.0 * (x * y - z * w);
181 matrix[0][2] = 2.0 * (x * z + y * w);
182 matrix[0][3] = 0.0;
183
184 matrix[1][0] = 2.0 * (x * y + z * w);
185 matrix[1][1] = 1.0 - 2.0 * (x * x + z * z);
186 matrix[1][2] = 2.0 * (y * z - x * w);
187 matrix[1][3] = 0.0;
188
189 matrix[2][0] = 2.0 * (x * z - y * w);
190 matrix[2][1] = 2.0 * (y * z + x * w);
191 matrix[2][2] = 1.0 - 2.0 * (x * x + y * y);
192 matrix[2][3] = 0.0;
193
194 matrix[3][0] = 0.0;
195 matrix[3][1] = 0.0;
196 matrix[3][2] = 0.0;
197 matrix[3][3] = 1.0;
198 }
199
200 void Rotation::setValue(const double q[4])
201 {
202 this->quat[0] = q[0];
203 this->quat[1] = q[1];
204 this->quat[2] = q[2];
205 this->quat[3] = q[3];
206 this->normalize();
207 this->evaluateVector();
208 }
209
210 void Rotation::setValue(const Matrix4D& m)
211 {
212 // Get the rotation part matrix
213 Matrix4D mc = m.decompose()[2];
214 // Extract quaternion
215 double trace = (mc[0][0] + mc[1][1] + mc[2][2]);
216 if (trace > 0.0) {
217 double s = sqrt(1.0 + trace);
218 this->quat[3] = 0.5 * s;
219 s = 0.5 / s;
220 this->quat[0] = ((mc[2][1] - mc[1][2]) * s);
221 this->quat[1] = ((mc[0][2] - mc[2][0]) * s);
222 this->quat[2] = ((mc[1][0] - mc[0][1]) * s);
223 }
224 else {
225 // Described in RotationIssues.pdf from <http://www.geometrictools.com>
226 //
227 // Get the max. element of the trace
228 unsigned short i = 0;
229 if (mc[1][1] > mc[0][0]) {
230 i = 1;
231 }
232 if (mc[2][2] > mc[i][i]) {
233 i = 2;
234 }
235
236 unsigned short j = (i + 1) % 3;
237 unsigned short k = (i + 2) % 3;
238
239 double s = sqrt((mc[i][i] - (mc[j][j] + mc[k][k])) + 1.0);
240 this->quat[i] = s * 0.5;
241 s = 0.5 / s;
242 this->quat[3] = ((mc[k][j] - mc[j][k]) * s);
243 this->quat[j] = ((mc[j][i] + mc[i][j]) * s);
244 this->quat[k] = ((mc[k][i] + mc[i][k]) * s);
245 }
246
247 this->evaluateVector();
248 }
249
250 void Rotation::setValue(const Vector3d& axis, double fAngle)
251 {
252 using std::numbers::pi;
253 // Taken from <http://de.wikipedia.org/wiki/Quaternionen>
254 //
255 // normalization of the angle to be in [0, 2pi[
256 _angle = fAngle;
257 double theAngle = fAngle - floor(fAngle / (2.0 * pi)) * (2.0 * pi);
258 this->quat[3] = cos(theAngle / 2.0);
259
260 Vector3d norm = axis;
261 norm.Normalize();
262 double l = norm.Length();
263 // Keep old axis in case the new axis is the null vector
264 if (l > 0.5) {
265 this->_axis = axis;
266 }
267 else {
268 norm = _axis;
269 norm.Normalize();
270 }
271
272 double scale = sin(theAngle / 2.0);
273 this->quat[0] = norm.x * scale;
274 this->quat[1] = norm.y * scale;
275 this->quat[2] = norm.z * scale;
276 }
277
278 void Rotation::setValue(const Vector3d& rotateFrom, const Vector3d& rotateTo)
279 {
280 Vector3d u(rotateFrom);
281 u.Normalize();
282 Vector3d v(rotateTo);
283 v.Normalize();
284
285 // The vector from x to is the rotation axis because it's the normal of the plane defined by
286 // (0,u,v)
287 const double dot = u * v;
288 Vector3d w = u % v;
289 const double wlen = w.Length();
290
291 if (wlen == 0.0) { // Parallel vectors
292 // Check if they are pointing in the same direction.
293 if (dot > 0.0) {
294 this->setValue(0.0, 0.0, 0.0, 1.0);
295 }
296 else {
297 // We can use any axis perpendicular to u (and v)
298 Vector3d t = u % Vector3d(1.0, 0.0, 0.0);
299 if (t.Length() < Base::Vector3d::epsilon()) {
300 t = u % Vector3d(0.0, 1.0, 0.0);
301 }
302 this->setValue(t.x, t.y, t.z, 0.0);
303 }
304 }
305 else { // Vectors are not parallel
306 // Note: A quaternion is not well-defined by specifying a point and its transformed point.
307 // Every quaternion with a rotation axis having the same angle to the vectors of both points
308 // is okay.
309 double angle = acos(dot);
310 this->setValue(w, angle);
311 }
312 }
313
314 void Rotation::normalize()
315 {
316 double len = sqrt(
317 this->quat[0] * this->quat[0] + this->quat[1] * this->quat[1]
318 + this->quat[2] * this->quat[2] + this->quat[3] * this->quat[3]
319 );
320 if (len > 0.0) {
321 this->quat[0] /= len;
322 this->quat[1] /= len;
323 this->quat[2] /= len;
324 this->quat[3] /= len;
325 }
326 }
327
328 Rotation& Rotation::invert()
329 {
330 this->quat[0] = -this->quat[0];
331 this->quat[1] = -this->quat[1];
332 this->quat[2] = -this->quat[2];
333
334 this->_axis.x = -this->_axis.x;
335 this->_axis.y = -this->_axis.y;
336 this->_axis.z = -this->_axis.z;
337
338 return *this;
339 }
340
341 Rotation Rotation::inverse() const
342 {
343 Rotation rot;
344 rot.quat[0] = -this->quat[0];
345 rot.quat[1] = -this->quat[1];
346 rot.quat[2] = -this->quat[2];
347 rot.quat[3] = this->quat[3];
348
349 rot._axis[0] = -this->_axis[0];
350 rot._axis[1] = -this->_axis[1];
351 rot._axis[2] = -this->_axis[2];
352 rot._angle = this->_angle;
353 return rot;
354 }
355
356 /*!
357 Let this rotation be right-multiplied by \a q. Returns reference to
358 self.
359
360 \sa multRight()
361 */
362 Rotation& Rotation::operator*=(const Rotation& q)
363 {
364 return multRight(q);
365 }
366
367 Rotation Rotation::operator*(const Rotation& q) const
368 {
369 Rotation quat(*this);
370 quat *= q;
371 return quat;
372 }
373
374 /*!
375 Let this rotation be right-multiplied by \a q. Returns reference to
376 self.
377
378 \sa multLeft()
379 */
380 Rotation& Rotation::multRight(const Base::Rotation& q)
381 {
382 // Taken from <http://de.wikipedia.org/wiki/Quaternionen>
383 double x0 {};
384 double y0 {};
385 double z0 {};
386 double w0 {};
387 this->getValue(x0, y0, z0, w0);
388
389 double x1 {};
390 double y1 {};
391 double z1 {};
392 double w1 {};
393 q.getValue(x1, y1, z1, w1);
394
395 this->setValue(
396 w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1,
397 w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1,
398 w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1,
399 w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1
400 );
401 return *this;
402 }
403
404 /*!
405 Let this rotation be left-multiplied by \a q. Returns reference to
406 self.
407
408 \sa multRight()
409 */
410 Rotation& Rotation::multLeft(const Base::Rotation& q)
411 {
412 // Taken from <http://de.wikipedia.org/wiki/Quaternionen>
413 double x0 {};
414 double y0 {};
415 double z0 {};
416 double w0 {};
417 q.getValue(x0, y0, z0, w0);
418
419 double x1 {};
420 double y1 {};
421 double z1 {};
422 double w1 {};
423 this->getValue(x1, y1, z1, w1);
424
425 this->setValue(
426 w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1,
427 w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1,
428 w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1,
429 w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1
430 );
431 return *this;
432 }
433
434 bool Rotation::operator==(const Rotation& q) const
435 {
436 return isSame(q);
437 }
438
439 bool Rotation::operator!=(const Rotation& q) const
440 {
441 return !(*this == q);
442 }
443
444 Vector3d Rotation::multVec(const Vector3d& src) const
445 {
446 Vector3d dst;
447 multVec(src, dst);
448 return dst;
449 }
450
451 void Rotation::multVec(const Vector3d& src, Vector3d& dst) const
452 {
453 double x = this->quat[0];
454 double y = this->quat[1];
455 double z = this->quat[2];
456 double w = this->quat[3];
457 double x2 = x * x;
458 double y2 = y * y;
459 double z2 = z * z;
460 double w2 = w * w;
461
462 double dx = (x2 + w2 - y2 - z2) * src.x + 2.0 * (x * y - z * w) * src.y
463 + 2.0 * (x * z + y * w) * src.z;
464 double dy = 2.0 * (x * y + z * w) * src.x + (w2 - x2 + y2 - z2) * src.y
465 + 2.0 * (y * z - x * w) * src.z;
466 double dz = 2.0 * (x * z - y * w) * src.x + 2.0 * (x * w + y * z) * src.y
467 + (w2 - x2 - y2 + z2) * src.z;
468 dst.x = dx;
469 dst.y = dy;
470 dst.z = dz;
471 }
472
473 void Rotation::multVec(const Vector3f& src, Vector3f& dst) const
474 {
475 Base::Vector3d srcd = Base::toVector<double>(src);
476 multVec(srcd, srcd);
477 dst = Base::toVector<float>(srcd);
478 }
479
480 Vector3f Rotation::multVec(const Vector3f& src) const
481 {
482 Vector3f dst;
483 multVec(src, dst);
484 return dst;
485 }
486
487 void Rotation::scaleAngle(const double scaleFactor)
488 {
489 Vector3d axis;
490 double fAngle {};
491 this->getValue(axis, fAngle);
492 this->setValue(axis, fAngle * scaleFactor);
493 }
494
495 Rotation Rotation::slerp(const Rotation& q0, const Rotation& q1, double t)
496 {
497 // Taken from <http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/>
498 if (t < 0.0) {
499 t = 0.0;
500 }
501 else if (t > 1.0) {
502 t = 1.0;
503 }
504
505 double scale0 = 1.0 - t;
506 double scale1 = t;
507 double dot = q0.quat[0] * q1.quat[0] + q0.quat[1] * q1.quat[1] + q0.quat[2] * q1.quat[2]
508 + q0.quat[3] * q1.quat[3];
509 bool neg = false;
510 if (dot < 0.0) {
511 dot = -dot;
512 neg = true;
513 }
514
515 if ((1.0 - dot) > Base::Vector3d::epsilon()) {
516 double angle = acos(dot);
517 double sinangle = sin(angle);
518 // If possible calculate spherical interpolation, otherwise use linear interpolation
519 if (sinangle > Base::Vector3d::epsilon()) {
520 scale0 = double(sin((1.0 - t) * angle)) / sinangle;
521 scale1 = double(sin(t * angle)) / sinangle;
522 }
523 }
524
525 if (neg) {
526 scale1 = -scale1;
527 }
528
529 double x = scale0 * q0.quat[0] + scale1 * q1.quat[0];
530 double y = scale0 * q0.quat[1] + scale1 * q1.quat[1];
531 double z = scale0 * q0.quat[2] + scale1 * q1.quat[2];
532 double w = scale0 * q0.quat[3] + scale1 * q1.quat[3];
533 return {x, y, z, w};
534 }
535
536 Rotation Rotation::identity()
537 {
538 return {0.0, 0.0, 0.0, 1.0};
539 }
540
541 Rotation Rotation::makeRotationByAxes(Vector3d xdir, Vector3d ydir, Vector3d zdir, const char* priorityOrder)
542 {
543 const double tol = Precision::Confusion();
544 enum dirIndex
545 {
546 X,
547 Y,
548 Z
549 };
550
551 // convert priorityOrder string into a sequence of ints.
552 if (strlen(priorityOrder) != 3) {
553 THROWM(ValueError, "makeRotationByAxes: length of priorityOrder is not 3");
554 }
555 int order[3];
556 for (int i = 0; i < 3; ++i) {
557 order[i] = priorityOrder[i] - 'X';
558 if (order[i] < 0 || order[i] > 2) {
559 THROWM(
560 ValueError,
561 "makeRotationByAxes: characters in priorityOrder must be uppercase X, Y, or Z. "
562 "Some other character encountered."
563 )
564 }
565 }
566
567 // ensure every axis is listed in priority list
568 if (order[0] == order[1] || order[1] == order[2] || order[2] == order[0]) {
569 THROWM(ValueError, "makeRotationByAxes: not all axes are listed in priorityOrder");
570 }
571
572
573 // group up dirs into an array, to access them by indexes stored in @order.
574 std::vector<Vector3d*> dirs = {&xdir, &ydir, &zdir};
575
576
577 auto dropPriority = [&order](int index) {
578 int tmp {};
579 if (index == 0) {
580 tmp = order[0];
581 order[0] = order[1];
582 order[1] = order[2];
583 order[2] = tmp;
584 }
585 else if (index == 1) {
586 tmp = order[1];
587 order[1] = order[2];
588 order[2] = tmp;
589 } // else if index == 2 do nothing
590 };
591
592 // pick up the strict direction
593 Vector3d mainDir;
594 for (int i = 0; i < 3; ++i) {
595 mainDir = *(dirs[size_t(order[0])]);
596 if (mainDir.Length() > tol) {
597 break;
598 }
599
600 dropPriority(0);
601
602 if (i == 2) {
603 THROWM(ValueError, "makeRotationByAxes: all directions supplied are zero");
604 }
605 }
606 mainDir.Normalize();
607
608 // pick up the 2nd priority direction, "hint" direction.
609 Vector3d hintDir;
610 for (int i = 0; i < 2; ++i) {
611 hintDir = *(dirs[size_t(order[1])]);
612 if ((hintDir.Cross(mainDir)).Length() > tol) {
613 break;
614 }
615
616 dropPriority(1);
617
618 if (i == 1) {
619 hintDir = Vector3d(); // no vector can be used as hint direction. Zero it out, to
620 // indicate that a guess is needed.
621 }
622 }
623 if (hintDir.Length() == 0.0) {
624 switch (order[0]) {
625 case X: { // xdir is main
626 // align zdir to OZ
627 order[1] = Z;
628 order[2] = Y;
629 hintDir = Vector3d(0, 0, 1);
630 if ((hintDir.Cross(mainDir)).Length() <= tol) {
631 // aligning to OZ is impossible, align to ydir to OY. Why so? I don't know, just
632 // feels right =)
633 hintDir = Vector3d(0, 1, 0);
634 order[1] = Y;
635 order[2] = Z;
636 }
637 } break;
638 case Y: { // ydir is main
639 // align zdir to OZ
640 order[1] = Z;
641 order[2] = X;
642 hintDir = mainDir.z > -tol ? Vector3d(0, 0, 1) : Vector3d(0, 0, -1);
643 if ((hintDir.Cross(mainDir)).Length() <= tol) {
644 // aligning zdir to OZ is impossible, align xdir to OX then.
645 hintDir = Vector3d(1, 0, 0);
646 order[1] = X;
647 order[2] = Z;
648 }
649 } break;
650 case Z: { // zdir is main
651 // align ydir to OZ
652 order[1] = Y;
653 order[2] = X;
654 hintDir = Vector3d(0, 0, 1);
655 if ((hintDir.Cross(mainDir)).Length() <= tol) {
656 // aligning ydir to OZ is impossible, align xdir to OX then.
657 hintDir = Vector3d(1, 0, 0);
658 order[1] = X;
659 order[2] = Y;
660 }
661 } break;
662 } // switch ordet[0]
663 }
664
665 // ensure every axis is listed in priority list
666 assert(order[0] != order[1]);
667 assert(order[1] != order[2]);
668 assert(order[2] != order[0]);
669
670 hintDir.Normalize();
671 // make hintDir perpendicular to mainDir. For that, we cross-product the two to obtain the third
672 // axis direction, and then recover back the hint axis by doing another cross product.
673 Vector3d lastDir = mainDir.Cross(hintDir);
674 lastDir.Normalize();
675 hintDir = lastDir.Cross(mainDir);
676 hintDir.Normalize(); // redundant?
677
678 Vector3d finaldirs[3];
679 finaldirs[order[0]] = mainDir;
680 finaldirs[order[1]] = hintDir;
681 finaldirs[order[2]] = lastDir;
682
683 // fix handedness
684 if (finaldirs[X].Cross(finaldirs[Y]) * finaldirs[Z] < 0.0) {
685 // handedness is wrong. Switch the direction of the least important axis
686 finaldirs[order[2]] = finaldirs[order[2]] * (-1.0);
687 }
688
689 // build the rotation, by constructing a matrix first.
690 Matrix4D m;
691 m.setToUnity();
692 for (int i = 0; i < 3; ++i) {
693 // matrix indexing: [row][col]
694 m[0][i] = finaldirs[i].x;
695 m[1][i] = finaldirs[i].y;
696 m[2][i] = finaldirs[i].z;
697 }
698
699 return {m};
700 }
701
702 void Rotation::setYawPitchRoll(double y, double p, double r)
703 {
704 // The Euler angles (yaw,pitch,roll) are in XY'Z''-notation
705 // convert to radians
706 y = toRadians(y);
707 p = toRadians(p);
708 r = toRadians(r);
709
710 double c1 = cos(y / 2.0);
711 double s1 = sin(y / 2.0);
712 double c2 = cos(p / 2.0);
713 double s2 = sin(p / 2.0);
714 double c3 = cos(r / 2.0);
715 double s3 = sin(r / 2.0);
716
717 this->setValue(
718 c1 * c2 * s3 - s1 * s2 * c3,
719 c1 * s2 * c3 + s1 * c2 * s3,
720 s1 * c2 * c3 - c1 * s2 * s3,
721 c1 * c2 * c3 + s1 * s2 * s3
722 );
723 }
724
725 void Rotation::getYawPitchRoll(double& y, double& p, double& r) const
726 {
727 using std::numbers::pi;
728
729 double q00 = quat[0] * quat[0];
730 double q11 = quat[1] * quat[1];
731 double q22 = quat[2] * quat[2];
732 double q33 = quat[3] * quat[3];
733 double q01 = quat[0] * quat[1];
734 double q02 = quat[0] * quat[2];
735 double q03 = quat[0] * quat[3];
736 double q12 = quat[1] * quat[2];
737 double q13 = quat[1] * quat[3];
738 double q23 = quat[2] * quat[3];
739 double qd2 = 2.0 * (q13 - q02);
740
741 // Tolerance copied from OCC "gp_Quaternion.cxx"
742 constexpr double tolerance = 16 * std::numeric_limits<double>::epsilon();
743 // handle gimbal lock
744 if (fabs(qd2 - 1.0) <= tolerance) {
745 // north pole
746 y = 0.0;
747 p = pi / 2.0;
748 r = 2.0 * atan2(quat[0], quat[3]);
749 }
750 else if (fabs(qd2 + 1.0) <= tolerance) {
751 // south pole
752 y = 0.0;
753 p = -pi / 2.0;
754 r = 2.0 * atan2(quat[0], quat[3]);
755 }
756 else {
757 y = atan2(2.0 * (q01 + q23), (q00 + q33) - (q11 + q22));
758 p = qd2 > 1.0 ? pi / 2.0 : (qd2 < -1.0 ? -pi / 2.0 : asin(qd2));
759 r = atan2(2.0 * (q12 + q03), (q22 + q33) - (q00 + q11));
760 }
761
762 // convert to degree
763 y = toDegrees(y);
764 p = toDegrees(p);
765 r = toDegrees(r);
766 }
767
768 bool Rotation::isSame(const Rotation& q) const
769 {
770 // clang-format off
771 return ((this->quat[0] == q.quat[0] &&
772 this->quat[1] == q.quat[1] &&
773 this->quat[2] == q.quat[2] &&
774 this->quat[3] == q.quat[3]) ||
775 (this->quat[0] == -q.quat[0] &&
776 this->quat[1] == -q.quat[1] &&
777 this->quat[2] == -q.quat[2] &&
778 this->quat[3] == -q.quat[3]));
779 // clang-format on
780 }
781
782 bool Rotation::isSame(const Rotation& q, double tol) const
783 {
784 // This follows the implementation of Coin3d where the norm
785 // (x1-y1)**2 + ... + (x4-y4)**2 is computed.
786 // This term can be simplified to
787 // 2 - 2*(x1*y1 + ... + x4*y4) so that for the equality we have to check
788 // 1 - tol/2 <= x1*y1 + ... + x4*y4
789 // This simplification only work if both quats are normalized
790 // Is it safe to assume that?
791 // Because a quaternion (x1,x2,x3,x4) is equal to (-x1,-x2,-x3,-x4) we use the
792 // absolute value of the scalar product
793 double dot = q.quat[0] * quat[0] + q.quat[1] * quat[1] + q.quat[2] * quat[2]
794 + q.quat[3] * quat[3];
795 return fabs(dot) >= 1.0 - tol / 2;
796 }
797
798 bool Rotation::isIdentity() const
799 {
800 return (
801 (this->quat[0] == 0.0 && this->quat[1] == 0.0 && this->quat[2] == 0.0)
802 && (this->quat[3] == 1.0 || this->quat[3] == -1.0)
803 );
804 }
805
806 bool Rotation::isIdentity(double tol) const
807 {
808 return isSame(Rotation(), tol);
809 }
810
811 bool Rotation::isNull() const
812 {
813 return (
814 this->quat[0] == 0.0 && this->quat[1] == 0.0 && this->quat[2] == 0.0 && this->quat[3] == 0.0
815 );
816 }
817
818 //=======================================================================
819 // The following code is borrowed from OCCT gp/gp_Quaternion.cxx
820
821 namespace
822 { // anonymous namespace
823 //=======================================================================
824 // function : translateEulerSequence
825 // purpose :
826 // Code supporting conversion between quaternion and generalized
827 // Euler angles (sequence of three rotations) is based on
828 // algorithm by Ken Shoemake, published in Graphics Gems IV, p. 222-22
829 // http://tog.acm.org/resources/GraphicsGems/gemsiv/euler_angle/EulerAngles.c
830 //=======================================================================
831
832 struct EulerSequence_Parameters
833 {
834 int i; // first rotation axis
835 int j; // next axis of rotation
836 int k; // third axis
837 bool isOdd; // true if order of two first rotation axes is odd permutation, e.g. XZ
838 bool isTwoAxes; // true if third rotation is about the same axis as first
839 bool isExtrinsic; // true if rotations are made around fixed axes
840
841 EulerSequence_Parameters(int theAx1, bool theisOdd, bool theisTwoAxes, bool theisExtrinsic)
842 : i(theAx1)
843 , j(1 + (theAx1 + (theisOdd ? 1 : 0)) % 3)
844 , k(1 + (theAx1 + (theisOdd ? 0 : 1)) % 3)
845 , isOdd(theisOdd)
846 , isTwoAxes(theisTwoAxes)
847 , isExtrinsic(theisExtrinsic)
848 {}
849 };
850
851 EulerSequence_Parameters translateEulerSequence(const Rotation::EulerSequence theSeq)
852 {
853 const bool F = false;
854 const bool T = true;
855
856 switch (theSeq) {
857 case Rotation::Extrinsic_XYZ:
858 return {1, F, F, T};
859 case Rotation::Extrinsic_XZY:
860 return {1, T, F, T};
861 case Rotation::Extrinsic_YZX:
862 return {2, F, F, T};
863 case Rotation::Extrinsic_YXZ:
864 return {2, T, F, T};
865 case Rotation::Extrinsic_ZXY:
866 return {3, F, F, T};
867 case Rotation::Extrinsic_ZYX:
868 return {3, T, F, T};
869
870 // Conversion of intrinsic angles is made by the same code as for extrinsic,
871 // using equivalence rule: intrinsic rotation is equivalent to extrinsic
872 // rotation by the same angles but with inverted order of elemental rotations.
873 // Swapping of angles (Alpha <-> Gamma) is done inside conversion procedure;
874 // sequence of axes is inverted by setting appropriate parameters here.
875 // Note that proper Euler angles (last block below) are symmetric for sequence of axes.
876 case Rotation::Intrinsic_XYZ:
877 return {3, T, F, F};
878 case Rotation::Intrinsic_XZY:
879 return {2, F, F, F};
880 case Rotation::Intrinsic_YZX:
881 return {1, T, F, F};
882 case Rotation::Intrinsic_YXZ:
883 return {3, F, F, F};
884 case Rotation::Intrinsic_ZXY:
885 return {2, T, F, F};
886 case Rotation::Intrinsic_ZYX:
887 return {1, F, F, F};
888
889 case Rotation::Extrinsic_XYX:
890 return {1, F, T, T};
891 case Rotation::Extrinsic_XZX:
892 return {1, T, T, T};
893 case Rotation::Extrinsic_YZY:
894 return {2, F, T, T};
895 case Rotation::Extrinsic_YXY:
896 return {2, T, T, T};
897 case Rotation::Extrinsic_ZXZ:
898 return {3, F, T, T};
899 case Rotation::Extrinsic_ZYZ:
900 return {3, T, T, T};
901
902 case Rotation::Intrinsic_XYX:
903 return {1, F, T, F};
904 case Rotation::Intrinsic_XZX:
905 return {1, T, T, F};
906 case Rotation::Intrinsic_YZY:
907 return {2, F, T, F};
908 case Rotation::Intrinsic_YXY:
909 return {2, T, T, F};
910 case Rotation::Intrinsic_ZXZ:
911 return {3, F, T, F};
912 case Rotation::Intrinsic_ZYZ:
913 return {3, T, T, F};
914
915 default:
916 case Rotation::EulerAngles:
917 return {3, F, T, F}; // = Intrinsic_ZXZ
918 case Rotation::YawPitchRoll:
919 return {1, F, F, F}; // = Intrinsic_ZYX
920 };
921 }
922
923 class Mat: public Base::Matrix4D
924 {
925 public:
926 double operator()(int i, int j) const
927 {
928 return this->operator[](i - 1)[j - 1];
929 }
930 double& operator()(int i, int j)
931 {
932 return this->operator[](i - 1)[j - 1];
933 }
934 };
935
936 const char* EulerSequenceNames[] = {
937 //! Classic Euler angles, alias to Intrinsic_ZXZ
938 "Euler",
939
940 //! Yaw Pitch Roll (or nautical) angles, alias to Intrinsic_ZYX
941 "YawPitchRoll",
942
943 // Tait-Bryan angles (using three different axes)
944 "XYZ",
945 "XZY",
946 "YZX",
947 "YXZ",
948 "ZXY",
949 "ZYX",
950
951 "IXYZ",
952 "IXZY",
953 "IYZX",
954 "IYXZ",
955 "IZXY",
956 "IZYX",
957
958 // Proper Euler angles (using two different axes, first and third the same)
959 "XYX",
960 "XZX",
961 "YZY",
962 "YXY",
963 "ZYZ",
964 "ZXZ",
965
966 "IXYX",
967 "IXZX",
968 "IYZY",
969 "IYXY",
970 "IZXZ",
971 "IZYZ",
972 };
973
974 } // anonymous namespace
975
976 const char* Rotation::eulerSequenceName(EulerSequence seq)
977 {
978 if (seq == Invalid || seq >= EulerSequenceLast) {
979 return nullptr;
980 }
981 return EulerSequenceNames[seq - 1];
982 }
983
984 Rotation::EulerSequence Rotation::eulerSequenceFromName(const char* name)
985 {
986 if (name) {
987 for (unsigned i = 0; i < sizeof(EulerSequenceNames) / sizeof(EulerSequenceNames[0]); ++i) {
988 if (boost::iequals(name, EulerSequenceNames[i])) {
989 return static_cast<EulerSequence>(i + 1);
990 }
991 }
992 }
993 return Invalid;
994 }
995
996 void Rotation::setEulerAngles(EulerSequence theOrder, double theAlpha, double theBeta, double theGamma)
997 {
998 using std::numbers::pi;
999
1000 if (theOrder == Invalid || theOrder >= EulerSequenceLast) {
1001 throw Base::ValueError("invalid euler sequence");
1002 }
1003
1004 EulerSequence_Parameters o = translateEulerSequence(theOrder);
1005
1006 theAlpha = Base::toRadians(theAlpha);
1007 theBeta = Base::toRadians(theBeta);
1008 theGamma = Base::toRadians(theGamma);
1009
1010 double a = theAlpha;
1011 double b = theBeta;
1012 double c = theGamma;
1013 if (!o.isExtrinsic) {
1014 std::swap(a, c);
1015 }
1016
1017 if (o.isOdd) {
1018 b = -b;
1019 }
1020
1021 double ti = 0.5 * a;
1022 double tj = 0.5 * b;
1023 double th = 0.5 * c;
1024 double ci = cos(ti);
1025 double cj = cos(tj);
1026 double ch = cos(th);
1027 double si = sin(ti);
1028 double sj = sin(tj);
1029 double sh = sin(th);
1030 double cc = ci * ch;
1031 double cs = ci * sh;
1032 double sc = si * ch;
1033 double ss = si * sh;
1034
1035 double values[4]; // w, x, y, z
1036 if (o.isTwoAxes) {
1037 values[o.i] = cj * (cs + sc);
1038 values[o.j] = sj * (cc + ss);
1039 values[o.k] = sj * (cs - sc);
1040 values[0] = cj * (cc - ss);
1041 }
1042 else {
1043 values[o.i] = cj * sc - sj * cs;
1044 values[o.j] = cj * ss + sj * cc;
1045 values[o.k] = cj * cs - sj * sc;
1046 values[0] = cj * cc + sj * ss;
1047 }
1048 if (o.isOdd) {
1049 values[o.j] = -values[o.j];
1050 }
1051
1052 quat[0] = values[1];
1053 quat[1] = values[2];
1054 quat[2] = values[3];
1055 quat[3] = values[0];
1056 this->evaluateVector();
1057 }
1058
1059 void Rotation::getEulerAngles(EulerSequence theOrder, double& theAlpha, double& theBeta, double& theGamma) const
1060 {
1061 Mat M;
1062 getValue(M);
1063
1064 EulerSequence_Parameters o = translateEulerSequence(theOrder);
1065 if (o.isTwoAxes) {
1066 double sy = sqrt(M(o.i, o.j) * M(o.i, o.j) + M(o.i, o.k) * M(o.i, o.k));
1067 if (sy > 16 * std::numeric_limits<double>::epsilon()) {
1068 theAlpha = atan2(M(o.i, o.j), M(o.i, o.k));
1069 theGamma = atan2(M(o.j, o.i), -M(o.k, o.i));
1070 }
1071 else {
1072 theAlpha = atan2(-M(o.j, o.k), M(o.j, o.j));
1073 theGamma = 0.;
1074 }
1075 theBeta = atan2(sy, M(o.i, o.i));
1076 }
1077 else {
1078 double cy = sqrt(M(o.i, o.i) * M(o.i, o.i) + M(o.j, o.i) * M(o.j, o.i));
1079 if (cy > 16 * std::numeric_limits<double>::epsilon()) {
1080 theAlpha = atan2(M(o.k, o.j), M(o.k, o.k));
1081 theGamma = atan2(M(o.j, o.i), M(o.i, o.i));
1082 }
1083 else {
1084 theAlpha = atan2(-M(o.j, o.k), M(o.j, o.j));
1085 theGamma = 0.;
1086 }
1087 theBeta = atan2(-M(o.k, o.i), cy);
1088 }
1089 if (o.isOdd) {
1090 theAlpha = -theAlpha;
1091 theBeta = -theBeta;
1092 theGamma = -theGamma;
1093 }
1094 if (!o.isExtrinsic) {
1095 double aFirst = theAlpha;
1096 theAlpha = theGamma;
1097 theGamma = aFirst;
1098 }
1099
1100 theAlpha = Base::toDegrees(theAlpha);
1101 theBeta = Base::toDegrees(theBeta);
1102 theGamma = Base::toDegrees(theGamma);
1103 }