Estado atual do TinyBlocks: editor estilo Scratch + graphics como interface
Snapshot do projeto antes de implementar o diálogo "Criar um Bloco": - runtime C block-based (src/, include/) - libraries: graphics (interface), sdl2 (backend), editor (estilo Scratch), python, mcp - exemplos (hello, sdl2, editor, vector, json, customappearance, python, mcp) - Makefile com alvo help e build do editor Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
commit
4950ad6006
49 files changed
+10596
No files matched your search
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* TinyBlocks — tb_graphics.h
|
||||
* Interface gráfica do TinyBlocks: janelas, entrada, desenho e texto.
|
||||
*
|
||||
* Tudo o que é gráfico passa por aqui antes de chegar a um backend concreto.
|
||||
* O backend (ex: tinyblocks-sdl2) implementa TinyBlocks_GraphicsBackend e
|
||||
* pode ser trocado livremente:
|
||||
* - estaticamente: tb_graphics_set_backend(tb_sdl2_graphics_backend());
|
||||
* - dinamicamente: tb_graphics_load_backend("build/libtinyblocks-sdl2.so");
|
||||
* (o .so exporta TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL)
|
||||
* Sem escolha explícita usa o backend padrão de compilação (SDL2) ou, na
|
||||
* falta dele, o backend nulo (headless — útil para testes).
|
||||
*
|
||||
* TypeBlocks registrados por tb_graphics_get_library():
|
||||
* Graphics.Input — estado de entrada de uma janela no frame (outputs GFX_IN_*)
|
||||
* Graphics.Window — uma janela do SO que mostra uma cena (qualquer bloco com on_draw)
|
||||
* in: título, largura, altura, cena(block), entrada(block), principal(int)
|
||||
* Graphics.Run — roda o loop até a janela principal fechar
|
||||
*
|
||||
* Esta library não conhece nenhum consumidor (editor, palco…): só define o
|
||||
* contrato e despacha para o backend. Cenas são quaisquer blocos com on_draw.
|
||||
*
|
||||
* Uso típico (host):
|
||||
* tb_library_register(rt, tb_graphics_get_library());
|
||||
* TinyBlocks_Block* in = tb_block_create(rt, tb_type_block_find(rt, "Graphics.Input"));
|
||||
* TinyBlocks_Block* win = tb_block_create(rt, tb_type_block_find(rt, "Graphics.Window"));
|
||||
* tb_block_set_default(win, 3, tb_value_block(cena));
|
||||
* tb_block_set_default(win, 4, tb_value_block(in));
|
||||
* tb_block_eval(win, rt); // abre a janela
|
||||
* tb_graphics_run(rt); // loop até a janela principal fechar
|
||||
*/
|
||||
#ifndef TINYBLOCKS_GRAPHICS_H
|
||||
#define TINYBLOCKS_GRAPHICS_H
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks/tb_renderable_block.h>
|
||||
|
||||
/* ── Teclas (neutras; o backend traduz as suas) ──────────────────────────── */
|
||||
enum {
|
||||
TB_KEY_NONE = 0,
|
||||
TB_KEY_ESCAPE, TB_KEY_RETURN, TB_KEY_BACKSPACE, TB_KEY_DELETE, TB_KEY_TAB,
|
||||
TB_KEY_SPACE, TB_KEY_LEFT, TB_KEY_RIGHT, TB_KEY_UP, TB_KEY_DOWN,
|
||||
TB_KEY_HOME, TB_KEY_END,
|
||||
TB_KEY_F1, TB_KEY_F2, TB_KEY_F3, TB_KEY_F4, TB_KEY_F5, TB_KEY_F6,
|
||||
TB_KEY_F7, TB_KEY_F8, TB_KEY_F9, TB_KEY_F10, TB_KEY_F11, TB_KEY_F12,
|
||||
TB_KEY_A = 64, /* TB_KEY_A + n = letra 'a'+n */
|
||||
TB_KEY_0 = TB_KEY_A + 26, /* TB_KEY_0 + n = dígito n */
|
||||
TB_KEY_OTHER = 127
|
||||
};
|
||||
|
||||
/* ── Modificadores (bitmask) ─────────────────────────────────────────────── */
|
||||
#define TB_MOD_SHIFT 0x1
|
||||
#define TB_MOD_CTRL 0x2
|
||||
#define TB_MOD_ALT 0x4
|
||||
|
||||
/* ── Índices de output do bloco Graphics.Input ───────────────────────────── */
|
||||
#define GFX_IN_MOUSE_X 0 /* real: posição X do mouse na janela */
|
||||
#define GFX_IN_MOUSE_Y 1 /* real: posição Y do mouse na janela */
|
||||
#define GFX_IN_MOUSE_L_HELD 2 /* int: botão esquerdo pressionado (estado) */
|
||||
#define GFX_IN_MOUSE_R_HELD 3 /* int: botão direito pressionado (estado) */
|
||||
#define GFX_IN_MOUSE_L_DOWN 4 /* int: 1 se pressionado neste frame */
|
||||
#define GFX_IN_MOUSE_L_UP 5 /* int: 1 se solto neste frame */
|
||||
#define GFX_IN_MOUSE_R_DOWN 6 /* int: 1 se pressionado neste frame */
|
||||
#define GFX_IN_MOUSE_R_UP 7 /* int: 1 se solto neste frame */
|
||||
#define GFX_IN_SCROLL_DX 8 /* real: scroll horizontal deste frame */
|
||||
#define GFX_IN_SCROLL_DY 9 /* real: scroll vertical deste frame */
|
||||
#define GFX_IN_KEY 10 /* int: TB_KEY_* pressionada neste frame */
|
||||
#define GFX_IN_KEY_MOD 11 /* int: TB_MOD_* no momento da tecla */
|
||||
#define GFX_IN_KEY_REPEAT 12 /* int: 1 se é repetição de tecla segurada */
|
||||
#define GFX_IN_TEXT 13 /* text: texto digitado neste frame */
|
||||
#define GFX_IN_CLOSE 14 /* int: 1 se o usuário pediu para fechar */
|
||||
#define GFX_IN_WIN_W 15 /* int: largura atual da janela */
|
||||
#define GFX_IN_WIN_H 16 /* int: altura atual da janela */
|
||||
#define GFX_IN_DROP_FILE 17 /* text: caminho de arquivo solto na janela */
|
||||
#define GFX_IN_MOD_STATE 18 /* int: TB_MOD_* segurados agora */
|
||||
#define GFX_IN_COUNT 19
|
||||
|
||||
/* Estado de entrada de uma janela em um frame (preenchido pelo backend) */
|
||||
typedef struct TinyBlocks_GfxInput {
|
||||
float mouse_x, mouse_y;
|
||||
int l_held, r_held;
|
||||
int l_down, l_up, r_down, r_up;
|
||||
float scroll_dx, scroll_dy;
|
||||
int key, key_mod, key_repeat;
|
||||
char text[64];
|
||||
int close;
|
||||
int win_w, win_h;
|
||||
char drop_file[512];
|
||||
int mod_state;
|
||||
} TinyBlocks_GfxInput;
|
||||
|
||||
/* ── Contrato de um backend gráfico ──────────────────────────────────────── */
|
||||
typedef struct TinyBlocks_GraphicsBackend {
|
||||
const char* name;
|
||||
bool (*init)(void); /* idempotente */
|
||||
void (*shutdown)(void);
|
||||
void* (*window_open)(const char* title, int w, int h); /* handle opaco ou NULL */
|
||||
void (*window_close)(void* win);
|
||||
void (*poll)(void); /* coleta eventos do SO */
|
||||
void (*window_input)(void* win, TinyBlocks_GfxInput* out);
|
||||
void (*window_present)(void* win, const TinyBlocks_RenderableBlock* rb);
|
||||
float (*measure_text)(const char* text, float font_size); /* NULL = estimativa */
|
||||
void (*frame_wait)(void); /* NULL = ~16 ms */
|
||||
} TinyBlocks_GraphicsBackend;
|
||||
|
||||
/* Símbolo exportado por um backend carregado como .so */
|
||||
#define TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL "tinyblocks_get_graphics_backend"
|
||||
typedef const TinyBlocks_GraphicsBackend* (*TinyBlocks_GetGraphicsBackendFn)(void);
|
||||
|
||||
/* ── API ─────────────────────────────────────────────────────────────────── */
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_graphics_get_library(void);
|
||||
|
||||
/* Escolhe o backend (antes de abrir a primeira janela) */
|
||||
TB_API bool tb_graphics_set_backend(const TinyBlocks_GraphicsBackend* backend);
|
||||
TB_API bool tb_graphics_load_backend(const char* so_path);
|
||||
TB_API const TinyBlocks_GraphicsBackend* tb_graphics_backend(void);
|
||||
TB_API const TinyBlocks_GraphicsBackend* tb_graphics_null_backend(void);
|
||||
|
||||
/* Largura de um texto na fonte do backend */
|
||||
TB_API float tb_graphics_measure_text(const char* text, float font_size);
|
||||
|
||||
/* Loop principal: roda todas as janelas abertas até a principal fechar */
|
||||
TB_API void tb_graphics_run(TinyBlocks* rt);
|
||||
TB_API bool tb_graphics_window_is_open(TinyBlocks_Block* window);
|
||||
|
||||
#endif /* TINYBLOCKS_GRAPHICS_H */
|
||||
@@ -0,0 +1,383 @@
|
||||
/*
|
||||
* TinyBlocks — tb_graphics.c
|
||||
* Interface gráfica: escolha de backend, janelas, entrada e loop principal.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#include "../include/tb_graphics.h"
|
||||
|
||||
#ifdef TB_GRAPHICS_DEFAULT_SDL2
|
||||
#include <tb_sdl2.h>
|
||||
#endif
|
||||
|
||||
/* ══════════════════════════════════════════════════════════════════════════
|
||||
* Backend nulo (headless): janelas sem tela, entrada vazia, texto estimado
|
||||
* ══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct { int w, h; } NullWin;
|
||||
|
||||
static bool null_init(void) { return true; }
|
||||
static void null_shutdown(void) { }
|
||||
static void* null_open(const char* title, int w, int h) {
|
||||
(void)title;
|
||||
NullWin* n = (NullWin*)calloc(1, sizeof(*n));
|
||||
if (n) { n->w = w; n->h = h; }
|
||||
return n;
|
||||
}
|
||||
static void null_close(void* win) { free(win); }
|
||||
static void null_poll(void) { }
|
||||
static void null_input(void* win, TinyBlocks_GfxInput* out) {
|
||||
memset(out, 0, sizeof(*out));
|
||||
const NullWin* n = (const NullWin*)win;
|
||||
if (n) { out->win_w = n->w; out->win_h = n->h; }
|
||||
}
|
||||
static void null_present(void* win, const TinyBlocks_RenderableBlock* rb) { (void)win; (void)rb; }
|
||||
|
||||
static const TinyBlocks_GraphicsBackend s_null_backend = {
|
||||
.name = "null",
|
||||
.init = null_init,
|
||||
.shutdown = null_shutdown,
|
||||
.window_open = null_open,
|
||||
.window_close = null_close,
|
||||
.poll = null_poll,
|
||||
.window_input = null_input,
|
||||
.window_present = null_present,
|
||||
.measure_text = NULL,
|
||||
.frame_wait = NULL,
|
||||
};
|
||||
|
||||
const TinyBlocks_GraphicsBackend* tb_graphics_null_backend(void) { return &s_null_backend; }
|
||||
|
||||
/* ══════════════════════════════════════════════════════════════════════════
|
||||
* Escolha do backend
|
||||
* ══════════════════════════════════════════════════════════════════════════ */
|
||||
static const TinyBlocks_GraphicsBackend* s_backend = NULL;
|
||||
static bool s_backend_ready = false;
|
||||
static void* s_backend_dl = NULL;
|
||||
|
||||
#define MAX_WINDOWS 16
|
||||
typedef struct { TinyBlocks_Block* block; uint64_t id; } WinEntry;
|
||||
static WinEntry s_wins[MAX_WINDOWS];
|
||||
static int s_win_n = 0;
|
||||
static uint64_t s_next_id = 1;
|
||||
|
||||
const TinyBlocks_GraphicsBackend* tb_graphics_backend(void) {
|
||||
if (!s_backend) {
|
||||
#ifdef TB_GRAPHICS_DEFAULT_SDL2
|
||||
s_backend = (const TinyBlocks_GraphicsBackend*)tb_sdl2_graphics_backend();
|
||||
#endif
|
||||
if (!s_backend) s_backend = &s_null_backend;
|
||||
}
|
||||
return s_backend;
|
||||
}
|
||||
|
||||
/* Backend inicializado; se o init falhar, cai para o nulo */
|
||||
static const TinyBlocks_GraphicsBackend* backend_ready(void) {
|
||||
const TinyBlocks_GraphicsBackend* b = tb_graphics_backend();
|
||||
if (s_backend_ready) return b;
|
||||
if (b->init && !b->init()) {
|
||||
fprintf(stderr, "tinyblocks-graphics: backend '%s' falhou ao iniciar; usando 'null'\n", b->name);
|
||||
s_backend = b = &s_null_backend;
|
||||
}
|
||||
s_backend_ready = true;
|
||||
return b;
|
||||
}
|
||||
|
||||
bool tb_graphics_set_backend(const TinyBlocks_GraphicsBackend* backend) {
|
||||
if (!backend || !backend->window_open || !backend->window_present) return false;
|
||||
if (backend == s_backend) return true;
|
||||
if (s_win_n > 0) {
|
||||
fprintf(stderr, "tinyblocks-graphics: feche as janelas antes de trocar o backend\n");
|
||||
return false;
|
||||
}
|
||||
if (s_backend_ready && s_backend->shutdown) s_backend->shutdown();
|
||||
s_backend_ready = false;
|
||||
s_backend = backend;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool tb_graphics_load_backend(const char* so_path) {
|
||||
void* dl = dlopen(so_path, RTLD_NOW | RTLD_LOCAL);
|
||||
if (!dl) {
|
||||
fprintf(stderr, "tinyblocks-graphics: dlopen: %s\n", dlerror());
|
||||
return false;
|
||||
}
|
||||
TinyBlocks_GetGraphicsBackendFn get =
|
||||
(TinyBlocks_GetGraphicsBackendFn)(uintptr_t)dlsym(dl, TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL);
|
||||
const TinyBlocks_GraphicsBackend* b = get ? get() : NULL;
|
||||
if (!b || !tb_graphics_set_backend(b)) {
|
||||
fprintf(stderr, "tinyblocks-graphics: '%s' não exporta um backend válido (%s)\n",
|
||||
so_path, TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL);
|
||||
dlclose(dl);
|
||||
return false;
|
||||
}
|
||||
if (s_backend_dl) dlclose(s_backend_dl);
|
||||
s_backend_dl = dl;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ══════════════════════════════════════════════════════════════════════════
|
||||
* Medição de texto
|
||||
* ══════════════════════════════════════════════════════════════════════════ */
|
||||
|
||||
/* Larguras de avanço da DejaVu Sans, em em, para ASCII 32..126 — estimativa
|
||||
* usada quando o backend não sabe medir (ex: backend nulo). */
|
||||
static const float s_adv[95] = {
|
||||
.318f,.401f,.460f,.838f,.636f,.950f,.780f,.275f,.390f,.390f,.500f,.838f,.318f,.361f,.318f,.337f,
|
||||
.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.337f,.337f,.838f,.838f,.838f,.531f,
|
||||
1.0f, .684f,.686f,.698f,.770f,.632f,.575f,.775f,.752f,.295f,.295f,.656f,.557f,.863f,.748f,.787f,
|
||||
.603f,.787f,.695f,.635f,.611f,.732f,.684f,.989f,.685f,.611f,.685f,.390f,.337f,.390f,.838f,.500f,
|
||||
.500f,.613f,.635f,.550f,.635f,.615f,.352f,.635f,.634f,.278f,.278f,.579f,.278f,.974f,.634f,.612f,
|
||||
.635f,.635f,.411f,.521f,.392f,.634f,.592f,.818f,.592f,.592f,.525f,.636f,.337f,.636f,.838f
|
||||
};
|
||||
|
||||
static float estimate_text(const char* s, float fs) {
|
||||
float w = 0.f;
|
||||
for (const unsigned char* p = (const unsigned char*)s; *p; p++) {
|
||||
if (*p >= 32 && *p < 127) w += s_adv[*p - 32];
|
||||
else if ((*p & 0xC0) == 0xC0) w += (*p >= 0xE0) ? 0.9f : 0.62f; /* início de UTF-8 */
|
||||
}
|
||||
return w * fs;
|
||||
}
|
||||
|
||||
float tb_graphics_measure_text(const char* text, float font_size) {
|
||||
if (!text || !text[0]) return 0.f;
|
||||
const TinyBlocks_GraphicsBackend* b = backend_ready();
|
||||
return b->measure_text ? b->measure_text(text, font_size) : estimate_text(text, font_size);
|
||||
}
|
||||
|
||||
/* ══════════════════════════════════════════════════════════════════════════
|
||||
* Graphics.Input — estado de entrada de uma janela no frame
|
||||
* ══════════════════════════════════════════════════════════════════════════ */
|
||||
static const TinyBlocks_SlotDesc s_input_outs[GFX_IN_COUNT] = {
|
||||
{"mouse_x", TB_VALUE_REAL}, {"mouse_y", TB_VALUE_REAL},
|
||||
{"l_held", TB_VALUE_INTEGER}, {"r_held", TB_VALUE_INTEGER},
|
||||
{"l_down", TB_VALUE_INTEGER}, {"l_up", TB_VALUE_INTEGER},
|
||||
{"r_down", TB_VALUE_INTEGER}, {"r_up", TB_VALUE_INTEGER},
|
||||
{"scroll_dx", TB_VALUE_REAL}, {"scroll_dy", TB_VALUE_REAL},
|
||||
{"key", TB_VALUE_INTEGER}, {"key_mod", TB_VALUE_INTEGER},
|
||||
{"key_repeat", TB_VALUE_INTEGER}, {"text", TB_VALUE_TEXT},
|
||||
{"close", TB_VALUE_INTEGER}, {"win_w", TB_VALUE_INTEGER},
|
||||
{"win_h", TB_VALUE_INTEGER}, {"drop_file", TB_VALUE_TEXT},
|
||||
{"mod_state", TB_VALUE_INTEGER},
|
||||
};
|
||||
|
||||
static void eval_input(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
/* Os outputs são preenchidos pelo loop; aqui só garante valores neutros */
|
||||
for (uint32_t i = 0; i < self->output_count && i < GFX_IN_COUNT; i++) {
|
||||
if (self->outputs[i].kind != TB_VALUE_NONE) continue;
|
||||
switch (s_input_outs[i].expected_kind) {
|
||||
case TB_VALUE_REAL: self->outputs[i] = tb_value_real(0.0); break;
|
||||
case TB_VALUE_TEXT: self->outputs[i] = tb_value_text(""); break;
|
||||
default: self->outputs[i] = tb_value_integer(0); break;
|
||||
}
|
||||
}
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void input_push(TinyBlocks_Block* b, const TinyBlocks_GfxInput* in) {
|
||||
if (!b || b->output_count < GFX_IN_COUNT) return;
|
||||
#define SET(idx, v) tb_block_set_output(b, idx, v)
|
||||
SET(GFX_IN_MOUSE_X, tb_value_real(in->mouse_x));
|
||||
SET(GFX_IN_MOUSE_Y, tb_value_real(in->mouse_y));
|
||||
SET(GFX_IN_MOUSE_L_HELD, tb_value_integer(in->l_held));
|
||||
SET(GFX_IN_MOUSE_R_HELD, tb_value_integer(in->r_held));
|
||||
SET(GFX_IN_MOUSE_L_DOWN, tb_value_integer(in->l_down));
|
||||
SET(GFX_IN_MOUSE_L_UP, tb_value_integer(in->l_up));
|
||||
SET(GFX_IN_MOUSE_R_DOWN, tb_value_integer(in->r_down));
|
||||
SET(GFX_IN_MOUSE_R_UP, tb_value_integer(in->r_up));
|
||||
SET(GFX_IN_SCROLL_DX, tb_value_real(in->scroll_dx));
|
||||
SET(GFX_IN_SCROLL_DY, tb_value_real(in->scroll_dy));
|
||||
SET(GFX_IN_KEY, tb_value_integer(in->key));
|
||||
SET(GFX_IN_KEY_MOD, tb_value_integer(in->key_mod));
|
||||
SET(GFX_IN_KEY_REPEAT, tb_value_integer(in->key_repeat));
|
||||
SET(GFX_IN_TEXT, tb_value_text(in->text));
|
||||
SET(GFX_IN_CLOSE, tb_value_integer(in->close));
|
||||
SET(GFX_IN_WIN_W, tb_value_integer(in->win_w));
|
||||
SET(GFX_IN_WIN_H, tb_value_integer(in->win_h));
|
||||
SET(GFX_IN_DROP_FILE, tb_value_text(in->drop_file));
|
||||
SET(GFX_IN_MOD_STATE, tb_value_integer(in->mod_state));
|
||||
#undef SET
|
||||
b->dirty = false;
|
||||
}
|
||||
|
||||
/* ══════════════════════════════════════════════════════════════════════════
|
||||
* Graphics.Window — uma janela do SO mostrando uma cena
|
||||
* inputs: 0 título, 1 largura, 2 altura, 3 cena(block), 4 entrada(block),
|
||||
* 5 principal(int: fechar esta janela encerra o loop; padrão 1)
|
||||
* output: 0 aberta(int)
|
||||
* ══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct { void* handle; uint64_t id; bool open; } WinState;
|
||||
|
||||
static int win_find(uint64_t id) {
|
||||
for (int i = 0; i < s_win_n; i++) if (s_wins[i].id == id) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static void win_close(TinyBlocks_Block* self) {
|
||||
WinState* ws = (WinState*)self->userdata;
|
||||
if (!ws->open) return;
|
||||
int i = win_find(ws->id);
|
||||
if (i >= 0) { s_wins[i] = s_wins[s_win_n - 1]; s_win_n--; }
|
||||
if (ws->handle && s_backend_ready) s_backend->window_close(ws->handle);
|
||||
ws->handle = NULL;
|
||||
ws->open = false;
|
||||
tb_block_set_output(self, 0, tb_value_integer(0));
|
||||
}
|
||||
|
||||
static bool win_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
memset(self->userdata, 0, sizeof(WinState));
|
||||
return true;
|
||||
}
|
||||
|
||||
static void win_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
win_close(self);
|
||||
}
|
||||
|
||||
static void eval_window(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
WinState* ws = (WinState*)self->userdata;
|
||||
self->dirty = false;
|
||||
if (ws->open) return;
|
||||
if (s_win_n >= MAX_WINDOWS) {
|
||||
tinyblocks_set_error(rt, "Graphics.Window: limite de %d janelas", MAX_WINDOWS);
|
||||
return;
|
||||
}
|
||||
TinyBlocks_Value vt = tb_block_get_input(self, rt, 0);
|
||||
TinyBlocks_Value vw = tb_block_get_input(self, rt, 1);
|
||||
TinyBlocks_Value vh = tb_block_get_input(self, rt, 2);
|
||||
const char* title = (vt.kind == TB_VALUE_TEXT && vt.as.text) ? vt.as.text : "TinyBlocks";
|
||||
int w = vw.kind == TB_VALUE_INTEGER && vw.as.integer > 0 ? (int)vw.as.integer : 640;
|
||||
int h = vh.kind == TB_VALUE_INTEGER && vh.as.integer > 0 ? (int)vh.as.integer : 480;
|
||||
|
||||
const TinyBlocks_GraphicsBackend* b = backend_ready();
|
||||
void* handle = b->window_open(title, w, h);
|
||||
if (!handle) {
|
||||
tinyblocks_set_error(rt, "Graphics.Window: o backend '%s' não abriu a janela", b->name);
|
||||
return;
|
||||
}
|
||||
ws->handle = handle;
|
||||
ws->id = s_next_id++;
|
||||
ws->open = true;
|
||||
s_wins[s_win_n++] = (WinEntry){ self, ws->id };
|
||||
tb_block_set_output(self, 0, tb_value_integer(1));
|
||||
}
|
||||
|
||||
bool tb_graphics_window_is_open(TinyBlocks_Block* window) {
|
||||
if (!window || !window->type || !window->type->type_name ||
|
||||
strcmp(window->type->type_name, "Graphics.Window") != 0) return false;
|
||||
return ((WinState*)window->userdata)->open;
|
||||
}
|
||||
|
||||
/* ══════════════════════════════════════════════════════════════════════════
|
||||
* Loop principal
|
||||
* ══════════════════════════════════════════════════════════════════════════ */
|
||||
static void default_wait(void) {
|
||||
struct timespec ts = { 0, 16 * 1000000L };
|
||||
nanosleep(&ts, NULL);
|
||||
}
|
||||
|
||||
void tb_graphics_run(TinyBlocks* rt) {
|
||||
const TinyBlocks_GraphicsBackend* b = backend_ready();
|
||||
bool running = s_win_n > 0;
|
||||
while (running) {
|
||||
if (b->poll) b->poll();
|
||||
|
||||
/* As cenas podem abrir/fechar janelas: itera sobre uma cópia dos ids */
|
||||
uint64_t ids[MAX_WINDOWS];
|
||||
int n = s_win_n;
|
||||
for (int i = 0; i < n; i++) ids[i] = s_wins[i].id;
|
||||
|
||||
for (int k = 0; k < n; k++) {
|
||||
int i = win_find(ids[k]);
|
||||
if (i < 0) continue;
|
||||
TinyBlocks_Block* wb = s_wins[i].block;
|
||||
WinState* ws = (WinState*)wb->userdata;
|
||||
|
||||
TinyBlocks_GfxInput in;
|
||||
b->window_input(ws->handle, &in);
|
||||
TinyBlocks_Value vin = tb_block_get_input(wb, rt, 4);
|
||||
if (vin.kind == TB_VALUE_BLOCK) input_push(vin.as.block, &in);
|
||||
|
||||
if (in.close) {
|
||||
TinyBlocks_Value vp = tb_block_get_input(wb, rt, 5);
|
||||
if (vp.kind != TB_VALUE_INTEGER || vp.as.integer) running = false;
|
||||
win_close(wb);
|
||||
continue;
|
||||
}
|
||||
|
||||
TinyBlocks_RenderableBlock* rb = NULL;
|
||||
TinyBlocks_Value vs = tb_block_get_input(wb, rt, 3);
|
||||
TinyBlocks_Block* scene = vs.kind == TB_VALUE_BLOCK ? vs.as.block : NULL;
|
||||
if (scene) {
|
||||
scene->dirty = true;
|
||||
tb_block_eval(scene, rt);
|
||||
if (win_find(ids[k]) < 0) continue; /* a cena fechou esta janela */
|
||||
if (scene->type && scene->type->on_draw) scene->type->on_draw(scene, rt, &rb);
|
||||
}
|
||||
b->window_present(ws->handle, rb);
|
||||
if (rb) tb_renderable_release(rb);
|
||||
}
|
||||
tb_renderable_release_all();
|
||||
|
||||
if (s_win_n == 0) running = false;
|
||||
if (running) { if (b->frame_wait) b->frame_wait(); else default_wait(); }
|
||||
}
|
||||
|
||||
while (s_win_n > 0) win_close(s_wins[s_win_n - 1].block);
|
||||
if (b->shutdown) b->shutdown();
|
||||
s_backend_ready = false;
|
||||
}
|
||||
|
||||
static void eval_run(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
self->dirty = false;
|
||||
tb_graphics_run(rt);
|
||||
}
|
||||
|
||||
/* ══════════════════════════════════════════════════════════════════════════
|
||||
* Registro da library
|
||||
* ══════════════════════════════════════════════════════════════════════════ */
|
||||
static bool graphics_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
TinyBlocks_TypeBlock* t;
|
||||
|
||||
t = tb_type_block_create(rt, "Graphics.Input", NULL, 0, s_input_outs, GFX_IN_COUNT, eval_input);
|
||||
if (!t) return false;
|
||||
tb_library_add(lib, &t->base);
|
||||
|
||||
static const TinyBlocks_SlotDesc win_in[] = {
|
||||
{"título", TB_VALUE_TEXT}, {"largura", TB_VALUE_INTEGER}, {"altura", TB_VALUE_INTEGER},
|
||||
{"cena", TB_VALUE_BLOCK}, {"entrada", TB_VALUE_BLOCK}, {"principal", TB_VALUE_INTEGER},
|
||||
};
|
||||
static const TinyBlocks_SlotDesc win_out[] = {{"aberta", TB_VALUE_INTEGER}};
|
||||
t = tb_type_block_create(rt, "Graphics.Window", win_in, 6, win_out, 1, eval_window);
|
||||
if (!t) return false;
|
||||
tb_type_block_set_instance_hooks(t, sizeof(WinState), win_instance_init, win_instance_deinit);
|
||||
tb_library_add(lib, &t->base);
|
||||
|
||||
t = tb_type_block_create(rt, "Graphics.Run", NULL, 0, NULL, 0, eval_run);
|
||||
if (!t) return false;
|
||||
tb_library_add(lib, &t->base);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void graphics_lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
(void)rt; (void)lib;
|
||||
if (s_backend_ready && s_backend->shutdown) s_backend->shutdown();
|
||||
s_backend_ready = false;
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(graphics,
|
||||
"tinyblocks-graphics",
|
||||
"1.0.0",
|
||||
graphics_lib_init,
|
||||
graphics_lib_deinit)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_graphics_get_library(void) {
|
||||
return &_tb_lib_desc_graphics;
|
||||
}
|
||||
Reference in new issue
Block a user