From 0a3680aa7d1e64a2fc0aff4f5b61673ad7c7486b Mon Sep 17 00:00:00 2001 From: Starbeamrainbowlabs Date: Sat, 26 Jun 2021 16:56:26 +0100 Subject: [PATCH] Vector3: add unit / normalise --- .tests/Vector3/unit.test.lua | 37 ++++++++++++++++++++++++++++ worldeditadditions/utils/vector3.lua | 12 +++++++++ 2 files changed, 49 insertions(+) create mode 100644 .tests/Vector3/unit.test.lua diff --git a/.tests/Vector3/unit.test.lua b/.tests/Vector3/unit.test.lua new file mode 100644 index 0000000..3d3b01d --- /dev/null +++ b/.tests/Vector3/unit.test.lua @@ -0,0 +1,37 @@ +local Vector3 = require("worldeditadditions.utils.vector3") + +-- To find these numbers, in Javascript: +-- function t(x) { return Math.sqrt((x*x)*3); } +-- for(let i = 0; i < 1000000000; i++) { let r = t(i); if(Math.floor(r) === r) console.log(`i ${i}, r ${r}`); } + + +describe("Vector3.unit", function() + it("should work with a positive vector", function() + local a = Vector3.new(10, 10, 10) + assert.are.same( + Vector3.new(57735, 57735, 57735), + a:unit():multiply(100000):floor() + ) + end) + it("should work with a the normalise alias", function() + local a = Vector3.new(10, 10, 10) + assert.are.same( + Vector3.new(57735, 57735, 57735), + a:normalise():multiply(100000):floor() + ) + end) + it("should work with a negative vector", function() + local a = Vector3.new(10, 10, 10) + assert.are.same( + Vector3.new(57735, 57735, 57735), + a:unit():multiply(100000):floor() + ) + end) + it("should work with a mixed vector", function() + local a = Vector3.new(-371635731, 371635731, -371635731) + assert.are.same( + Vector3.new(-57736, 57735, -57736), + a:unit():multiply(100000):floor() + ) + end) +end) diff --git a/worldeditadditions/utils/vector3.lua b/worldeditadditions/utils/vector3.lua index 30771ff..3d4bcc5 100644 --- a/worldeditadditions/utils/vector3.lua +++ b/worldeditadditions/utils/vector3.lua @@ -208,6 +208,18 @@ function Vector3.set_to(a, length) return (a / a:length()) * length end +--- Returns the unit vector of this vector. +-- The unit vector is a vector with a length of 1. +-- Returns a new vector. +-- Does not change the direction of the vector. +-- @param a Vector3 The vector to operate on. +-- @returns Vector3 The unit vector of this vector. +function Vector3.unit(a) + return a / a:length() +end +--- Alias of Vector3.unit. +function Vector3.normalise(a) return a:unit() end + --- Return a vector that is amount distance towards b from a. -- @param a Vector3 The vector to move from.