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
+2463
-183
No files matched your search
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user