Debian Codegraph @

texmf-dist/tex/latex/pixelart/pixelart.lua

raw
1 --[[
2 Copyright 2017-2023 Louis Paternault
3
4 This work may be distributed and/or modified under the
5 conditions of the LaTeX Project Public License, either version 1.3
6 of this license or (at your option) any later version.
7 The latest version of this license is in
8 http://www.latex-project.org/lppl.txt
9 and version 1.3 or later is part of all distributions of LaTeX
10 version 2005/12/01 or later.
11
12 This work has the LPPL maintenance status `maintained'.
13
14 The Current Maintainer of this work is Louis Paternault
15
16 This work consists of the files pixelart.sty, pixelart.lua, pixelart.tex.
17 --]]
18
19 require("lualibs-lpeg")
20 local luakeys = require("luakeys")()
21
22 pixelart = {
23 _debug = false,
24 _counter = 0,
25 }
26
27 --------------------------------------------------------------------------------
28 --[[ Debug on/off
29 --]]
30
31 local function pixelart_setpixelartdebug(flag)
32 luakeys.opts.debug = flag
33 pixelart._debug = flag
34 end
35
36 pixelart.setpixelartdebug = pixelart_setpixelartdebug
37
38 --------------------------------------------------------------------------------
39 --[[ Print
40 --]]
41
42 local function tex_sprint(text)
43 tex.sprint(text)
44 if pixelart._debug then
45 io.write(text)
46 end
47 end
48
49 local function tex_print(text)
50 tex.print(text)
51 if pixelart._debug then
52 io.write(text, "\n")
53 end
54 end
55
56 --------------------------------------------------------------------------------
57 --[[ Define and use colors
58 -- ]]
59 pixelart._colors = {}
60
61 local function pixelart_parsecolors(argument)
62 return luakeys.parse(
63 argument,
64 {
65 naked_as_value = true,
66 hooks = {
67 keys = function(key, value, depth, current, result)
68 return tostring(key), value
69 end,
70 }
71 }
72 )
73 end
74
75 local function pixelart_newpixelartcolors(name, argument)
76 if pixelart._colors[name] == nil then
77 pixelart._colors[name] = pixelart_parsecolors(argument)
78 else
79 error(string.format("Error: Colors '%s' is already defined.", name))
80 end
81 end
82
83 local function pixelart_renewpixelartcolors(name, argument)
84 pixelart._colors[name] = pixelart_parsecolors(argument)
85 end
86
87 pixelart.newpixelartcolors = pixelart_newpixelartcolors
88 pixelart.renewpixelartcolors = pixelart_renewpixelartcolors
89
90 -- Default color sets
91 pixelart._colors["explicit"] = {}
92
93 pixelart._colors["RGB"] = {
94 R = "red",
95 G = "green",
96 B = "blue",
97 W = "white",
98 K = "black"
99 }
100
101 pixelart._colors["BW"] = {
102 ["0"] = "white",
103 ["1"] = "black",
104 }
105
106 pixelart._colors["gray"] = {
107 ["0"] = "white",
108 ["1"] = "white!89!black",
109 ["2"] = "white!78!black",
110 ["3"] = "white!67!black",
111 ["4"] = "white!56!black",
112 ["5"] = "white!44!black",
113 ["6"] = "white!33!black",
114 ["7"] = "white!22!black",
115 ["8"] = "white!11!black",
116 ["9"] = "black",
117 }
118
119 pixelart._colors["mono"] = {}
120 for _, char in pairs(string.explode("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "")) do
121 pixelart._colors["mono"][char] = ""
122 end
123
124
125 --------------------------------------------------------------------------------
126 --[[ Options
127 --]]
128
129 local ALGORITHMS = {squares = true, stack = true}
130
131 local function parse(str, default)
132 local parser = luakeys.define({
133 tikz = {},
134 colors = {
135 process = function(value, input, result, unknown)
136 -- If argument is a string, convert numeric keys into strings
137 if type(value) ~= "table" then
138 return value
139 end
140
141 local converted = {}
142 for k, v in pairs(value) do
143 converted[tostring(k)] = v
144 end
145 return converted
146 end,
147 },
148 margin = {
149 data_type = "number",
150 default = 0,
151 always_present = true,
152 },
153 style = {
154 data_type = "string",
155 default = "pixelart",
156 always_present = true,
157 },
158 squares = {
159 exclusive_group = "algo",
160 },
161 stack = {
162 exclusive_group = "algo",
163 },
164 draft = {
165 data_type = "boolean",
166 },
167 })
168
169 options = parser(str, {
170 defaults = default,
171 })
172
173 -- Algo option
174 local algo = nil
175 for key, value in pairs(ALGORITHMS) do
176 if options[key] then
177 algo = key
178 end
179 end
180 if not algo then
181 options[pixelart._default_algo[1]] = pixelart._default_algo[2]
182 end
183
184 -- Convert Tikz option back to string
185 if type(options.tikz) == type({}) then
186 options.tikz = luakeys.render(options.tikz)
187 end
188
189 return options
190 end
191
192 local DEFAULT = {colors = "mono"}
193 local function pixelart_setpixelartdefault(str)
194 pixelart._default = parse(str, DEFAULT)
195
196 for key, value in pairs(pixelart._default) do
197 if ALGORITHMS[key] then
198 pixelart._default_algo = {key, value}
199 pixelart._default[key] = nil
200 end
201 end
202 end
203
204 pixelart._default = {colors = "mono"}
205 pixelart._default_algo = {"stack", {}}
206 pixelart.setpixelartdefault = pixelart_setpixelartdefault
207
208 --------------------------------------------------------------------------------
209 --[[ Parse pixelart string
210 --Parse arguments, and build a table of tables.
211 --]]
212 --
213 local lineRE = lpeg.Ct(
214 -- Regular expression to match a line of colors
215 (
216 (lpeg.P("{") * lpeg.C((lpeg.P(1) - lpeg.S("{}"))^0) * lpeg.P("}"))
217 +
218 lpeg.C((lpeg.P(1) - lpeg.S("{}")))
219 )^0
220 )
221
222 local function str2arrays(str)
223 -- Turn the \pixelart{} argument into a table (of lines) of tables (of colors).
224
225 -- Trim string: remove leading and trailing whitespaces
226 str = str:gsub("^%s*(.-)%s*$", "%1")
227
228 -- Turn it into a table (which is called "array" not to clash with the "table" library)
229 local array = {}
230 for k, line in ipairs(string.explode(str, " ")) do
231 array[k] = lineRE:match(line)
232 end
233
234 -- Ensure each row has the same number of columns
235 local length = 0
236 for k, line in ipairs(array) do
237 if #line > length then
238 length = #line
239 end
240 end
241 for k, line in ipairs(array) do
242 if #line < length then
243 for i=#line+1, length do
244 line[i] = false
245 end
246 end
247 end
248
249 -- Flip array so that flipped[x][y] gives the pixel with coordinates (x, y), in the standard frame
250 local flipped = {}
251 for y, line in ipairs(array) do
252 for x, color in ipairs(array[y]) do
253 if y == 1 then
254 flipped[x] = {}
255 end
256 flipped[x][#array - y + 1] = color
257 end
258 end
259
260 return flipped
261 end
262
263 --------------------------------------------------------------------------------
264 --[[ Color tools
265 --]]
266 local function color2color(colors, color)
267 -- Convert a color (as given by the user) into a color (usable by TikZ).
268 if color == "." or not color then
269 -- Transparent pixel: do not print anything
270 return nil
271 elseif colors[color] and colors[color] ~= "" then
272 -- A color has been defined: use it
273 return string.format("color=%s", colors[color])
274 elseif colors[color] and colors[color] == "" then
275 -- An empty color has been defined: use the default TikZ color
276 return ""
277 else
278 -- No color has been defined: use the argument as the TikZ color
279 return color
280 end
281 end
282
283 --------------------------------------------------------------------------------
284 -- Turn pixelart string into TikZ code, using the SQUARES algorithm
285
286 local function pixelart_body_squares(array, colors, options)
287 -- Draw the tikz pixels, as a set of squares.
288
289 if #array == 0 then
290 -- Empty array
291 return
292 end
293
294 tex_print(string.format(
295 [[\clip ({0-%s}, {0-%s}) rectangle (%s, %s); ]],
296 options.margin,
297 options.margin,
298 #array + options.margin,
299 #array[1] + options.margin
300 ))
301
302 for x, column in ipairs(array) do
303 for y, color in ipairs(column) do
304 color = color2color(colors, color)
305
306 ---------------------
307 -- Which pixel size?
308 local overlap
309 if type(options.squares) == type({}) then
310 overlap = options.squares["overlap"] or "0"
311 else
312 overlap = "0"
313 end
314
315 ---------------------
316 -- At last, we can display the pixel…
317 if color ~= nil then
318 tex_print(string.format([[\fill[%s, %s] (%s, %s) rectangle ++(1+%s, 1+%s);]],
319 options.style,
320 color,
321 string.format("{%s-%s}", x-1, overlap),
322 string.format("{%s-%s}", y-1, overlap),
323 2*overlap,
324 2*overlap
325 ))
326 end
327 end
328 end
329 end
330
331 --------------------------------------------------------------------------------
332 -- Turn pixelart string into TikZ code, using the STACK algorithm
333
334 local function remove_zone(write, coord, read)
335 -- Remove the zone of the pixel `coord`
336 -- If both write and read are present (they are expected to be 2D-arrays of the same size, then read zones from `read`, and remove them from `write`.
337
338 -- Default values for options
339 if read == nil then
340 read = write
341 end
342 if colorblind == nil then
343 colorblind = false
344 end
345
346 local originalcolor = read[coord[1]][coord[2]]
347 local samecolor = function(color) return color == originalcolor end
348
349 -- Go!
350 local stack = {}
351 table.insert(stack, coord)
352 while #stack ~= 0 do
353 local current = table.remove(stack)
354 for _, neighbour in pairs({
355 {current[1]-1, current[2]},
356 {current[1]+1, current[2]},
357 {current[1], current[2]-1},
358 {current[1], current[2]+1},
359 }) do
360 if (
361 neighbour[1] >= 1 and neighbour[1] <= #read -- First coordinate inside the array
362 and
363 neighbour[2] >= 1 and neighbour[2] <= #read[1] -- Second coordinate inside the array
364 and
365 write[neighbour[1]][neighbour[2]] -- Not processed yet
366 and
367 samecolor(read[neighbour[1]][neighbour[2]]) -- Same color
368 ) then
369 table.insert(stack, neighbour)
370 end
371 end
372 write[current[1]][current[2]] = false
373 end
374 end
375
376 local border_transitions = {
377 westtop = {
378 tests = {
379 {1, 1},
380 {1, 0},
381 },
382 next = {
383 ["true true"] = {
384 step = {1, 1},
385 state = "northleft",
386 mark = {0, 0},
387 },
388 ["false true"] = {
389 step = {1, 0},
390 state = "westtop",
391 mark = nil,
392 },
393 ["true false"] = {
394 step = {0, 0},
395 state = "southright",
396 mark = {1, 1},
397 },
398 ["false false"] = {
399 step = {0, 0},
400 state = "southright",
401 mark = {1, 1},
402 },
403 },
404 },
405 northleft = {
406 tests = {
407 {-1, 1},
408 {0, 1},
409 },
410 next = {
411 ["true true"] = {
412 step = {-1, 1},
413 state = "eastbottom",
414 mark = {1, 0},
415 },
416 ["true false"] = {
417 step = {0, 0},
418 state = "westtop",
419 mark = {0, 1},
420 },
421 ["false true"] = {
422 step = {0, 1},
423 state = "northleft",
424 mark = nil,
425 },
426 ["false false"] = {
427 step = {0, 0},
428 state = "westtop",
429 mark = {0, 1},
430 },
431 },
432 },
433 southright = {
434 tests = {
435 {0, -1},
436 {1, -1},
437 },
438 next = {
439 ["true true"] = {
440 step = {1, -1},
441 state = "westtop",
442 mark = {0, 1},
443 },
444 ["false true"] = {
445 step = {0, 0},
446 state = "eastbottom",
447 mark = {1, 0},
448 },
449 ["true false"] = {
450 step = {0, -1},
451 state = "southright",
452 mark = nil,
453 },
454 ["false false"] = {
455 step = {0, 0},
456 state = "eastbottom",
457 mark = {1, 0},
458 },
459 },
460 },
461 eastbottom = {
462 tests = {
463 {-1, 0},
464 {-1, -1},
465 },
466 next = {
467 ["true true"] = {
468 step = {-1, -1},
469 state = "southright",
470 mark = {1, 1},
471 },
472 ["false true"] = {
473 step = {0, 0},
474 state = "northleft",
475 mark = {0, 0},
476 },
477 ["true false"] = {
478 step = {-1, 0},
479 state = "eastbottom",
480 mark = nil,
481 },
482 ["false false"] = {
483 step = {0, 0},
484 state = "northleft",
485 mark = {0, 0},
486 },
487 },
488 },
489 }
490
491 local function iter_border(array, start, colorblind)
492 -- If colorblind==true, all colors are considered the same (that is, a pixel is either transparent or colored, with no difference between the colors)
493 local samecolor
494 if colorblind then
495 samecolor = function(current, test)
496 if (
497 current[1] + test[1] < 1
498 or
499 current[1] + test[1] > #array
500 ) then
501 return false
502 end
503 color = array[current[1] + test[1]][current[2] + test[2]]
504 if color == nil or color == false then
505 return false
506 end
507 return (
508 color == "." and array[start[1]][start[2]] == "."
509 ) or (
510 color ~= "." and array[start[1]][start[2]] ~= "."
511 )
512 end
513 else
514 samecolor = function(current, test)
515 if (
516 current[1] + test[1] < 1
517 or
518 current[1] + test[1] > #array
519 ) then
520 return false
521 end
522 color = array[current[1] + test[1]][current[2] + test[2]]
523 return color == array[start[1]][start[2]]
524 end
525 end
526
527 local current = {start[1], start[2]}
528 local state = "northleft"
529
530 return function()
531 while true do
532 tests = border_transitions[state].tests
533 local transition = border_transitions[state].next[string.format(
534 "%s %s",
535 samecolor(current, tests[1]),
536 samecolor(current, tests[2])
537 )]
538 state = transition.state
539 current = {
540 current[1] + transition.step[1],
541 current[2] + transition.step[2]
542 }
543 if transition.mark then
544 if current[1] == start[1] and current[2] == start[2] and state == "northleft" then
545 return
546 else
547 return {
548 current[1] + transition.mark[1],
549 current[2] + transition.mark[2],
550 }
551 end
552 end
553 end
554 end
555 end
556
557 local function iter_unprocessed_zones(array)
558 -- Iterate coordinates of pixels that haven't been processed yet (their value is not false)
559 local x = 1
560 local y = 1
561
562 return function()
563 while not array[x][y] do
564 x = x + 1
565 if x > #array then
566 x = 1
567 y = y + 1
568 if y > #array[1] then
569 return
570 end
571 end
572 end
573 return {x, y}
574 end
575 end
576
577 local function pixelart_body_stack(array, colors, options)
578 -- The first argument is an array of lines, each of them being an array of colors (i.e. color of the first pixel of the line, color of the second pixel of the line, etc).
579 -- Some "colors" have meaning:
580 -- - false (the boolean): pixel has already been processed
581 -- - "." (the character dot): pixel is transparent
582 -- - anything else: the color of the pixel
583
584 if #array == 0 then
585 return
586 end
587
588 tex_print([[\begin{scope}[even odd rule] ]])
589
590 -- Clip away transparent zones
591 tex_print(string.format(
592 [[\clip ({0-%s}, {0-%s}) rectangle (%s, %s) ]],
593 options.margin,
594 options.margin,
595 #array + options.margin,
596 #array[1] + options.margin
597 ))
598
599 for x = 1, #array do
600 for y = 1, #array[x] do
601 if array[x][y] == "." then
602 tex_print(string.format("(%s, %s) rectangle ++(1, 1) ", x-1, y-1))
603 end
604 end
605 end
606
607 tex_print(";")
608
609 -- Draw color zones
610 for current in iter_unprocessed_zones(array) do
611 local color = color2color(colors, array[current[1]][current[2]])
612 if color == nil then
613 -- Nothing to do: transparent zone
614 else
615 tex_sprint(string.format([[\fill[%s, %s] (%s, %s) ]], options.style, color, current[1]-1, current[2]-1))
616 for coord in iter_border(array, current, false) do
617 tex_sprint(string.format([[ -- (%s, %s) ]], coord[1]-1, coord[2]-1))
618 end
619 tex_print(string.format([[ -- cycle ;]]))
620 end
621 remove_zone(array, {current[1], current[2]})
622 end
623
624 tex_print([[\end{scope} ]])
625 end
626
627 --------------------------------------------------------------------------------
628 -- Functions pixelart() and tikzpixelart()
629
630 local function pixelart_body(str, options)
631 -- Debug
632 pixelart._counter = pixelart._counter + 1
633 if pixelart._debug then
634 io.write("\n%", str, "\n")
635 io.write("% pixelart ", pixelart._counter, ", file ", status.filename, ", input line ", tex.inputlineno, "\n")
636 else
637 io.write("(pixelart ", pixelart._counter, ", file ", status.filename, ", input line ", tex.inputlineno)
638 end
639
640 -- Colors
641 local colors
642 if type(options.colors) == "table" then
643 colors = options.colors
644 else
645 colors = pixelart._colors[options.colors]
646 end
647
648 if (pixelart._draft or options.draft) and options.draft ~= false then
649 local array = str2arrays(str)
650 tex_print(string.format(
651 [[ \draw[pattern=checkerboard] (0, 0) rectangle (%s, %s); ]],
652 #array, #array[1]
653 ))
654 elseif options.stack then
655 pixelart_body_stack(str2arrays(str), colors, options)
656 else -- options.squares is the default
657 pixelart_body_squares(str2arrays(str), colors, options)
658 end
659
660 if pixelart._debug then
661 -- Nothing
662 else
663 io.write(")")
664 end
665 end
666
667 local function pixelart_tikzpixelart(coord, str, options)
668 -- Parse options
669 local options = parse(options, pixelart._default)
670
671 if options.tikz then
672 tex_sprint(string.format([[\begin{scope}[%s] ]], options.tikz))
673 end
674 tex_print(string.format(
675 [[\begin{scope}[shift={%s}] ]],
676 coord
677 ))
678
679 pixelart_body(str, options)
680
681 tex_print([[\end{scope} ]])
682 if options.tikz then
683 tex_print([[\end{scope} ]])
684 end
685 end
686
687 local function pixelart_pixelart(str, options)
688 -- Parse options
689 local options = parse(options, pixelart._default)
690 -- Tikz environment
691 tex_print([[\begin{tikzpicture}]])
692 if options.tikz then
693 tex_sprint(string.format("[%s]", options.tikz))
694 end
695
696 pixelart_body(str, options)
697
698 tex_print([[\end{tikzpicture}]])
699 end
700
701 pixelart.pixelart = pixelart_pixelart
702 pixelart.tikzpixelart = pixelart_tikzpixelart