Skip to content

Commit ade2256

Browse files
authored
optimize q_diff_mag and ensure scalar is positive (#123)
1 parent 71ed713 commit ade2256

File tree

1 file changed

+13
-16
lines changed

1 file changed

+13
-16
lines changed

src/util.c

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,15 @@ void q_negate(const float* q, float* out) {
5858
out[3] = -q[3];
5959
}
6060

61-
float q_diff_mag(const float* x, const float* y) {
62-
float z[4];
63-
float q[4];
64-
q_conj(x, z);
65-
q_multiply(z, y, q);
66-
if (q[0] > 1) {
61+
float q_diff_mag(const float *x, const float *y)
62+
{
63+
/* same as quatmultiply(quatconj(x), y, z), where s is scalar of z
64+
* to handle possible inverted quaternions, it should be enough to make sure s is positive
65+
*/
66+
float s = fabsf(x[0]*y[0] + x[1]*y[1] + x[2]*y[2] + x[3]*y[3]);
67+
if (s > 1)
6768
return 0;
68-
}
69-
return fabsf(2 * acosf(q[0]));
69+
return 2 * acosf(s);
7070
}
7171

7272
void v_rotate(const float* v, const float* q, float* out) // TODO: not the most optimal
@@ -89,15 +89,12 @@ float v_diff_mag(const float* a, const float* b) {
8989
return sqrtf(x * x + y * y + z * z);
9090
}
9191

92-
bool q_epsilon(const float* x, const float* y, float eps) {
93-
float z[4];
94-
float q[4];
95-
q_conj(x, z);
96-
q_multiply(z, y, q);
97-
if (q[0] > 1) {
92+
bool q_epsilon(const float *x, const float *y, float eps)
93+
{
94+
float s = fabsf(x[0]*y[0] + x[1]*y[1] + x[2]*y[2] + x[3]*y[3]);
95+
if (s > 1)
9896
return true;
99-
}
100-
return fabsf(2 * acosf(q[0])) < eps;
97+
return (2 * acosf(s)) < eps;
10198
}
10299

103100
bool v_epsilon(const float* a, const float* b, float eps) {

0 commit comments

Comments
 (0)