Graph Prototype 1 - displays a few graphs in a demo graphing window
This file contains 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
--[[ | |
PUBLIC DOMAIN | |
Where this designation is not recognized, you are | |
permitted to copy, modify, and distribute this code | |
without restriction. | |
Lucien Greathouse | |
(LPGhatguy) | |
]] | |
colors = { | |
{200, 50, 50}, | |
{30, 180, 30}, | |
{50, 50, 200} | |
} | |
setmetatable(colors, { | |
__index = function(self, key) | |
return {255, 255, 255} | |
end | |
}) | |
local render = function(fs, x_range, y_range, canvas_size) | |
local canvas_w, canvas_h = canvas and unpack(canvas_size) | |
canvas_w = canvas_w or 400 | |
canvas_h = canvas_h or 400 | |
local scale_x = canvas_w / (x_range[2] - x_range[1]) | |
local scale_y = canvas_h / (y_range[2] - y_range[1]) | |
local step = 0.05 | |
local canvas = love.graphics.newCanvas(canvas_w, canvas_h) | |
love.graphics.setCanvas(canvas) | |
love.graphics.rectangle("line", 0, 0, canvas_w, canvas_h) | |
love.graphics.scale(1, 1) | |
love.graphics.translate(math.abs(x_range[1]) * scale_x, math.abs(y_range[1]) * scale_y) | |
for index, f in pairs(fs) do | |
love.graphics.setColor(colors[index]) | |
for x = x_range[1], x_range[2], step do | |
love.graphics.line(x * scale_x, -f(x) * scale_y, (x + step) * scale_x, -f(x + step) * scale_y) | |
end | |
end | |
love.graphics.setColor(255, 255, 255) | |
love.graphics.line(0, y_range[2] * scale_y, 0, y_range[1] * scale_y) | |
love.graphics.line(x_range[2] * scale_x, 0, x_range[1] * scale_x, 0) | |
for x = x_range[1], x_range[2] do | |
love.graphics.line(x * scale_x, 4, x * scale_x, -4) | |
love.graphics.print(tostring(x), x * scale_x + 2, 2) | |
end | |
for y = y_range[1], y_range[2] do | |
love.graphics.line(-4, -y * scale_y, 4, -y * scale_y) | |
love.graphics.print(tostring(y), 2, -y * scale_y + 2) | |
end | |
love.graphics.setCanvas() | |
return canvas | |
end | |
local result | |
function love.load() | |
result = render({ | |
function(x) | |
return x^2 | |
end, | |
function(x) | |
return x^3 | |
end, | |
function(x) | |
return math.log(x) | |
end, | |
function(x) | |
return x | |
end | |
}, {-5, 5}, {-5, 5}) | |
end | |
function love.draw() | |
love.graphics.draw(result, 100, 100) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment