/* * TinyBlocks - tb_sdl2.c * Backend SDL2 para TinyBlocks. * * Blocos principais: * SDL2.Events - snapshot de eventos do frame, pré-preenchido pelo SDL2.App * SDL2.App - janela + renderer + loop principal + executor de renderables * * Blocos primitivos legados: Init, Quit, Window, Renderer, etc. * * Também implementa o contrato TinyBlocks_GraphicsBackend da interface * tinyblocks-graphics (várias janelas, entrada por janela, desenho com AA e * medição de texto com a fonte real) - ver tb_sdl2_graphics_backend(). */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include #include #include #include "../include/tb_sdl2.h" /* === * Handles opacos de Window/Renderer (blocos wrapper) * === */ static TinyBlocks_TypeBlock* s_type_window_handle = NULL; static TinyBlocks_TypeBlock* s_type_renderer_handle = NULL; static TinyBlocks_Block* make_handle_block(TinyBlocks* rt, TinyBlocks_TypeBlock* type, void* ptr) { TinyBlocks_Block* b = tb_block_create(rt, type); if (b) b->userdata = ptr; return b; } static void eval_handle_noop(TinyBlocks_Block* self, TinyBlocks* rt) { (void)self; (void)rt; } /* === * Fonte TTF - cache por tamanho * === */ #define FONT_CACHE_CAP 8 #define FONT_SEARCH_COUNT 6 typedef struct { int size; TTF_Font* font; } FontEntry; static FontEntry s_font_cache[FONT_CACHE_CAP]; static int s_font_cache_n = 0; static const char* s_font_paths[FONT_SEARCH_COUNT] = { "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/TTF/DejaVuSans.ttf", "/usr/share/fonts/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", "/usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf", "/System/Library/Fonts/Helvetica.ttc", }; static TTF_Font* get_font(int size) { for (int i = 0; i < s_font_cache_n; i++) if (s_font_cache[i].size == size) return s_font_cache[i].font; TTF_Font* f = NULL; for (int i = 0; i < FONT_SEARCH_COUNT && !f; i++) f = TTF_OpenFont(s_font_paths[i], size); if (f && s_font_cache_n < FONT_CACHE_CAP) { s_font_cache[s_font_cache_n].size = size; s_font_cache[s_font_cache_n].font = f; s_font_cache_n++; } return f; } static void fonts_close_all(void) { for (int i = 0; i < s_font_cache_n; i++) { TTF_CloseFont(s_font_cache[i].font); s_font_cache[i].font = NULL; } s_font_cache_n = 0; } /* === * Executor de TinyBlocks_RenderableBlock via SDL2 * === */ /* -- Rasterização com antialias --- * As formas preenchidas são varridas linha a linha com AA_SUB sub-linhas por * pixel e cobertura horizontal exata. Cada pixel é pintado uma única vez, com * alpha proporcional à cobertura: bordas suavizadas e sem overdraw (cores * translúcidas ficam uniformes, inclusive nos cantos arredondados). */ #define AA_SUB 4 typedef struct { Uint8 r, g, b, a; } Rgba; static Rgba rgba_of(const TinyBlocks_DrawCmd* cmd) { return (Rgba){ (Uint8)(cmd->r*255.f + 0.5f), (Uint8)(cmd->g*255.f + 0.5f), (Uint8)(cmd->b*255.f + 0.5f), (Uint8)(cmd->a*255.f + 0.5f) }; } /* Preenche [x0,x1) x [y0,y1) com a cor c atenuada pela cobertura cov */ static void aa_rect(SDL_Renderer* ren, Rgba c, int x0, int y0, int x1, int y1, float cov) { if (x1 <= x0 || y1 <= y0 || cov <= 0.f) return; Uint8 a = (Uint8)(c.a * (cov > 1.f ? 1.f : cov) + 0.5f); if (!a) return; SDL_SetRenderDrawColor(ren, c.r, c.g, c.b, a); SDL_Rect rc = { x0, y0, x1 - x0, y1 - y0 }; SDL_RenderFillRect(ren, &rc); } /* Fração do pixel px coberta pelos intervalos [l,r] das sub-linhas */ static float aa_cover(const float* l, const float* r, const bool* ok, int px) { float s = 0.f; for (int i = 0; i < AA_SUB; i++) { if (!ok[i]) continue; float a = l[i] > (float)px ? l[i] : (float)px; float b = r[i] < (float)(px + 1) ? r[i] : (float)(px + 1); if (b > a) s += b - a; } return s / AA_SUB; } /* Uma linha de pixels de uma forma convexa: interior sólido + bordas parciais */ static void aa_row(SDL_Renderer* ren, Rgba c, int py, const float* l, const float* r, const bool* ok) { float L = 0.f, R = 0.f; int sl = 0, sr = 0; bool any = false, all = true; for (int i = 0; i < AA_SUB; i++) { if (!ok[i]) { all = false; continue; } int cl = (int)ceilf(l[i]), fr = (int)floorf(r[i]); if (!any) { L = l[i]; R = r[i]; sl = cl; sr = fr; any = true; continue; } if (l[i] < L) L = l[i]; if (r[i] > R) R = r[i]; if (cl > sl) sl = cl; if (fr < sr) sr = fr; } if (!any) return; int x0 = (int)floorf(L), x1 = (int)ceilf(R); if (!all || sl >= sr) sl = sr = x1; /* sem interior totalmente coberto */ for (int px = x0; px < sl; px++) aa_rect(ren, c, px, py, px + 1, py + 1, aa_cover(l, r, ok, px)); aa_rect(ren, c, sl, py, sr, py + 1, 1.f); for (int px = sr; px < x1; px++) aa_rect(ren, c, px, py, px + 1, py + 1, aa_cover(l, r, ok, px)); } /* Extensão horizontal de um retângulo arredondado na altura yc */ static bool rrect_span(float x, float y, float w, float h, float rad, float yc, float* l, float* r) { if (yc < y || yc > y + h) return false; float d = 0.f; if (yc < y + rad) d = y + rad - yc; else if (yc > y + h - rad) d = yc - (y + h - rad); float dx = d > 0.f ? rad - sqrtf(fmaxf(rad*rad - d*d, 0.f)) : 0.f; *l = x + dx; *r = x + w - dx; return *r > *l; } static void aa_fill_rrect(SDL_Renderer* ren, Rgba c, float x, float y, float w, float h, float rad) { if (w <= 0.f || h <= 0.f || !c.a) return; if (rad < 0.f) rad = 0.f; if (rad > w*0.5f) rad = w*0.5f; if (rad > h*0.5f) rad = h*0.5f; /* Trecho reto do meio: um retângulo sólido + duas colunas de borda */ int by0 = (int)ceilf(y + rad), by1 = (int)floorf(y + h - rad); if (by1 > by0) { int xl = (int)ceilf(x), xr = (int)floorf(x + w); if (xr > xl) { aa_rect(ren, c, xl, by0, xr, by1, 1.f); aa_rect(ren, c, xl - 1, by0, xl, by1, (float)xl - x); aa_rect(ren, c, xr, by0, xr + 1, by1, x + w - (float)xr); } else { aa_rect(ren, c, (int)floorf(x), by0, (int)floorf(x) + 1, by1, w); } } else { by0 = by1 = 0; } /* Cantos e bordas superior/inferior: varredura */ float l[AA_SUB], r[AA_SUB]; bool ok[AA_SUB]; for (int py = (int)floorf(y); py < (int)ceilf(y + h); py++) { if (py >= by0 && py < by1) continue; for (int i = 0; i < AA_SUB; i++) ok[i] = rrect_span(x, y, w, h, rad, py + (i + 0.5f)/AA_SUB, &l[i], &r[i]); aa_row(ren, c, py, l, r, ok); } } /* Extensão horizontal de um polígono convexo na altura yc */ static bool poly_span(const float* px, const float* py, int n, float yc, float* l, float* r) { bool hit = false; float lo = 0.f, hi = 0.f; for (int i = 0; i < n; i++) { int j = (i + 1) % n; float y0 = py[i], y1 = py[j]; if (yc < fminf(y0, y1) || yc > fmaxf(y0, y1)) continue; float xa, xb; if (y1 == y0) { xa = fminf(px[i], px[j]); xb = fmaxf(px[i], px[j]); } else { xa = xb = px[i] + (yc - y0)/(y1 - y0)*(px[j] - px[i]); } if (!hit) { lo = xa; hi = xb; hit = true; } else { lo = fminf(lo, xa); hi = fmaxf(hi, xb); } } *l = lo; *r = hi; return hit && hi > lo; } static void aa_fill_poly(SDL_Renderer* ren, Rgba c, const float* px, const float* py, int n) { float y0 = py[0], y1 = py[0]; for (int i = 1; i < n; i++) { y0 = fminf(y0, py[i]); y1 = fmaxf(y1, py[i]); } float l[AA_SUB], r[AA_SUB]; bool ok[AA_SUB]; for (int y = (int)floorf(y0); y < (int)ceilf(y1); y++) { for (int i = 0; i < AA_SUB; i++) ok[i] = poly_span(px, py, n, y + (i + 0.5f)/AA_SUB, &l[i], &r[i]); aa_row(ren, c, y, l, r, ok); } } /* Linha com espessura: retângulo orientado, com meia espessura de "capa" * nas pontas. As coordenadas são de pixel (o centro do pixel é +0.5). */ static void aa_line(SDL_Renderer* ren, Rgba c, float x0, float y0, float x1, float y1, float thick) { if (thick < 1.f) thick = 1.f; x0 += 0.5f; y0 += 0.5f; x1 += 0.5f; y1 += 0.5f; float dx = x1 - x0, dy = y1 - y0, len = sqrtf(dx*dx + dy*dy); if (len < 1e-4f) { dx = 1.f; dy = 0.f; } else { dx /= len; dy /= len; } float hx = dx*0.5f, hy = dy*0.5f; /* capa de meio pixel */ float nx = -dy*thick*0.5f, ny = dx*thick*0.5f; /* normal */ float qx[4] = { x0 - hx + nx, x1 + hx + nx, x1 + hx - nx, x0 - hx - nx }; float qy[4] = { y0 - hy + ny, y1 + hy + ny, y1 + hy - ny, y0 - hy - ny }; aa_fill_poly(ren, c, qx, qy, 4); } /* Anel: círculo de raio rad menos o de raio rad - thick (por pixel) */ static void aa_stroke_circle(SDL_Renderer* ren, Rgba c, float cx, float cy, float rad, float thick) { if (rad <= 0.f || !c.a) return; if (thick < 1.f) thick = 1.f; float ri = rad - thick > 0.f ? rad - thick : 0.f; float lo[AA_SUB], ro[AA_SUB], li[AA_SUB], rri[AA_SUB]; bool oko[AA_SUB], oki[AA_SUB]; for (int py = (int)floorf(cy - rad); py < (int)ceilf(cy + rad); py++) { for (int i = 0; i < AA_SUB; i++) { float yc = py + (i + 0.5f)/AA_SUB; oko[i] = rrect_span(cx - rad, cy - rad, 2*rad, 2*rad, rad, yc, &lo[i], &ro[i]); oki[i] = ri > 0.f && rrect_span(cx - ri, cy - ri, 2*ri, 2*ri, ri, yc, &li[i], &rri[i]); } for (int px = (int)floorf(cx - rad); px < (int)ceilf(cx + rad); px++) aa_rect(ren, c, px, py, px + 1, py + 1, aa_cover(lo, ro, oko, px) - aa_cover(li, rri, oki, px)); } } static void set_color(SDL_Renderer* ren, float r, float g, float b, float a) { SDL_SetRenderDrawColor(ren, (Uint8)(r*255.f), (Uint8)(g*255.f), (Uint8)(b*255.f), (Uint8)(a*255.f)); } static void sdl2_execute(SDL_Renderer* ren, const TinyBlocks_RenderableBlock* rb) { if (!ren || !rb) return; SDL_SetRenderDrawBlendMode(ren, SDL_BLENDMODE_BLEND); for (uint32_t i = 0; i < rb->count; i++) { const TinyBlocks_DrawCmd* cmd = &rb->cmds[i]; switch (cmd->kind) { case TB_DRAW_CLEAR: set_color(ren, cmd->r, cmd->g, cmd->b, cmd->a); SDL_RenderClear(ren); break; case TB_DRAW_FILL_RECT: aa_fill_rrect(ren, rgba_of(cmd), cmd->x, cmd->y, cmd->w, cmd->h, 0.f); break; case TB_DRAW_FILL_RRECT: aa_fill_rrect(ren, rgba_of(cmd), cmd->x, cmd->y, cmd->w, cmd->h, cmd->param); break; case TB_DRAW_FILL_CIRCLE: aa_fill_rrect(ren, rgba_of(cmd), cmd->x - cmd->param, cmd->y - cmd->param, 2*cmd->param, 2*cmd->param, cmd->param); break; case TB_DRAW_STROKE_LINE: aa_line(ren, rgba_of(cmd), cmd->x, cmd->y, cmd->w, cmd->h, cmd->param); break; case TB_DRAW_STROKE_RECT: { /* Quatro faixas sem sobreposição, espessura para dentro */ Rgba c = rgba_of(cmd); float t = cmd->param < 1.f ? 1.f : cmd->param; float x = cmd->x, y = cmd->y, w = cmd->w, h = cmd->h; if (2*t >= w || 2*t >= h) { aa_fill_rrect(ren, c, x, y, w, h, 0.f); break; } aa_fill_rrect(ren, c, x, y, w, t, 0.f); aa_fill_rrect(ren, c, x, y + h - t, w, t, 0.f); aa_fill_rrect(ren, c, x, y + t, t, h - 2*t, 0.f); aa_fill_rrect(ren, c, x + w - t, y + t, t, h - 2*t, 0.f); break; } case TB_DRAW_STROKE_CIRCLE: aa_stroke_circle(ren, rgba_of(cmd), cmd->x, cmd->y, cmd->param, cmd->w); break; case TB_DRAW_SET_CLIP: { SDL_Rect clip = {(int)cmd->x, (int)cmd->y, (int)cmd->w, (int)cmd->h}; SDL_RenderSetClipRect(ren, &clip); } break; case TB_DRAW_CLEAR_CLIP: SDL_RenderSetClipRect(ren, NULL); break; case TB_DRAW_IMAGE: if (cmd->image) { int iw = tb_image_width(cmd->image); int ih = tb_image_height(cmd->image); int ch = tb_image_channels(cmd->image); const uint8_t* px = tb_image_data_const(cmd->image); if (iw > 0 && ih > 0 && px) { SDL_Surface* surf = NULL; uint8_t* tmp = NULL; if (ch == 4) { surf = SDL_CreateRGBSurfaceWithFormatFrom((void*)px, iw, ih, 32, iw*4, SDL_PIXELFORMAT_RGBA32); } else if (ch == 3) { surf = SDL_CreateRGBSurfaceWithFormatFrom((void*)px, iw, ih, 24, iw*3, SDL_PIXELFORMAT_RGB24); } else if (ch == 1) { tmp = (uint8_t*)malloc((size_t)iw * (size_t)ih * 4); if (tmp) { size_t n = (size_t)iw * (size_t)ih; for (size_t k = 0; k < n; k++) { tmp[k*4+0] = tmp[k*4+1] = tmp[k*4+2] = px[k]; tmp[k*4+3] = 255; } surf = SDL_CreateRGBSurfaceWithFormatFrom(tmp, iw, ih, 32, iw*4, SDL_PIXELFORMAT_RGBA32); } } if (surf) { SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, surf); if (tex) { SDL_Rect dst = {(int)cmd->x, (int)cmd->y, (int)cmd->w, (int)cmd->h}; SDL_RenderCopy(ren, tex, NULL, &dst); SDL_DestroyTexture(tex); } SDL_FreeSurface(surf); } free(tmp); } } break; case TB_DRAW_TEXT: if (cmd->text[0]) { TTF_Font* font = get_font((int)cmd->font_size); if (font) { SDL_Color col = { (Uint8)(cmd->r*255.f), (Uint8)(cmd->g*255.f), (Uint8)(cmd->b*255.f), (Uint8)(cmd->a*255.f) }; SDL_Surface* surf = TTF_RenderUTF8_Blended(font, cmd->text, col); if (surf) { SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, surf); if (tex) { /* cmd->x,cmd->y é baseline-left; converte para o topo do retângulo usando o ascent real da fonte. */ SDL_Rect dst = {(int)cmd->x, (int)cmd->y - TTF_FontAscent(font), surf->w, surf->h}; SDL_RenderCopy(ren, tex, NULL, &dst); SDL_DestroyTexture(tex); } SDL_FreeSurface(surf); } } } break; } } } /* === * Backend da interface tinyblocks-graphics * === */ typedef struct SdlWin { SDL_Window* win; SDL_Renderer* ren; Uint32 id; TinyBlocks_GfxInput in; int pos_fresh; /* posicao do mouse veio de um evento neste quadro */ struct SdlWin* next; } SdlWin; static SdlWin* s_wins = NULL; static bool s_be_inited = false; static int map_key(SDL_Scancode sc) { if (sc >= SDL_SCANCODE_A && sc <= SDL_SCANCODE_Z) return TB_KEY_A + (sc - SDL_SCANCODE_A); if (sc >= SDL_SCANCODE_1 && sc <= SDL_SCANCODE_9) return TB_KEY_0 + 1 + (sc - SDL_SCANCODE_1); if (sc >= SDL_SCANCODE_F1 && sc <= SDL_SCANCODE_F12) return TB_KEY_F1 + (sc - SDL_SCANCODE_F1); switch (sc) { case SDL_SCANCODE_0: return TB_KEY_0; case SDL_SCANCODE_ESCAPE: return TB_KEY_ESCAPE; case SDL_SCANCODE_RETURN: case SDL_SCANCODE_KP_ENTER: return TB_KEY_RETURN; case SDL_SCANCODE_BACKSPACE: return TB_KEY_BACKSPACE; case SDL_SCANCODE_DELETE: case SDL_SCANCODE_KP_PERIOD: return TB_KEY_DELETE; case SDL_SCANCODE_TAB: return TB_KEY_TAB; case SDL_SCANCODE_SPACE: return TB_KEY_SPACE; case SDL_SCANCODE_LEFT: return TB_KEY_LEFT; case SDL_SCANCODE_RIGHT: return TB_KEY_RIGHT; case SDL_SCANCODE_UP: return TB_KEY_UP; case SDL_SCANCODE_DOWN: return TB_KEY_DOWN; case SDL_SCANCODE_HOME: return TB_KEY_HOME; case SDL_SCANCODE_END: return TB_KEY_END; default: return TB_KEY_OTHER; } } static int map_mod(Uint16 m) { return ((m & KMOD_SHIFT) ? TB_MOD_SHIFT : 0) | ((m & KMOD_CTRL) ? TB_MOD_CTRL : 0) | ((m & KMOD_ALT) ? TB_MOD_ALT : 0); } static SdlWin* win_by_id(Uint32 id) { for (SdlWin* w = s_wins; w; w = w->next) if (w->id == id) return w; return NULL; } /* Sensores do dispositivo (celular/tablet; no desktop costuma nao haver) */ static SDL_Sensor* s_accel = NULL; static SDL_Sensor* s_gyro = NULL; static void sensors_open(void) { if (SDL_InitSubSystem(SDL_INIT_SENSOR) != 0) return; for (int i = 0; i < SDL_NumSensors(); i++) { SDL_SensorType t = SDL_SensorGetDeviceType(i); if (t == SDL_SENSOR_ACCEL && !s_accel) s_accel = SDL_SensorOpen(i); if (t == SDL_SENSOR_GYRO && !s_gyro) s_gyro = SDL_SensorOpen(i); } } static void sensors_close(void) { if (s_accel) { SDL_SensorClose(s_accel); s_accel = NULL; } if (s_gyro) { SDL_SensorClose(s_gyro); s_gyro = NULL; } } static bool be_init(void) { if (s_be_inited) return true; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { fprintf(stderr, "tinyblocks-sdl2: SDL_Init: %s\n", SDL_GetError()); return false; } if (TTF_Init() != 0) { fprintf(stderr, "tinyblocks-sdl2: TTF_Init: %s\n", TTF_GetError()); SDL_Quit(); return false; } SDL_EventState(SDL_DROPFILE, SDL_ENABLE); SDL_StartTextInput(); sensors_open(); s_be_inited = true; return true; } static void be_window_close(void* handle) { SdlWin* w = (SdlWin*)handle; for (SdlWin** pp = &s_wins; *pp; pp = &(*pp)->next) if (*pp == w) { *pp = w->next; break; } if (w->ren) SDL_DestroyRenderer(w->ren); if (w->win) SDL_DestroyWindow(w->win); free(w); } static void be_shutdown(void) { if (!s_be_inited) return; while (s_wins) be_window_close(s_wins); sensors_close(); fonts_close_all(); TTF_Quit(); SDL_Quit(); s_be_inited = false; } static void* be_window_open(const char* title, int w, int h) { if (!be_init()) return NULL; SdlWin* sw = (SdlWin*)calloc(1, sizeof(SdlWin)); if (!sw) return NULL; sw->win = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (!sw->win) { fprintf(stderr, "tinyblocks-sdl2: janela: %s\n", SDL_GetError()); free(sw); return NULL; } /* Sem vsync: com várias janelas cada present esperaria um retraço */ sw->ren = SDL_CreateRenderer(sw->win, -1, SDL_RENDERER_ACCELERATED); if (!sw->ren) sw->ren = SDL_CreateRenderer(sw->win, -1, SDL_RENDERER_SOFTWARE); if (!sw->ren) { fprintf(stderr, "tinyblocks-sdl2: renderer: %s\n", SDL_GetError()); SDL_DestroyWindow(sw->win); free(sw); return NULL; } SDL_SetRenderDrawBlendMode(sw->ren, SDL_BLENDMODE_BLEND); sw->id = SDL_GetWindowID(sw->win); sw->in.win_w = w; sw->in.win_h = h; sw->next = s_wins; s_wins = sw; return sw; } /* Evento que nao coube no quadro anterior (segunda tecla, texto alem do buffer, clique repetido): e o primeiro a ser aplicado no proximo quadro, assim nada se perde ao digitar rapido ou colar texto. */ static SDL_Event s_pending; static bool s_has_pending = false; /* Aplica um evento a entrada da sua janela. false = nao cabe neste quadro. */ static bool be_apply(SDL_Event* ev) { SdlWin* w = NULL; switch (ev->type) { case SDL_QUIT: /* SIGTERM/Ctrl+C ou o SO pediu para sair */ for (w = s_wins; w; w = w->next) w->in.close = 1; break; case SDL_WINDOWEVENT: if ((w = win_by_id(ev->window.windowID)) && ev->window.event == SDL_WINDOWEVENT_CLOSE) w->in.close = 1; break; case SDL_MOUSEMOTION: if ((w = win_by_id(ev->motion.windowID))) { w->in.mouse_x = (float)ev->motion.x; w->in.mouse_y = (float)ev->motion.y; w->pos_fresh = 1; } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: if ((w = win_by_id(ev->button.windowID))) { bool down = ev->type == SDL_MOUSEBUTTONDOWN; w->in.mouse_x = (float)ev->button.x; w->in.mouse_y = (float)ev->button.y; w->pos_fresh = 1; /* clique repetido no mesmo quadro: espera o proximo */ if (ev->button.button == SDL_BUTTON_LEFT && (down ? w->in.l_down : w->in.l_up)) return false; if (ev->button.button == SDL_BUTTON_LEFT) { if (down) w->in.l_down = 1; else w->in.l_up = 1; } if (ev->button.button == SDL_BUTTON_RIGHT) { if (down) w->in.r_down = 1; else w->in.r_up = 1; } } break; case SDL_MOUSEWHEEL: if ((w = win_by_id(ev->wheel.windowID))) { w->in.scroll_dx += (float)ev->wheel.x; w->in.scroll_dy += (float)ev->wheel.y; } break; case SDL_KEYDOWN: if ((w = win_by_id(ev->key.windowID))) { if (w->in.key) return false; /* uma tecla por quadro */ w->in.key = map_key(ev->key.keysym.scancode); w->in.key_mod = map_mod(ev->key.keysym.mod); w->in.key_repeat = ev->key.repeat ? 1 : 0; } break; case SDL_TEXTINPUT: if ((w = win_by_id(ev->text.windowID))) { size_t cur = strlen(w->in.text), add = strlen(ev->text.text); if (cur + add >= sizeof(w->in.text)) { if (cur > 0) return false; /* nao cabe: vai no proximo quadro */ add = sizeof(w->in.text) - 1; /* sozinho e maior que o buffer: corta */ } memcpy(w->in.text + cur, ev->text.text, add); w->in.text[cur + add] = 0; } break; case SDL_DROPFILE: if ((w = win_by_id(ev->drop.windowID)) && ev->drop.file) snprintf(w->in.drop_file, sizeof(w->in.drop_file), "%s", ev->drop.file); SDL_free(ev->drop.file); break; default: break; } return true; } /* Coleta os eventos do SO e distribui para a janela de cada evento */ static void be_poll(void) { for (SdlWin* w = s_wins; w; w = w->next) { TinyBlocks_GfxInput* in = &w->in; in->l_down = in->l_up = in->r_down = in->r_up = 0; in->scroll_dx = in->scroll_dy = 0.f; in->key = in->key_mod = in->key_repeat = 0; in->text[0] = 0; in->drop_file[0] = 0; in->close = 0; w->pos_fresh = 0; } if (s_has_pending) { s_has_pending = false; if (!be_apply(&s_pending)) s_has_pending = true; } SDL_Event ev; while (!s_has_pending && SDL_PollEvent(&ev)) { if (!be_apply(&ev)) { s_pending = ev; s_has_pending = true; } } /* Dispositivo: teclas seguradas (janela com o foco do teclado), dedos na tela e sensores (todas as janelas) */ SDL_Window* kfocus = SDL_GetKeyboardFocus(); int nkeys = 0; const Uint8* ks = SDL_GetKeyboardState(&nkeys); unsigned char held[128]; memset(held, 0, sizeof(held)); for (int sc = 0; ks && sc < nkeys; sc++) { if (!ks[sc]) continue; int k = map_key((SDL_Scancode)sc); if (k > 0 && k < 128) held[k] = 1; } float tx[GFX_MAX_TOUCHES], ty[GFX_MAX_TOUCHES]; /* 0..1 na janela */ int tn = 0; for (int d = 0; d < SDL_GetNumTouchDevices(); d++) { SDL_TouchID tid = SDL_GetTouchDevice(d); for (int f = 0; f < SDL_GetNumTouchFingers(tid) && tn < GFX_MAX_TOUCHES; f++) { SDL_Finger* fg = SDL_GetTouchFinger(tid, f); if (fg) { tx[tn] = fg->x; ty[tn] = fg->y; tn++; } } } float acc[3] = {0, 0, 0}, gyr[3] = {0, 0, 0}; bool has_acc = s_accel && SDL_SensorGetData(s_accel, acc, 3) == 0; bool has_gyr = s_gyro && SDL_SensorGetData(s_gyro, gyr, 3) == 0; /* Mouse na tela: consulta direta, confiavel mesmo logo depois de o gerenciador de janelas mover a janela (a posicao local do SDL atrasa) */ int gmx = 0, gmy = 0; SDL_GetGlobalMouseState(&gmx, &gmy); /* Estado contínuo: botões segurados só valem na janela com o foco do mouse */ SDL_Window* focus = SDL_GetMouseFocus(); int mx, my; Uint32 btns = SDL_GetMouseState(&mx, &my); int mods = map_mod((Uint16)SDL_GetModState()); for (SdlWin* w = s_wins; w; w = w->next) { bool f = w->win == focus; /* a posicao do evento vale mais: o estado global fica velho quando a janela acabou de ganhar o foco com aquele mesmo clique */ if (f && !w->pos_fresh) { w->in.mouse_x = (float)mx; w->in.mouse_y = (float)my; } w->in.l_held = f && (btns & SDL_BUTTON_LMASK) ? 1 : 0; w->in.r_held = f && (btns & SDL_BUTTON_RMASK) ? 1 : 0; w->in.mod_state = mods; SDL_GetWindowSize(w->win, &w->in.win_w, &w->in.win_h); SDL_GetWindowPosition(w->win, &w->in.win_x, &w->in.win_y); w->in.gmouse_x = (float)gmx; w->in.gmouse_y = (float)gmy; w->in.mouse_in = f ? 1 : 0; if (w->win == kfocus) memcpy(w->in.keys_held, held, sizeof(held)); else memset(w->in.keys_held, 0, sizeof(w->in.keys_held)); w->in.touch_n = (w->win == kfocus || w->win == focus) ? tn : 0; for (int i = 0; i < w->in.touch_n; i++) { w->in.touch_x[i] = tx[i] * (float)w->in.win_w; w->in.touch_y[i] = ty[i] * (float)w->in.win_h; } w->in.has_accel = has_acc; w->in.has_gyro = has_gyr; memcpy(w->in.accel, acc, sizeof(acc)); memcpy(w->in.gyro, gyr, sizeof(gyr)); } } static void be_window_input(void* handle, TinyBlocks_GfxInput* out) { *out = ((SdlWin*)handle)->in; } static bool be_clipboard_set(const char* text) { return be_init() && SDL_SetClipboardText(text ? text : "") == 0; } static char* be_clipboard_get(void) { if (!be_init() || !SDL_HasClipboardText()) return NULL; char* t = SDL_GetClipboardText(); char* r = t ? strdup(t) : NULL; if (t) SDL_free(t); return r; } static void be_window_present(void* handle, const TinyBlocks_RenderableBlock* rb) { SdlWin* w = (SdlWin*)handle; SDL_SetRenderDrawColor(w->ren, 0, 0, 0, 255); SDL_RenderClear(w->ren); if (rb) sdl2_execute(w->ren, rb); SDL_RenderPresent(w->ren); } static float be_measure_text(const char* text, float font_size) { if (!be_init()) return 0.f; TTF_Font* font = get_font((int)(font_size + 0.5f)); int w = 0, h = 0; if (!font || TTF_SizeUTF8(font, text, &w, &h) != 0) return 0.f; return (float)w; } static void be_frame_wait(void) { SDL_Delay(14); } static const TinyBlocks_GraphicsBackend s_sdl2_backend = { .name = "sdl2", .init = be_init, .shutdown = be_shutdown, .window_open = be_window_open, .window_close = be_window_close, .poll = be_poll, .window_input = be_window_input, .window_present = be_window_present, .measure_text = be_measure_text, .frame_wait = be_frame_wait, .clipboard_set = be_clipboard_set, .clipboard_get = be_clipboard_get, }; const TinyBlocks_GraphicsBackend* tb_sdl2_graphics_backend(void) { return &s_sdl2_backend; } /* Ponto de entrada quando esta library é carregada como backend (.so) */ TB_API __attribute__((weak)) const TinyBlocks_GraphicsBackend* tinyblocks_get_graphics_backend(void) { return &s_sdl2_backend; } /* === * SDL2.Events - snapshot de eventos do frame * === */ static void eval_sdl2_events(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; /* Outputs são pré-preenchidos pelo SDL2.App antes de cada frame. Se não há SDL2.App, inicializa com zeros/strings vazias. */ for (uint32_t i = 0; i < self->output_count; i++) { if (self->outputs[i].kind == TB_VALUE_NONE) { if (i == SDL2_EV_MOUSE_X || i == SDL2_EV_MOUSE_Y || i == SDL2_EV_SCROLL_DY || i == SDL2_EV_SCROLL_DX) self->outputs[i] = tb_value_real(0.0); else if (i == SDL2_EV_TEXT_INPUT || i == SDL2_EV_DROP_FILE) self->outputs[i] = tb_value_text(""); else self->outputs[i] = tb_value_integer(0); } } self->dirty = false; } /* Preenche os outputs do bloco SDL2.Events com o estado de um frame */ typedef struct { float mouse_x, mouse_y; int l_held, r_held; int l_down, l_up, r_down, r_up; float scroll_dy, scroll_dx; int key_scancode, key_mod, key_repeat; char text_input[64]; int quit; int win_w, win_h; char drop_file[512]; int mod_state; } FrameEvents; static void events_push(TinyBlocks_Block* ev, const FrameEvents* fe) { if (!ev || ev->output_count < SDL2_EV_COUNT) return; #define SET_R(idx, val) do { tb_value_free(&ev->outputs[idx]); \ ev->outputs[idx] = tb_value_real((double)(val)); } while(0) #define SET_I(idx, val) do { tb_value_free(&ev->outputs[idx]); \ ev->outputs[idx] = tb_value_integer((int64_t)(val)); } while(0) #define SET_T(idx, val) do { tb_value_free(&ev->outputs[idx]); \ ev->outputs[idx] = tb_value_text(val); } while(0) SET_R(SDL2_EV_MOUSE_X, fe->mouse_x); SET_R(SDL2_EV_MOUSE_Y, fe->mouse_y); SET_I(SDL2_EV_MOUSE_L_HELD, fe->l_held); SET_I(SDL2_EV_MOUSE_R_HELD, fe->r_held); SET_I(SDL2_EV_MOUSE_L_DOWN, fe->l_down); SET_I(SDL2_EV_MOUSE_L_UP, fe->l_up); SET_I(SDL2_EV_MOUSE_R_DOWN, fe->r_down); SET_I(SDL2_EV_MOUSE_R_UP, fe->r_up); SET_R(SDL2_EV_SCROLL_DY, fe->scroll_dy); SET_I(SDL2_EV_KEY_SCANCODE, fe->key_scancode); SET_I(SDL2_EV_KEY_MOD, fe->key_mod); SET_I(SDL2_EV_KEY_REPEAT, fe->key_repeat); SET_T(SDL2_EV_TEXT_INPUT, fe->text_input); SET_I(SDL2_EV_QUIT, fe->quit); SET_I(SDL2_EV_WIN_W, fe->win_w); SET_I(SDL2_EV_WIN_H, fe->win_h); SET_T(SDL2_EV_DROP_FILE, fe->drop_file); SET_R(SDL2_EV_SCROLL_DX, fe->scroll_dx); SET_I(SDL2_EV_MOD_STATE, fe->mod_state); #undef SET_R #undef SET_I #undef SET_T ev->dirty = false; } /* === * SDL2.App - janela + loop principal * === */ typedef struct { SDL_Window* win; SDL_Renderer* ren; } AppState; static bool app_init(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; AppState* s = (AppState*)self->userdata; s->win = NULL; s->ren = NULL; return true; } static void app_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; AppState* s = (AppState*)self->userdata; if (s->ren) { SDL_DestroyRenderer(s->ren); s->ren = NULL; } if (s->win) { SDL_DestroyWindow(s->win); s->win = NULL; } } static void eval_sdl2_app(TinyBlocks_Block* self, TinyBlocks* rt) { AppState* s = (AppState*)self->userdata; /* inputs: 0=title, 1=w, 2=h, 3=scene(block), 4=events(block) */ TinyBlocks_Value vtitle = 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); TinyBlocks_Value vscene = tb_block_get_input(self, rt, 3); TinyBlocks_Value vevents = tb_block_get_input(self, rt, 4); const char* title = (vtitle.kind == TB_VALUE_TEXT && vtitle.as.text) ? vtitle.as.text : "TinyBlocks"; int win_w = (int)(vw.kind == TB_VALUE_INTEGER ? vw.as.integer : 1280); int win_h = (int)(vh.kind == TB_VALUE_INTEGER ? vh.as.integer : 720); TinyBlocks_Block* scene = (vscene.kind == TB_VALUE_BLOCK) ? vscene.as.block : NULL; TinyBlocks_Block* ev_blk = (vevents.kind == TB_VALUE_BLOCK) ? vevents.as.block : NULL; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { fprintf(stderr, "SDL2.App SDL_Init: %s\n", SDL_GetError()); return; } if (TTF_Init() != 0) { fprintf(stderr, "SDL2.App TTF_Init: %s\n", TTF_GetError()); SDL_Quit(); return; } s->win = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, win_w, win_h, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (!s->win) { fprintf(stderr, "SDL2.App window: %s\n", SDL_GetError()); TTF_Quit(); SDL_Quit(); return; } s->ren = SDL_CreateRenderer(s->win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (!s->ren) s->ren = SDL_CreateRenderer(s->win, -1, SDL_RENDERER_SOFTWARE); if (!s->ren) { fprintf(stderr, "SDL2.App renderer: %s\n", SDL_GetError()); SDL_DestroyWindow(s->win); s->win = NULL; TTF_Quit(); SDL_Quit(); return; } SDL_SetRenderDrawBlendMode(s->ren, SDL_BLENDMODE_BLEND); SDL_EventState(SDL_DROPFILE, SDL_ENABLE); SDL_StartTextInput(); FrameEvents fe; bool quit = false; while (!quit) { memset(&fe, 0, sizeof(fe)); /* Coleta todos os eventos do frame */ SDL_Event ev; while (SDL_PollEvent(&ev)) { switch (ev.type) { case SDL_QUIT: fe.quit = 1; quit = true; break; case SDL_MOUSEBUTTONDOWN: if (ev.button.button == SDL_BUTTON_LEFT) fe.l_down = 1; if (ev.button.button == SDL_BUTTON_RIGHT) fe.r_down = 1; break; case SDL_MOUSEBUTTONUP: if (ev.button.button == SDL_BUTTON_LEFT) fe.l_up = 1; if (ev.button.button == SDL_BUTTON_RIGHT) fe.r_up = 1; break; case SDL_MOUSEWHEEL: fe.scroll_dy += (float)ev.wheel.y; fe.scroll_dx += (float)ev.wheel.x; break; case SDL_KEYDOWN: fe.key_scancode = (int)ev.key.keysym.scancode; fe.key_mod = (int)ev.key.keysym.mod; fe.key_repeat = ev.key.repeat ? 1 : 0; break; case SDL_TEXTINPUT: { size_t cur = strlen(fe.text_input); size_t add = strlen(ev.text.text); if (cur + add < sizeof(fe.text_input) - 1) strcat(fe.text_input, ev.text.text); break; } case SDL_DROPFILE: if (ev.drop.file) { strncpy(fe.drop_file, ev.drop.file, sizeof(fe.drop_file) - 1); SDL_free(ev.drop.file); } break; default: break; } } /* Estado contínuo do mouse */ { int mx, my; Uint32 btns = SDL_GetMouseState(&mx, &my); fe.mouse_x = (float)mx; fe.mouse_y = (float)my; fe.l_held = (btns & SDL_BUTTON_LMASK) ? 1 : 0; fe.r_held = (btns & SDL_BUTTON_RMASK) ? 1 : 0; } /* Tamanho atual da janela e estado dos modificadores */ SDL_GetWindowSize(s->win, &fe.win_w, &fe.win_h); fe.mod_state = (int)SDL_GetModState(); /* Preenche o bloco SDL2.Events */ if (ev_blk) events_push(ev_blk, &fe); /* Avalia a cena e obtém renderable */ TinyBlocks_RenderableBlock* rb = NULL; if (scene) { scene->dirty = true; tb_block_eval(scene, rt); if (scene->type && scene->type->on_draw) scene->type->on_draw(scene, rt, &rb); } /* Renderiza */ SDL_SetRenderDrawColor(s->ren, 30, 30, 46, 255); SDL_RenderClear(s->ren); if (rb) sdl2_execute(s->ren, rb); SDL_RenderPresent(s->ren); /* Libera os renderables adquiridos neste frame */ tb_renderable_release_all(); SDL_Delay(14); } fonts_close_all(); TTF_Quit(); SDL_DestroyRenderer(s->ren); s->ren = NULL; SDL_DestroyWindow(s->win); s->win = NULL; SDL_Quit(); self->dirty = false; } /* === * Blocos primitivos legados * === */ static void eval_sdl2_init(TinyBlocks_Block* self, TinyBlocks* rt) { (void)self; if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_EVENTS) != 0) tinyblocks_set_error(rt, "SDL2.Init: %s", SDL_GetError()); } static void eval_sdl2_quit(TinyBlocks_Block* self, TinyBlocks* rt) { (void)self; (void)rt; SDL_Quit(); } static void eval_sdl2_window(TinyBlocks_Block* self, TinyBlocks* rt) { TinyBlocks_Value vtitle = tb_block_get_input(self, rt, 0); TinyBlocks_Value vx = tb_block_get_input(self, rt, 1); TinyBlocks_Value vy = tb_block_get_input(self, rt, 2); TinyBlocks_Value vw = tb_block_get_input(self, rt, 3); TinyBlocks_Value vh = tb_block_get_input(self, rt, 4); const char* title = vtitle.kind==TB_VALUE_TEXT ? vtitle.as.text : "TinyBlocks"; int x = (int)(vx.kind==TB_VALUE_INTEGER ? vx.as.integer : SDL_WINDOWPOS_CENTERED); int y = (int)(vy.kind==TB_VALUE_INTEGER ? vy.as.integer : SDL_WINDOWPOS_CENTERED); int w = (int)(vw.kind==TB_VALUE_INTEGER ? vw.as.integer : 800); int h = (int)(vh.kind==TB_VALUE_INTEGER ? vh.as.integer : 600); SDL_Window* win = SDL_CreateWindow(title, x, y, w, h, SDL_WINDOW_SHOWN); if (!win) { tinyblocks_set_error(rt,"SDL2.Window: %s",SDL_GetError()); return; } tb_block_set_output(self, 0, tb_value_block(make_handle_block(rt, s_type_window_handle, win))); } static void eval_sdl2_destroy_window(TinyBlocks_Block* self, TinyBlocks* rt) { TinyBlocks_Value v = tb_block_get_input(self, rt, 0); if (v.kind==TB_VALUE_BLOCK && v.as.block) { SDL_DestroyWindow((SDL_Window*)v.as.block->userdata); v.as.block->userdata = NULL; } } static void eval_sdl2_renderer(TinyBlocks_Block* self, TinyBlocks* rt) { TinyBlocks_Value v = tb_block_get_input(self, rt, 0); if (v.kind!=TB_VALUE_BLOCK || !v.as.block) return; SDL_Window* win = (SDL_Window*)v.as.block->userdata; SDL_Renderer* ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); if (!ren) ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_SOFTWARE); if (!ren) { tinyblocks_set_error(rt,"SDL2.Renderer: %s",SDL_GetError()); return; } tb_block_set_output(self, 0, tb_value_block(make_handle_block(rt, s_type_renderer_handle, ren))); } static void eval_sdl2_destroy_renderer(TinyBlocks_Block* self, TinyBlocks* rt) { TinyBlocks_Value v = tb_block_get_input(self, rt, 0); if (v.kind==TB_VALUE_BLOCK && v.as.block) { SDL_DestroyRenderer((SDL_Renderer*)v.as.block->userdata); v.as.block->userdata = NULL; } } static SDL_Renderer* get_ren(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { TinyBlocks_Value v = tb_block_get_input(self, rt, idx); return (v.kind==TB_VALUE_BLOCK && v.as.block) ? (SDL_Renderer*)v.as.block->userdata : NULL; } static void eval_sdl2_set_draw_color(TinyBlocks_Block* self, TinyBlocks* rt) { SDL_Renderer* ren = get_ren(self, rt, 0); if (!ren) return; TinyBlocks_Value vr=tb_block_get_input(self,rt,1), vg=tb_block_get_input(self,rt,2); TinyBlocks_Value vb=tb_block_get_input(self,rt,3), va=tb_block_get_input(self,rt,4); SDL_SetRenderDrawColor(ren, (Uint8)(vr.kind==TB_VALUE_INTEGER?vr.as.integer:0), (Uint8)(vg.kind==TB_VALUE_INTEGER?vg.as.integer:0), (Uint8)(vb.kind==TB_VALUE_INTEGER?vb.as.integer:0), (Uint8)(va.kind==TB_VALUE_INTEGER?va.as.integer:255)); } static void eval_sdl2_clear(TinyBlocks_Block* self, TinyBlocks* rt) { SDL_Renderer* ren = get_ren(self, rt, 0); if (ren) SDL_RenderClear(ren); } static void eval_sdl2_fill_rect(TinyBlocks_Block* self, TinyBlocks* rt) { SDL_Renderer* ren = get_ren(self, rt, 0); if (!ren) return; TinyBlocks_Value vx=tb_block_get_input(self,rt,1), vy=tb_block_get_input(self,rt,2); TinyBlocks_Value vw=tb_block_get_input(self,rt,3), vh=tb_block_get_input(self,rt,4); SDL_Rect rc={ (int)(vx.kind==TB_VALUE_INTEGER?vx.as.integer:0), (int)(vy.kind==TB_VALUE_INTEGER?vy.as.integer:0), (int)(vw.kind==TB_VALUE_INTEGER?vw.as.integer:100), (int)(vh.kind==TB_VALUE_INTEGER?vh.as.integer:100)}; SDL_RenderFillRect(ren, &rc); } static void eval_sdl2_draw_rect(TinyBlocks_Block* self, TinyBlocks* rt) { SDL_Renderer* ren = get_ren(self, rt, 0); if (!ren) return; TinyBlocks_Value vx=tb_block_get_input(self,rt,1), vy=tb_block_get_input(self,rt,2); TinyBlocks_Value vw=tb_block_get_input(self,rt,3), vh=tb_block_get_input(self,rt,4); SDL_Rect rc={ (int)(vx.kind==TB_VALUE_INTEGER?vx.as.integer:0), (int)(vy.kind==TB_VALUE_INTEGER?vy.as.integer:0), (int)(vw.kind==TB_VALUE_INTEGER?vw.as.integer:100), (int)(vh.kind==TB_VALUE_INTEGER?vh.as.integer:100)}; SDL_RenderDrawRect(ren, &rc); } static void eval_sdl2_present(TinyBlocks_Block* self, TinyBlocks* rt) { SDL_Renderer* ren = get_ren(self, rt, 0); if (ren) SDL_RenderPresent(ren); } static void eval_sdl2_delay(TinyBlocks_Block* self, TinyBlocks* rt) { TinyBlocks_Value v = tb_block_get_input(self, rt, 0); SDL_Delay((Uint32)(v.kind==TB_VALUE_INTEGER && v.as.integer>0 ? v.as.integer : 0)); } static void eval_sdl2_poll_event(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; SDL_Event ev; if (SDL_PollEvent(&ev)) { tb_block_set_output(self, 0, tb_value_integer((int64_t)ev.type)); tb_block_set_output(self, 1, tb_value_integer(ev.type==SDL_QUIT?1:0)); int64_t sc = (ev.type==SDL_KEYDOWN||ev.type==SDL_KEYUP) ? (int64_t)ev.key.keysym.scancode : 0; tb_block_set_output(self, 2, tb_value_integer(sc)); } else { tb_block_set_output(self, 0, tb_value_integer(TB_SDL2_EVENT_NONE)); tb_block_set_output(self, 1, tb_value_integer(0)); tb_block_set_output(self, 2, tb_value_integer(0)); } } /* === * Registro da library * === */ static bool sdl2_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { s_type_window_handle = tb_type_block_create(rt, "SDL2._WindowHandle", NULL,0,NULL,0, eval_handle_noop); s_type_renderer_handle = tb_type_block_create(rt, "SDL2._RendererHandle", NULL,0,NULL,0, eval_handle_noop); if (!s_type_window_handle || !s_type_renderer_handle) return false; #define IN(n,k) { .name=(n), .expected_kind=(k) } #define BLOCK_IN(n) IN(n, TB_VALUE_BLOCK) #define INT_IN(n) IN(n, TB_VALUE_INTEGER) #define TEXT_IN(n) IN(n, TB_VALUE_TEXT) #define OUT(n,k) { .name=(n), .expected_kind=(k) } /* SDL2.Events */ { static const TinyBlocks_SlotDesc outs[SDL2_EV_COUNT] = { OUT("mouse_x", TB_VALUE_REAL), OUT("mouse_y", TB_VALUE_REAL), OUT("mouse_l_held", TB_VALUE_INTEGER), OUT("mouse_r_held", TB_VALUE_INTEGER), OUT("mouse_l_down", TB_VALUE_INTEGER), OUT("mouse_l_up", TB_VALUE_INTEGER), OUT("mouse_r_down", TB_VALUE_INTEGER), OUT("mouse_r_up", TB_VALUE_INTEGER), OUT("scroll_dy", TB_VALUE_REAL), OUT("key_scancode", TB_VALUE_INTEGER), OUT("key_mod", TB_VALUE_INTEGER), OUT("key_repeat", TB_VALUE_INTEGER), OUT("text_input", TB_VALUE_TEXT), OUT("quit", TB_VALUE_INTEGER), OUT("win_w", TB_VALUE_INTEGER), OUT("win_h", TB_VALUE_INTEGER), OUT("drop_file", TB_VALUE_TEXT), OUT("scroll_dx", TB_VALUE_REAL), OUT("mod_state", TB_VALUE_INTEGER), }; TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "SDL2.Events", NULL, 0, outs, SDL2_EV_COUNT, eval_sdl2_events); if (!t) return false; tb_library_add(lib, &t->base); } /* SDL2.App */ { static const TinyBlocks_SlotDesc ins[] = { TEXT_IN("title"), INT_IN("w"), INT_IN("h"), IN("scene", TB_VALUE_BLOCK), IN("events", TB_VALUE_BLOCK), }; TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "SDL2.App", ins, 5, NULL, 0, eval_sdl2_app); if (!t) return false; tb_type_block_set_instance_hooks(t, sizeof(AppState), app_init, app_deinit); tb_library_add(lib, &t->base); } /* Blocos primitivos legados */ { TinyBlocks_TypeBlock* t = tb_type_block_create(rt,"SDL2.Init",NULL,0,NULL,0,eval_sdl2_init); if (t) tb_library_add(lib, &t->base); } { TinyBlocks_TypeBlock* t = tb_type_block_create(rt,"SDL2.Quit",NULL,0,NULL,0,eval_sdl2_quit); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc ins[]={TEXT_IN("title"),INT_IN("x"),INT_IN("y"),INT_IN("w"),INT_IN("h")}; static const TinyBlocks_SlotDesc outs[]={OUT("window",TB_VALUE_BLOCK)}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.Window",ins,5,outs,1,eval_sdl2_window); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("window")}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.DestroyWindow",ins,1,NULL,0,eval_sdl2_destroy_window); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("window")}; static const TinyBlocks_SlotDesc outs[]={OUT("renderer",TB_VALUE_BLOCK)}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.Renderer",ins,1,outs,1,eval_sdl2_renderer); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer")}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.DestroyRenderer",ins,1,NULL,0,eval_sdl2_destroy_renderer); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer"),INT_IN("r"),INT_IN("g"),INT_IN("b"),INT_IN("a")}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.SetDrawColor",ins,5,NULL,0,eval_sdl2_set_draw_color); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer")}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.Clear",ins,1,NULL,0,eval_sdl2_clear); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer"),INT_IN("x"),INT_IN("y"),INT_IN("w"),INT_IN("h")}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.FillRect",ins,5,NULL,0,eval_sdl2_fill_rect); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer"),INT_IN("x"),INT_IN("y"),INT_IN("w"),INT_IN("h")}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.DrawRect",ins,5,NULL,0,eval_sdl2_draw_rect); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc ins[]={BLOCK_IN("renderer")}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.Present",ins,1,NULL,0,eval_sdl2_present); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc ins[]={INT_IN("ms")}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.Delay",ins,1,NULL,0,eval_sdl2_delay); if (t) tb_library_add(lib, &t->base); } { static const TinyBlocks_SlotDesc outs[]={ OUT("type",TB_VALUE_INTEGER),OUT("quit",TB_VALUE_INTEGER), OUT("key_scancode",TB_VALUE_INTEGER)}; TinyBlocks_TypeBlock* t=tb_type_block_create(rt,"SDL2.PollEvent",NULL,0,outs,3,eval_sdl2_poll_event); if (t) tb_library_add(lib, &t->base); } #undef IN #undef BLOCK_IN #undef INT_IN #undef TEXT_IN #undef OUT return true; } static void sdl2_lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; s_type_window_handle = NULL; s_type_renderer_handle = NULL; } TINYBLOCKS_DEFINE_LIBRARY(sdl2, "tinyblocks-sdl2", "2.0.0", sdl2_lib_init, sdl2_lib_deinit) const TinyBlocks_LibraryDescriptor* tb_sdl2_get_library(void) { return &_tb_lib_desc_sdl2; }