Initial commit

Wed, 04 Nov 2009 01:54:36 +0000

author
Matthew Wild <mwild1@gmail.com>
date
Wed, 04 Nov 2009 01:54:36 +0000
changeset 0
c75ae749adf5
child 1
8724d7c9318e

Initial commit

xpm.lua file | annotate | diff | comparison | revisions
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/xpm.lua	Wed Nov 04 01:54:36 2009 +0000
@@ -0,0 +1,73 @@
+
+module("xpm", package.seeall);
+_M.__index = _M;
+
+function new(width, height, name)
+	return setmetatable({
+			name = name,
+			width = width,
+			height = height,
+			colours = { [false] = true }, ncolours = 1;
+		}, _M);
+end
+
+function setpixel(xpm, x, y, colour)
+	if not xpm[y] then
+		xpm[y] = { [x] = colour };
+	else
+		xpm[y][x] = colour;
+	end
+	if colour and not xpm.colours[colour] then
+		xpm.colours[colour] = true;
+		xpm.ncolours = xpm.ncolours + 1;
+	end
+end
+
+function render(xpm, f)
+	local err;
+	if type(f) == "string" then
+		f = io.open(out, "w+");
+	end
+	if io.type(f) ~= "file" then
+		error("No valid output file", 2);
+	end
+	
+	f:write("/* XPM */\n");
+	f:write("static char * ", name or "xpm", "[] = {\n");
+	f:write(string.format([["%d %d %d %d",]], xpm.width, xpm.height, xpm.ncolours, 1), "\n");
+
+	local colourmap = new_colourmap(xpm.colours);
+
+	for colour in pairs(xpm.colours) do
+		f:write('"', colourmap[colour], "      c ", colour or "None", '",\n');
+	end
+
+	for y=1,xpm.height do
+		if xpm[y] then
+			f:write('"');
+			for x=1,xpm.width do
+				local pixel = xpm[y][x];
+				if pixel then
+					f:write(colourmap[pixel]);
+				else
+					f:write(" ");
+				end
+			end
+			f:write('"', y == xpm.height and "" or ",",'\n');
+		else
+			f:write('"', string.rep(" ", xpm.width), '"', y == xpm.height and "" or ",", '\n');
+		end
+	end
+	f:write("};\n");
+end
+
+function new_colourmap(colours)
+	return setmetatable({ [false] = " ", curr = 35 }, { __index = 
+		function (cm, colour)
+			cm.curr = cm.curr + 1;
+			cm[colour] = string.char(cm.curr);
+			return rawget(cm, colour);
+		end; });
+end
+
+return _M;

mercurial