Last active
June 27, 2022 22:56
-
-
Save b0mbie/fcd73e30a8c7226fb25279bf8da8f876 to your computer and use it in GitHub Desktop.
Small linear function library. linf stands for linear function
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
| -- | |
| -- linf.lua | |
| -- | |
| -- Written by [aka]bomb, 2022 | |
| -- | |
| -- Permission is hereby granted, free of charge, to any person obtaining a copy of | |
| -- this software and associated documentation files (the "Software"), to deal in | |
| -- the Software without restriction, including without limitation the rights to | |
| -- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies | |
| -- of the Software, and to permit persons to whom the Software is furnished to do | |
| -- so, subject to the following conditions: | |
| -- | |
| -- The above copyright notice and this permission notice shall be included in all | |
| -- copies or substantial portions of the Software. | |
| -- | |
| -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| -- SOFTWARE. | |
| -- | |
| local huge = math.huge | |
| local L = {} | |
| _ENV = L | |
| -- Solve x for y = ax + b: | |
| -- x = (y - b) / a | |
| function linfx(y, a, b) | |
| return (y - b) / a | |
| end | |
| -- Solve ax + b = cx + d: | |
| -- x = (d - b) / (a - c) | |
| -- This x is then plugged into y = ax + b to get y. | |
| function linfintersect(a, b, c, d) | |
| local x = (d - b) / (a - c) | |
| return x, a*x + b | |
| end | |
| -- Get a, b in ax + b to make a line of (x1, y1)->(x2, y2). | |
| -- If a == math.huge, the line is vertical and b is the x offset. | |
| function line(x1, y1, x2, y2) | |
| if x1 == x2 then return huge, x1 end | |
| if x1 > x2 then | |
| -- switch points places if not in x1->x2 order | |
| x1, y1, x2, y2 = x2, y2, x1, y1 | |
| end | |
| local rate = (y2 - y1) / (x2 - x1) | |
| return rate, y1 - rate * x1 | |
| end | |
| local line, linfintersect = line, linfintersect | |
| -- Convenience function to automatically do line(...) and linfintersect(...). | |
| function intersect(x1, y1, x2, y2, x3, y3, x4, y4) | |
| local a, b = line(x1, y1, x2, y2) | |
| return linfintersect(a, b, line(x3, y3, x4, y4)) | |
| end | |
| _ENV = _G | |
| return L |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment