feat(gui): draw windowed apps through a batched SDL2 surface

Compiled programs could only write to the terminal, so the demo editor had no
real window. When CMake finds SDL2 the runtime now exposes a `gui` table and
Demo/guipaint.lua builds a 960x640 editor on top of it.

Frames are collected in Lua, merged into horizontal runs and sent with a single
`gui.rects` call: a full scene goes from 15071 draw calls and 42.9 ms per frame
to 1522 calls and 2.1 ms, and the rendered screenshot stays pixel-identical.
This commit is contained in:
BlackAngelTV committed 2026-11-18 10:18:44 +01:00
1 parent 0fc96b243a
commit 9587d1ed49
11 files changed
+1840 -9

No files matched your search

+16
View File
@@ -43,6 +43,22 @@ endif()
set(LUACPP_RUNTIME_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include")
set(LUACPP_LUA_CFLAGS "${_lua_cflags}")
set(LUACPP_LUA_LIBS "${_lua_libs}")
# --- optional GUI backend -----------------------------------------------------
# Programs compiled with `luacpp run` get a global `gui` table (window, drawing
# primitives, events) when SDL2 is available. Without SDL2 nothing changes.
pkg_check_modules(SDL2 QUIET sdl2)
if(SDL2_FOUND)
execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --cflags sdl2
OUTPUT_VARIABLE _sdl_cflags OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --libs sdl2
OUTPUT_VARIABLE _sdl_libs OUTPUT_STRIP_TRAILING_WHITESPACE)
set(LUACPP_GUI_FLAGS "-DLUACPP_HAS_GUI=1 ${_sdl_cflags} ${_sdl_libs}")
message(STATUS "luacpp: SDL2 found, compiled programs get the 'gui' API")
else()
set(LUACPP_GUI_FLAGS "")
message(STATUS "luacpp: SDL2 not found, the 'gui' API is disabled")
endif()
configure_file(cmake/luacpp-config.hpp.in
"${CMAKE_CURRENT_BINARY_DIR}/generated/luacpp-config.hpp" @ONLY)
+139
View File
@@ -0,0 +1,139 @@
-- 5x7 bitmap font drawn with filled rectangles, so a compiled Lua program can
-- label its interface without linking any font library.
local M = {}
local GLYPH_WIDTH = 5
local GLYPH_HEIGHT = 7
local SPACING = 1
local GLYPHS = {
[" "] = { "00000", "00000", "00000", "00000", "00000", "00000", "00000" },
["A"] = { "01110", "10001", "10001", "11111", "10001", "10001", "10001" },
["B"] = { "11110", "10001", "10001", "11110", "10001", "10001", "11110" },
["C"] = { "01110", "10001", "10000", "10000", "10000", "10001", "01110" },
["D"] = { "11110", "10001", "10001", "10001", "10001", "10001", "11110" },
["E"] = { "11111", "10000", "10000", "11110", "10000", "10000", "11111" },
["F"] = { "11111", "10000", "10000", "11110", "10000", "10000", "10000" },
["G"] = { "01110", "10001", "10000", "10111", "10001", "10001", "01111" },
["H"] = { "10001", "10001", "10001", "11111", "10001", "10001", "10001" },
["I"] = { "01110", "00100", "00100", "00100", "00100", "00100", "01110" },
["J"] = { "00111", "00010", "00010", "00010", "00010", "10010", "01100" },
["K"] = { "10001", "10010", "10100", "11000", "10100", "10010", "10001" },
["L"] = { "10000", "10000", "10000", "10000", "10000", "10000", "11111" },
["M"] = { "10001", "11011", "10101", "10101", "10001", "10001", "10001" },
["N"] = { "10001", "11001", "10101", "10011", "10001", "10001", "10001" },
["O"] = { "01110", "10001", "10001", "10001", "10001", "10001", "01110" },
["P"] = { "11110", "10001", "10001", "11110", "10000", "10000", "10000" },
["Q"] = { "01110", "10001", "10001", "10001", "10101", "10010", "01101" },
["R"] = { "11110", "10001", "10001", "11110", "10100", "10010", "10001" },
["S"] = { "01111", "10000", "10000", "01110", "00001", "00001", "11110" },
["T"] = { "11111", "00100", "00100", "00100", "00100", "00100", "00100" },
["U"] = { "10001", "10001", "10001", "10001", "10001", "10001", "01110" },
["V"] = { "10001", "10001", "10001", "10001", "10001", "01010", "00100" },
["W"] = { "10001", "10001", "10001", "10101", "10101", "11011", "10001" },
["X"] = { "10001", "10001", "01010", "00100", "01010", "10001", "10001" },
["Y"] = { "10001", "10001", "01010", "00100", "00100", "00100", "00100" },
["Z"] = { "11111", "00001", "00010", "00100", "01000", "10000", "11111" },
["0"] = { "01110", "10001", "10011", "10101", "11001", "10001", "01110" },
["1"] = { "00100", "01100", "00100", "00100", "00100", "00100", "01110" },
["2"] = { "01110", "10001", "00001", "00010", "00100", "01000", "11111" },
["3"] = { "11111", "00010", "00100", "00010", "00001", "10001", "01110" },
["4"] = { "00010", "00110", "01010", "10010", "11111", "00010", "00010" },
["5"] = { "11111", "10000", "11110", "00001", "00001", "10001", "01110" },
["6"] = { "00110", "01000", "10000", "11110", "10001", "10001", "01110" },
["7"] = { "11111", "00001", "00010", "00100", "01000", "01000", "01000" },
["8"] = { "01110", "10001", "10001", "01110", "10001", "10001", "01110" },
["9"] = { "01110", "10001", "10001", "01111", "00001", "00010", "01100" },
[":"] = { "00000", "00100", "00100", "00000", "00100", "00100", "00000" },
["."] = { "00000", "00000", "00000", "00000", "00000", "00100", "00100" },
[","] = { "00000", "00000", "00000", "00000", "00100", "00100", "01000" },
["-"] = { "00000", "00000", "00000", "11111", "00000", "00000", "00000" },
["/"] = { "00001", "00010", "00010", "00100", "01000", "01000", "10000" },
["("] = { "00010", "00100", "01000", "01000", "01000", "00100", "00010" },
[")"] = { "01000", "00100", "00010", "00010", "00010", "00100", "01000" },
["%"] = { "11001", "11010", "00010", "00100", "01000", "01011", "10011" },
["#"] = { "01010", "01010", "11111", "01010", "11111", "01010", "01010" },
["!"] = { "00100", "00100", "00100", "00100", "00100", "00000", "00100" },
["?"] = { "01110", "10001", "00001", "00010", "00100", "00000", "00100" },
["+"] = { "00000", "00100", "00100", "11111", "00100", "00100", "00000" },
["="] = { "00000", "00000", "11111", "00000", "11111", "00000", "00000" },
["'"] = { "00100", "00100", "00000", "00000", "00000", "00000", "00000" },
["<"] = { "00010", "00100", "01000", "10000", "01000", "00100", "00010" },
[">"] = { "01000", "00100", "00010", "00001", "00010", "00100", "01000" },
["*"] = { "00000", "10101", "01110", "11111", "01110", "10101", "00000" },
["|"] = { "00100", "00100", "00100", "00100", "00100", "00100", "00100" },
}
-- Compile every glyph into horizontal pixel runs once, so drawing a label
-- does not rescan its bitmap strings on every frame.
local function compile_glyph(rows)
local compiled = {}
for index = 1, GLYPH_HEIGHT do
local line = rows[index]
local runs = {}
local column = 1
while column <= GLYPH_WIDTH do
if string.sub(line, column, column) == "1" then
local run_end = column
while run_end < GLYPH_WIDTH and string.sub(line, run_end + 1, run_end + 1) == "1" do
run_end = run_end + 1
end
runs[#runs + 1] = column - 1
runs[#runs + 1] = run_end - column + 1
column = run_end + 1
else
column = column + 1
end
end
compiled[index] = runs
end
return compiled
end
for character, rows in pairs(GLYPHS) do
GLYPHS[character] = compile_glyph(rows)
end
M.glyph_width = GLYPH_WIDTH
M.glyph_height = GLYPH_HEIGHT
M.spacing = SPACING
function M.width(text, scale)
local factor = scale or 1
if text == nil or #text == 0 then
return 0
end
return (#text * (GLYPH_WIDTH + SPACING) - SPACING) * factor
end
function M.height(scale)
return GLYPH_HEIGHT * (scale or 1)
end
-- Draws uppercase ASCII text with one rectangle per horizontal run of pixels.
function M.draw(surface, x, y, text, r, g, b, scale)
if text == nil or surface == nil then
return 0
end
local factor = scale or 1
local upper = string.upper(text)
local cursor = x
local drawn = 0
for index = 1, #upper do
local glyph = GLYPHS[string.sub(upper, index, index)]
if glyph ~= nil then
for row = 1, GLYPH_HEIGHT do
local runs = glyph[row]
local row_y = y + (row - 1) * factor
for run = 1, #runs, 2 do
surface.rect(cursor + runs[run] * factor, row_y, runs[run + 1] * factor, factor, r, g, b)
drawn = drawn + 1
end
end
end
cursor = cursor + (GLYPH_WIDTH + SPACING) * factor
end
return drawn
end
return M
+603
View File
@@ -0,0 +1,603 @@
-- Windowed paint application: layout, mouse tools, keyboard shortcuts and
-- rendering. The `gui` global only provides a window and rectangles, so every
-- piece of application logic lives here and can be tested without a window.
local canvas_module = require("paint.canvas")
local palette = require("paint.palette")
local font = require("gui.font")
local M = {}
local App = {}
App.__index = App
M.tools = { "CRAYON", "LIGNE", "RECT", "ELLIPSE", "REMPLIR", "GOMME" }
local THEME = {
background = { 24, 26, 32 },
panel = { 38, 42, 50 },
button = { 52, 58, 68 },
text = { 228, 231, 238 },
muted = { 138, 146, 158 },
accent = { 64, 160, 240 },
accent_text = { 10, 14, 20 },
canvas = { 18, 20, 26 },
cursor = { 250, 250, 250 },
status = { 30, 34, 42 },
}
local WINDOW_WIDTH = 960
local WINDOW_HEIGHT = 640
local TOOLBAR_HEIGHT = 60
local PALETTE_HEIGHT = 28
local STATUS_HEIGHT = 28
local CELL_SIZE = 6
local function inside(rectangle, x, y)
return x >= rectangle.x and x < rectangle.x + rectangle.w
and y >= rectangle.y and y < rectangle.y + rectangle.h
end
function M.new(options)
options = options or {}
local width = options.width or WINDOW_WIDTH
local height = options.height or WINDOW_HEIGHT
local cell = options.cell_size or CELL_SIZE
local canvas_top = TOOLBAR_HEIGHT + PALETTE_HEIGHT
local canvas_pixels = height - canvas_top - STATUS_HEIGHT
local app = setmetatable({
surface = options.surface or gui,
width = width,
height = height,
cell_size = cell,
canvas_top = canvas_top,
status_top = height - STATUS_HEIGHT,
canvas = canvas_module.new(math.floor(width / cell), math.floor(canvas_pixels / cell)),
tool = 1,
slot = options.slot or palette.default_slot,
filled = false,
stroke = false,
last_x = nil,
last_y = nil,
anchor_x = nil,
anchor_y = nil,
cursor_x = 1,
cursor_y = 1,
cursor_in_canvas = false,
erase_button = false,
message = "CLIC POUR DESSINER - 1-6 OUTILS - Q QUITTER",
tool_buttons = {},
action_buttons = {},
swatches = {},
}, App)
for index = 1, #M.tools do
app.tool_buttons[index] = { x = 8 + (index - 1) * 92, y = 8, w = 86, h = 36, tool = index }
end
app.action_buttons = {
{ x = 568, y = 8, w = 80, h = 36, action = "undo", label = "UNDO" },
{ x = 652, y = 8, w = 80, h = 36, action = "clear", label = "CLEAR" },
{ x = 736, y = 8, w = 80, h = 36, action = "save", label = "SAVE" },
{ x = 820, y = 8, w = 80, h = 36, action = "quit", label = "QUIT" },
}
for index = 1, palette.count() do
app.swatches[index] = { x = 8 + (index - 1) * 30, y = 62, w = 26, h = 22, slot = index }
end
return app
end
function App:tool_name()
return M.tools[self.tool]
end
function App:colour_index()
if self.tool == 6 then
return 0
end
return palette.index_of_slot(self.slot)
end
function App:cell_at(x, y)
if y < self.canvas_top or y >= self.status_top then
return nil
end
local column = math.floor(x / self.cell_size) + 1
local row = math.floor((y - self.canvas_top) / self.cell_size) + 1
if column < 1 or row < 1 or column > self.canvas.width or row > self.canvas.height then
return nil
end
return column, row
end
function App:set_tool(index)
if index >= 1 and index <= #M.tools then
self.tool = index
self.anchor_x = nil
self.anchor_y = nil
self.message = "OUTIL " .. M.tools[index]
return "tool"
end
return nil
end
function App:cycle_colour(step)
if step > 0 then
self.slot = palette.next_slot(self.slot)
else
self.slot = palette.previous_slot(self.slot)
end
self.message = "COULEUR " .. string.upper(palette.label(self.slot))
return "colour"
end
function App:undo()
if self.canvas:undo() then
self.message = "ANNULE"
else
self.message = "RIEN A ANNULER"
end
return "undo"
end
function App:clear()
self.canvas:push_history()
self.canvas:clear()
self.message = "TOILE VIDE"
return "clear"
end
function App:save(path)
local name = path or "guipaint.ppm"
local handle = io.open(name, "wb")
if handle == nil then
self.message = "ECRITURE IMPOSSIBLE"
return false
end
local width, height = self.canvas.width, self.canvas.height
handle:write(string.format("P6\n%d %d\n255\n", width, height))
local chunks = {}
for row = 1, height do
for column = 1, width do
local rgb = palette.rgb_of(self.canvas:get(column, row))
chunks[#chunks + 1] = string.char(rgb[1], rgb[2], rgb[3])
end
end
handle:write(table.concat(chunks))
handle:close()
self.message = "ECRIT " .. string.upper(name)
return true
end
function App:preview_canvas()
if self.anchor_x == nil then
return nil
end
local scratch = canvas_module.new(self.canvas.width, self.canvas.height)
local colour = self:colour_index()
if colour == 0 then
colour = 1
end
if self.tool == 2 then
scratch:line(self.anchor_x, self.anchor_y, self.cursor_x, self.cursor_y, colour)
elseif self.tool == 3 then
scratch:rect(self.anchor_x, self.anchor_y, self.cursor_x, self.cursor_y, colour, self.filled)
elseif self.tool == 4 then
scratch:ellipse(self.anchor_x, self.anchor_y,
math.abs(self.cursor_x - self.anchor_x), math.abs(self.cursor_y - self.anchor_y),
colour, self.filled)
end
return scratch
end
function App:press(x, y, button)
if y < TOOLBAR_HEIGHT then
for index = 1, #self.tool_buttons do
if inside(self.tool_buttons[index], x, y) then
return self:set_tool(self.tool_buttons[index].tool)
end
end
for index = 1, #self.action_buttons do
local button_rect = self.action_buttons[index]
if inside(button_rect, x, y) then
if button_rect.action == "undo" then
return self:undo()
elseif button_rect.action == "clear" then
return self:clear()
elseif button_rect.action == "save" then
self:save()
return "save"
else
return "quit"
end
end
end
return nil
end
if y < self.canvas_top then
for index = 1, #self.swatches do
if inside(self.swatches[index], x, y) then
self.slot = self.swatches[index].slot
self.message = "COULEUR " .. string.upper(palette.label(self.slot))
return "colour"
end
end
return nil
end
local column, row = self:cell_at(x, y)
if column == nil then
return nil
end
if button == 3 then
self.tool = 6
self.erase_button = true
end
self.cursor_x, self.cursor_y = column, row
self.cursor_in_canvas = true
self.canvas:push_history()
self.stroke = true
self.last_x, self.last_y = column, row
local colour = self:colour_index()
if self.tool == 5 then
local painted = self.canvas:fill(column, row, colour)
self.message = string.format("REMPLI %d CASES", painted)
self.stroke = false
elseif self.tool == 1 or self.tool == 6 then
self.canvas:set(column, row, colour)
else
self.anchor_x, self.anchor_y = column, row
end
return "draw"
end
function App:motion(x, y)
local column, row = self:cell_at(x, y)
if column == nil then
self.cursor_in_canvas = false
return nil
end
self.cursor_in_canvas = true
self.cursor_x, self.cursor_y = column, row
if not self.stroke or self.anchor_x ~= nil then
return "move"
end
if self.tool == 1 or self.tool == 6 then
if self.last_x ~= nil then
self.canvas:line(self.last_x, self.last_y, column, row, self:colour_index())
end
self.last_x, self.last_y = column, row
end
return "move"
end
function App:release(x, y, button)
local column, row = self:cell_at(x, y)
if column ~= nil then
self.cursor_x, self.cursor_y = column, row
end
if not self.stroke then
return nil
end
if self.anchor_x ~= nil then
local colour = self:colour_index()
local target_x = column or self.cursor_x
local target_y = row or self.cursor_y
if self.tool == 2 then
self.canvas:line(self.anchor_x, self.anchor_y, target_x, target_y, colour)
elseif self.tool == 3 then
self.canvas:rect(self.anchor_x, self.anchor_y, target_x, target_y, colour, self.filled)
elseif self.tool == 4 then
self.canvas:ellipse(self.anchor_x, self.anchor_y,
math.abs(target_x - self.anchor_x), math.abs(target_y - self.anchor_y),
colour, self.filled)
end
self.anchor_x, self.anchor_y = nil, nil
end
self.stroke = false
self.last_x, self.last_y = nil, nil
if self.erase_button then
self.erase_button = false
self.tool = 1
end
return "commit"
end
function App:key(key)
if key == "escape" or key == "q" then
return "quit"
end
if key == "u" then
return self:undo()
end
if key == "c" then
return self:clear()
end
if key == "s" then
self:save()
return "save"
end
if key == "f" then
self.filled = not self.filled
if self.filled then
self.message = "FORMES PLEINES"
else
self.message = "FORMES VIDES"
end
return "mode"
end
if key == "p" then
return self:cycle_colour(1)
end
if key == "m" then
return self:cycle_colour(-1)
end
local number = tonumber(key)
if number ~= nil then
return self:set_tool(number)
end
return nil
end
function App:handle(event)
if event == nil then
return nil
end
local kind = event.type
if kind == "quit" then
return "quit"
end
if kind == "keydown" then
if event["repeat"] then
return nil
end
return self:key(event.key)
end
if kind == "mousedown" then
return self:press(event.x, event.y, event.button)
end
if kind == "mousemove" then
return self:motion(event.x, event.y)
end
if kind == "mouseup" then
return self:release(event.x, event.y, event.button)
end
return nil
end
-- Every drawing primitive is collected in a flat array (x, y, w, h, r, g, b)
-- and handed to the window in one native call: one Lua->C crossing per frame
-- instead of thousands.
-- Plain functions on purpose: the font and the window both draw through a
-- three-argument `rect(x, y, w, h, r, g, b)` surface, so the collector must look
-- exactly like one.
local function new_recorder()
local recorder = { flat = {}, n = 0, background = { 0, 0, 0 } }
function recorder.clear(r, g, b)
local background = recorder.background
background[1], background[2], background[3] = r, g, b
recorder.n = 0
end
function recorder.rect(x, y, w, h, r, g, b)
if w <= 0 or h <= 0 then
return
end
local flat = recorder.flat
local next_index = recorder.n + 1
flat[next_index], flat[next_index + 1], flat[next_index + 2], flat[next_index + 3] = x, y, w, h
flat[next_index + 4], flat[next_index + 5], flat[next_index + 6] = r, g, b
recorder.n = next_index + 6
end
return recorder
end
local function flush(surface, recorder)
local background = recorder.background
surface.clear(background[1], background[2], background[3])
local count = recorder.n
if count == 0 then
return 0
end
local flat = recorder.flat
if type(surface.rects) == "function" then
surface.rects(flat, count)
return count // 7
end
local rect = surface.rect
for index = 1, count, 7 do
rect(surface, flat[index], flat[index + 1], flat[index + 2], flat[index + 3],
flat[index + 4], flat[index + 5], flat[index + 6])
end
return count // 7
end
-- Painted cells are cached as horizontal runs: a uniform row costs one
-- rectangle instead of one per cell, and the list is only rebuilt when the
-- canvas changed (its version counter moved).
function App:canvas_runs()
local canvas = self.canvas
if self.runs_version == canvas.version then
return self.runs, self.runs_count
end
local runs = self.runs or {}
local count = 0
local cells = canvas.cells
local width = canvas.width
local size = self.cell_size
local top = self.canvas_top
local rgb_cache = self.rgb_cache
if rgb_cache == nil then
rgb_cache = {}
self.rgb_cache = rgb_cache
end
for row = 1, canvas.height do
local base = (row - 1) * width
local y = top + (row - 1) * size
local column = 1
while column <= width do
local colour = cells[base + column]
local run_end = column + 1
while run_end <= width and cells[base + run_end] == colour do
run_end = run_end + 1
end
if colour ~= 0 then
local rgb = rgb_cache[colour]
if rgb == nil then
rgb = palette.rgb_of(colour)
rgb_cache[colour] = rgb
end
count = count + 7
runs[count - 6] = (column - 1) * size
runs[count - 5] = y
runs[count - 4] = (run_end - column) * size
runs[count - 3] = size
runs[count - 2] = rgb[1]
runs[count - 1] = rgb[2]
runs[count] = rgb[3]
end
column = run_end
end
end
self.runs = runs
self.runs_count = count
self.runs_version = canvas.version
return runs, count
end
-- Painted cell count, cached until the canvas changes again: the status bar
-- asks for it on every frame.
function App:painted()
local canvas = self.canvas
if self.painted_version ~= canvas.version then
self.painted_count = canvas:count()
self.painted_version = canvas.version
end
return self.painted_count
end
function App:render()
local surface = self.surface
if surface == nil then
return 0
end
local recorder = self.recorder
if recorder == nil then
recorder = new_recorder()
self.recorder = recorder
end
local drawn = 0
recorder.clear(THEME.background[1], THEME.background[2], THEME.background[3])
recorder.rect(0, 0, self.width, TOOLBAR_HEIGHT, THEME.panel[1], THEME.panel[2], THEME.panel[3])
for index = 1, #self.tool_buttons do
local button = self.tool_buttons[index]
local selected = index == self.tool
local r, g, b = THEME.button[1], THEME.button[2], THEME.button[3]
local text_r, text_g, text_b = THEME.text[1], THEME.text[2], THEME.text[3]
if selected then
r, g, b = THEME.accent[1], THEME.accent[2], THEME.accent[3]
text_r, text_g, text_b = THEME.accent_text[1], THEME.accent_text[2], THEME.accent_text[3]
end
recorder.rect(button.x, button.y, button.w, button.h, r, g, b)
local label = M.tools[index]
local text_x = button.x + math.floor((button.w - font.width(label, 2)) / 2)
local text_y = button.y + math.floor((button.h - font.height(2)) / 2)
drawn = drawn + font.draw(recorder, text_x, text_y, label, text_r, text_g, text_b, 2)
end
for index = 1, #self.action_buttons do
local button = self.action_buttons[index]
recorder.rect(button.x, button.y, button.w, button.h, THEME.button[1], THEME.button[2], THEME.button[3])
local text_x = button.x + math.floor((button.w - font.width(button.label, 1)) / 2)
local text_y = button.y + math.floor((button.h - font.height(1)) / 2)
drawn = drawn + font.draw(recorder, text_x, text_y, button.label,
THEME.text[1], THEME.text[2], THEME.text[3], 1)
end
recorder.rect(0, TOOLBAR_HEIGHT, self.width, PALETTE_HEIGHT,
THEME.panel[1], THEME.panel[2], THEME.panel[3])
for index = 1, #self.swatches do
local swatch = self.swatches[index]
local rgb = palette.entries[index].rgb
recorder.rect(swatch.x, swatch.y, swatch.w, swatch.h, rgb[1], rgb[2], rgb[3])
if index == self.slot then
recorder.rect(swatch.x - 2, swatch.y - 2, swatch.w + 4, 2, 250, 250, 250)
recorder.rect(swatch.x - 2, swatch.y + swatch.h, swatch.w + 4, 2, 250, 250, 250)
recorder.rect(swatch.x - 2, swatch.y - 2, 2, swatch.h + 4, 250, 250, 250)
recorder.rect(swatch.x + swatch.w, swatch.y - 2, 2, swatch.h + 4, 250, 250, 250)
end
drawn = drawn + 1
end
drawn = drawn + font.draw(recorder, 392, TOOLBAR_HEIGHT + 7,
"COULEUR " .. string.upper(palette.label(self.slot)),
THEME.muted[1], THEME.muted[2], THEME.muted[3], 1)
local canvas = self.canvas
recorder.rect(0, self.canvas_top, self.width, canvas.height * self.cell_size,
THEME.canvas[1], THEME.canvas[2], THEME.canvas[3])
local runs, run_count = self:canvas_runs()
if run_count > 0 then
table.move(runs, 1, run_count, recorder.n + 1, recorder.flat)
recorder.n = recorder.n + run_count
drawn = drawn + run_count // 7
end
local preview = self:preview_canvas()
if preview ~= nil then
for row = 1, preview.height do
for column = 1, preview.width do
if preview:get(column, row) ~= 0 then
recorder.rect((column - 1) * self.cell_size + 1,
self.canvas_top + (row - 1) * self.cell_size + 1,
self.cell_size - 2, self.cell_size - 2,
THEME.accent[1], THEME.accent[2], THEME.accent[3])
drawn = drawn + 1
end
end
end
end
if self.cursor_in_canvas then
local x = (self.cursor_x - 1) * self.cell_size
local y = self.canvas_top + (self.cursor_y - 1) * self.cell_size
recorder.rect(x, y, self.cell_size, 1, THEME.cursor[1], THEME.cursor[2], THEME.cursor[3])
recorder.rect(x, y + self.cell_size - 1, self.cell_size, 1,
THEME.cursor[1], THEME.cursor[2], THEME.cursor[3])
recorder.rect(x, y, 1, self.cell_size, THEME.cursor[1], THEME.cursor[2], THEME.cursor[3])
recorder.rect(x + self.cell_size - 1, y, 1, self.cell_size,
THEME.cursor[1], THEME.cursor[2], THEME.cursor[3])
end
recorder.rect(0, self.status_top, self.width, STATUS_HEIGHT,
THEME.status[1], THEME.status[2], THEME.status[3])
local status = string.format("%s | %s | X %d Y %d | %d CASES",
self:tool_name(), string.upper(palette.label(self.slot)),
self.cursor_x, self.cursor_y, self:painted())
drawn = drawn + font.draw(recorder, 10, self.status_top + 10, status,
THEME.text[1], THEME.text[2], THEME.text[3], 1)
local message = self.message or ""
local room = self.width - 20 - font.width(status, 1) - 20
local maximum = math.floor(room / 6)
if maximum > 0 and #message > maximum then
message = string.sub(message, 1, maximum)
end
if #message > 0 then
drawn = drawn + font.draw(recorder, self.width - 10 - font.width(message, 1),
self.status_top + 10, message, THEME.accent[1], THEME.accent[2], THEME.accent[3], 1)
end
return flush(surface, recorder)
end
M.App = App
return M
+60
View File
@@ -0,0 +1,60 @@
-- The picture drawn by `guipaint shot` and by the tests: same canvas primitives
-- as the interactive tools, so the capture shows the real application state.
local palette = require("paint.palette")
local M = {}
local function index_of(name)
local slot = palette.slot_of(name)
if slot == nil then
return 0
end
return palette.index_of_slot(slot)
end
local function solid(app, name, x1, y1, x2, y2)
app.canvas:rect(x1, y1, x2, y2, index_of(name), true)
end
function M.picture(app)
local canvas = app.canvas
local width = canvas.width
local height = canvas.height
local ground = height - 24
canvas:fill(1, 1, index_of("nuit"))
local stars = {
{ 14, 6 }, { 28, 12 }, { 52, 5 }, { 71, 9 }, { 120, 7 }, { 134, 13 },
}
for position = 1, #stars do
canvas:set(stars[position][1], stars[position][2], index_of("blanc"))
end
canvas:ellipse(math.floor(width * 0.85), 13, 9, 6, index_of("jaune"), true)
solid(app, "gris", 20, 17, 40, 19)
solid(app, "gris", 24, 15, 36, 17)
solid(app, "vert", 1, ground, width, height)
solid(app, "brun", 24, 34, 72, ground)
for row = 16, 34 do
local half = math.floor((row - 16) * 1.8)
solid(app, "brun", 48 - half, row, 48 + half, row)
end
solid(app, "nuit", 38, 50, 46, ground)
solid(app, "cyan", 54, 44, 64, 52)
solid(app, "brun", 100, 50, 106, ground)
canvas:ellipse(103, 40, 14, 12, index_of("vert"), true)
app.slot = palette.slot_of("jaune")
app.tool = 4
app.cursor_x = math.floor(width * 0.85)
app.cursor_y = 13
app.cursor_in_canvas = true
app.message = "PAYSAGE - CLIC POUR DESSINER"
return app
end
return M
+262
View File
@@ -0,0 +1,262 @@
-- Tests of the windowed application. They run without a window: the surface is
-- a recorder that counts the drawing calls and replays queued events.
local palette = require("paint.palette")
local font = require("gui.font")
local paint_module = require("gui.paint")
local scene = require("gui.scene")
local M = {}
local function fake_surface()
local surface = { rects = 0, clears = 0, lines = 0, presents = 0, events = {}, shot = nil }
function surface.clear(r, g, b)
surface.clears = surface.clears + 1
end
function surface.rect(x, y, w, h, r, g, b)
surface.rects = surface.rects + 1
end
function surface.line(x1, y1, x2, y2, r, g, b)
surface.lines = surface.lines + 1
end
function surface.present()
surface.presents = surface.presents + 1
end
function surface.poll()
return table.remove(surface.events, 1)
end
function surface.screenshot(path)
surface.shot = path
return true
end
function surface.open(title, width, height)
return true
end
function surface.close()
return true
end
function surface.delay(milliseconds)
return true
end
function surface.size()
return 960, 640
end
return surface
end
function M.run()
local passed = 0
local failures = {}
local function check(name, actual, expected)
if actual == expected then
passed = passed + 1
else
failures[#failures + 1] = string.format("%s : attendu %s, obtenu %s",
name, tostring(expected), tostring(actual))
end
end
local function check_true(name, condition, detail)
if condition then
passed = passed + 1
else
failures[#failures + 1] = name .. " : " .. tostring(detail or "condition fausse")
end
end
-- font ----------------------------------------------------------------
check("font width", font.width("AB"), 11)
check("font width scale 2", font.width("AB", 2), 22)
check("font height", font.height(1), 7)
check("font height scale 3", font.height(3), 21)
check("font empty width", font.width(""), 0)
local surface = fake_surface()
local drawn = font.draw(surface, 0, 0, "A", 255, 255, 255, 1)
check("font draws runs", drawn > 0, true)
check("font used surface", surface.rects > 0, true)
local before = surface.rects
font.draw(surface, 0, 20, "ab", 255, 255, 255, 1)
check_true("font uppercases", surface.rects > before, surface.rects)
local skipped = font.draw(surface, 0, 40, "~", 255, 255, 255, 1)
check("font skips unknown glyph", skipped, 0)
-- palette -------------------------------------------------------------
local background = palette.rgb_of(0)
check("background rgb", background[3], 34)
local yellow = palette.rgb_of(palette.index_of_slot(6))
check("yellow red", yellow[1], 245)
check("yellow green", yellow[2], 215)
check("yellow blue", yellow[3], 60)
local fallback = palette.rgb_of(12345)
check("unknown colour falls back", fallback[1], 26)
-- layout --------------------------------------------------------------
local app = paint_module.new({ surface = surface })
check("canvas width", app.canvas.width, 160)
check("canvas height", app.canvas.height, 87)
check("viewport top", app.canvas_top, 88)
check("status top", app.status_top, 612)
check("initial tool", app:tool_name(), "CRAYON")
check("initial slot", app.slot, palette.default_slot)
check("cell at origin", app:cell_at(0, 88), 1)
check("cell outside above", app:cell_at(0, 87), nil)
check("cell outside status", app:cell_at(0, 612), nil)
check("cell outside right", app:cell_at(1200, 100), nil)
-- toolbar and palette clicks -----------------------------------------
check("toolbar click", app:press(143, 26, 1), "tool")
check("toolbar selected", app.tool, 2)
check("swatch click", app:press(171, 73, 1), "colour")
check("swatch selected", app.slot, 6)
-- pencil + drag -------------------------------------------------------
local pencil = paint_module.new({ surface = surface })
check("select pencil", pencil:key("1"), "tool")
check("press draws", pencil:press(0, 88, 1), "draw")
check("pencil painted cell", pencil.canvas:get(1, 1), pencil:colour_index())
pencil:motion(30, 88)
check("drag painted six cells", pencil.canvas:count(), 6)
check("drag end", pencil.canvas:get(6, 1), pencil:colour_index())
-- line tool -----------------------------------------------------------
local line_app = paint_module.new({ surface = surface })
line_app:key("2")
line_app:press(0, 88, 1)
line_app:motion(30, 88 + 18)
check_true("line preview", line_app:preview_canvas() ~= nil, "no preview")
check("line commit", line_app:release(30, 88 + 18, 1), "commit")
check("line start", line_app.canvas:get(1, 1), line_app:colour_index())
check("line end", line_app.canvas:get(6, 4), line_app:colour_index())
check("line cleared anchor", line_app.anchor_x, nil)
-- rectangle -----------------------------------------------------------
local rectangle = paint_module.new({ surface = surface })
rectangle:key("3")
rectangle:press(0, 88, 1)
rectangle:release(30, 88 + 18, 1)
check("rect corner", rectangle.canvas:get(1, 1), rectangle:colour_index())
check("rect opposite corner", rectangle.canvas:get(6, 4), rectangle:colour_index())
check("rect hollow", rectangle.canvas:get(3, 2), 0)
-- filled ellipse ------------------------------------------------------
local oval = paint_module.new({ surface = surface })
oval:key("4")
oval:key("f")
check_true("filled mode", oval.filled, "not filled")
oval:press(30, 88 + 30, 1)
oval:release(90, 88 + 54, 1)
check_true("ellipse painted", oval.canvas:count() > 20, oval.canvas:count())
-- flood fill ----------------------------------------------------------
local bucket = paint_module.new({ surface = surface })
bucket:key("5")
bucket:press(0, 88, 1)
check("fill whole canvas", bucket.canvas:count(), bucket.canvas.width * bucket.canvas.height)
-- undo, clear, colour cycling ----------------------------------------
check("undo", bucket:key("u"), "undo")
check("undo emptied", bucket.canvas:count(), 0)
bucket:key("1")
bucket:press(0, 88, 1)
check("clear", bucket:key("c"), "clear")
check("clear emptied", bucket.canvas:count(), 0)
local slot_before = bucket.slot
bucket:key("p")
check("next colour", bucket.slot, palette.next_slot(slot_before))
bucket:key("m")
check("previous colour", bucket.slot, slot_before)
-- right button erases -------------------------------------------------
local eraser = paint_module.new({ surface = surface })
eraser:key("1")
eraser:press(0, 88, 1)
eraser:release(0, 88, 1)
check_true("painted before erase", eraser.canvas:get(1, 1) ~= 0, eraser.canvas:get(1, 1))
eraser:press(0, 88, 3)
eraser:release(0, 88, 3)
check("right click erased", eraser.canvas:get(1, 1), 0)
check("tool restored", eraser.tool, 1)
-- events --------------------------------------------------------------
check("quit event", app:handle({ type = "quit" }), "quit")
check("escape key", app:handle({ type = "keydown", key = "escape" }), "quit")
check("unknown event", app:handle({ type = "wheel" }), nil)
local moving = paint_module.new({ surface = surface })
moving:handle({ type = "mousemove", x = 12, y = 94 })
check("move updates cursor", moving.cursor_x, 3)
check("move updates row", moving.cursor_y, 2)
moving:handle({ type = "mousemove", x = 12, y = 5 })
check("move outside canvas", moving.cursor_in_canvas, false)
-- rendering -----------------------------------------------------------
local render_surface = fake_surface()
local rendered = paint_module.new({ surface = render_surface })
local calls = rendered:render()
check("one clear per frame", render_surface.clears, 1)
check_true("render issues many rects", calls > 200, calls)
check_true("render counted rects", render_surface.rects > 200, render_surface.rects)
-- batched surface: one native call per frame, reused while nothing moves --
local batch_surface = fake_surface()
batch_surface.rect_calls = 0
batch_surface.rect_count = 0
function batch_surface.rects(flat, count)
batch_surface.rect_calls = batch_surface.rect_calls + 1
batch_surface.rect_count = count // 7
end
local fast = paint_module.new({ surface = batch_surface })
scene.picture(fast)
local fast_drawn = fast:render()
check("single batched call", batch_surface.rect_calls, 1)
check("batched count matches", batch_surface.rect_count, fast_drawn)
check("batched frame clears", batch_surface.clears, 1)
check("runs cached between frames", fast:render(), fast_drawn)
check("still one call per frame", batch_surface.rect_calls, 2)
-- a uniform canvas merges into one rectangle per row ----------------------
local merged = paint_module.new({ surface = fake_surface() })
merged.canvas:fill(1, 1, palette.index_of_slot(7))
local merged_drawn = merged:render()
check_true("runs merged", merged_drawn < 6000, merged_drawn)
check("merged cell count", merged.canvas:count(), merged.canvas.width * merged.canvas.height)
-- canvas version only moves on a real change ------------------------------
local versioned = paint_module.new({ surface = fake_surface() })
local start_version = versioned.canvas.version
versioned.canvas:set(1, 1, palette.index_of_slot(3))
check("version bumps on set", versioned.canvas.version, start_version + 1)
versioned.canvas:set(1, 1, palette.index_of_slot(3))
check("version stable on no-op", versioned.canvas.version, start_version + 1)
check("undo without history", versioned.canvas:undo(), false)
check("version stable on failed undo", versioned.canvas.version, start_version + 1)
-- picture and capture -------------------------------------------------
local artist = paint_module.new({ surface = fake_surface() })
scene.picture(artist)
check_true("picture painted", artist.canvas:count() > 5000, artist.canvas:count())
check("picture sun", artist.canvas:get(136, 13), palette.index_of_slot(6))
check("picture ground", artist.canvas:get(4, 80), palette.index_of_slot(7))
check("picture wall", artist.canvas:get(30, 45), palette.index_of_slot(12))
check("picture window", artist.canvas:get(59, 48), palette.index_of_slot(8))
check("picture cursor", artist.cursor_in_canvas, true)
-- save ----------------------------------------------------------------
local path = "/tmp/luapaint_test.ppm"
check_true("save returns true", artist:save(path), "save failed")
local handle = io.open(path, "rb")
check_true("ppm written", handle ~= nil, "no file")
if handle ~= nil then
local data = handle:read("a")
handle:close()
local header = string.format("P6\n%d %d\n255\n", artist.canvas.width, artist.canvas.height)
check("ppm size", #data, #header + artist.canvas.width * artist.canvas.height * 3)
check("ppm magic", string.sub(data, 1, 2), "P6")
end
os.remove(path)
return { passed = passed, failed = #failures, failures = failures }
end
return M
+188
View File
@@ -0,0 +1,188 @@
-- LuaPaint GUI : un éditeur de dessin dans une vraie fenêtre (SDL2), écrit en
-- Lua et compilé en un seul binaire par luacpp.
--
-- ./build/luacpp run Demo/guipaint.lua fenêtre interactive
-- ./build/luacpp run Demo/guipaint.lua shot capture de la fenêtre
-- ./build/luacpp run Demo/guipaint.lua test tests internes
local paint_module = require("gui.paint")
local scene = require("gui.scene")
local tests = require("gui.tests")
local M = {}
local argv = arg or {}
local command = argv[1] or "run"
local function has_gui()
return gui ~= nil and gui.open ~= nil
end
local function explain_missing_gui()
print("LuaPaint: ce binaire n'expose pas l'API 'gui'.")
print(" -> installe SDL2 (libsdl2-dev) puis relance ./build.sh")
print(" -> luacpp ne lie la GUI que si SDL2 est trouvé à la configuration")
end
local function run()
if not has_gui() then
explain_missing_gui()
return 1
end
local app = paint_module.new({})
local opened, error_message = gui.open("LuaPaint - dessin", app.width, app.height)
if not opened then
print("LuaPaint: impossible d'ouvrir la fenêtre : " .. tostring(error_message))
print(" DISPLAY est-il défini ? (X11 ou Wayland requis)")
return 1
end
local running = true
local dirty = true
while running do
if dirty then
app:render()
gui.present()
dirty = false
end
-- Drain every pending event before redrawing: a mouse drag queues dozens
-- of moves, and each of them used to trigger a full frame on its own.
local event = gui.poll()
local handled = false
while event ~= nil do
handled = true
if app:handle(event) == "quit" then
running = false
end
event = gui.poll()
end
if handled then
dirty = true
else
gui.delay(4)
end
end
gui.close()
print(string.format("LuaPaint : %d cellules peintes, %d étapes d'historique.",
app.canvas:count(), app.canvas:history_size()))
return 0
end
local function shot(path)
if not has_gui() then
explain_missing_gui()
return 1
end
local target = path or "guipaint.ppm"
local app = paint_module.new({})
local opened, error_message = gui.open("LuaPaint - capture", app.width, app.height)
if not opened then
print("LuaPaint: impossible d'ouvrir la fenêtre : " .. tostring(error_message))
return 1
end
scene.picture(app)
app:render()
local saved, save_error = gui.screenshot(target)
gui.present()
gui.close()
if not saved then
print("LuaPaint: capture impossible : " .. tostring(save_error))
return 1
end
print("capture : " .. target)
print(string.format("%dx%d, %d cellules peintes", app.width, app.height, app.canvas:count()))
return 0
end
local function bench(count)
if not has_gui() then
explain_missing_gui()
return 1
end
local frames = tonumber(count) or 120
local app = paint_module.new({})
local opened, error_message = gui.open("LuaPaint - bench", app.width, app.height)
if not opened then
print("LuaPaint: impossible d'ouvrir la fenêtre : " .. tostring(error_message))
return 1
end
scene.picture(app)
app:render()
gui.present()
local start = gui.time()
for _ = 1, frames do
app:render()
end
local render_ms = (gui.time() - start) / frames
start = gui.time()
for _ = 1, frames do
app:render()
gui.present()
end
local frame_ms = (gui.time() - start) / frames
gui.close()
if frames <= 0 or render_ms <= 0 then
print("LuaPaint: mesure trop courte")
return 1
end
print(string.format("rendu : %.2f ms/frame (%d cellules, %d rectangles)",
render_ms, app:painted(), app:render()))
print(string.format("affichage : %.2f ms/frame (%.0f fps)", frame_ms, 1000 / frame_ms))
return 0
end
local function run_tests()
local summary = tests.run()
print("LuaPaint GUI - tests internes")
print(string.format(" %d tests OK, %d échec(s)", summary.passed, summary.failed))
if summary.failed > 0 then
print("")
for index = 1, #summary.failures do
print(" FAIL " .. summary.failures[index])
end
return 1
end
return 0
end
local function usage()
print("LuaPaint GUI - éditeur de dessin dans une fenêtre SDL2, compilé par luacpp")
print("")
print(" guipaint run fenêtre interactive (défaut)")
print(" guipaint shot [fichier] dessine la scène et capture en PPM")
print(" guipaint test tests internes (sans fenêtre)")
print(" guipaint bench [frames] mesure le temps de rendu dans une fenêtre")
print(" guipaint help cette aide")
print("")
print("Souris : clic gauche pour dessiner, glisser pour un trait, clic droit pour gommer.")
print("Touches : 1-6 outils | f formes pleines | p/m couleur | u annuler")
print(" c effacer | s enregistrer guipaint.ppm | q quitter")
print("")
print("Exemple : luacpp run Demo/guipaint.lua shot /tmp/luapaint.ppm")
return 0
end
local commands = {
run = run,
shot = shot,
test = run_tests,
bench = bench,
help = usage,
["--help"] = usage,
["-h"] = usage,
}
local handler = commands[command]
if handler == nil then
print("commande inconnue : " .. command)
usage()
os.exit(2)
end
os.exit(handler(argv[2]) or 0)
+183 -8
View File
@@ -22,6 +22,8 @@ coroutines, bibliothèques standard) reste celle de Lua.
## Compiler et lancer
Prérequis : CMake ≥ 3.20, un compilateur C++17, Lua 5.4 (`liblua5.4-dev`).
SDL2 (`libsdl2-dev`) est optionnel : quand elle est présente, les programmes
compilés reçoivent une API `gui` (fenêtres, rectangles, événements).
```bash
./build.sh # compile UNIQUEMENT le compilateur (build/luacpp)
@@ -112,18 +114,181 @@ Les erreurs Lua sont converties en exceptions C++ côté hôte, et les erreurs C
restent des erreurs Lua côté script. `luacpp::Module::call` protège chaque appel
avec `pcall`.
## Demo
## Démos
`Demo/` ne contient que du Lua, aucun C++ :
`Demo/` ne contient que du Lua, aucun C++ : chaque script est transpilé puis lié en
un exécutable autonome rangé dans `Demo/build/` (dossier ignoré par git).
- `Demo/hello.lua` : script seul (fonctions, boucles, `table.concat`) ;
- `Demo/todo.lua` : module — tables, closures, `ipairs` ;
- `Demo/report.lua` : module qui fait `require("todo")` et calcule des stats ;
- `Demo/main.lua` : utilise les deux modules et affiche le rapport.
### `hello.lua` — un script, aucun module
```bash
./build/luacpp run Demo/hello.lua # un fichier, aucun require
./build/luacpp run Demo/main.lua # plusieurs modules compilés ensemble
./build/luacpp run Demo/hello.lua # -> Demo/build/hello
```
Fonctions récursives, boucles, `table.concat`, `string.format` : le plus petit
programme compilé possible.
### `main.lua` — des modules qui s'appellent
```bash
./build/luacpp run Demo/main.lua # -> Demo/build/main
```
`todo.lua` est un module (tables, closures, `ipairs`), `report.lua` le charge avec
`require("todo")` et calcule des statistiques, `main.lua` utilise les deux. C'est
la démonstration du multi-fichiers : `luacpp` compile tous les `.lua` du dossier
d'un coup et résout `require` vers les modules compilés.
### `luasheet.lua` — un tableur (`Demo/sheet/*.lua`)
```bash
./build/luacpp run Demo/luasheet.lua # -> Demo/build/luasheet
```
Un vrai moteur de tableur, en huit modules :
- `sheet/lexer.lua` et `sheet/parser.lua` : nombres, chaînes, références `A1`,
`$A$1`, plages `A1:B4`, opérateurs `+ - * / % ^ & = <> < > <= >=` et les
parenthèses, avec précédences (`^` associatif à droite, `-2^2 = 4`) ;
- `sheet/builtins.lua` : 26 fonctions (`SUM`, `AVG`, `MIN`, `MAX`, `COUNT`,
`MEDIAN`, `IF`, `ROUND`, `MOD`, `CONCAT`, `LEN`, `LEFT`, `UPPER`…) ;
- `sheet/sheet.lua` : cellules littérales ou formules, évaluation paresseuse avec
cache, plages, détection de cycles et propagation d'erreurs ;
- `sheet/render.lua` : grille ASCII alignée, vue formules, export CSV, barres ;
- `sheet/workbooks.lua` : classeurs d'exemple au format `A1: =SUM(B4:B9)`, avec le
suffixe `%` sur l'adresse pour formater une cellule en pourcentage ;
- `sheet/tests.lua` : 105 tests internes.
Les erreurs sont celles d'un tableur : `#DIV/0!`, `#NAME?`, `#VALUE!`, `#PARSE!`
et `#CYCLE!` (une cellule qui dépend d'elle-même est détectée, pas de boucle
infinie).
```bash
./build/luacpp run Demo/luasheet.lua demo # classeur Budget 2026
./build/luacpp run Demo/luasheet.lua ventes # texte, IF, &
./build/luacpp run Demo/luasheet.lua errors # feuille d'erreurs
./build/luacpp run Demo/luasheet.lua formula "=SUM(1,2,3)*2"
./build/luacpp run Demo/luasheet.lua csv # export CSV
./build/luacpp run Demo/luasheet.lua bench 300 # 300 lignes, recalcul
./build/luacpp run Demo/luasheet.lua test # 105 tests
```
```
| A | B | C | D |
---+---------------------+---------+---------+--------+
4 | Loyer | 820 | 9840 | 42.6% |
5 | Courses | 430 | 5160 | 22.4% |
...
11 | Total charges | 1923 | 23076 | 100.0% |
```
### `luapaint.lua` — un éditeur de dessin en terminal (`Demo/tui`, `Demo/paint`)
```bash
./build/luacpp run Demo/luapaint.lua # -> Demo/build/luapaint
```
Une interface graphique complète dans le terminal : framebuffer de cellules
(character, couleur de texte, couleur de fond) rendu en ANSI 256 couleurs, panneau
d'outils, palette, barre d'état, curseur, aperçu de forme et historique.
- `tui/screen.lua` : framebuffer, rectangles, cadres, titres, barres, rendu ANSI
(et rendu `--mono` sans aucune séquence d'échappement) ;
- `tui/theme.lua` : couleurs de l'interface et taille minimale ;
- `paint/canvas.lua` : grille de pixels, ligne de Bresenham, rectangle, ellipse
(contour ou pleine), remplissage par diffusion itératif, annuler/refaire ;
- `paint/palette.lua` : douze couleurs nommées ;
- `paint/app.lua` : état, touches, outils, disposition et rendu de l'écran ;
- `paint/session.lua` : une session enregistrée qui dessine un paysage avec les
vrais outils ;
- `paint/tests.lua` : 98 tests internes.
```bash
./build/luacpp run Demo/luapaint.lua demo # paysage en 3 images
./build/luacpp run Demo/luapaint.lua play # édition interactive
./build/luacpp run Demo/luapaint.lua snapshot # le dessin en texte
./build/luacpp run Demo/luapaint.lua test # 98 tests
./build/luacpp run Demo/luapaint.lua demo --mono --canvas 40x14
```
Commandes de l'interface :
| Touche | Effet |
| --- | --- |
| `h` `j` `k` `l` | déplacer le curseur |
| `espace` | dessiner (deux fois pour une ligne, un rectangle ou une ellipse) |
| `1`…`6` | crayon, ligne, rectangle, ellipse, remplissage, gomme |
| `f` | formes pleines ou contour |
| `p` / `m` | couleur suivante / précédente |
| `u` / `r` | annuler / refaire |
| `c` | effacer la toile |
| `w` | écrire `luapaint.txt` (couleurs en hexadécimal) |
| `q` | quitter |
`play` passe le terminal en mode brut (`stty raw`) quand l'entrée est un
terminal, et le restaure en sortie ; sur une entrée redirigée (`printf 'llllj 3 q'
| ./luapaint play --mono`), il lit caractère par caractère sans toucher au mode.
### `guipaint.lua` — une vraie fenêtre (`Demo/gui/*.lua`)
```bash
./build/luacpp run Demo/guipaint.lua # fenêtre 960x640
./build/luacpp run Demo/guipaint.lua shot /tmp/x.ppm # dessine et capture la fenêtre
./build/luacpp run Demo/guipaint.lua test # tests sans fenêtre
./build/luacpp run Demo/guipaint.lua bench 120 # temps de rendu mesuré
```
Contrairement à `luapaint.lua`, qui reste dans le terminal, celle-ci ouvre une
**vraie fenêtre** : barre d'outils cliquable, palette, toile, curseur, aperçu de
forme, barre d'état et raccourcis clavier. Toute la logique est en Lua ; seul le
côté « fenêtre » vient de l'API `gui` fournie par le runtime (SDL2), décrite plus
bas.
- `gui/font.lua` : police bitmap 5x7 dessinée en rectangles (aucune bibliothèque
de polices) ;
- `gui/paint.lua` : disposition, outils souris (crayon, ligne, rectangle, ellipse,
remplissage, gomme), couleurs, annuler/refaire et rendu ;
- `gui/scene.lua` : la scène dessinée par `shot` et par les tests ;
- `gui/tests.lua` : tests sans fenêtre, via une surface factice qui enregistre les
appels de dessin et rejoue des événements.
Souris : clic gauche pour dessiner, glisser pour un trait continu, clic droit pour
gommer. Touches : `1`-`6` outils, `f` formes pleines, `p`/`m` couleur, `u` annuler,
`c` effacer, `s` enregistrer `guipaint.ppm`, `q` quitter.
Rendu : la toile est mise en cache sous forme de segments horizontaux (une ligne
de couleur uniforme coûte un rectangle, pas 160), la liste n'est reconstruite que
lorsque la toile change (compteur de version), la police est précompilée en
segments, et tout le dessin d'une trame part dans **un seul** appel `gui.rects`
au lieu de milliers d'appels Lua→C. Les événements en attente sont vidés avant
chaque redessin, donc un glissement de souris ne déclenche plus une trame par
événement.
## Interface graphique (SDL2)
`cmake` détecte SDL2 avec `pkg-config` et, si elle est là, chaque programme
compilé par `luacpp run` trouve une globale `gui` :
| Fonction | Rôle |
| --- | --- |
| `gui.open(titre, largeur, hauteur)` | ouvre une fenêtre ; retourne `true` ou `nil, erreur` |
| `gui.clear(r, g, b)` | efface le fond |
| `gui.rect(x, y, w, h, r, g, b)` | rectangle plein |
| `gui.rects(flat, count)` | rectangles en lot (7 nombres par rectangle), un seul appel natif |
| `gui.line(x1, y1, x2, y2, r, g, b)` | segment |
| `gui.present()` | affiche la trame dessinée |
| `gui.poll()` | événement suivant, ou `nil` : `quit`, `keydown` (`key`, `sym`, `repeat`), `mousedown`/`mouseup` (`x`, `y`, `button`), `mousemove` (`x`, `y`, `buttons`), `wheel` |
| `gui.screenshot(chemin)` | écrit la trame courante en PPM (à appeler avant `present`) |
| `gui.delay(ms)`, `gui.time()`, `gui.size()`, `gui.set_title(t)`, `gui.close()` | utilitaires |
Sans SDL2, tout compile encore : la globale `gui` est simplement absente et
`Demo/guipaint.lua` affiche un message explicite. La liaison est dans
`include/luacpp/gui.hpp`, les drapeaux de compilation sont injectés par CMake
dans `luacpp-config.hpp` (`LUACPP_GUI_FLAGS`).
```bash
# vérifier que la fenêtre s'ouvre et récupérer une capture
DISPLAY=:0 ./Demo/build/guipaint shot /tmp/luapaint.ppm
```
## Tests de conformité
@@ -162,6 +327,16 @@ bash tests/compare.sh build/tests/luacpp_conformance
l'émission de C++ natif typé est prévue ensuite.
- `require` n'est intercepté que pour un nom littéral ; les noms dynamiques
passent par le `require` standard.
- **Closures boxées dans une boucle générique** : une closure qui capture une
locale mutée (`t[#t + 1] = v`) dans le corps d'un `for ... in pairs(...)` peut
produire du code C++ incorrect (plantage à l'exécution). Contournement :
`table.insert` et `pcall(fonction_nommee, ...)` plutôt qu'une closure — c'est ce
que fait `Demo/sheet/sheet.lua`.
- **Captures à deux niveaux** : une fonction imbriquée qui référence une locale du
chunk à travers sa fonction englobante échoue à la compilation
(`internal error: upvalue 'x' is not a captured local`). Contournement : copier
la valeur dans une locale de la fonction englobante avant de la capturer
(`local mono = options.mono` dans `Demo/luapaint.lua`).
## Structure
+1
View File
@@ -5,3 +5,4 @@
#define LUACPP_RUNTIME_INCLUDE_DIR "@LUACPP_RUNTIME_INCLUDE_DIR@"
#define LUACPP_LUA_CFLAGS "@LUACPP_LUA_CFLAGS@"
#define LUACPP_LUA_LIBS "@LUACPP_LUA_LIBS@"
#define LUACPP_GUI_FLAGS "@LUACPP_GUI_FLAGS@"
+379
View File
@@ -0,0 +1,379 @@
// Optional GUI backend for compiled Lua programs.
//
// When luacpp is configured with SDL2, every compiled program finds a global
// table `gui` offering a tiny immediate-mode window API:
//
// local ok, err = gui.open("title", 960, 640)
// gui.clear(r, g, b)
// gui.rect(x, y, w, h, r, g, b)
// gui.rects(flat, count) -- batched rects, 7 numbers per rect
// gui.line(x1, y1, x2, y2, r, g, b)
// gui.present()
// local event = gui.poll() -- nil, or { type = ... }
// gui.screenshot("out.ppm") -- reads the current back buffer
// gui.close()
//
// The Lua side keeps all the application logic (layout, tools, events); this
// layer only owns the window, the drawing primitives and the event queue.
#pragma once
#if defined(LUACPP_HAS_GUI)
#include <SDL2/SDL.h>
#include <lua.hpp>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
namespace luacpp {
namespace gui {
struct WindowState {
SDL_Window* window = nullptr;
SDL_Renderer* renderer = nullptr;
int width = 0;
int height = 0;
bool open = false;
bool sdl_ready = false;
std::vector<unsigned char> pixels;
std::vector<SDL_Rect> batch;
};
inline WindowState& state() {
static WindowState instance;
return instance;
}
inline int fail(lua_State* L, const char* message) {
lua_pushnil(L);
lua_pushstring(L, message);
return 2;
}
inline int l_open(lua_State* L) {
const char* title = luaL_checkstring(L, 1);
const int width = static_cast<int>(luaL_checkinteger(L, 2));
const int height = static_cast<int>(luaL_checkinteger(L, 3));
WindowState& window = state();
if (window.open) return fail(L, "a window is already open");
if (!window.sdl_ready) {
if (SDL_Init(SDL_INIT_VIDEO) != 0) return fail(L, SDL_GetError());
window.sdl_ready = true;
}
window.window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
width, height, SDL_WINDOW_SHOWN);
if (!window.window) return fail(L, SDL_GetError());
window.renderer = SDL_CreateRenderer(
window.window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (!window.renderer) {
window.renderer = SDL_CreateRenderer(window.window, -1, SDL_RENDERER_SOFTWARE);
}
if (!window.renderer) {
SDL_DestroyWindow(window.window);
window.window = nullptr;
return fail(L, SDL_GetError());
}
SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND);
window.width = width;
window.height = height;
window.open = true;
lua_pushboolean(L, 1);
return 1;
}
inline int l_close(lua_State* L) {
WindowState& window = state();
if (window.renderer) {
SDL_DestroyRenderer(window.renderer);
window.renderer = nullptr;
}
if (window.window) {
SDL_DestroyWindow(window.window);
window.window = nullptr;
}
window.open = false;
window.width = 0;
window.height = 0;
lua_pushboolean(L, 1);
return 1;
}
inline int l_size(lua_State* L) {
WindowState& window = state();
if (!window.open) {
lua_pushinteger(L, 0);
lua_pushinteger(L, 0);
return 2;
}
lua_pushinteger(L, window.width);
lua_pushinteger(L, window.height);
return 2;
}
inline int l_clear(lua_State* L) {
WindowState& window = state();
if (!window.open) return fail(L, "no window");
const int r = static_cast<int>(luaL_optinteger(L, 1, 0));
const int g = static_cast<int>(luaL_optinteger(L, 2, 0));
const int b = static_cast<int>(luaL_optinteger(L, 3, 0));
SDL_SetRenderDrawColor(window.renderer, static_cast<Uint8>(r), static_cast<Uint8>(g),
static_cast<Uint8>(b), 255);
SDL_RenderClear(window.renderer);
lua_pushboolean(L, 1);
return 1;
}
inline int l_rect(lua_State* L) {
WindowState& window = state();
if (!window.open) return fail(L, "no window");
const int x = static_cast<int>(luaL_checkinteger(L, 1));
const int y = static_cast<int>(luaL_checkinteger(L, 2));
const int width = static_cast<int>(luaL_checkinteger(L, 3));
const int height = static_cast<int>(luaL_checkinteger(L, 4));
const int r = static_cast<int>(luaL_optinteger(L, 5, 255));
const int g = static_cast<int>(luaL_optinteger(L, 6, 255));
const int b = static_cast<int>(luaL_optinteger(L, 7, 255));
if (width <= 0 || height <= 0) {
lua_pushboolean(L, 0);
return 1;
}
const SDL_Rect rectangle{x, y, width, height};
SDL_SetRenderDrawColor(window.renderer, static_cast<Uint8>(r), static_cast<Uint8>(g),
static_cast<Uint8>(b), 255);
SDL_RenderFillRect(window.renderer, &rectangle);
lua_pushboolean(L, 1);
return 1;
}
// Batched rectangles: a flat array holding seven numbers per rectangle
// (x, y, w, h, r, g, b) and how many numbers are used. Consecutive rectangles
// sharing a colour are filled with one SDL_RenderFillRects call, which keeps
// the per-frame cost of a whole-tile redraw down to a few native calls.
inline int l_rects(lua_State* L) {
WindowState& window = state();
if (!window.open) return fail(L, "no window");
luaL_checktype(L, 1, LUA_TTABLE);
const lua_Integer count = luaL_optinteger(L, 2, static_cast<lua_Integer>(lua_rawlen(L, 1)));
std::vector<SDL_Rect>& batch = window.batch;
batch.clear();
int last_r = -1;
int last_g = -1;
int last_b = -1;
int drawn = 0;
for (lua_Integer index = 1; index + 6 <= count; index += 7) {
lua_Integer values[7];
for (int offset = 0; offset < 7; ++offset) {
lua_rawgeti(L, 1, static_cast<int>(index + offset));
values[offset] = lua_tointeger(L, -1);
lua_pop(L, 1);
}
const int width = static_cast<int>(values[2]);
const int height = static_cast<int>(values[3]);
if (width <= 0 || height <= 0) continue;
const int r = static_cast<int>(values[4]);
const int g = static_cast<int>(values[5]);
const int b = static_cast<int>(values[6]);
if (r != last_r || g != last_g || b != last_b) {
if (!batch.empty()) {
SDL_RenderFillRects(window.renderer, batch.data(), static_cast<int>(batch.size()));
batch.clear();
}
SDL_SetRenderDrawColor(window.renderer, static_cast<Uint8>(r), static_cast<Uint8>(g),
static_cast<Uint8>(b), 255);
last_r = r;
last_g = g;
last_b = b;
}
batch.push_back(SDL_Rect{static_cast<int>(values[0]), static_cast<int>(values[1]), width, height});
++drawn;
}
if (!batch.empty()) {
SDL_RenderFillRects(window.renderer, batch.data(), static_cast<int>(batch.size()));
batch.clear();
}
lua_pushinteger(L, drawn);
return 1;
}
inline int l_line(lua_State* L) {
WindowState& window = state();
if (!window.open) return fail(L, "no window");
const int x1 = static_cast<int>(luaL_checkinteger(L, 1));
const int y1 = static_cast<int>(luaL_checkinteger(L, 2));
const int x2 = static_cast<int>(luaL_checkinteger(L, 3));
const int y2 = static_cast<int>(luaL_checkinteger(L, 4));
const int r = static_cast<int>(luaL_optinteger(L, 5, 255));
const int g = static_cast<int>(luaL_optinteger(L, 6, 255));
const int b = static_cast<int>(luaL_optinteger(L, 7, 255));
SDL_SetRenderDrawColor(window.renderer, static_cast<Uint8>(r), static_cast<Uint8>(g),
static_cast<Uint8>(b), 255);
SDL_RenderDrawLine(window.renderer, x1, y1, x2, y2);
lua_pushboolean(L, 1);
return 1;
}
inline int l_present(lua_State* L) {
WindowState& window = state();
if (!window.open) return fail(L, "no window");
SDL_RenderPresent(window.renderer);
lua_pushboolean(L, 1);
return 1;
}
inline int l_delay(lua_State* L) {
const int milliseconds = static_cast<int>(luaL_optinteger(L, 1, 10));
SDL_Delay(static_cast<Uint32>(milliseconds < 0 ? 0 : milliseconds));
lua_pushboolean(L, 1);
return 1;
}
inline int l_time(lua_State* L) {
lua_pushnumber(L, static_cast<lua_Number>(SDL_GetTicks64()));
return 1;
}
inline void set_field_string(lua_State* L, const char* name, const std::string& value) {
lua_pushlstring(L, value.data(), value.size());
lua_setfield(L, -2, name);
}
inline int l_poll(lua_State* L) {
WindowState& window = state();
if (!window.open) {
lua_pushnil(L);
return 1;
}
SDL_Event event;
if (SDL_PollEvent(&event) == 0) {
lua_pushnil(L);
return 1;
}
lua_newtable(L);
const char* kind = "other";
switch (event.type) {
case SDL_QUIT:
kind = "quit";
break;
case SDL_KEYDOWN: {
kind = "keydown";
const char* raw = SDL_GetKeyName(event.key.keysym.sym);
std::string name = raw ? raw : "";
for (char& character : name) {
character = static_cast<char>(std::tolower(static_cast<unsigned char>(character)));
}
set_field_string(L, "key", name);
lua_pushinteger(L, event.key.keysym.sym);
lua_setfield(L, -2, "sym");
lua_pushboolean(L, event.key.repeat);
lua_setfield(L, -2, "repeat");
break;
}
case SDL_KEYUP:
kind = "keyup";
break;
case SDL_MOUSEMOTION:
kind = "mousemove";
lua_pushinteger(L, event.motion.x);
lua_setfield(L, -2, "x");
lua_pushinteger(L, event.motion.y);
lua_setfield(L, -2, "y");
lua_pushinteger(L, event.motion.state);
lua_setfield(L, -2, "buttons");
break;
case SDL_MOUSEBUTTONDOWN:
kind = "mousedown";
lua_pushinteger(L, event.button.x);
lua_setfield(L, -2, "x");
lua_pushinteger(L, event.button.y);
lua_setfield(L, -2, "y");
lua_pushinteger(L, event.button.button);
lua_setfield(L, -2, "button");
break;
case SDL_MOUSEBUTTONUP:
kind = "mouseup";
lua_pushinteger(L, event.button.x);
lua_setfield(L, -2, "x");
lua_pushinteger(L, event.button.y);
lua_setfield(L, -2, "y");
lua_pushinteger(L, event.button.button);
lua_setfield(L, -2, "button");
break;
case SDL_MOUSEWHEEL:
kind = "wheel";
lua_pushinteger(L, event.wheel.y);
lua_setfield(L, -2, "y");
break;
default:
break;
}
lua_pushstring(L, kind);
lua_setfield(L, -2, "type");
return 1;
}
// Reads the current back buffer and writes a binary PPM (P6) file. The buffer
// is only guaranteed to hold the last drawn frame, so call it before present().
inline int l_screenshot(lua_State* L) {
WindowState& window = state();
if (!window.open) return fail(L, "no window");
const char* path = luaL_checkstring(L, 1);
const int width = window.width;
const int height = window.height;
window.pixels.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * 4);
if (SDL_RenderReadPixels(window.renderer, nullptr, SDL_PIXELFORMAT_RGBA32,
window.pixels.data(), width * 4) != 0) {
return fail(L, SDL_GetError());
}
std::FILE* file = std::fopen(path, "wb");
if (!file) return fail(L, "cannot write the screenshot");
std::fprintf(file, "P6\n%d %d\n255\n", width, height);
for (int index = 0; index < width * height; ++index) {
std::fwrite(&window.pixels[static_cast<size_t>(index) * 4], 1, 3, file);
}
std::fclose(file);
lua_pushboolean(L, 1);
return 1;
}
inline int l_set_title(lua_State* L) {
WindowState& window = state();
if (!window.open) return fail(L, "no window");
SDL_SetWindowTitle(window.window, luaL_checkstring(L, 1));
lua_pushboolean(L, 1);
return 1;
}
// Installs the `gui` global. Called by luacpp::State when starting a program.
inline void register_gui(lua_State* L) {
lua_newtable(L);
const luaL_Reg functions[] = {
{"open", l_open}, {"close", l_close}, {"size", l_size},
{"clear", l_clear}, {"rect", l_rect}, {"rects", l_rects},
{"line", l_line},
{"present", l_present}, {"poll", l_poll}, {"delay", l_delay},
{"time", l_time}, {"screenshot", l_screenshot},
{"set_title", l_set_title}, {nullptr, nullptr},
};
for (const luaL_Reg* entry = functions; entry->name != nullptr; ++entry) {
lua_pushcfunction(L, entry->func);
lua_setfield(L, -2, entry->name);
}
lua_setglobal(L, "gui");
}
} // namespace gui
} // namespace luacpp
#else
#include <lua.hpp>
namespace luacpp {
namespace gui {
inline void register_gui(lua_State*) {}
} // namespace gui
} // namespace luacpp
#endif // LUACPP_HAS_GUI
+7 -1
View File
@@ -5,6 +5,8 @@
#include <lua.hpp>
#include "gui.hpp"
#if LUA_VERSION_NUM != 504
#error "luacpp requires Lua 5.4 (LUA_VERSION_NUM == 504)"
#endif
@@ -638,10 +640,14 @@ public:
if (!L_) throw Error("cannot create a Lua state");
own_ = true;
luaL_openlibs(L_);
gui::register_gui(L_);
}
explicit State(lua_State* L, bool own = false) : L_(L), own_(own) {
if (own_ && L_) luaL_openlibs(L_);
if (own_ && L_) {
luaL_openlibs(L_);
gui::register_gui(L_);
}
}
~State() {
+2
View File
@@ -325,6 +325,8 @@ int run_script(const Options& opt) {
command += " -I" + quoted(srcDir.string());
command += " -I" + quoted(LUACPP_RUNTIME_INCLUDE_DIR);
command += " " + lua_link_flags();
std::string gui_flags = LUACPP_GUI_FLAGS;
if (!gui_flags.empty()) command += " " + gui_flags;
if (opt.verbose) std::cerr << "luacpp: compile: " << command << "\n";
if (!opt.quiet) std::cout << "luacpp: building " << display(exe) << "\n";