xpm.lua

changeset 0
c75ae749adf5
child 2
475bf0c54822
equal deleted inserted replaced
-1:000000000000 0:c75ae749adf5
1
2 module("xpm", package.seeall);
3 _M.__index = _M;
4
5 function new(width, height, name)
6 return setmetatable({
7 name = name,
8 width = width,
9 height = height,
10 colours = { [false] = true }, ncolours = 1;
11 }, _M);
12 end
13
14 function setpixel(xpm, x, y, colour)
15 if not xpm[y] then
16 xpm[y] = { [x] = colour };
17 else
18 xpm[y][x] = colour;
19 end
20 if colour and not xpm.colours[colour] then
21 xpm.colours[colour] = true;
22 xpm.ncolours = xpm.ncolours + 1;
23 end
24 end
25
26 function render(xpm, f)
27 local err;
28 if type(f) == "string" then
29 f = io.open(out, "w+");
30 end
31 if io.type(f) ~= "file" then
32 error("No valid output file", 2);
33 end
34
35 f:write("/* XPM */\n");
36 f:write("static char * ", name or "xpm", "[] = {\n");
37 f:write(string.format([["%d %d %d %d",]], xpm.width, xpm.height, xpm.ncolours, 1), "\n");
38
39 local colourmap = new_colourmap(xpm.colours);
40
41 for colour in pairs(xpm.colours) do
42 f:write('"', colourmap[colour], " c ", colour or "None", '",\n');
43 end
44
45 for y=1,xpm.height do
46 if xpm[y] then
47 f:write('"');
48 for x=1,xpm.width do
49 local pixel = xpm[y][x];
50 if pixel then
51 f:write(colourmap[pixel]);
52 else
53 f:write(" ");
54 end
55 end
56 f:write('"', y == xpm.height and "" or ",",'\n');
57 else
58 f:write('"', string.rep(" ", xpm.width), '"', y == xpm.height and "" or ",", '\n');
59 end
60 end
61 f:write("};\n");
62 end
63
64 function new_colourmap(colours)
65 return setmetatable({ [false] = " ", curr = 35 }, { __index =
66 function (cm, colour)
67 cm.curr = cm.curr + 1;
68 cm[colour] = string.char(cm.curr);
69 return rawget(cm, colour);
70 end; });
71 end
72
73 return _M;

mercurial