Skip to content

Instantly share code, notes, and snippets.

@scythe
Created June 27, 2011 16:02
Show Gist options
  • Save scythe/1049155 to your computer and use it in GitHub Desktop.
Save scythe/1049155 to your computer and use it in GitHub Desktop.
de Casteljau's algorithm in lua metatables
--[[a parametric function describing the Bezier curve determined by given control points,
which takes t from 0 to 1 and returns the x, y of the corresponding point on the Bezier curve]]
function bezier(xv, yv)
local reductor = {__index = function(self, ind)
return setmetatable({tree = self, level = ind}, {__index = function(curves, ind)
return function(t)
local x1, y1 = curves.tree[curves.level-1][ind](t)
local x2, y2 = curves.tree[curves.level-1][ind+1](t)
return x1 + (x2 - x1) * t, y1 + (y2 - y1) * t
end
end})
end
}
local points = {}
for i = 1, #xv do
points[i] = function(t) return xv[i], yv[i] end
end
return setmetatable({points}, reductor)[#points][1]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment