-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgeometry.lua
72 lines (63 loc) · 1.55 KB
/
geometry.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
local geometry = {}
-- http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
-- rasterize a line and calls fun(x,y) for each point
function geometry.raster_line(x0,y0, x1,y1, fun)
local dx = math.abs(x1-x0)
local dy = math.abs(y1-y0)
if x0 < x1 then sx = 1 else sx = -1 end
if y0 < y1 then sy = 1 else sy = -1 end
local err = dx-dy
while true do
fun(x0,y0)
if x0 == x1 and y0 == y1 then return end
local e2 = 2*err
if e2 > -dy then
err = err - dy
x0 = x0 + sx
end
if x0 == x1 and y0 == y1 then
fun(x0,y0)
return
end
if e2 < dx then
err = err + dx
y0 = y0 + sy
end
end
end
-- result = {x,y,numInLine,x,y,numLine,...} using table.insert
function geometry.raster_line_it(x0,y0, x1,y1, result)
local numInLine = 0
local dx = math.abs(x1-x0)
local dy = math.abs(y1-y0)
if x0 < x1 then sx = 1 else sx = -1 end
if y0 < y1 then sy = 1 else sy = -1 end
local err = dx-dy
while true do
table.insert(result, x0)
table.insert(result, y0)
table.insert(result, numInLine)
numInLine = numInLine + 1
if x0 == x1 and y0 == y1 then return end
local e2 = 2*err
if e2 > -dy then
err = err - dy
x0 = x0 + sx
end
if x0 == x1 and y0 == y1 then
table.insert(result, x0)
table.insert(result, y0)
table.insert(result, numInLine)
numInLine = numInLine + 1
return
end
if e2 < dx then
err = err + dx
y0 = y0 + sy
end
end
end
--~ geometry.raster_line(0,0, 10,0, function(x,y) print(x,y) end)
--~ print("---")
--~ for x,y in geometry.raster_line_it(0,0, 10,0) do print(x,y) end
return geometry