toji / gl-matrix

Javascript Matrix and Vector library for High Performance WebGL apps
glmatrix.net
MIT License
5.4k stars 725 forks source link

quat.lerp is not sign-preserving #404

Open magcius opened 4 years ago

magcius commented 4 years ago

I was wondering why I was seeing incorrect results with quat.lerp, until I realized it's just a vec4 lerp and isn't a quaternion lerp at all! A proper quaternion lerp would look something like this:

export function lerp(out, a, b, t) {
  var ax = a[0],
      ay = a[1],
      az = a[2],
      aw = a[3];
  var bx = b[0],
      by = b[1],
      bz = b[2],
      bw = b[3];
  var cosom, scale0, scale1; // calc cosine

  cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)

  scale0 = 1.0 - t;
  scale1 = cosom >= 0.0 ? t : -t;

  out[0] = scale0 * ax + scale1 * bx;
  out[1] = scale0 * ay + scale1 * by;
  out[2] = scale0 * az + scale1 * bz;
  out[3] = scale0 * aw + scale1 * bw;
  return out;
}

( Reference, if necessary: https://fabiensanglard.net/doom3_documentation/37725-293747_293747.pdf#page=4 )

stefnotch commented 4 years ago

Oh, that is a bug indeed. I'd gladly accept a PR that fixes this.

(Other reference for myself https://github.com/FlaxEngine/FlaxAPI/blob/master/FlaxEngine/Math/Quaternion.cs#L743 )

magcius commented 4 years ago

And one more: Unity as well (https://github.com/Unity-Technologies/Unity.Mathematics/blob/master/src/Unity.Mathematics/quaternion.cs#L563-L572).

This is far from the first time I've seen this :) . I'm slightly worried about back-compat, but I think pretty much everybody wants the fixed behavior.

stefnotch commented 4 years ago

If you're worried about backwards compatibility, I can add this to the 4.0 milestone.

(Though, the 4.0 milestone isn't progressing very fast, because on one hand I'm waiting for WebAssembly to become better and on the other hand, I'm busy with other projects and pretty much have abandoned WebGL. Thus, I'm not using gl-matrix for anything.)