;;-*-Lisp-*-
(in-package goal)
(bundles "ENGINE.CGO" "GAME.CGO")
(require "kernel-defs.gc")

;; DECOMP BEGINS

;; A 4x4 matrix, stored in row-major order
;; some, but not all, functions assume that a matrix is an affine transform.
;; others assume that the rotation has no scale or shear (and that its inverse is its transpose)
(deftype matrix (structure)
  ((vector vector 4 :inline :offset 0)
   (quad   uint128 4 :overlay-at vector)
   (data   float 16 :overlay-at vector))
  (:methods
   (transform-vectors! (_type_ (inline-array vector) (inline-array vector) int) none)))

;; A 3x3 matrix, stored in row-major order.
;; NOTE: the rows each have an extra 4-bytes of padding
;;  so this is really a 3x4 matrix.
;; this type is rarely used
(deftype matrix3 (structure)
  ((data   float 12)
   (vector vector 3 :inline :overlay-at (-> data 0))
   (quad   uint128 3 :overlay-at (-> data 0))))

;; a matrix stored using 16-bit integers.
;; note that these usually have different scaling for the 4th row which
;; contains the translation in an affine transform.
;; so you generally should not unpack these to floats without knowing where they came from
;; and how they were originally packed (for example, in tie/shrub)
(deftype matrix4h (structure)
  ((data     int16 16)
   (vector4h vector4h 4 :inline :overlay-at (-> data 0))
   (long     int64 4 :overlay-at (-> data 0))))

(defun matrix-copy! ((dst matrix) (src matrix))
  "Copy src to dst"
  (let ((v1-0 (-> src vector 0 quad))
        (a2-0 (-> src vector 1 quad))
        (a3-0 (-> src vector 2 quad))
        (a1-1 (-> src vector 3 quad)))
    (set! (-> dst vector 0 quad) v1-0)
    (set! (-> dst vector 1 quad) a2-0)
    (set! (-> dst vector 2 quad) a3-0)
    (set! (-> dst vector 3 quad) a1-1))
  dst)

(defmacro new-stack-matrix0 ()
  "Get a new matrix on the stack that's set to zero."
  `(let ((mat (new 'stack-no-clear 'matrix)))
    (set! (-> mat quad 0) (the-as uint128 0))
    (set! (-> mat quad 1) (the-as uint128 0))
    (set! (-> mat quad 2) (the-as uint128 0))
    (set! (-> mat quad 3) (the-as uint128 0))
    mat))
