editor: Sensores, avisos flutuantes, áreas e abas destacáveis (estilo Blender/navegador)
Sensores (tinyblocks-input, categoria Sensores) - Mouse (posição no palco, botões, rolagem), teclas seguradas e última tecla, toques, acelerômetro, giroscópio e cronômetro. - Estado no core (tinyblocks/tb_input.h), alimentado pelo editor em coordenadas do palco (tb_stage_view_to_stage); o graphics passa teclas seguradas, toques e sensores (saídas JSON do Graphics.Input) e o backend SDL2 os lê (SDL_GetKeyboardState, toque, SDL_Sensor). - test-input + cenário no harness. Avisos flutuantes (estilo EditorToaster do Godot) - Mensagens de status viram avisos no canto da área de scripts, com barra de tempo, pausa com o mouse em cima, "x" para fechar e contador para repetidas. O menu fica só com os botões. Áreas (estilo Blender) - Layout em árvore de divisões (paleta, scripts, palco, saída): bordas arrastáveis, alça para trocar views de lugar, destacar qualquer view numa janela própria (cena Editor.Area) e voltar pelo menu ou fechando a janela; blocos podem ser arrastados entre janelas. - Layout salvo em "editor.layout" nas configurações. - Coluna de categorias se compacta para caber. Abas (estilo navegador) - Arrastar reordena; arrastar para fora destaca a aba numa janela; soltar na barra principal, o menu ou fechar a janela devolvem. - Blocos passam da paleta/outra aba para a janela de uma aba (só abas de blocos recebem blocos). Correções - SDL2: SDL_QUIT (SIGTERM/Ctrl+C) fecha o editor; posição do clique do evento vale mais que o estado global; posição da janela e mouse global no contrato (a posição local do SDL atrasa depois de mover a janela). - Aba de código não mostra mais "</code>" na última linha. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
22588b281e
commit
649ae14fb3
17 files changed
+2447
-167
No files matched your search
@@ -66,6 +66,7 @@ SRCS := src/tinyblocks.c \
|
||||
src/tb_vector_block.c \
|
||||
src/tb_renderable_block.c \
|
||||
src/tb_stage.c \
|
||||
src/tb_input.c \
|
||||
src/tb_json_block.c \
|
||||
src/tb_image.c \
|
||||
src/tb_meta.c
|
||||
@@ -73,7 +74,7 @@ SRCS := src/tinyblocks.c \
|
||||
OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS))
|
||||
OBJS_DBG := $(patsubst src/%.c,$(BUILD)/%-dbg.o,$(SRCS))
|
||||
|
||||
CAT_LIBS := events control operators number string variables vector appearance pen fs os environ
|
||||
CAT_LIBS := events control input operators number string variables vector appearance pen fs os environ
|
||||
CAT_A := $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/build/libtinyblocks-$(l).a)
|
||||
CAT_LDFLAGS := $(foreach l,$(CAT_LIBS),-ltinyblocks-$(l))
|
||||
CAT_INCS := $(foreach l,$(CAT_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include)
|
||||
@@ -95,9 +96,9 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \
|
||||
editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \
|
||||
appdir appimage run-appimage icon \
|
||||
test-toml test-plugin test-blueprint test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \
|
||||
test-syntax test-os test-stdlib test-regex test-markdown test-opentype \
|
||||
test-syntax test-os test-input test-stdlib test-regex test-markdown test-opentype \
|
||||
category-libs category-sos libs \
|
||||
lib-events lib-control lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \
|
||||
lib-events lib-control lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \
|
||||
lib-environ \
|
||||
lib-editor lib-graphics lib-sdl2 lib-python lib-mcp lib-toml \
|
||||
lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-regex lib-markdown lib-opentype lib-api lib-libman \
|
||||
@@ -234,7 +235,7 @@ lib-mcp:
|
||||
$(MAKE) -C $(MC_DIR)
|
||||
|
||||
libs: static lib-events lib-control lib-operators lib-variables \
|
||||
lib-appearance lib-pen lib-fs lib-os lib-number lib-string lib-vector lib-environ lib-graphics lib-sdl2 lib-toml \
|
||||
lib-appearance lib-pen lib-fs lib-os lib-input lib-number lib-string lib-vector lib-environ lib-graphics lib-sdl2 lib-toml \
|
||||
lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-regex lib-markdown lib-opentype lib-api lib-libman lib-editor
|
||||
@echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + base64 + curves + ppm + bmp + png + image + vg + svg + jpg + syntax + regex + markdown + opentype + api + libman + editor"
|
||||
|
||||
@@ -619,6 +620,15 @@ $(BUILD)/os_fs_test: tests/os_fs_test.c $(FS_DIR)/src/tb_fs.c $(LIBDIR)/tinybloc
|
||||
test-os: $(BUILD)/os_fs_test ## Roda o teste de tinyblocks-os + pastas do tinyblocks-fs (ASan/UBSan)
|
||||
./$(BUILD)/os_fs_test
|
||||
|
||||
$(BUILD)/input_test: tests/input_test.c $(LIBDIR)/tinyblocks-input/src/tb_input.c static
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS_DBG) -I$(LIBDIR)/tinyblocks-input/include -I$(GFX_INC) \
|
||||
$(LIBDIR)/tinyblocks-input/src/tb_input.c tests/input_test.c \
|
||||
-o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group -lm $(EXTRA_TEST_LIBS)
|
||||
|
||||
test-input: $(BUILD)/input_test ## Roda o teste de tinyblocks-input + estado de entrada do core (ASan/UBSan)
|
||||
./$(BUILD)/input_test
|
||||
|
||||
STD_DIRS := $(LIBDIR)/tinyblocks-string $(LIBDIR)/tinyblocks-number $(LIBDIR)/tinyblocks-vector
|
||||
STD_SRCS := $(foreach d,$(STD_DIRS),$(d)/src/$(patsubst tinyblocks-%,tb_%,$(notdir $(d))).c)
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
#include <tb_pen.h>
|
||||
#include <tb_fs.h>
|
||||
#include <tb_os.h>
|
||||
#include <tb_input_lib.h>
|
||||
#include <tb_number.h>
|
||||
#include <tb_string.h>
|
||||
#include <tb_vector.h>
|
||||
@@ -65,6 +66,7 @@ int main(int argc, char** argv) {
|
||||
Preferimos o .so: recompilar a library recarrega a paleta ao vivo. */
|
||||
reg_core(rt, "tinyblocks-events", tb_events_get_library);
|
||||
reg_core(rt, "tinyblocks-control", tb_control_get_library);
|
||||
reg_core(rt, "tinyblocks-input", tb_input_get_library);
|
||||
reg_core(rt, "tinyblocks-operators", tb_operators_get_library);
|
||||
reg_core(rt, "tinyblocks-number", tb_number_get_library);
|
||||
reg_core(rt, "tinyblocks-string", tb_string_get_library);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* TinyBlocks - tb_input.h
|
||||
* Estado de entrada do programa (mouse, teclado, toque, sensores, cronometro)
|
||||
* em coordenadas do PALCO, lido pelos blocos de Sensores (tinyblocks-input).
|
||||
*
|
||||
* Fica no core, como o palco (tb_stage.h): existe uma copia so, mesmo com as
|
||||
* libraries carregadas como .so. Quem mostra o palco (o editor) alimenta o
|
||||
* estado a cada quadro com pontos em px da VISTA do palco; aqui eles viram
|
||||
* coordenadas do palco (x -240..240, y -180..180, y para cima).
|
||||
*
|
||||
* Teclas sao codigos 1..127 (os TB_KEY_* do tinyblocks-graphics).
|
||||
*/
|
||||
#ifndef TINYBLOCKS_TB_INPUT_H
|
||||
#define TINYBLOCKS_TB_INPUT_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
#define TB_INPUT_MAX_KEYS 128
|
||||
#define TB_INPUT_MAX_TOUCHES 10
|
||||
|
||||
/* -- Alimentacao (host do palco), uma vez por quadro --- */
|
||||
TB_API void tb_input_begin_frame(void); /* zera o que vale so neste quadro */
|
||||
TB_API void tb_input_set_mouse(float vx, float vy, bool left, bool right);
|
||||
TB_API void tb_input_add_wheel(float dy);
|
||||
TB_API void tb_input_clear_keys(void);
|
||||
TB_API void tb_input_set_key(int key, bool held);
|
||||
TB_API void tb_input_key_pressed(int key); /* tecla apertada neste quadro */
|
||||
TB_API void tb_input_set_touches(int n, const float* vx, const float* vy);
|
||||
TB_API void tb_input_set_accel(bool has, float x, float y, float z); /* m/s² */
|
||||
TB_API void tb_input_set_gyro(bool has, float x, float y, float z); /* rad/s */
|
||||
TB_API void tb_input_reset(void); /* tudo solto, cronometro zerado */
|
||||
|
||||
/* -- Leitura (blocos) --- */
|
||||
TB_API float tb_input_mouse_x(void); /* palco, preso as bordas */
|
||||
TB_API float tb_input_mouse_y(void);
|
||||
TB_API bool tb_input_mouse_over_stage(void);
|
||||
TB_API bool tb_input_mouse_down(void);
|
||||
TB_API bool tb_input_mouse_right_down(void);
|
||||
TB_API float tb_input_wheel(void); /* rolagem deste quadro */
|
||||
TB_API bool tb_input_key_held(int key);
|
||||
TB_API bool tb_input_any_key_held(void);
|
||||
TB_API int tb_input_last_key(void); /* 0 = nenhuma ainda */
|
||||
TB_API int tb_input_touch_count(void);
|
||||
TB_API float tb_input_touch_x(int i); /* i = 0..count-1, palco */
|
||||
TB_API float tb_input_touch_y(int i);
|
||||
TB_API bool tb_input_has_accel(void);
|
||||
TB_API float tb_input_accel(int axis); /* 0=x 1=y 2=z */
|
||||
TB_API bool tb_input_has_gyro(void);
|
||||
TB_API float tb_input_gyro(int axis); /* graus/s */
|
||||
TB_API double tb_input_timer(void); /* segundos desde o ultimo zerar */
|
||||
TB_API void tb_input_timer_reset(void);
|
||||
|
||||
#endif /* TINYBLOCKS_TB_INPUT_H */
|
||||
@@ -28,6 +28,10 @@ TB_API bool tb_stage_image_number(int number, float x, float y);
|
||||
|
||||
/* Vista: tamanho da area onde o palco sera desenhado (letterbox 4:3) */
|
||||
TB_API void tb_stage_set_view(float w, float h);
|
||||
/* Ponto da vista (px, origem no canto da vista) -> coordenadas do palco
|
||||
(x -240..240 para a direita, y -180..180 para cima). Devolve true se o
|
||||
ponto cai dentro do palco (fora da faixa do letterbox). */
|
||||
TB_API bool tb_stage_view_to_stage(float vx, float vy, float* sx, float* sy);
|
||||
|
||||
/* Emite os desenhos num RenderableBlock ja adquirido */
|
||||
TB_API bool tb_stage_render(TinyBlocks_RenderableBlock* rb);
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#include <tinyblocks/tb_json_block.h>
|
||||
#include <tb_graphics.h>
|
||||
#include <tinyblocks/tb_stage.h>
|
||||
#include <tinyblocks/tb_input.h>
|
||||
#include <tb_variables.h>
|
||||
#include <tb_blueprint.h>
|
||||
#include <tb_api.h>
|
||||
@@ -50,16 +51,25 @@
|
||||
#define FLY_W 250
|
||||
#define FLY_PAD 12
|
||||
#define FLY_BTN_W 150
|
||||
#define PALETTE_W (CAT_W + FLY_W)
|
||||
#define STAGE_W 360
|
||||
#define PALETTE_W (CAT_W + FLY_W) /* largura padrao da paleta */
|
||||
#define STAGE_W 360 /* largura padrao da coluna do palco */
|
||||
#define STAGE_BAR_H 44
|
||||
#define PAL_Y (MENU_H + TAB_H)
|
||||
#define WS_X PALETTE_W
|
||||
#define WS_Y (MENU_H + TAB_H)
|
||||
#define WIN_W (ed->win_w)
|
||||
#define WIN_H (ed->win_h)
|
||||
#define WS_W (ed->win_w - PALETTE_W - STAGE_W)
|
||||
#define WS_H (ed->win_h - WS_Y)
|
||||
|
||||
/* Retangulo de cada view, calculado a cada quadro pela arvore de areas
|
||||
(lay_compute em tb_editor.c). As views podem mudar de lugar e tamanho. */
|
||||
#define AREA(v) (ed->area[(v)])
|
||||
#define PAL_X (AREA(V_PALETTE).x)
|
||||
#define PAL_Y (AREA(V_PALETTE).y + TAB_H) /* abaixo do cabecalho */
|
||||
#define PAL_B (AREA(V_PALETTE).y + AREA(V_PALETTE).h)
|
||||
#define FLY_X (PAL_X + CAT_W)
|
||||
#define FLY_R (PAL_X + AREA(V_PALETTE).w)
|
||||
#define WS_X (AREA(V_SCRIPTS).x)
|
||||
#define WS_Y (AREA(V_SCRIPTS).y + TAB_H) /* abaixo das abas */
|
||||
#define WS_W (AREA(V_SCRIPTS).w)
|
||||
#define WS_H (AREA(V_SCRIPTS).h - TAB_H)
|
||||
#define WS_R (WS_X + WS_W)
|
||||
#define TAB_W 150
|
||||
#define PLUS_W 28
|
||||
|
||||
@@ -265,6 +275,25 @@ static const BlockSpec s_specs[] = {
|
||||
{"Events.WhenRun", "quando a bandeira for clicado", NULL},
|
||||
{"Control.Repeat", "repita %1 vezes", "10"},
|
||||
{"Control.Forever", "sempre", NULL},
|
||||
/* Sensores (tinyblocks-input) */
|
||||
{"Input.MouseX", "posição x do mouse", NULL},
|
||||
{"Input.MouseY", "posição y do mouse", NULL},
|
||||
{"Input.MouseDown", "mouse pressionado?", NULL},
|
||||
{"Input.MouseRight", "botão direito pressionado?", NULL},
|
||||
{"Input.MouseOver", "mouse sobre o palco?", NULL},
|
||||
{"Input.Wheel", "rolagem do mouse", NULL},
|
||||
{"Input.KeyPressed", "tecla %1 pressionada?", "espaço"},
|
||||
{"Input.LastKey", "última tecla", NULL},
|
||||
{"Input.Touching", "tocando a tela?", NULL},
|
||||
{"Input.TouchCount", "número de toques", NULL},
|
||||
{"Input.TouchX", "x do toque %1", "1"},
|
||||
{"Input.TouchY", "y do toque %1", "1"},
|
||||
{"Input.HasAccel", "tem acelerômetro?", NULL},
|
||||
{"Input.Accel", "aceleração em %1", "x"},
|
||||
{"Input.HasGyro", "tem giroscópio?", NULL},
|
||||
{"Input.Gyro", "giro em %1 (graus/s)", "x"},
|
||||
{"Input.Timer", "cronômetro", NULL},
|
||||
{"Input.ResetTimer", "zere o cronômetro", NULL},
|
||||
{"Control.RepeatUntil", "repita até que %1", NULL},
|
||||
{"Control.If", "se %1 então", NULL},
|
||||
{"Control.IfElse", "se %1 então", NULL},
|
||||
@@ -631,6 +660,52 @@ typedef struct {
|
||||
TinyBlocks_Block* r;
|
||||
} RtCacheEnt;
|
||||
|
||||
/* Areas (layout estilo Blender): arvore de divisoes. Cada no divide um
|
||||
retangulo lado a lado (HSPLIT: a | b) ou um em cima do outro (VSPLIT:
|
||||
a sobre b); as folhas sao as views. Um lado de cada divisao tem tamanho
|
||||
fixo em px e o outro absorve o redimensionamento da janela. */
|
||||
enum { V_PALETTE, V_SCRIPTS, V_STAGE, V_OUTPUT, V_COUNT };
|
||||
enum { LN_LEAF, LN_HSPLIT, LN_VSPLIT };
|
||||
typedef struct {
|
||||
int kind; /* LN_* */
|
||||
int a, b; /* filhos */
|
||||
int view; /* folha: V_* */
|
||||
int fix; /* lado com tamanho fixo: 0 = a, 1 = b */
|
||||
float px; /* tamanho desse lado em px */
|
||||
float x, y, w, h; /* calculados a cada quadro */
|
||||
float pos; /* coordenada da borda entre a e b */
|
||||
} LayNode;
|
||||
#define LAY_MAX 16
|
||||
typedef struct { float x, y, w, h; bool shown, detached; } AreaRect;
|
||||
|
||||
/* Aba destacada numa janela propria (como arrastar a aba para fora no
|
||||
navegador). Enquanto a janela trata eventos ou desenha, o editor troca a
|
||||
aba atual e o retangulo dos scripts pelos dela ("contexto" da aba). */
|
||||
#define TABWIN_MAX 6
|
||||
typedef struct {
|
||||
int tab; /* aba mostrada (-1 = slot livre) */
|
||||
TinyBlocks_Block* win;
|
||||
TinyBlocks_Block* in;
|
||||
TinyBlocks_Block* scene;
|
||||
float geom[4]; /* x, y na tela, largura, altura */
|
||||
bool attach_pending;
|
||||
float chip_x, chip_w; /* botao "voltar" no menu */
|
||||
} TabWin;
|
||||
|
||||
/* Notificacoes flutuantes (estilo EditorToaster do Godot): cada mensagem
|
||||
escrita em hot_status vira um aviso com temporizador sobre a area de
|
||||
scripts; mensagens repetidas viram contador. */
|
||||
#define TOAST_MAX 6
|
||||
#define TOAST_INFO_MS 4000.f
|
||||
#define TOAST_ERR_MS 8000.f
|
||||
typedef struct {
|
||||
char text[256];
|
||||
bool ok; /* false = erro (vermelho, fica mais tempo) */
|
||||
int count; /* repeticoes da mesma mensagem */
|
||||
float left_ms, total_ms;
|
||||
float x, y, w, h; /* geometria do ultimo desenho (clique/hover) */
|
||||
} Toast;
|
||||
|
||||
/* Formatos de exportacao */
|
||||
enum { EX_JSON, EX_XML, EX_CSV };
|
||||
|
||||
@@ -722,16 +797,17 @@ typedef struct Ed {
|
||||
|
||||
/* Palco: embutido no painel ou numa janela própria (Graphics.Window) */
|
||||
TinyBlocks_Block* stage;
|
||||
TinyBlocks_Block* stage_win;
|
||||
TinyBlocks_Block* stage_in;
|
||||
|
||||
bool clip_on;
|
||||
float clip[4];
|
||||
|
||||
TbEdModules mods; /* libraries privadas (bundle) por dlopen */
|
||||
int hot_check_frame; /* contador para checar hot reload */
|
||||
char hot_status[256];
|
||||
char hot_status[256]; /* escreva aqui: vira notificacao (toast) */
|
||||
bool hot_status_ok;
|
||||
Toast toasts[TOAST_MAX]; /* mais nova no fim */
|
||||
int toast_n;
|
||||
unsigned toast_ms; /* relogio do ultimo quadro (temporizador) */
|
||||
|
||||
bool path_input_active;
|
||||
char path_input_buf[512];
|
||||
@@ -783,6 +859,40 @@ typedef struct Ed {
|
||||
float img_mx, img_my; /* ultimo ponto do traco (aba de imagem) */
|
||||
|
||||
int win_w, win_h;
|
||||
|
||||
/* Areas (layout estilo Blender) */
|
||||
LayNode lay[LAY_MAX];
|
||||
int lay_n, lay_root;
|
||||
AreaRect area[V_COUNT];
|
||||
int split_hover, split_drag; /* borda sob o mouse / sendo arrastada */
|
||||
int area_drag, area_drop; /* view levada pela alca / view alvo */
|
||||
|
||||
/* Views destacadas: cada uma numa janela propria (Graphics.Window com uma
|
||||
cena Editor.Area). Tudo usa as coordenadas da janela principal: a area
|
||||
destacada fica em (posicao da janela dela - posicao da principal). */
|
||||
TinyBlocks_Block* vwin[V_COUNT];
|
||||
TinyBlocks_Block* vwin_in[V_COUNT];
|
||||
TinyBlocks_Block* vwin_scene[V_COUNT];
|
||||
float vgeom[V_COUNT][4]; /* janela: x, y na tela, largura, altura */
|
||||
bool attach_pending[V_COUNT]; /* recolher no proximo quadro */
|
||||
int swap_pending[2]; /* trocar depois de recolher (-1 = nada) */
|
||||
float chip_x[V_COUNT], chip_w[V_COUNT]; /* botoes "voltar" no menu */
|
||||
float main_wx, main_wy; /* posicao da janela principal na tela */
|
||||
int mouse_owner; /* janela com o mouse (-1 = principal) */
|
||||
int capture_view; /* janela do clique em andamento (-2 = nenhum) */
|
||||
|
||||
/* Arrastar abas (reordenar como no navegador) */
|
||||
int tab_press; /* aba apertada (-1 = nenhuma) */
|
||||
bool tab_drag; /* passou do limiar: esta sendo arrastada */
|
||||
float tab_press_x, tab_press_y, tab_grab_dx;
|
||||
|
||||
/* Abas destacadas */
|
||||
TabWin twin[TABWIN_MAX];
|
||||
int tabctx; /* janela de aba ativa (-1 = principal) */
|
||||
int ctx_main_tab; /* aba atual da principal durante o contexto */
|
||||
AreaRect main_scripts; /* area de scripts da principal */
|
||||
int drag_tab; /* aba de onde vem o bloco arrastado */
|
||||
float drag_ws_x, drag_ws_y; /* origem da area de scripts dessa aba */
|
||||
} Ed;
|
||||
|
||||
#define CT (ed->tabs[ed->cur_tab])
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -73,7 +73,18 @@ enum {
|
||||
#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
|
||||
#define GFX_IN_KEYS_HELD 19 /* json: lista dos TB_KEY_* segurados agora */
|
||||
#define GFX_IN_TOUCHES 20 /* json: toques [[x,y],...] em px da janela */
|
||||
#define GFX_IN_ACCEL 21 /* json: [x,y,z] em m/s² ou [] sem sensor */
|
||||
#define GFX_IN_GYRO 22 /* json: [x,y,z] em rad/s ou [] sem sensor */
|
||||
#define GFX_IN_WIN_X 23 /* int: posição da janela na tela (x) */
|
||||
#define GFX_IN_WIN_Y 24 /* int: posição da janela na tela (y) */
|
||||
#define GFX_IN_MOUSE_IN 25 /* int: 1 se o mouse está sobre esta janela */
|
||||
#define GFX_IN_GMOUSE_X 26 /* real: mouse na tela (global), x */
|
||||
#define GFX_IN_GMOUSE_Y 27 /* real: mouse na tela (global), y */
|
||||
#define GFX_IN_COUNT 28
|
||||
|
||||
#define GFX_MAX_TOUCHES 10
|
||||
|
||||
/* Estado de entrada de uma janela em um frame (preenchido pelo backend) */
|
||||
typedef struct TinyBlocks_GfxInput {
|
||||
@@ -87,6 +98,15 @@ typedef struct TinyBlocks_GfxInput {
|
||||
int win_w, win_h;
|
||||
char drop_file[512];
|
||||
int mod_state;
|
||||
unsigned char keys_held[128]; /* indice = TB_KEY_* */
|
||||
int touch_n; /* dedos na tela agora */
|
||||
float touch_x[GFX_MAX_TOUCHES], touch_y[GFX_MAX_TOUCHES]; /* px da janela */
|
||||
int has_accel, has_gyro; /* o dispositivo tem o sensor? */
|
||||
float accel[3]; /* m/s² (inclui a gravidade) */
|
||||
float gyro[3]; /* rad/s */
|
||||
int win_x, win_y; /* posicao da janela na tela */
|
||||
int mouse_in; /* o mouse esta sobre esta janela */
|
||||
float gmouse_x, gmouse_y; /* mouse na tela (coordenadas globais) */
|
||||
} TinyBlocks_GfxInput;
|
||||
|
||||
/* -- Contrato de um backend gráfico --- */
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <time.h>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#include <tinyblocks/tb_json_block.h>
|
||||
#include "../include/tb_graphics.h"
|
||||
|
||||
#ifdef TB_GRAPHICS_DEFAULT_SDL2
|
||||
@@ -164,6 +165,11 @@ static const TinyBlocks_SlotDesc s_input_outs[GFX_IN_COUNT] = {
|
||||
{"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},
|
||||
};
|
||||
|
||||
static void eval_input(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
@@ -174,12 +180,57 @@ static void eval_input(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
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)
|
||||
@@ -202,6 +253,15 @@ static void input_push(TinyBlocks_Block* b, const TinyBlocks_GfxInput* in) {
|
||||
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));
|
||||
#undef SET
|
||||
b->dirty = false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Makefile da library input (categoria "Sensores")
|
||||
# Constroi build/libtinyblocks-input.a e build/libtinyblocks-input.so
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-I../../include -Iinclude -I../tinyblocks-graphics/include
|
||||
|
||||
OBJ := $(BUILD)/tb_input.o
|
||||
LIB_A := $(BUILD)/libtinyblocks-input.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-input.so
|
||||
|
||||
.PHONY: all static shared clean
|
||||
all: static shared
|
||||
static: $(LIB_A)
|
||||
shared: $(LIB_SO)
|
||||
|
||||
$(OBJ): src/tb_input.c include/tb_input_lib.h ../tinyblocks-graphics/include/tb_graphics.h
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
$(LIB_A): $(OBJ)
|
||||
ar rcs $@ $^
|
||||
|
||||
$(LIB_SO): $(OBJ)
|
||||
$(CC) -shared -o $@ $^ -lm
|
||||
|
||||
clean:
|
||||
$(RM) -r $(BUILD)
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* TinyBlocks - tb_input_lib.h
|
||||
* Library tinyblocks-input: blocos de Sensores (mouse, teclado, toque,
|
||||
* acelerometro, giroscopio e cronometro). Le o estado do core
|
||||
* (tinyblocks/tb_input.h), alimentado por quem mostra o palco.
|
||||
*/
|
||||
#ifndef TINYBLOCKS_INPUT_LIB_H
|
||||
#define TINYBLOCKS_INPUT_LIB_H
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_input_get_library(void);
|
||||
|
||||
/* Codigo TB_KEY_* de um nome de tecla ("espaço", "seta para cima", "a",
|
||||
"7", "enter", "space", "up"...); "qualquer"/"any" = -1; 0 = desconhecida */
|
||||
TB_API int tb_input_key_from_name(const char* name);
|
||||
/* Nome em portugues de um TB_KEY_* ("" se desconhecido) */
|
||||
TB_API const char* tb_input_key_name(int key);
|
||||
|
||||
#endif /* TINYBLOCKS_INPUT_LIB_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library input. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-input"
|
||||
version = "1.0.0"
|
||||
category = "Sensores"
|
||||
description = "Mouse, teclado, toque, acelerometro, giroscopio e cronometro"
|
||||
color = [92, 177, 214, 255]
|
||||
dark = [46, 142, 184, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/tb_input.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-input.so"
|
||||
static = "build/libtinyblocks-input.a"
|
||||
depends = []
|
||||
@@ -0,0 +1,270 @@
|
||||
/*
|
||||
* TinyBlocks - tb_input.c (library tinyblocks-input)
|
||||
* Categoria "Sensores": Input.MouseX / MouseY / Wheel / KeyPressed /
|
||||
* LastKey / TouchCount / TouchX / TouchY / Accel / Gyro / Timer /
|
||||
* ResetTimer e os booleanos Input.MouseDown / MouseRight / MouseOver /
|
||||
* Touching / HasAccel / HasGyro.
|
||||
*
|
||||
* Nao conhece janela nem editor: le o estado do core (tinyblocks/tb_input.h)
|
||||
* em coordenadas do palco. Os nomes de tecla usam os TB_KEY_* do
|
||||
* tinyblocks-graphics (so o cabecalho).
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <ctype.h>
|
||||
#include <math.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks/tb_input.h>
|
||||
#include <tb_graphics.h>
|
||||
#include "tb_input_lib.h"
|
||||
|
||||
/* -- Nomes de tecla ------------------------------------------------------- */
|
||||
|
||||
typedef struct { const char* name; int key; } KeyName;
|
||||
|
||||
/* O primeiro nome de cada tecla e o usado em "ultima tecla" */
|
||||
static const KeyName s_keys[] = {
|
||||
{"espaço", TB_KEY_SPACE}, {"espaco", TB_KEY_SPACE}, {"space", TB_KEY_SPACE},
|
||||
{"seta para cima", TB_KEY_UP}, {"cima", TB_KEY_UP}, {"up", TB_KEY_UP},
|
||||
{"seta para baixo", TB_KEY_DOWN}, {"baixo", TB_KEY_DOWN}, {"down", TB_KEY_DOWN},
|
||||
{"seta para esquerda", TB_KEY_LEFT}, {"esquerda", TB_KEY_LEFT}, {"left", TB_KEY_LEFT},
|
||||
{"seta para direita", TB_KEY_RIGHT}, {"direita", TB_KEY_RIGHT}, {"right", TB_KEY_RIGHT},
|
||||
{"enter", TB_KEY_RETURN}, {"return", TB_KEY_RETURN},
|
||||
{"esc", TB_KEY_ESCAPE}, {"escape", TB_KEY_ESCAPE},
|
||||
{"apagar", TB_KEY_BACKSPACE}, {"backspace", TB_KEY_BACKSPACE},
|
||||
{"delete", TB_KEY_DELETE}, {"del", TB_KEY_DELETE},
|
||||
{"tab", TB_KEY_TAB},
|
||||
{"home", TB_KEY_HOME}, {"end", TB_KEY_END},
|
||||
};
|
||||
|
||||
TB_API int tb_input_key_from_name(const char* name) {
|
||||
if (!name) return 0;
|
||||
while (isspace((unsigned char)*name)) name++;
|
||||
size_t n = strlen(name);
|
||||
while (n && isspace((unsigned char)name[n - 1])) n--;
|
||||
if (n == 0) return 0;
|
||||
char buf[32];
|
||||
if (n >= sizeof(buf)) return 0;
|
||||
memcpy(buf, name, n);
|
||||
buf[n] = 0;
|
||||
if (!strcasecmp(buf, "qualquer") || !strcasecmp(buf, "any")) return -1;
|
||||
if (n == 1) {
|
||||
char c = (char)tolower((unsigned char)buf[0]);
|
||||
if (c >= 'a' && c <= 'z') return TB_KEY_A + (c - 'a');
|
||||
if (c >= '0' && c <= '9') return TB_KEY_0 + (c - '0');
|
||||
}
|
||||
if ((buf[0] == 'f' || buf[0] == 'F') && n <= 3) {
|
||||
int k = atoi(buf + 1);
|
||||
if (k >= 1 && k <= 12) return TB_KEY_F1 + (k - 1);
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(s_keys) / sizeof(s_keys[0]); i++)
|
||||
if (!strcasecmp(buf, s_keys[i].name)) return s_keys[i].key;
|
||||
return 0;
|
||||
}
|
||||
|
||||
TB_API const char* tb_input_key_name(int key) {
|
||||
static char one[4][8];
|
||||
static int slot = 0;
|
||||
if (key >= TB_KEY_A && key < TB_KEY_A + 26) {
|
||||
char* b = one[slot++ & 3];
|
||||
snprintf(b, 8, "%c", 'a' + (key - TB_KEY_A));
|
||||
return b;
|
||||
}
|
||||
if (key >= TB_KEY_0 && key < TB_KEY_0 + 10) {
|
||||
char* b = one[slot++ & 3];
|
||||
snprintf(b, 8, "%c", '0' + (key - TB_KEY_0));
|
||||
return b;
|
||||
}
|
||||
if (key >= TB_KEY_F1 && key <= TB_KEY_F12) {
|
||||
char* b = one[slot++ & 3];
|
||||
snprintf(b, 8, "f%d", key - TB_KEY_F1 + 1);
|
||||
return b;
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(s_keys) / sizeof(s_keys[0]); i++)
|
||||
if (s_keys[i].key == key) return s_keys[i].name;
|
||||
return "";
|
||||
}
|
||||
|
||||
/* -- Entradas/saidas ------------------------------------------------------ */
|
||||
|
||||
static const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
static char num[32];
|
||||
if (v.kind == TB_VALUE_TEXT && v.as.text) return v.as.text;
|
||||
if (v.kind == TB_VALUE_INTEGER) { snprintf(num, sizeof(num), "%lld", (long long)v.as.integer); return num; }
|
||||
return "";
|
||||
}
|
||||
|
||||
static long long in_int(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
if (v.kind == TB_VALUE_INTEGER) return v.as.integer;
|
||||
if (v.kind == TB_VALUE_REAL) return (long long)llround(v.as.real);
|
||||
if (v.kind == TB_VALUE_TEXT && v.as.text) return strtoll(v.as.text, NULL, 10);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Eixo "x"/"y"/"z" (ou 1/2/3) -> 0..2; -1 se invalido */
|
||||
static int in_axis(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
const char* s = in_text(self, rt, i);
|
||||
while (isspace((unsigned char)*s)) s++;
|
||||
switch (tolower((unsigned char)*s)) {
|
||||
case 'x': case '1': return 0;
|
||||
case 'y': case '2': return 1;
|
||||
case 'z': case '3': return 2;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Numero: inteiro quando exato (como o Scratch mostra "120", nao "120.0") */
|
||||
static void out_num(TinyBlocks_Block* self, double x) {
|
||||
if (x == floor(x) && fabs(x) < 1e15) tb_block_set_output(self, 0, tb_value_integer((int64_t)x));
|
||||
else tb_block_set_output(self, 0, tb_value_real(x));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void out_bool(TinyBlocks_Block* self, bool b) {
|
||||
tb_block_set_output(self, 0, tb_value_integer(b ? 1 : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* -- Blocos --------------------------------------------------------------- */
|
||||
|
||||
static void eval_mouse_x(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, roundf(tb_input_mouse_x())); }
|
||||
static void eval_mouse_y(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, roundf(tb_input_mouse_y())); }
|
||||
static void eval_mouse_down(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_mouse_down()); }
|
||||
static void eval_mouse_right(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_mouse_right_down()); }
|
||||
static void eval_mouse_over(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_mouse_over_stage()); }
|
||||
static void eval_wheel(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, tb_input_wheel()); }
|
||||
|
||||
static void eval_key_pressed(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
const char* nm = in_text(self, rt, 0);
|
||||
int k = tb_input_key_from_name(nm);
|
||||
if (k == 0 && nm[0]) tinyblocks_set_error(rt, "tecla desconhecida: '%s'", nm);
|
||||
out_bool(self, k < 0 ? tb_input_any_key_held() : tb_input_key_held(k));
|
||||
}
|
||||
|
||||
static void eval_last_key(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
tb_block_set_output(self, 0, tb_value_text(tb_input_key_name(tb_input_last_key())));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_touch_count(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, tb_input_touch_count()); }
|
||||
static void eval_touching(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_touch_count() > 0); }
|
||||
|
||||
static void eval_touch_x(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
out_num(self, roundf(tb_input_touch_x((int)in_int(self, rt, 0) - 1)));
|
||||
}
|
||||
static void eval_touch_y(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
out_num(self, roundf(tb_input_touch_y((int)in_int(self, rt, 0) - 1)));
|
||||
}
|
||||
|
||||
static void eval_has_accel(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_has_accel()); }
|
||||
static void eval_has_gyro(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_bool(self, tb_input_has_gyro()); }
|
||||
|
||||
/* sensores: 2 casas, para nao piscar com o ruido */
|
||||
static void eval_accel(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int a = in_axis(self, rt, 0);
|
||||
out_num(self, a < 0 ? 0.0 : round(tb_input_accel(a) * 100.0) / 100.0);
|
||||
}
|
||||
static void eval_gyro(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int a = in_axis(self, rt, 0);
|
||||
out_num(self, a < 0 ? 0.0 : round(tb_input_gyro(a) * 100.0) / 100.0);
|
||||
}
|
||||
|
||||
static void eval_timer(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
out_num(self, round(tb_input_timer() * 1000.0) / 1000.0);
|
||||
}
|
||||
static void eval_reset_timer(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
tb_input_timer_reset();
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* -- Registro ------------------------------------------------------------- */
|
||||
|
||||
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
||||
const TinyBlocks_SlotDesc* in, uint32_t ni,
|
||||
const TinyBlocks_SlotDesc* out, uint32_t no,
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
|
||||
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
|
||||
return t && tb_library_add(lib, &t->base);
|
||||
}
|
||||
|
||||
static bool input_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
static const TinyBlocks_Category cat = {
|
||||
"Sensores",
|
||||
{ 92/255.f, 177/255.f, 214/255.f, 1.f},
|
||||
{ 46/255.f, 142/255.f, 184/255.f, 1.f},
|
||||
};
|
||||
tb_library_set_category(lib, &cat);
|
||||
|
||||
TB_BLOCK_META("Input.MouseX", "eval_mouse_x", "Posicao x do mouse no palco (-240 a 240)");
|
||||
TB_BLOCK_META("Input.MouseY", "eval_mouse_y", "Posicao y do mouse no palco (-180 a 180)");
|
||||
TB_BLOCK_META("Input.MouseDown", "eval_mouse_down", "Verdadeiro enquanto o botao do mouse estiver apertado");
|
||||
TB_BLOCK_META("Input.MouseRight", "eval_mouse_right", "Verdadeiro enquanto o botao direito estiver apertado");
|
||||
TB_BLOCK_META("Input.MouseOver", "eval_mouse_over", "Verdadeiro se o mouse estiver sobre o palco");
|
||||
TB_BLOCK_META("Input.Wheel", "eval_wheel", "Quanto a roda do mouse girou neste quadro");
|
||||
TB_BLOCK_META("Input.KeyPressed", "eval_key_pressed", "Verdadeiro enquanto a tecla estiver apertada");
|
||||
TB_BLOCK_META("Input.LastKey", "eval_last_key", "Nome da ultima tecla apertada");
|
||||
TB_BLOCK_META("Input.TouchCount", "eval_touch_count", "Quantos dedos estao na tela");
|
||||
TB_BLOCK_META("Input.Touching", "eval_touching", "Verdadeiro se algum dedo estiver na tela");
|
||||
TB_BLOCK_META("Input.TouchX", "eval_touch_x", "Posicao x do toque N no palco");
|
||||
TB_BLOCK_META("Input.TouchY", "eval_touch_y", "Posicao y do toque N no palco");
|
||||
TB_BLOCK_META("Input.HasAccel", "eval_has_accel", "Verdadeiro se o aparelho tiver acelerometro");
|
||||
TB_BLOCK_META("Input.Accel", "eval_accel", "Aceleracao no eixo x, y ou z (m/s², inclui a gravidade)");
|
||||
TB_BLOCK_META("Input.HasGyro", "eval_has_gyro", "Verdadeiro se o aparelho tiver giroscopio");
|
||||
TB_BLOCK_META("Input.Gyro", "eval_gyro", "Velocidade de giro no eixo x, y ou z (graus por segundo)");
|
||||
TB_BLOCK_META("Input.Timer", "eval_timer", "Segundos desde a bandeira verde (ou do ultimo zerar)");
|
||||
TB_BLOCK_META("Input.ResetTimer", "eval_reset_timer", "Zera o cronometro");
|
||||
|
||||
static const TinyBlocks_SlotDesc key_in[] = {{"tecla", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc n_in[] = {{"n", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc axis_in[] = {{"eixo", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc num_out[] = {{"numero", TB_VALUE_NONE}};
|
||||
static const TinyBlocks_SlotDesc txt_out[] = {{"texto", TB_VALUE_TEXT}};
|
||||
/* saidas terminadas em '?' = blocos booleanos (hexagonais no editor) */
|
||||
static const TinyBlocks_SlotDesc down_out[] = {{"pressionado?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc over_out[] = {{"sobre o palco?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc key_out[] = {{"pressionada?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc touch_out[] = {{"tocando?", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc has_out[] = {{"tem?", TB_VALUE_INTEGER}};
|
||||
|
||||
return reg(rt, lib, "Input.MouseX", NULL, 0, num_out, 1, eval_mouse_x)
|
||||
&& reg(rt, lib, "Input.MouseY", NULL, 0, num_out, 1, eval_mouse_y)
|
||||
&& reg(rt, lib, "Input.MouseDown", NULL, 0, down_out, 1, eval_mouse_down)
|
||||
&& reg(rt, lib, "Input.MouseRight", NULL, 0, down_out, 1, eval_mouse_right)
|
||||
&& reg(rt, lib, "Input.MouseOver", NULL, 0, over_out, 1, eval_mouse_over)
|
||||
&& reg(rt, lib, "Input.Wheel", NULL, 0, num_out, 1, eval_wheel)
|
||||
&& reg(rt, lib, "Input.KeyPressed", key_in, 1, key_out, 1, eval_key_pressed)
|
||||
&& reg(rt, lib, "Input.LastKey", NULL, 0, txt_out, 1, eval_last_key)
|
||||
&& reg(rt, lib, "Input.Touching", NULL, 0, touch_out, 1, eval_touching)
|
||||
&& reg(rt, lib, "Input.TouchCount", NULL, 0, num_out, 1, eval_touch_count)
|
||||
&& reg(rt, lib, "Input.TouchX", n_in, 1, num_out, 1, eval_touch_x)
|
||||
&& reg(rt, lib, "Input.TouchY", n_in, 1, num_out, 1, eval_touch_y)
|
||||
&& reg(rt, lib, "Input.HasAccel", NULL, 0, has_out, 1, eval_has_accel)
|
||||
&& reg(rt, lib, "Input.Accel", axis_in, 1, num_out, 1, eval_accel)
|
||||
&& reg(rt, lib, "Input.HasGyro", NULL, 0, has_out, 1, eval_has_gyro)
|
||||
&& reg(rt, lib, "Input.Gyro", axis_in, 1, num_out, 1, eval_gyro)
|
||||
&& reg(rt, lib, "Input.Timer", NULL, 0, num_out, 1, eval_timer)
|
||||
&& reg(rt, lib, "Input.ResetTimer", NULL, 0, NULL, 0, eval_reset_timer);
|
||||
}
|
||||
|
||||
static void input_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
(void)rt; (void)lib;
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(input,
|
||||
"tinyblocks-input",
|
||||
"1.0.0",
|
||||
input_init,
|
||||
input_deinit)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_input_get_library(void) {
|
||||
return &_tb_lib_desc_input;
|
||||
}
|
||||
@@ -398,6 +398,7 @@ typedef struct SdlWin {
|
||||
SDL_Renderer* ren;
|
||||
Uint32 id;
|
||||
TinyBlocks_GfxInput in;
|
||||
int pos_fresh; /* posicao do mouse veio de um evento neste quadro */
|
||||
struct SdlWin* next;
|
||||
} SdlWin;
|
||||
|
||||
@@ -439,6 +440,24 @@ static SdlWin* win_by_id(Uint32 id) {
|
||||
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) {
|
||||
@@ -452,6 +471,7 @@ static bool be_init(void) {
|
||||
}
|
||||
SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
|
||||
SDL_StartTextInput();
|
||||
sensors_open();
|
||||
s_be_inited = true;
|
||||
return true;
|
||||
}
|
||||
@@ -468,6 +488,7 @@ static void be_window_close(void* handle) {
|
||||
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();
|
||||
@@ -512,6 +533,9 @@ static bool s_has_pending = false;
|
||||
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;
|
||||
@@ -520,6 +544,7 @@ static bool be_apply(SDL_Event* ev) {
|
||||
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:
|
||||
@@ -528,6 +553,7 @@ static bool be_apply(SDL_Event* ev) {
|
||||
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; }
|
||||
@@ -580,6 +606,7 @@ static void be_poll(void) {
|
||||
in->text[0] = 0;
|
||||
in->drop_file[0] = 0;
|
||||
in->close = 0;
|
||||
w->pos_fresh = 0;
|
||||
}
|
||||
|
||||
if (s_has_pending) {
|
||||
@@ -591,6 +618,36 @@ static void be_poll(void) {
|
||||
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;
|
||||
@@ -598,11 +655,28 @@ static void be_poll(void) {
|
||||
int mods = map_mod((Uint16)SDL_GetModState());
|
||||
for (SdlWin* w = s_wins; w; w = w->next) {
|
||||
bool f = w->win == focus;
|
||||
if (f) { w->in.mouse_x = (float)mx; w->in.mouse_y = (float)my; }
|
||||
/* 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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* TinyBlocks - tb_input.c
|
||||
* Estado de entrada em coordenadas do palco (ver tb_input.h).
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "tinyblocks/tb_input.h"
|
||||
#include "tinyblocks/tb_stage.h"
|
||||
|
||||
#define HALF_W 240.f
|
||||
#define HALF_H 180.f
|
||||
#define RAD2DEG 57.29577951308232f
|
||||
|
||||
typedef struct {
|
||||
float mx, my; /* palco, sem prender */
|
||||
bool over, left, right;
|
||||
float wheel;
|
||||
unsigned char keys[TB_INPUT_MAX_KEYS];
|
||||
int last_key;
|
||||
int touch_n;
|
||||
float tx[TB_INPUT_MAX_TOUCHES], ty[TB_INPUT_MAX_TOUCHES];
|
||||
bool has_accel, has_gyro;
|
||||
float accel[3], gyro[3];
|
||||
double timer_t0;
|
||||
bool timer_started;
|
||||
} InputState;
|
||||
|
||||
static InputState s_in;
|
||||
|
||||
static double now_s(void) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;
|
||||
}
|
||||
|
||||
static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; }
|
||||
|
||||
/* -- Alimentacao --- */
|
||||
|
||||
void tb_input_begin_frame(void) {
|
||||
s_in.wheel = 0.f;
|
||||
}
|
||||
|
||||
void tb_input_set_mouse(float vx, float vy, bool left, bool right) {
|
||||
s_in.over = tb_stage_view_to_stage(vx, vy, &s_in.mx, &s_in.my);
|
||||
s_in.left = left;
|
||||
s_in.right = right;
|
||||
}
|
||||
|
||||
void tb_input_add_wheel(float dy) { s_in.wheel += dy; }
|
||||
|
||||
void tb_input_clear_keys(void) { memset(s_in.keys, 0, sizeof(s_in.keys)); }
|
||||
|
||||
void tb_input_set_key(int key, bool held) {
|
||||
if (key > 0 && key < TB_INPUT_MAX_KEYS) s_in.keys[key] = held ? 1 : 0;
|
||||
}
|
||||
|
||||
void tb_input_key_pressed(int key) {
|
||||
if (key > 0 && key < TB_INPUT_MAX_KEYS) s_in.last_key = key;
|
||||
}
|
||||
|
||||
void tb_input_set_touches(int n, const float* vx, const float* vy) {
|
||||
if (n < 0) n = 0;
|
||||
if (n > TB_INPUT_MAX_TOUCHES) n = TB_INPUT_MAX_TOUCHES;
|
||||
s_in.touch_n = n;
|
||||
for (int i = 0; i < n; i++) tb_stage_view_to_stage(vx[i], vy[i], &s_in.tx[i], &s_in.ty[i]);
|
||||
}
|
||||
|
||||
void tb_input_set_accel(bool has, float x, float y, float z) {
|
||||
s_in.has_accel = has;
|
||||
s_in.accel[0] = has ? x : 0.f; s_in.accel[1] = has ? y : 0.f; s_in.accel[2] = has ? z : 0.f;
|
||||
}
|
||||
|
||||
void tb_input_set_gyro(bool has, float x, float y, float z) {
|
||||
s_in.has_gyro = has;
|
||||
s_in.gyro[0] = has ? x : 0.f; s_in.gyro[1] = has ? y : 0.f; s_in.gyro[2] = has ? z : 0.f;
|
||||
}
|
||||
|
||||
void tb_input_reset(void) {
|
||||
memset(&s_in, 0, sizeof(s_in));
|
||||
}
|
||||
|
||||
/* -- Leitura --- */
|
||||
|
||||
float tb_input_mouse_x(void) { return clampf(s_in.mx, -HALF_W, HALF_W); }
|
||||
float tb_input_mouse_y(void) { return clampf(s_in.my, -HALF_H, HALF_H); }
|
||||
bool tb_input_mouse_over_stage(void) { return s_in.over; }
|
||||
bool tb_input_mouse_down(void) { return s_in.left; }
|
||||
bool tb_input_mouse_right_down(void) { return s_in.right; }
|
||||
float tb_input_wheel(void) { return s_in.wheel; }
|
||||
|
||||
bool tb_input_key_held(int key) {
|
||||
return key > 0 && key < TB_INPUT_MAX_KEYS && s_in.keys[key];
|
||||
}
|
||||
|
||||
bool tb_input_any_key_held(void) {
|
||||
for (int k = 1; k < TB_INPUT_MAX_KEYS; k++) if (s_in.keys[k]) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
int tb_input_last_key(void) { return s_in.last_key; }
|
||||
|
||||
int tb_input_touch_count(void) { return s_in.touch_n; }
|
||||
float tb_input_touch_x(int i) { return (i >= 0 && i < s_in.touch_n) ? s_in.tx[i] : 0.f; }
|
||||
float tb_input_touch_y(int i) { return (i >= 0 && i < s_in.touch_n) ? s_in.ty[i] : 0.f; }
|
||||
|
||||
bool tb_input_has_accel(void) { return s_in.has_accel; }
|
||||
float tb_input_accel(int axis) { return (axis >= 0 && axis < 3) ? s_in.accel[axis] : 0.f; }
|
||||
bool tb_input_has_gyro(void) { return s_in.has_gyro; }
|
||||
float tb_input_gyro(int axis) { return (axis >= 0 && axis < 3) ? s_in.gyro[axis] * RAD2DEG : 0.f; }
|
||||
|
||||
double tb_input_timer(void) {
|
||||
if (!s_in.timer_started) { s_in.timer_t0 = now_s(); s_in.timer_started = true; }
|
||||
return now_s() - s_in.timer_t0;
|
||||
}
|
||||
|
||||
void tb_input_timer_reset(void) {
|
||||
s_in.timer_t0 = now_s();
|
||||
s_in.timer_started = true;
|
||||
}
|
||||
@@ -124,6 +124,18 @@ void tb_stage_set_view(float w, float h) {
|
||||
if (w > 0 && h > 0) { s_stage.view_w = w; s_stage.view_h = h; }
|
||||
}
|
||||
|
||||
bool tb_stage_view_to_stage(float vx, float vy, float* sx, float* sy) {
|
||||
const Stage* s = &s_stage;
|
||||
float sc = s->view_w / STAGE_W < s->view_h / STAGE_H ? s->view_w / STAGE_W : s->view_h / STAGE_H;
|
||||
if (sc <= 0.f) sc = 1.f;
|
||||
float ox = (s->view_w - STAGE_W*sc) * 0.5f, oy = (s->view_h - STAGE_H*sc) * 0.5f;
|
||||
float x = (vx - ox) / sc - STAGE_W * 0.5f;
|
||||
float y = STAGE_H * 0.5f - (vy - oy) / sc;
|
||||
if (sx) *sx = x;
|
||||
if (sy) *sy = y;
|
||||
return x >= -STAGE_W * 0.5f && x <= STAGE_W * 0.5f && y >= -STAGE_H * 0.5f && y <= STAGE_H * 0.5f;
|
||||
}
|
||||
|
||||
void tb_stage_reset(void) {
|
||||
free(s_stage.cmds);
|
||||
s_stage.cmds = NULL; s_stage.n = 0; s_stage.cap = 0;
|
||||
|
||||
+157
-4
@@ -1,3 +1,4 @@
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
/* Harness headless do editor: dirige Editor.Scene com um bloco de eventos
|
||||
* falso e inspeciona os comandos de desenho produzidos por on_draw. */
|
||||
#include <stdio.h>
|
||||
@@ -19,6 +20,8 @@
|
||||
#include <tb_curves.h>
|
||||
#include <tb_base64.h>
|
||||
#include <tb_ppm.h>
|
||||
#include <tb_input_lib.h>
|
||||
#include <tb_environ.h>
|
||||
|
||||
static TinyBlocks* rt;
|
||||
static TinyBlocks_Block *ev, *scene;
|
||||
@@ -93,9 +96,10 @@ static bool stage_has(const char* s) {
|
||||
if (cmds[i].kind == TB_DRAW_TEXT && cmds[i].x >= 920 && strstr(cmds[i].text, s)) return true;
|
||||
return false;
|
||||
}
|
||||
/* Mensagens de status: palco/saída ou avisos flutuantes (toasts), em qualquer lugar */
|
||||
static bool any_has(const char* s) {
|
||||
for (uint32_t i = 0; i < ncmd; i++)
|
||||
if (cmds[i].kind == TB_DRAW_TEXT && cmds[i].x >= 920 && strstr(cmds[i].text, s)) return true;
|
||||
if (cmds[i].kind == TB_DRAW_TEXT && strstr(cmds[i].text, s)) return true;
|
||||
return false;
|
||||
}
|
||||
static bool ws_has(const char* s) {
|
||||
@@ -192,6 +196,10 @@ static bool need(const char* s, int region, int nth, float* x, float* y) {
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
/* configurações isoladas: o harness não lê nem grava o ~/.config real */
|
||||
setenv("XDG_CONFIG_HOME", "/tmp/tb_harness_cfg", 1);
|
||||
unsetenv("TINYBLOCKS_SETTINGS");
|
||||
remove("/tmp/tb_harness_cfg/tinyblocks/settings.csv");
|
||||
tinyblocks_init(&rt, NULL);
|
||||
tb_graphics_set_backend(tb_graphics_null_backend());
|
||||
tb_library_register(rt, tb_events_get_library());
|
||||
@@ -203,6 +211,7 @@ int main(void) {
|
||||
tb_library_register(rt, tb_curves_get_library());
|
||||
tb_library_register(rt, tb_base64_get_library());
|
||||
tb_library_register(rt, tb_ppm_get_library());
|
||||
tb_library_register(rt, tb_input_get_library());
|
||||
tb_library_register(rt, tb_graphics_get_library());
|
||||
tb_library_register(rt, tb_editor_get_library());
|
||||
(void)eval_ev;
|
||||
@@ -370,10 +379,22 @@ int main(void) {
|
||||
CHECK(circles == circles_before, "\"apague tudo\" limpa o palco");
|
||||
|
||||
/* 11. Destacar o palco numa janela própria e recolher de volta */
|
||||
{
|
||||
click(1280 - 50 + 20, 44 + 22);
|
||||
CHECK(any_has("Palco aberto em outra janela"), "palco destacado abre janela própria");
|
||||
click(1280 - 50 + 20, 44 + 22);
|
||||
CHECK(!any_has("Palco aberto em outra janela"), "palco recolhido volta ao painel");
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
/* a área do palco sai da janela principal; fica um botão "Palco" no menu */
|
||||
bool no_menu = false, no_painel = false;
|
||||
float cx = 0, cy = 0;
|
||||
for (uint32_t i = 0; i < ncmd; i++) {
|
||||
if (cmds[i].kind != TB_DRAW_TEXT || strcmp(cmds[i].text, "Palco") != 0) continue;
|
||||
if (cmds[i].y < 44) { no_menu = true; cx = cmds[i].x + 3; cy = 22; }
|
||||
else no_painel = true;
|
||||
}
|
||||
CHECK(no_menu && !no_painel, "palco destacado abre janela própria (botão \"Palco\" no menu)");
|
||||
if (no_menu) click(cx, cy); /* recolhe no próximo quadro */
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
CHECK(find("Palco", R_ANY, 0, &x, &y) && x > 920 && y > 44, "palco recolhido volta ao painel");
|
||||
}
|
||||
|
||||
/* 12. Salvar e abrir projeto (.json) via tinyblocks-blueprint */
|
||||
const char* proj = "/tmp/tb_harness_proj.json";
|
||||
@@ -383,6 +404,22 @@ int main(void) {
|
||||
type(proj);
|
||||
key(TB_KEY_RETURN, 0, 0);
|
||||
CHECK(any_has("Projeto salvo"), "salvar projeto escreve o .json");
|
||||
{
|
||||
/* aviso flutuante (toast) sobre a área de scripts, não no menu */
|
||||
bool flutua = false;
|
||||
for (uint32_t i = 0; i < ncmd; i++)
|
||||
if (cmds[i].kind == TB_DRAW_TEXT && strstr(cmds[i].text, "Projeto salvo") &&
|
||||
cmds[i].x > 318 && cmds[i].x < 920 && cmds[i].y > 400) flutua = true;
|
||||
CHECK(flutua, "mensagem vira aviso flutuante no canto da área de scripts");
|
||||
/* salvar de novo: a mesma mensagem vira contador (x2) */
|
||||
if (need("Salvar", R_FLY, 0, &x, &y)) click(x, y);
|
||||
for (int i = 0; i < 40; i++) key(TB_KEY_BACKSPACE, 0, 0);
|
||||
type(proj);
|
||||
key(TB_KEY_RETURN, 0, 0);
|
||||
if (find("Substituir", R_ANY, 0, &x, &y)) click(x, y);
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
CHECK(any_has("(x2)"), "mensagem repetida vira contador (x2)");
|
||||
}
|
||||
if (need("Abrir", R_FLY, 0, &x, &y)) click(x, y);
|
||||
for (int i = 0; i < 40; i++) key(TB_KEY_BACKSPACE, 0, 0);
|
||||
type(proj);
|
||||
@@ -546,6 +583,45 @@ int main(void) {
|
||||
remove(fj);
|
||||
}
|
||||
|
||||
/* 13e. Sensores: posição do mouse no palco e última tecla, num "sempre" */
|
||||
{
|
||||
const char* sj = "/tmp/tb_harness_sensores.json";
|
||||
FILE* sf = fopen(sj, "wb");
|
||||
if (sf) {
|
||||
fputs("{\"format\":\"tinyblocks-project\",\"version\":1,\"cur_tab\":0,"
|
||||
"\"tabs\":[{\"name\":\"Sensores\",\"composite\":false,\"comp_id\":-1,\"color\":0,"
|
||||
"\"blocks\":["
|
||||
"{\"i\":0,\"type\":\"Events.WhenRun\",\"x\":40,\"y\":40,\"next\":1},"
|
||||
"{\"i\":1,\"type\":\"Control.Forever\",\"x\":40,\"y\":100,\"parent\":0,\"prel\":0,\"sub\":[2,-1]},"
|
||||
"{\"i\":2,\"type\":\"Stage.Clear\",\"x\":0,\"y\":0,\"parent\":1,\"prel\":1,\"next\":3},"
|
||||
"{\"i\":3,\"type\":\"IO.Print\",\"x\":0,\"y\":0,\"parent\":2,\"prel\":0,\"args\":[4,5]},"
|
||||
"{\"i\":4,\"type\":\"Input.MouseX\",\"x\":0,\"y\":0,\"parent\":3,\"prel\":3},"
|
||||
"{\"i\":5,\"type\":\"Input.LastKey\",\"x\":0,\"y\":0,\"parent\":3,\"prel\":4}"
|
||||
"],\"top\":[0]}],\"user_blocks\":[],\"variables\":[]}", sf);
|
||||
fclose(sf);
|
||||
}
|
||||
if (need("Abrir", R_FLY, 0, &x, &y)) click(x, y);
|
||||
for (int i = 0; i < 40; i++) key(TB_KEY_BACKSPACE, 0, 0);
|
||||
type(sj);
|
||||
key(TB_KEY_RETURN, 0, 0);
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
flag();
|
||||
/* vista do palco no painel: origem (929, 89), 342 px = 480 do palco;
|
||||
x do palco 100 -> 929 + 171 + 100 * 342/480 */
|
||||
float px = 929.f + 171.f + 100.f * 342.f / 480.f, py = 89.f + 100.f;
|
||||
for (int i = 0; i < 3; i++) frame(px, py, 0, 0, 0, 0, NULL);
|
||||
CHECK(stage_has("100"), "posição x do mouse sobre o palco = 100");
|
||||
if (!stage_has("100"))
|
||||
for (uint32_t i = 0; i < ncmd; i++)
|
||||
if (cmds[i].kind == TB_DRAW_TEXT && cmds[i].x >= 920) printf(" palco: '%s'\n", cmds[i].text);
|
||||
frame(px, py, 0, 0, 0, TB_KEY_SPACE, NULL);
|
||||
for (int i = 0; i < 3; i++) frame(px, py, 0, 0, 0, 0, NULL);
|
||||
CHECK(stage_has("espaço"), "última tecla = espaço");
|
||||
click(1280 - 360 + 76, 44 + 22); /* botão vermelho */
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
remove(sj);
|
||||
}
|
||||
|
||||
/* 14. Exportar pelo menu de contexto do botao Exportar */
|
||||
if (need("Exportar", R_FLY, 0, &x, &y)) click(x, y);
|
||||
CHECK(find("Exportar JSON", R_FLY, 0, &x, &y) && find("Exportar XML", R_FLY, 0, &x, &y)
|
||||
@@ -705,6 +781,7 @@ int main(void) {
|
||||
CHECK(ws_has("int"), "aba de codigo realca 'int' (palavra-chave)");
|
||||
CHECK(ws_has("42"), "aba de codigo realca o numero 42");
|
||||
CHECK(ws_has(";"), "aba de codigo realca a pontuacao");
|
||||
CHECK(!any_has("</code>"), "aba de codigo nao mostra a marcacao </code>");
|
||||
}
|
||||
|
||||
/* 23. Botao "+" -> nova aba: Edicao de Imagem */
|
||||
@@ -797,6 +874,82 @@ int main(void) {
|
||||
CHECK(img_nonwhite() > 0, "camada pode ser mostrada de novo");
|
||||
}
|
||||
|
||||
/* 22. Áreas estilo Blender: redimensionar arrastando a borda, trocar de lugar pela alça */
|
||||
{
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
CHECK(find("Blocos", R_ANY, 0, &x, &y) && x < 100, "paleta tem cabeçalho \"Blocos\" com alça");
|
||||
/* borda paleta | scripts em x = 318: arrasta 100 px para a direita */
|
||||
drag(318, 400, 418, 400);
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
bool largo = false;
|
||||
for (uint32_t i = 0; i < ncmd; i++)
|
||||
if (cmds[i].kind == TB_DRAW_SET_CLIP && cmds[i].x == 68 && cmds[i].w > 340) largo = true;
|
||||
CHECK(largo, "arrastar a borda alarga a paleta (418 px)");
|
||||
float px0 = 0, py0 = 0;
|
||||
CHECK(find("Palco", R_ANY, 0, &px0, &py0) && px0 > 920, "palco continua na direita");
|
||||
/* alça do palco (ao lado do botão de destacar) -> solta sobre os scripts */
|
||||
drag(1280 - 50 - 18 - 8 + 9, 44 + 22, 640, 400);
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
CHECK(find("Palco", R_ANY, 0, &x, &y) && x > 418 && x < 900, "alça troca o palco com a área de scripts");
|
||||
/* e de volta: a alça do palco agora está no meio da tela */
|
||||
drag(418 + (1280 - 360 - 418) - 50 - 18 - 8 + 9, 44 + 22, 1100, 200); /* scripts, em cima à direita */
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
CHECK(find("Palco", R_ANY, 0, &x, &y) && x > 920, "trocar de novo devolve o palco à direita");
|
||||
/* layout salvo nas configurações (arquivo isolado do harness) */
|
||||
CHECK(!strcmp(tb_environ_get("editor.layout"), "H0:418(p,H1:360(s,V0:310(t,o)))"),
|
||||
"layout salvo em editor.layout (paleta com 418 px)");
|
||||
FILE* cf = fopen("/tmp/tb_harness_cfg/tinyblocks/settings.csv", "rb");
|
||||
char cbuf[1024] = "";
|
||||
if (cf) { size_t n = fread(cbuf, 1, sizeof(cbuf) - 1, cf); cbuf[n] = 0; fclose(cf); }
|
||||
CHECK(strstr(cbuf, "editor.layout") != NULL, "layout gravado no arquivo de configurações");
|
||||
}
|
||||
|
||||
/* 23. Abas: arrastar na barra reordena (como no navegador) */
|
||||
{
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
/* rótulos das abas na barra (y 44..80), em ordem de x */
|
||||
char nomes[8][64]; float xs[8]; int n = 0;
|
||||
for (uint32_t i = 0; i < ncmd && n < 8; i++) {
|
||||
if (cmds[i].kind != TB_DRAW_TEXT || cmds[i].y < 50 || cmds[i].y > 80) continue;
|
||||
if (cmds[i].x < 318 || cmds[i].x > 900 || !strcmp(cmds[i].text, "=") || !strcmp(cmds[i].text, "+")) continue;
|
||||
snprintf(nomes[n], 64, "%s", cmds[i].text); xs[n] = cmds[i].x; n++;
|
||||
}
|
||||
CHECK(n >= 2, "há pelo menos duas abas para reordenar");
|
||||
if (n >= 2) {
|
||||
char primeira[64]; snprintf(primeira, 64, "%s", nomes[0]);
|
||||
float sx = xs[0] + 10;
|
||||
drag(sx, 62, sx + 150 + 20, 62); /* passa do meio da vizinha */
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
float nx = 0, ny = 0;
|
||||
bool achou = false;
|
||||
for (uint32_t i = 0; i < ncmd; i++)
|
||||
if (cmds[i].kind == TB_DRAW_TEXT && !strcmp(cmds[i].text, primeira) && cmds[i].y > 50 && cmds[i].y < 80) {
|
||||
nx = cmds[i].x; ny = cmds[i].y; achou = true;
|
||||
}
|
||||
(void)ny;
|
||||
CHECK(achou && nx > xs[1] - 20, "arrastar a aba para a direita troca a ordem com a vizinha");
|
||||
|
||||
/* arrastar a aba para longe da barra destaca numa janela própria */
|
||||
drag(nx + 10, 62, nx + 10, 400);
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
bool na_barra = false, no_menu = false;
|
||||
float mxp = 0;
|
||||
for (uint32_t i = 0; i < ncmd; i++) {
|
||||
if (cmds[i].kind != TB_DRAW_TEXT || strcmp(cmds[i].text, primeira) != 0) continue;
|
||||
if (cmds[i].y > 50 && cmds[i].y < 80) na_barra = true;
|
||||
if (cmds[i].y < 44) { no_menu = true; mxp = cmds[i].x + 3; }
|
||||
}
|
||||
CHECK(!na_barra && no_menu, "aba arrastada para fora vira janela (botão no menu)");
|
||||
if (no_menu) click(mxp, 22); /* volta para a barra */
|
||||
frame(0, 0, 0, 0, 0, 0, NULL);
|
||||
na_barra = false;
|
||||
for (uint32_t i = 0; i < ncmd; i++)
|
||||
if (cmds[i].kind == TB_DRAW_TEXT && !strcmp(cmds[i].text, primeira) && cmds[i].y > 50 && cmds[i].y < 80)
|
||||
na_barra = true;
|
||||
CHECK(na_barra, "botão no menu traz a aba de volta para a barra");
|
||||
}
|
||||
}
|
||||
|
||||
printf("comandos de desenho no último frame: %u\n", ncmd);
|
||||
tinyblocks_deinit(&rt);
|
||||
printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails);
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* input_test.c - testa o estado de entrada do core (tb_input) e os blocos
|
||||
* de Sensores da tinyblocks-input: mouse em coordenadas do palco, teclas
|
||||
* por nome, toques, sensores e cronometro.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks/tb_input.h>
|
||||
#include <tinyblocks/tb_stage.h>
|
||||
#include <tb_graphics.h>
|
||||
#include <tb_input_lib.h>
|
||||
|
||||
static int fails = 0;
|
||||
#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0)
|
||||
|
||||
static TinyBlocks* rt;
|
||||
static TinyBlocks_Block* last;
|
||||
|
||||
static TinyBlocks_Value* run(const char* type, const char* arg) {
|
||||
if (last) { tb_block_destroy(last, rt); last = NULL; }
|
||||
TinyBlocks_TypeBlock* t = tb_rt_find_type(rt, type);
|
||||
if (!t) { printf(" (tipo %s nao existe)\n", type); return NULL; }
|
||||
last = tb_block_create(rt, t);
|
||||
if (arg) {
|
||||
TinyBlocks_Value v = t->input_descs[0].expected_kind == TB_VALUE_INTEGER
|
||||
? tb_value_integer(atoll(arg)) : tb_value_text(arg);
|
||||
tb_block_set_default(last, 0, v);
|
||||
tb_value_free(&v);
|
||||
}
|
||||
tb_block_eval(last, rt);
|
||||
return last->output_count ? &last->outputs[0] : NULL;
|
||||
}
|
||||
|
||||
static long long num(TinyBlocks_Value* v) {
|
||||
if (!v) return -99999;
|
||||
if (v->kind == TB_VALUE_INTEGER) return v->as.integer;
|
||||
if (v->kind == TB_VALUE_REAL) return llround(v->as.real);
|
||||
return -99999;
|
||||
}
|
||||
static double real(TinyBlocks_Value* v) {
|
||||
if (!v) return -99999;
|
||||
return v->kind == TB_VALUE_REAL ? v->as.real : v->kind == TB_VALUE_INTEGER ? (double)v->as.integer : -99999;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
tinyblocks_init(&rt, NULL);
|
||||
TinyBlocks_LibraryBlock* lib = tb_library_register(rt, tb_input_get_library());
|
||||
CHECK(lib && !strcmp(tb_library_category(lib)->name, "Sensores"), "categoria 'Sensores'");
|
||||
|
||||
/* vista 480x360 = palco 1:1; (240,180) da vista = centro do palco */
|
||||
tb_stage_set_view(480, 360);
|
||||
tb_input_reset();
|
||||
tb_input_begin_frame();
|
||||
tb_input_set_mouse(240, 180, false, false);
|
||||
CHECK(num(run("Input.MouseX", NULL)) == 0 && num(run("Input.MouseY", NULL)) == 0,
|
||||
"centro da vista = (0, 0) do palco");
|
||||
tb_input_set_mouse(480, 0, true, false);
|
||||
CHECK(num(run("Input.MouseX", NULL)) == 240 && num(run("Input.MouseY", NULL)) == 180,
|
||||
"canto superior direito = (240, 180), y para cima");
|
||||
CHECK(num(run("Input.MouseDown", NULL)) == 1, "mouse pressionado?");
|
||||
tb_input_set_mouse(900, 500, false, false);
|
||||
CHECK(num(run("Input.MouseX", NULL)) == 240 && num(run("Input.MouseOver", NULL)) == 0,
|
||||
"fora do palco: posição presa na borda e 'sobre o palco?' falso");
|
||||
|
||||
/* vista maior com faixas (letterbox): 960x540 -> escala 1.5, faixas laterais */
|
||||
tb_stage_set_view(960, 540);
|
||||
tb_input_set_mouse(480, 270, false, false);
|
||||
CHECK(num(run("Input.MouseX", NULL)) == 0 && num(run("Input.MouseY", NULL)) == 0,
|
||||
"letterbox: centro continua (0, 0)");
|
||||
tb_input_set_mouse(120 + 720, 270, false, false);
|
||||
CHECK(num(run("Input.MouseX", NULL)) == 240, "letterbox: borda direita do palco = 240");
|
||||
tb_stage_set_view(480, 360);
|
||||
|
||||
/* teclado */
|
||||
CHECK(tb_input_key_from_name("espaço") == TB_KEY_SPACE && tb_input_key_from_name("Space") == TB_KEY_SPACE &&
|
||||
tb_input_key_from_name("seta para cima") == TB_KEY_UP && tb_input_key_from_name("a") == TB_KEY_A &&
|
||||
tb_input_key_from_name("7") == TB_KEY_0 + 7 && tb_input_key_from_name("qualquer") == -1 &&
|
||||
tb_input_key_from_name("f5") == TB_KEY_F5, "nomes de tecla (PT/EN, letras, números, F)");
|
||||
tb_input_clear_keys();
|
||||
tb_input_set_key(TB_KEY_SPACE, true);
|
||||
CHECK(num(run("Input.KeyPressed", "espaço")) == 1, "tecla espaço pressionada?");
|
||||
CHECK(num(run("Input.KeyPressed", "a")) == 0, "tecla a não pressionada");
|
||||
CHECK(num(run("Input.KeyPressed", "qualquer")) == 1, "qualquer tecla");
|
||||
tb_input_clear_keys();
|
||||
CHECK(num(run("Input.KeyPressed", "qualquer")) == 0, "soltou todas");
|
||||
tb_input_key_pressed(TB_KEY_UP);
|
||||
TinyBlocks_Value* lk = run("Input.LastKey", NULL);
|
||||
CHECK(lk && lk->kind == TB_VALUE_TEXT && !strcmp(lk->as.text, "seta para cima"), "última tecla em português");
|
||||
|
||||
/* toque */
|
||||
float tx[2] = {240, 0}, ty[2] = {180, 0};
|
||||
tb_input_set_touches(2, tx, ty);
|
||||
CHECK(num(run("Input.TouchCount", NULL)) == 2 && num(run("Input.Touching", NULL)) == 1, "dois dedos na tela");
|
||||
CHECK(num(run("Input.TouchX", "2")) == -240 && num(run("Input.TouchY", "2")) == 180, "toque 2 no canto (-240, 180)");
|
||||
tb_input_set_touches(0, NULL, NULL);
|
||||
CHECK(num(run("Input.Touching", NULL)) == 0, "sem toque");
|
||||
|
||||
/* sensores */
|
||||
CHECK(num(run("Input.HasAccel", NULL)) == 0 && num(run("Input.HasGyro", NULL)) == 0, "sem sensores por padrão");
|
||||
tb_input_set_accel(true, 0.5f, -9.81f, 0.f);
|
||||
tb_input_set_gyro(true, 0.f, 0.f, 3.14159265f);
|
||||
CHECK(num(run("Input.HasAccel", NULL)) == 1 && fabs(real(run("Input.Accel", "y")) + 9.81) < 1e-6,
|
||||
"acelerômetro y = -9.81");
|
||||
CHECK(fabs(real(run("Input.Gyro", "z")) - 180.0) < 0.01, "giroscópio em graus/s (pi rad/s = 180)");
|
||||
|
||||
/* cronômetro */
|
||||
run("Input.ResetTimer", NULL);
|
||||
double t = real(run("Input.Timer", NULL));
|
||||
CHECK(t >= 0 && t < 0.5, "zere o cronômetro");
|
||||
|
||||
/* booleanos declarados com '?' */
|
||||
TinyBlocks_TypeBlock* tk = tb_rt_find_type(rt, "Input.KeyPressed");
|
||||
CHECK(tk && tk->output_descs[0].name[strlen(tk->output_descs[0].name) - 1] == '?',
|
||||
"tecla pressionada? é booleano ('?')");
|
||||
|
||||
if (last) tb_block_destroy(last, rt);
|
||||
tinyblocks_deinit(&rt);
|
||||
if (fails) printf("\n%d FALHA(S)\n", fails);
|
||||
else printf("\nTUDO OK\n");
|
||||
return fails != 0;
|
||||
}
|
||||
Reference in new issue
Block a user