title: What is the Proper Formula for Converting a Quaternion to a Matrix
body: <p>I am currently writing my own game engine and I am having trouble properly implementing quaternions. My current quaternion implementation looks like this:</p>
  <pre class="lang-c prettyprint-override"><code>/*
  CybRender - Quaternion API
  */
  
  #include &quot;CybQuat.h&quot;
  
  
  //Functions
  //=================================================================================
  void Cyb_QuatFromAxisAndAngle(Cyb_Vec4 *quat, float x, float y, float z,
      float angle)
  {
      quat-&gt;x = x * sinf(radians(angle) / 2.0f);
      quat-&gt;y = y * sinf(radians(angle) / 2.0f);
      quat-&gt;z = z * sinf(radians(angle) / 2.0f);
      quat-&gt;w = cosf(radians(angle) / 2.0f);
  }
  
  
  void Cyb_MulQuat(Cyb_Vec4 *c, const Cyb_Vec4 *a, const Cyb_Vec4 *b)
  {
      c-&gt;x = a-&gt;w * b-&gt;x + a-&gt;x * b-&gt;w + a-&gt;y * b-&gt;z - a-&gt;z * b-&gt;y;
      c-&gt;y = a-&gt;w * b-&gt;y - a-&gt;x * b-&gt;z + a-&gt;y * b-&gt;w + a-&gt;z * b-&gt;x;
      c-&gt;z = a-&gt;w * b-&gt;z + a-&gt;x * b-&gt;y - a-&gt;y * b-&gt;x + a-&gt;z * b-&gt;w;
      c-&gt;w = a-&gt;w * b-&gt;w - a-&gt;x * b-&gt;x - a-&gt;y * b-&gt;y - a-&gt;z * b-&gt;z;
  }
  
  
  void Cyb_QuatToMatrix(Cyb_Mat4 *mat, const Cyb_Vec4 *quat)
  {
      //Start with the identity matrix
      Cyb_Identity(mat);
      
      //Row 1
      mat-&gt;a = 1 - 2 * quat-&gt;y * quat-&gt;y - 2 * quat-&gt;z * quat-&gt;z;
      mat-&gt;b = 2 * quat-&gt;x * quat-&gt;y - 2 * quat-&gt;w * quat-&gt;z;
      mat-&gt;c = 2 * quat-&gt;x * quat-&gt;z + 2 * quat-&gt;w * quat-&gt;y;
      
      //Row 2
      mat-&gt;e = 2 * quat-&gt;x * quat-&gt;y + 2 * quat-&gt;w * quat-&gt;z;
      mat-&gt;f = 1 - 2 * quat-&gt;x * quat-&gt;x - 2 * quat-&gt;z * quat-&gt;z;
      mat-&gt;g = 2 * quat-&gt;y * quat-&gt;z + 2 * quat-&gt;w * quat-&gt;x;
      
      //Row 3
      mat-&gt;i = 2 * quat-&gt;x * quat-&gt;z - 2 * quat-&gt;w * quat-&gt;y;
      mat-&gt;j = 2 * quat-&gt;y * quat-&gt;z - 2 * quat-&gt;w * quat-&gt;x;
      mat-&gt;k = 1 - 2 * quat-&gt;x * quat-&gt;x - 2 * quat-&gt;y * quat-&gt;y;
  }
  </code></pre>
  <p>It works properly if I only rotate around the X, Y, or Z axis. However, when I try to rotate around an arbitrary axis, I get odd distortion:</p>
  <p><img src="https://i.imgur.com/VBXVdH0.png" alt="image" /></p>
  <p>I have tried different formulas for converting my quaternion to a matrix, but every time I get similar distortion. I already tested my matrix implementation  to make sure it was working correctly and found no problems with it.</p>
  <p>What is the correct formula for converting a quaternion to a matrix?</p>