Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An attempt of porting a triangle rasterizer (http://forum.devmaster.net/t/advanced-rasterization/6145) to pico-8
static function trifill(x1:Fixed, y1:Fixed, x2:Fixed, y2:Fixed, x3:Fixed, y3:Fixed) {
var dx12 = x1 - x2;
var dx23 = x2 - x3;
var dx31 = x3 - x1;
//
var dy12 = y1 - y2;
var dy23 = y2 - y3;
var dy31 = y3 - y1;
//
var minx = min(x1, min(x2, x3));
var maxx = max(x1, max(x2, x3));
var miny = min(y1, min(y2, y3));
var maxy = max(y1, max(y2, y3));
//
var c1 = dy12 * x1 - dx12 * y1;
var c2 = dy23 * x2 - dx23 * y2;
var c3 = dy31 * x3 - dx31 * y3;
//
if (dy12 < 0 || (dy12 == 0 && dx12 > 0)) c1 += 1;
if (dy23 < 0 || (dy23 == 0 && dx23 > 0)) c2 += 1;
if (dy31 < 0 || (dy31 == 0 && dx31 > 0)) c3 += 1;
//
var cy1 = c1 + dx12 * miny - dy12 * minx;
var cy2 = c2 + dx23 * miny - dy23 * minx;
var cy3 = c3 + dx31 * miny - dy31 * minx;
//
for (y in flr(miny) ... flr(maxy)) {
var cx1 = cy1;
var cx2 = cy2;
var cx3 = cy3;
for (x in flr(minx) ... flr(maxx)) {
if (cx1 > 0 && cx2 > 0 && cx3 > 0) {
pset(x, y);
}
cx1 -= dy12;
cx2 -= dy23;
cx3 -= dy31;
}
cy1 += dx12;
cy2 += dx23;
cy3 += dx31;
}
}
function trifill(x1, y1, x2, y2, x3, y3)
local dx12 = x1 - x2
local dx23 = x2 - x3
local dx31 = x3 - x1
local dy12 = y1 - y2
local dy23 = y2 - y3
local dy31 = y3 - y1
local minx = min(x1, min(x2, x3))
local maxx = max(x1, max(x2, x3))
local miny = min(y1, min(y2, y3))
local maxy = max(y1, max(y2, y3))
local c1 = dy12 * x1 - dx12 * y1
local c2 = dy23 * x2 - dx23 * y2
local c3 = dy31 * x3 - dx31 * y3
if dy12 < 0 or dy12 == 0 and dx12 > 0 then
c1 += 1
end
if dy23 < 0 or dy23 == 0 and dx23 > 0 then
c2 += 1
end
if dy31 < 0 or dy31 == 0 and dx31 > 0 then
c3 += 1
end
local cy1 = c1 + dx12 * miny - dy12 * minx
local cy2 = c2 + dx23 * miny - dy23 * minx
local cy3 = c3 + dx31 * miny - dy31 * minx
for y = flr(miny), flr(maxy) - 1 do
local cx1 = cy1
local cx2 = cy2
local cx3 = cy3
for x = flr(minx), flr(maxx) - 1 do
if cx1 > 0 and cx2 > 0 and cx3 > 0 then
pset(x, y)
end
cx1 -= dy12
cx2 -= dy23
cx3 -= dy31
end
cy1 += dx12
cy2 += dx23
cy3 += dx31
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment