go-gl / mathgl

A pure Go 3D math library.
BSD 3-Clause "New" or "Revised" License
554 stars 65 forks source link

Matrix view methods #10

Closed UserAB1236872 closed 10 years ago

UserAB1236872 commented 10 years ago

I got a proposal via email for methods that are essentially Matrix views. These go along with Issue #9 for adding Swizzle operators. A sample of the methods would be:

func (mat Mat4f) Row(index int) Vec4f {
    return Vec4f{mat[index], mat[index+4], mat[index+8], mat[index+12]}
}

func (mat Mat4f) Col(index int) Vec4f {
    return Vec4f{mat[index*4], mat[index*4+1], mat[index*4+2], mat[index*4+3]}
}

// Could be multiple return values
func (mat Mat4f) Rows() [4]Vec4f {
     // return an array matching calling Row on indices 0-4
}

func (mat *Mat4f) SetRow(index int, row Vec4f) {
     mat[index], mat[index+4], mat[index+8], mat[index+12] = row[0], row[1], row[2], row[3]
}

Another possible good method that's missing is an At function for matrices. Currently you have to do the array access yourself, but it would be nice to have a wrapper function for that

func (mat Mat4f) At(row, col int) float32 {
    return mat[col*4+row]
}

func (mat *Mat4f) Set(row, col int, val float32) {
    mat[col*4+row] = val
}

Finally, a Swap method of some sort could be nice for rows and columns

func (mat *Mat4f) SwapRows(r1, r2 int) {
    // Do the essentially the same work as v1,v2 := mat.Row(1), mat.Row(2)
    // mat.SetRow(r2, v1); mat.SetRow(r1, v2)
}

Along with the proposed Swizzle operators, this should allow for fairly sophisticated matrix and vector manipulation.

UserAB1236872 commented 10 years ago

I added everything except Set[Row|Col] and Swap[Rows/Cols]. The swap functions (along with scale, etc) may be added later if we need to do, e.g., gaussian elimination. Right now anyone that needs it can write it themselves or construct elementary matrices (we already provide Scale matrices, for instance).