Wed, 27 Oct 2010 14:12:51 +0100
test_mandelbrot.lua: Remove some trailing whitespace
2 | 1 | -- Lua XPM generating library |
2 | -- (C) 2009 Matthew Wild <mwild1@gmail.com> | |
3 | -- Released under the MIT/X11 license | |
0 | 4 | |
5 | module("xpm", package.seeall); | |
6 | _M.__index = _M; | |
7 | ||
8 | function new(width, height, name) | |
9 | return setmetatable({ | |
10 | name = name, | |
11 | width = width, | |
12 | height = height, | |
13 | colours = { [false] = true }, ncolours = 1; | |
14 | }, _M); | |
15 | end | |
16 | ||
17 | function setpixel(xpm, x, y, colour) | |
18 | if not xpm[y] then | |
19 | xpm[y] = { [x] = colour }; | |
20 | else | |
21 | xpm[y][x] = colour; | |
22 | end | |
23 | if colour and not xpm.colours[colour] then | |
24 | xpm.colours[colour] = true; | |
25 | xpm.ncolours = xpm.ncolours + 1; | |
26 | end | |
27 | end | |
28 | ||
29 | function render(xpm, f) | |
30 | local err; | |
31 | if type(f) == "string" then | |
3
7f619444bc2a
Fix wrong variable name preventing saving to filename
Matthew Wild <mwild1@gmail.com>
parents:
2
diff
changeset
|
32 | f = io.open(f, "w+"); |
0 | 33 | end |
34 | if io.type(f) ~= "file" then | |
35 | error("No valid output file", 2); | |
36 | end | |
37 | ||
38 | f:write("/* XPM */\n"); | |
39 | f:write("static char * ", name or "xpm", "[] = {\n"); | |
40 | f:write(string.format([["%d %d %d %d",]], xpm.width, xpm.height, xpm.ncolours, 1), "\n"); | |
41 | ||
42 | local colourmap = new_colourmap(xpm.colours); | |
43 | ||
44 | for colour in pairs(xpm.colours) do | |
45 | f:write('"', colourmap[colour], " c ", colour or "None", '",\n'); | |
46 | end | |
47 | ||
48 | for y=1,xpm.height do | |
49 | if xpm[y] then | |
50 | f:write('"'); | |
51 | for x=1,xpm.width do | |
52 | local pixel = xpm[y][x]; | |
53 | if pixel then | |
54 | f:write(colourmap[pixel]); | |
55 | else | |
56 | f:write(" "); | |
57 | end | |
58 | end | |
59 | f:write('"', y == xpm.height and "" or ",",'\n'); | |
60 | else | |
61 | f:write('"', string.rep(" ", xpm.width), '"', y == xpm.height and "" or ",", '\n'); | |
62 | end | |
63 | end | |
64 | f:write("};\n"); | |
65 | end | |
66 | ||
67 | function new_colourmap(colours) | |
68 | return setmetatable({ [false] = " ", curr = 35 }, { __index = | |
69 | function (cm, colour) | |
70 | cm.curr = cm.curr + 1; | |
71 | cm[colour] = string.char(cm.curr); | |
72 | return rawget(cm, colour); | |
73 | end; }); | |
74 | end | |
75 | ||
76 | return _M; |