/* * TinyBlocks - tb_graphics.c * Interface gráfica: escolha de backend, janelas, entrada e loop principal. */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include "../include/tb_graphics.h" #ifdef TB_GRAPHICS_DEFAULT_SDL2 #include #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; } /* Area de transferencia: a do backend, ou esta memoria (backend nulo/testes) */ static char* s_clip = NULL; bool tb_graphics_set_clipboard(const char* text) { const TinyBlocks_GraphicsBackend* b = backend_ready(); if (b->clipboard_set) return b->clipboard_set(text ? text : ""); free(s_clip); s_clip = text ? strdup(text) : NULL; return true; } char* tb_graphics_get_clipboard(void) { const TinyBlocks_GraphicsBackend* b = backend_ready(); if (b->clipboard_get) return b->clipboard_get(); return s_clip ? strdup(s_clip) : NULL; } void tb_graphics_text_input(bool on, float x, float y, float w, float h) { const TinyBlocks_GraphicsBackend* b = backend_ready(); if (b->text_input) b->text_input(on, x, y, w, h); } 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}, {"keys_held", TB_VALUE_JSON}, {"touches", TB_VALUE_JSON}, {"accel", TB_VALUE_JSON}, {"gyro", TB_VALUE_JSON}, {"win_x", TB_VALUE_INTEGER}, {"win_y", TB_VALUE_INTEGER}, {"mouse_in", TB_VALUE_INTEGER}, {"gmouse_x", TB_VALUE_REAL}, {"gmouse_y", TB_VALUE_REAL}, {"zoom", TB_VALUE_REAL}, }; 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; case TB_VALUE_JSON: { TinyBlocks_JsonValue* e = tb_json_array(); self->outputs[i] = tb_value_json(e); tb_json_release(e); break; } default: self->outputs[i] = tb_value_integer(0); break; } } self->dirty = false; } /* Valores JSON das saidas de dispositivo (teclas seguradas, toques, sensores) */ static void json_push_num(TinyBlocks_JsonValue* arr, double d) { TinyBlocks_JsonValue* n = tb_json_number(d); if (n) { tb_json_array_push(arr, n); tb_json_release(n); } } static TinyBlocks_Value json_out(TinyBlocks_JsonValue* arr) { TinyBlocks_Value v = tb_value_json(arr); /* retem */ tb_json_release(arr); return v; } static TinyBlocks_Value json_keys(const TinyBlocks_GfxInput* in) { TinyBlocks_JsonValue* arr = tb_json_array(); for (int k = 1; arr && k < 128; k++) if (in->keys_held[k]) json_push_num(arr, k); return json_out(arr); } static TinyBlocks_Value json_touches(const TinyBlocks_GfxInput* in) { TinyBlocks_JsonValue* arr = tb_json_array(); int n = in->touch_n < GFX_MAX_TOUCHES ? in->touch_n : GFX_MAX_TOUCHES; for (int i = 0; arr && i < n; i++) { TinyBlocks_JsonValue* p = tb_json_array(); if (!p) break; json_push_num(p, in->touch_x[i]); json_push_num(p, in->touch_y[i]); tb_json_array_push(arr, p); tb_json_release(p); } return json_out(arr); } static TinyBlocks_Value json_vec3(int has, const float v[3]) { TinyBlocks_JsonValue* arr = tb_json_array(); for (int i = 0; arr && has && i < 3; i++) json_push_num(arr, v[i]); return json_out(arr); } 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)); SET(GFX_IN_KEYS_HELD, json_keys(in)); SET(GFX_IN_TOUCHES, json_touches(in)); SET(GFX_IN_ACCEL, json_vec3(in->has_accel, in->accel)); SET(GFX_IN_GYRO, json_vec3(in->has_gyro, in->gyro)); SET(GFX_IN_WIN_X, tb_value_integer(in->win_x)); SET(GFX_IN_WIN_Y, tb_value_integer(in->win_y)); SET(GFX_IN_MOUSE_IN, tb_value_integer(in->mouse_in)); SET(GFX_IN_GMOUSE_X, tb_value_real(in->gmouse_x)); SET(GFX_IN_GMOUSE_Y, tb_value_real(in->gmouse_y)); SET(GFX_IN_ZOOM, tb_value_real(in->zoom)); #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 * === */ /* Completa o quadro em ~16,7 ms contando desde o anterior (60 fps) */ static void default_wait(void) { static struct timespec prev = { 0, 0 }; struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); if (prev.tv_sec || prev.tv_nsec) { long ns = (now.tv_sec - prev.tv_sec) * 1000000000L + (now.tv_nsec - prev.tv_nsec); long left = 16666667L - ns; if (left > 500000L) { struct timespec ts = { 0, left }; nanosleep(&ts, NULL); } } clock_gettime(CLOCK_MONOTONIC, &prev); } 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; /* tipos de infraestrutura: nao aparecem na paleta */ t = tb_type_block_create(rt, "Graphics.Input", NULL, 0, s_input_outs, GFX_IN_COUNT, eval_input); if (!t) return false; tb_type_block_set_flags(t, TB_TYPE_HIDDEN); 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_type_block_set_flags(t, TB_TYPE_HIDDEN); 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_type_block_set_flags(t, TB_TYPE_HIDDEN); 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; }