From 2ac5321bdf0aa1da27b9396473ab9f99cfe9b672 Mon Sep 17 00:00:00 2001 From: bjorn Date: Fri, 5 Jan 2018 22:08:11 -0800 Subject: [PATCH] mat4:reflect; --- modules/mat4.lua | 28 ++++++++++++++++++++++++++++ spec/mat4_spec.lua | 10 ++++++++++ 2 files changed, 38 insertions(+) diff --git a/modules/mat4.lua b/modules/mat4.lua index 98db3fd..7db4c5a 100644 --- a/modules/mat4.lua +++ b/modules/mat4.lua @@ -491,6 +491,34 @@ function mat4.shear(out, a, yx, zx, xy, zy, xz, yz) return out:mul(tmp, a) end +--- Reflect a matrix across a plane. +-- @tparam mat4 Matrix to store the result +-- @tparam a Matrix to reflect +-- @tparam vec3 position A point on the plane +-- @tparam vec3 normal The (normalized!) normal vector of the plane +function mat4.reflect(out, a, position, normal) + local nx, ny, nz = normal:unpack() + local d = -position:dot(normal) + tmp[1] = 1 - 2 * nx ^ 2 + tmp[2] = 2 * nx * ny + tmp[3] = -2 * nx * nz + tmp[4] = 0 + tmp[5] = -2 * nx * ny + tmp[6] = 1 - 2 * ny ^ 2 + tmp[7] = -2 * ny * nz + tmp[8] = 0 + tmp[9] = -2 * nx * nz + tmp[10] = -2 * ny * nz + tmp[11] = 1 - 2 * nz ^ 2 + tmp[12] = 0 + tmp[13] = -2 * nx * d + tmp[14] = -2 * ny * d + tmp[15] = -2 * nz * d + tmp[16] = 1 + + return out:mul(tmp, a) +end + --- Transform matrix to look at a point. -- @tparam mat4 out Matrix to store result -- @tparam mat4 a Matrix to transform diff --git a/spec/mat4_spec.lua b/spec/mat4_spec.lua index 201d4b1..19b0fff 100644 --- a/spec/mat4_spec.lua +++ b/spec/mat4_spec.lua @@ -261,6 +261,16 @@ describe("mat4:", function() assert.is.equal(-1, a[10]) end) + it("reflects a matrix along a plane", function() + local origin = vec3(5, 1, 0) + local normal = vec3(0, -1, 0):normalize() + local a = mat4():reflect(mat4(), origin, normal) + local p = a * vec3(-5, 2, 5) + assert.is.equal(p.x, -5) + assert.is.equal(p.y, 0) + assert.is.equal(p.z, 5) + end) + it("projects a matrix into screen space", function() local v = vec3(0, 0, 10) local a = mat4()