Created
January 7, 2018 12:15
-
-
Save Caaz/5f693a90441f9abc58ddc12f1e13c665 to your computer and use it in GitHub Desktop.
Rendering polygons in pico-8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- require partials/class.lua | |
class.polygon = class{ | |
new = function(this,args) | |
merge(this,{ | |
points = {}, | |
lines = {} | |
}) | |
merge(this,args) | |
this:rasterize() | |
end, | |
methods = { | |
draw_fill = function(this,x,y,color) | |
this:draw(x,y,color) | |
for l in all(this.lines) do | |
-- debugp(l) | |
line(l[1][1]+x, l[1][2]+y, l[2][1]+x, l[2][2]+y, color) | |
end | |
end, | |
draw = function(this,x,y,color) | |
for i,c in pairs(this.points) do | |
local n = this.points[i+1] | |
if not n then n = this.points[1] end | |
line(c[1]+x,c[2]+y,n[1]+x,n[2]+y,color) | |
end | |
end, | |
rasterize = function(this) | |
this:set_bounds() | |
for x = 0, this.max_x do | |
local drawing_line = false | |
for y = 0, this.max_y do | |
if this:contains(x, y) then | |
if not drawing_line then | |
drawing_line = true | |
this:start_line(x,y) | |
end | |
elseif drawing_line then | |
drawing_line = false | |
this:end_line(x,y) | |
end | |
end | |
if drawing_line then | |
this:end_line(x,this.max_y) | |
end | |
end | |
end, | |
start_line = function(this, x, y) | |
this.lines[#this.lines+1] = {{x,y}} | |
end, | |
end_line = function(this,x,y) | |
this.lines[#this.lines][2] = {x,y} | |
end, | |
contains = function(this,x,y) | |
local out, last_point = false, this.points[#this.points] | |
for i, point in pairs(this.points) do | |
if point[2] < y and last_point[2] >= y or last_point[2] < y and point[2] >= y then | |
if point[1] + (y-point[2]) / (last_point[2] - point[2]) * (last_point[1] - point[1]) < x then | |
out = not out | |
end | |
end | |
last_point = point | |
end | |
return out | |
end, | |
transpose = function(this,x,y) | |
for point in all(this.points) do | |
point[1] += x | |
point[2] += x | |
end | |
end, | |
set_bounds = function(this) | |
local minx, miny = this.points[1][1], this.points[1][2] | |
local maxx, miny = minx, miny | |
for i,c in pairs(this.points) do | |
minx = min(minx,c[1]) | |
maxx = max(maxx,c[1]) | |
miny = min(miny,c[2]) | |
maxy = max(maxy,c[2]) | |
end | |
local adjust, adjustx, adjusty = false, 0,0 | |
if minx != 0 then | |
adjustx = -minx | |
adjust = true | |
end | |
if miny != 0 then | |
adjusty = -miny | |
adjust = true | |
end | |
if adjust then | |
this:transpose(adjustx,adjusty) | |
end | |
this.max_x = maxx+adjustx | |
this.max_y = maxy+adjusty | |
end, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment