quikbild-cd2025/utils.lua
2024-12-23 12:01:21 -05:00

76 lines
2.7 KiB
Lua

local S = core.get_translator("quikbild")
-- Utility functions
-- Given two positions of an area, returns them so
-- that the first position has the minimum, and the
-- second position has the maximum value.
function quikbild.sort_positions(pos1, pos2)
local ppos1 = table.copy(pos1)
local ppos2 = table.copy(pos2)
local coords = { "x", "y", "z" }
for c=1, #coords do
local coord = coords[c]
if pos1[coord] > pos2[coord] then
ppos1[coord] = pos2[coord]
ppos2[coord] = pos1[coord]
end
end
return ppos1, ppos2
end
-- List of position properties
local posprops = {"artist_spawn_pos", "build_area_pos_1", "build_area_pos_2"}
-- Checks the position properties of the given arena for syntactical validity.
-- Returns true if everything is OK, false otherwise.
-- In case of failure, 2nd return value is localized error message
-- that can be shown to an user
function quikbild.check_positions(arena)
for p=1, #posprops do
local propname = posprops[p]
local prop = arena[propname]
if type(prop) ~= "table" then
return false, S("Invalid arena property '@1': Position is not a table!", propname)
elseif type(prop.x) ~= "number" or type(prop.y) ~= "number" or type(prop.z) ~= "number" then
return false, S("Invalid arena property '@1': Coordinate x, y or z missing or not a number!", propname)
end
end
return true
end
-- Checks whether all positions of the arena position properties
-- are within the arena region, if present.
-- Returns true if they all are in the arena region OR there is no arena region.
-- Returns false otherwise. In case of failure, the 2nd return value
-- is an error message that can be shown to the user.
-- Note: This function assumes the position properties are syntactically valid.
function quikbild.are_positions_in_arena_region(arena)
if not arena.pos1 or not arena.pos2 then
return true
end
local arpos1, arpos2 = quikbild.sort_positions(arena.pos1, arena.pos2)
for p=1, #posprops do
local posprop = posprops[p]
local ppos = arena[posprop]
-- Compare the positions with the arena region
if ppos.x < arpos1.x or ppos.y < arpos1.y or ppos.z < arpos1.z or
ppos.x > arpos2.x or ppos.y > arpos2.y or ppos.z > arpos2.z then
return false, S("Arena position property '@1' is not within the arena region.", posprop)
end
end
return true
end
-- Checks the arena properties of the given arena for
-- validity.
-- Returns true if everything is OK, false otherwise.
-- In case of failure, 2nd return value is localized error message
-- that can be shown to an user
function quikbild.check_arena_properties(arena)
if arena.build_time < 1 then
return false, S("Arena property '@1' cannot be smaller than 1.", "build_time")
end
return quikbild.check_positions(arena)
end