From d0916d568a00f5171b96fbc3bfc19ff263affc27 Mon Sep 17 00:00:00 2001 From: ubq323 Date: Fri, 27 Jan 2023 13:43:49 +0000 Subject: coords, hexagons, drawing, chunks --- common/chunk.lua | 30 +++++++++++++++++++ common/coords.lua | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 common/chunk.lua create mode 100644 common/coords.lua (limited to 'common') diff --git a/common/chunk.lua b/common/chunk.lua new file mode 100644 index 0000000..38cdaf0 --- /dev/null +++ b/common/chunk.lua @@ -0,0 +1,30 @@ +local CHUNK_SIZE = 128 + +-- for now tiles shall be booleans + +local function index(offq,offr) + -- indexes start at 0 + -- and go up to (CHUNK_SIZE^2)-1 + assert(0<=offq and 0<=offr and offqdr and dq>ds then + rq = -rr-rs + elseif dr>ds then + rr = -rq-rs + else + rs = -rq-rr + end + + return Hex.make(rq,rr,rs) +end + +function Hex.to_pos(self) + local x = self.q*SR3 + self.r*(SR3/2) + local y = self.r*(3/2) + return Pos.make(x,y) +end + +function Hex.__add(self,other) return Hex.make(self.q+other.q, self.r+other.r, self.s+other.s) end +function Hex.__sub(self,other) return Hex.make(self.q-other.q, self.r-other.r, self.s-other.s) end +function Hex.__tostring(self) return string.format("H(%.2f,%.2f)",self.q,self.r) end + + +Pos = {} +Pos.__index=Pos +function Pos.make(x,y) + return setmetatable({x=x,y=y},Pos) +end +function Pos.__add(self,other) return Pos.make(self.x+other.x,self.y+other.y) end +function Pos.__sub(self,other) return Pos.make(self.x-other.x,self.y-other.y) end +function Pos.__mul(a,b) + if type(a) == "number" then + return Pos.make(a*b.x,a*b.y) + elseif type(b) == "number" then + return Pos.make(a.x*b,a.y*b) + else + error("can only multiply Pos by scalar") + end +end +function Pos.__div(a,b) + assert(type(b) == "number","can only divide Pos by scalar, and can't divide scalar by Pos") + return a*(1/b) +end +function Pos.lensq(self) return self.x^2 + self.y^2 end +function Pos.len(self) return math.sqrt(self:lensq()) end +function Pos.to_hex(self) + local q = self.x*(SR3/3) - self.y*(1/3) + local r = (2/3)*self.y + return Hex.make(q,r,-q-r) +end +function Pos.__tostring(self) return string.format("(%.2f,%.2f)",self.x,self.y) end + + + +return {Hex=Hex,Pos=Pos} + + -- cgit v1.2.3