Skip to content

Instantly share code, notes, and snippets.

@Validark
Created March 19, 2020 17:06
Show Gist options
  • Select an option

  • Save Validark/3e3f32de97b9f1e441ce9ab0c88e3c1b to your computer and use it in GitHub Desktop.

Select an option

Save Validark/3e3f32de97b9f1e441ce9ab0c88e3c1b to your computer and use it in GitHub Desktop.
-- From Wikipedia @https://en.wikipedia.org/wiki/Xiaolin_Wu's_line_algorithm
-- Xiaolin Wu's line algorithm
local StarterGui = game:GetService("StarterGui")
StarterGui:ClearAllChildren()
local Screen = Instance.new("ScreenGui", StarterGui)
local Triangle = Instance.new("Frame", Screen)
Triangle.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Triangle.Size = UDim2.new(1, 0, 1, 0)
local Pixel = Instance.new("Frame")
Pixel.BackgroundColor3 = Color3.fromRGB(255, 0, 0)
Pixel.BorderSizePixel = 0
Pixel.Size = UDim2.new(0, 1, 0, 1)
-- Draws a Circle
local function Plot(x, y, Opacity)
local Point = Pixel:Clone()
Point.Position = UDim2.new(0, x, 0, y)
Point.BackgroundTransparency = 1 - Opacity
Point.Parent = Triangle
end
local abs = math.abs
local floor = math.floor
local function DrawLine(x0, y0, x1, y1)
local steep = abs(y1 - y0) > abs(x1 - x0)
if steep then
x0, y0 = y0, x0
x1, y1 = y1, x1
end
if x0 > x1 then
x0, x1 = x1, x0
y0, y1 = y1, y0
end
local dx = x1 - x0
local dy = y1 - y0
local gradient = dy / dx
if dx == 0.0 then
gradient = 1.0
end
-- handle first endpoint
local xend = floor(x0 + 0.5)
local yend = y0 + gradient * (xend - x0)
local xgap = 1 - (x0 + 0.5) % 1
local xpxl1 = xend -- this will be used in the main loop
local ypxl1 = floor(yend)
if steep then
Plot(ypxl1, xpxl1, (1 - yend % 1) * xgap)
Plot(ypxl1 + 1, xpxl1, yend % 1 * xgap)
else
Plot(xpxl1, ypxl1, (1 - yend % 1) * xgap)
Plot(xpxl1, ypxl1 + 1, yend % 1 * xgap)
end
local intery = yend + gradient -- first y-intersection for the main loop
-- handle second endpoint
xend = floor(x1 + 0.5)
yend = y1 + gradient * (xend - x1)
xgap = (x1 + 0.5) % 1
local xpxl2 = xend -- this will be used in the main loop
local ypxl2 = floor(yend)
if steep then
Plot(ypxl2 , xpxl2, (1 - yend % 1) * xgap)
Plot(ypxl2 + 1, xpxl2, yend % 1 * xgap)
else
Plot(xpxl2, ypxl2, (1 - yend % 1) * xgap)
Plot(xpxl2, ypxl2 + 1, yend % 1 * xgap)
end
-- main loop
if steep then
for x = xpxl1 + 1, xpxl2 - 1 do
Plot(floor(intery) , x, 1 - intery % 1)
Plot(floor(intery) + 1, x, intery % 1)
intery = intery + gradient
end
else
for x = xpxl1 + 1, xpxl2 - 1 do
Plot(x, floor(intery), 1 - intery % 1)
Plot(x, floor(intery) + 1, intery % 1)
intery = intery + gradient
end
end
end
local t1 = tick()
DrawLine(200, 200, 600, 600)
print(tick() - t1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment