Files
BlackAngelTV 9587d1ed49 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.
2026-11-18 10:18:44 +01:00

380 lines
12 KiB
C++

// 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