From 9d13e08c63d26b74a4b88084cc91ff2afcc5b02a Mon Sep 17 00:00:00 2001 From: Emmanuel Lepage Vallee Date: Sun, 15 May 2016 23:44:54 -0400 Subject: [PATCH] gears: Add a geometry modules Add an abstract geometry module to `gears` --- lib/gears/geometry.lua | 60 ++++++++++++++++++++++++++++++++++++++++++ lib/gears/init.lua | 1 + 2 files changed, 61 insertions(+) create mode 100644 lib/gears/geometry.lua diff --git a/lib/gears/geometry.lua b/lib/gears/geometry.lua new file mode 100644 index 000000000..b578eea85 --- /dev/null +++ b/lib/gears/geometry.lua @@ -0,0 +1,60 @@ +--------------------------------------------------------------------------- +-- +-- Helper functions used to compute geometries. +-- +-- When this module refer to a geometry table, this assume a table with at least +-- an *x*, *y*, *width* and *height* keys and numeric values. +-- +-- @author Julien Danjou <julien@danjou.info> +-- @copyright 2008 Julien Danjou +-- @release @AWESOME_VERSION@ +-- @module gears.geometry +--------------------------------------------------------------------------- +local math = math + +local gears = {geometry = {rectangle = {} } } + +--- Get the square distance between a rectangle and a point. +-- @tparam table geom A rectangle +-- @tparam number geom.x The horizontal coordinate +-- @tparam number geom.y The vertical coordinate +-- @tparam number geom.width The rectangle width +-- @tparam number geom.height The rectangle height +-- @tparam number x X coordinate of point +-- @tparam number y Y coordinate of point +-- @treturn number The squared distance of the rectangle to the provided point +function gears.geometry.rectangle.get_square_distance(geom, x, y) + local dist_x, dist_y = 0, 0 + if x < geom.x then + dist_x = geom.x - x + elseif x >= geom.x + geom.width then + dist_x = x - geom.x - geom.width + 1 + end + if y < geom.y then + dist_y = geom.y - y + elseif y >= geom.y + geom.height then + dist_y = y - geom.y - geom.height + 1 + end + return dist_x * dist_x + dist_y * dist_y +end + +--- Return the closest rectangle from `list` for a given point. +-- @tparam table list A list of geometry tables. +-- @tparam number x The x coordinate +-- @tparam number y The y coordinate +-- @return The key from the closest geometry. +function gears.geometry.rectangle.get_closest_by_coord(list, x, y) + local dist = math.huge + local ret = nil + + for k, v in pairs(list) do + local d = gears.geometry.rectangle.get_square_distance(v, x, y) + if d < dist then + ret, dist = k, d + end + end + + return ret +end + +return gears.geometry diff --git a/lib/gears/init.lua b/lib/gears/init.lua index 3fe46b448..2d35de36c 100644 --- a/lib/gears/init.lua +++ b/lib/gears/init.lua @@ -19,6 +19,7 @@ return shape = require("gears.shape"); protected_call = require("gears.protected_call"); screen = require("gears.screen"); + geometry = require("gears.geometry"); } -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80