Created
December 13, 2012 07:10
-
-
Save leafo/4274688 to your computer and use it in GitHub Desktop.
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
pt_in_box = (px, py, x1, y1, x2, y2) -> | |
if x2 < x1 | |
x1,x2 = x2, x1 | |
if y2 < y1 | |
y1,y2 = y2, y1 | |
not (px < x1 or px > x2 or py < y1 or py > y2) | |
line_intersection = (x1, y1, x2, y2, x3, y3, x4, y4, is_axis=false) -> | |
swap = false | |
if x2 - x1 == 0 | |
x1, y1, x2, y2, x3, y3, x4, y4 = y1, x1, y2, x2, y3, x3, y4, x4 | |
swap = true | |
m = (y2 - y1) / (x2 - x1) | |
a = m * (x3 - x1) + y1 - y3 | |
b = m * (x3 - x4) + y4 - y3 | |
t = a/b | |
if t >= 0 and t <= 1 | |
x = x3 + t * (x4 - x3) | |
y = y3 + t * (y4 - y3) | |
if is_axis or pt_in_box x,y, x1, y1, x2,y2 | |
if swap | |
y, x, t | |
else | |
x, y, t | |
t_for_p = (x1, y1, x2, y2, px, py) -> | |
b = x2 - x1 | |
if b != 0 | |
(px - x1) / b | |
else | |
(py - y1) / (y2 - y1) | |
triangle_weights = (x1, y1, x2, y2, x3, y3, px, py) -> | |
-- vector of axis | |
ax = x1 - x3 | |
ay = y1 - y3 | |
cx1, cy1 = line_intersection px, py, px + ax, py + ay, | |
x1, y1, x2, y2, true | |
cx2, cy2 = line_intersection px, py, px + ax, py + ay, | |
x2, y2, x3, y3, true | |
return nil unless cx1 and cx2 | |
t1 = t_for_p x1, y1, x2, y2, cx1, cy1 -- progress from 1 to 2 | |
t2 = t_for_p x2, y2, x3, y3, cx2, cy2 -- progress from 2 to 3 | |
t3 = t_for_p cx1, cy1, cx2, cy2, px, py -- progress of t1 to t3 | |
a = (1 - t1) * (1 - t3) | |
b = t1 * (1 - t3) + (1 - t2) * t3 | |
c = t2 * t3 | |
a,b,c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment