init: tool for graphing functions and slope fields in love2d

This commit is contained in:
Devyn Freet
2026-10-11 23:03:35 -04:00
parent 0bae59383e
commit db61937809
4 changed files with 243 additions and 0 deletions
+56
View File
@@ -0,0 +1,56 @@
local function getPixelPosition(point, minPoint, maxPoint, drawBounds)
if
point[1] < minPoint[1]
or point[1] > maxPoint[1]
or point[2] < minPoint[2]
or point[2] > maxPoint[2]
then
error("Point ("..point[1]..", "..point[2]..") outside the bounds ("
..minPoint[1]..", "..minPoint[2]..") to ("..maxPoint[1]..", "..maxPoint[2]..")")
end
local pointBound = {maxPoint[1] - minPoint[1], maxPoint[2] - minPoint[2]}
local pointOffset = {point[1] - minPoint[1], -point[2] - minPoint[2]}
local position = {
(pointOffset[1] / pointBound[1]) * drawBounds.width + drawBounds.x,
(pointOffset[2] / pointBound[2]) * drawBounds.height + drawBounds.y
}
return position[1], position[2]
end
function GraphFunction(x, y, width, height, func)
local points = {}
local origin = {x = (width + x) / 2, y = (height + y) / 2}
local neg_x, neg_y = -math.floor(origin.x), -math.floor(origin.y)
local pos_x, pos_y = math.floor(origin.x), math.floor(origin.y)
for i = neg_x, pos_x, 1 do
local j = math.floor(func(i))
if j > neg_y and j < pos_y then
local k, l = getPixelPosition({i,j}, {neg_x,neg_y}, {pos_x,pos_y},
{x=x,y=x,width=width,height=height})
table.insert(points, k)
table.insert(points, l)
end
end
return points
end
function GetLineFromSlope(midpoint, slope, length, color)
color = color or {1, 1, 1}
local delta_x, delta_y
if slope == nil then
delta_x, delta_y = 0, length
else
delta_x = math.sqrt((length ^ 2) / (1 + slope ^ 2))
delta_y = -(slope * delta_x)
end
local x1 = midpoint.x - delta_x / 2
local y1 = midpoint.y - delta_y / 2
local x2 = x1 + delta_x
local y2 = y1 + delta_y
return {
p1 = {x = x1, y = y1},
p2 = {x = x2, y = y2},
midpoint = midpoint,
color = color
}
end