From 68f81ace97db0d41b4a51876870c30cebec1338c Mon Sep 17 00:00:00 2001 From: AFCMS Date: Wed, 12 Apr 2023 11:46:26 +0200 Subject: [PATCH] Add `vector.in_area()` utility function (#13390) --- builtin/common/tests/vector_spec.lua | 7 +++++++ builtin/common/vector.lua | 6 ++++++ doc/lua_api.txt | 5 +++++ 3 files changed, 18 insertions(+) diff --git a/builtin/common/tests/vector_spec.lua b/builtin/common/tests/vector_spec.lua index a738e068f..67dbd2d6b 100644 --- a/builtin/common/tests/vector_spec.lua +++ b/builtin/common/tests/vector_spec.lua @@ -462,4 +462,11 @@ describe("vector", function() end end) + + it("in_area()", function() + assert.True(vector.in_area(vector.zero(), vector.new(-10, -10, -10), vector.new(10, 10, 10))) + assert.True(vector.in_area(vector.new(-2, 5, -8), vector.new(-10, -10, -10), vector.new(10, 10, 10))) + assert.True(vector.in_area(vector.new(-10, -10, -10), vector.new(-10, -10, -10), vector.new(10, 10, 10))) + assert.False(vector.in_area(vector.new(-10, -10, -10), vector.new(10, 10, 10), vector.new(-11, -10, -10))) + end) end) diff --git a/builtin/common/vector.lua b/builtin/common/vector.lua index 5ea527708..e2008a9d7 100644 --- a/builtin/common/vector.lua +++ b/builtin/common/vector.lua @@ -369,6 +369,12 @@ function vector.dir_to_rotation(forward, up) return rot end +function vector.in_area(pos, min, max) + return (pos.x >= min.x) and (pos.x <= max.x) and + (pos.y >= min.y) and (pos.y <= max.y) and + (pos.z >= min.z) and (pos.z <= max.z) +end + if rawget(_G, "core") and core.set_read_vector and core.set_push_vector then local function read_vector(v) return v.x, v.y, v.z diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 3e85da2f6..7fd56c9f7 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -3540,6 +3540,11 @@ vectors are written like this: `(x, y, z)`: * Returns a boolean value indicating whether `v` is a real vector, eg. created by a `vector.*` function. * Returns `false` for anything else, including tables like `{x=3,y=1,z=4}`. +* `vector.in_area(pos, min, max)`: + * Returns a boolean value indicating if `pos` is inside area formed by `min` and `max`. + * `min` and `max` are inclusive. + * If `min` is bigger than `max` on some axis, function always returns false. + * You can use `vector.sort` if you have two vectors and don't know which are the minimum and the maximum. For the following functions `x` can be either a vector or a number: