diff --git a/docs/blocos.md b/docs/blocos.md index 4baece2..a5c1265 100644 --- a/docs/blocos.md +++ b/docs/blocos.md @@ -23,7 +23,7 @@ ver [referencia-api.md](referencia-api.md)). Para regerar: [ferramentas/README.md](ferramentas/README.md). -Total: 437 tipos em 40 libraries. +Total: 438 tipos em 40 libraries. ## Índice @@ -49,7 +49,7 @@ Total: 437 tipos em 40 libraries. - [tinyblocks-ai](#tinyblocks-ai) (categoria "IA") - 39 blocos - [tinyblocks-plot](#tinyblocks-plot) (categoria "Gráficos") - 19 blocos - [tinyblocks-3d](#tinyblocks-3d) (categoria "3D") - 39 blocos -- [tinyblocks-shader](#tinyblocks-shader) (categoria "Shader") - 23 blocos +- [tinyblocks-shader](#tinyblocks-shader) (categoria "Shader") - 24 blocos - [tinyblocks-toml](#tinyblocks-toml) (categoria "TOML") - 1 bloco - [tinyblocks-json](#tinyblocks-json) (categoria "JSON") - 2 blocos - [tinyblocks-xml](#tinyblocks-xml) (categoria "XML") - 2 blocos @@ -568,7 +568,8 @@ Categoria na paleta: **Shader**. | Tipo | Rótulo no editor | Forma | Entradas | Saídas | Descrição | |---|---|---|---|---|---| -| `Shader.Pixel` | cor do pixel = (a) | comando | `a` (qualquer) | - | Muda a cor do pixel (uma cor, ou um número para cinza) | +| `Shader.Pixel` | cor do pixel = (a) | comando | `a` (qualquer) | - | Muda a cor do pixel (uma cor, ou um número para cinza). Faz o shader ser de FRAGMENTO | +| `Shader.Vertex` | mude a posição do vértice para x (a) y (b) z (c)
padrões: `\|0\|0` | comando | `a` (qualquer), `b` (qualquer), `c` (qualquer) | - | A posição do vértice no espaço do objeto (a câmera e o mova/gire aplicam por cima). Faz o shader ser de VÉRTICE | | `Shader.PixelColor` | cor do pixel | repórter | - | `valor` (qualquer) | A cor do pixel até aqui (começa com a cor do objeto já iluminada) | | `Shader.ObjectColor` | cor do objeto | repórter | - | `valor` (qualquer) | A cor dada ao objeto ("mude a cor de"), sem luz | | `Shader.Light` | luz | repórter | - | `valor` (qualquer) | Claridade do ponto (luz ambiente + sol), de 0 a 1 | diff --git a/docs/libraries.md b/docs/libraries.md index ace4bf4..2c2df29 100644 --- a/docs/libraries.md +++ b/docs/libraries.md @@ -267,12 +267,16 @@ vocabulário (blocos que, fora de um shader, dão erro), e o compilador da 3d ``` "compile o shader [pilha]" (repórter da 3d; a pilha vem como código JSON) - -> d3_shader_compile: nós com tipo (número, cor, condição) - |-> GLSL "vec3 tb_shade(P, N, base, light, time)" - | -> Tb3dRenderer.compile de cada backend disponível: - | vk: monta o fragment 450 e gera SPIR-V (libshaderc, dlopen) + -> d3_shader_compile: nós com tipo (número, cor, condição) e o estágio + ("cor do pixel" = fragmento; "mude a posição do vértice" = vértice) + |-> GLSL "vec3 tb_shade(P, N, L, UV, base, light, time)" (fragmento) + | ou "vec3 tb_vert(P, N, L, UV, base, light, time)" (vértice) + | -> Tb3dRenderer.compile de cada backend disponível (com o estágio): + | vk: monta o shader 450 e gera SPIR-V (libshaderc, dlopen); + | no vértice junta com um fragmento padrão ao desenhar | gl: liga o programa e devolve o binário do driver (glGetProgramBinary) - `-> interpretador (o renderizador em software, pixel a pixel) + `-> interpretador (o renderizador em software, pixel a pixel, + ou vértice a vértice no shader de vértice) = o shader compilado: um bloco-handle (valor), com referências contadas ``` diff --git a/docs/pendencias.md b/docs/pendencias.md index 3bf53e7..cd73b7f 100644 --- a/docs/pendencias.md +++ b/docs/pendencias.md @@ -114,13 +114,16 @@ Um rótulo como `%1 encosta em %2?` não é reconhecido na importação de uma palavra (`tecla %1 pressionada?`) funciona. A 3d usa `objeto %1 encosta em %2` (o formato booleano vem do nome da saída). -### Shaders: só a cor do pixel +### Shaders: falta textura e material -Os shaders feitos com blocos mudam a cor do pixel (fragment); ainda não há -shader de vértice (deformar a malha), texturas nem luz por pixel nos objetos -sem shader (estes usam luz por vértice). O binário do OpenGL só vale para -a mesma placa e driver (o projeto salvo não guarda binários: o shader é -compilado de novo quando o programa roda). +Os shaders feitos com blocos mudam a cor do pixel (fragmento) e a posição +do vértice (vértice, `mude a posição do vértice`); o estágio sai sozinho do +que a pilha usa. Cada objeto usa um shader (não dá para ter um de vértice e +um de fragmento no mesmo objeto ao mesmo tempo). Ainda não há texturas, +materiais nem luz por pixel nos objetos sem shader (estes usam luz por +vértice). O binário do OpenGL só vale para a mesma placa e driver (o +projeto salvo não guarda binários: o shader é compilado de novo quando o +programa roda). ### Campo de texto de um bloco corta em 63 caracteres diff --git a/docs/referencia-api.md b/docs/referencia-api.md index 3454851..7dbe846 100644 --- a/docs/referencia-api.md +++ b/docs/referencia-api.md @@ -57,6 +57,7 @@ Convenções que valem para toda a API: - [`libraries/tinyblocks-curves/include/tb_curves.h`](#librariestinyblocks-curvesincludetb_curvesh) - [`libraries/tinyblocks-editor/include/tb_editor.h`](#librariestinyblocks-editorincludetb_editorh) - [`libraries/tinyblocks-editor/include/tb_editor_internal.h`](#librariestinyblocks-editorincludetb_editor_internalh) +- [`libraries/tinyblocks-editor/include/tb_editor_m3.h`](#librariestinyblocks-editorincludetb_editor_m3h) - [`libraries/tinyblocks-editor/include/tb_editor_modules.h`](#librariestinyblocks-editorincludetb_editor_modulesh) - [`libraries/tinyblocks-editor/include/tb_stage_widget.h`](#librariestinyblocks-editorincludetb_stage_widgeth) - [`libraries/tinyblocks-editor/libraries/tinyblocks-editor-files/include/tb_editor_files.h`](#librariestinyblocks-editorlibrariestinyblocks-editor-filesincludetb_editor_filesh) @@ -80,6 +81,7 @@ Convenções que valem para toda a API: - [`libraries/tinyblocks-mcp-server/include/tb_mcp_server.h`](#librariestinyblocks-mcp-serverincludetb_mcp_serverh) - [`libraries/tinyblocks-mcp-server/include/tb_mcp_server_internal.h`](#librariestinyblocks-mcp-serverincludetb_mcp_server_internalh) - [`libraries/tinyblocks-mcp/include/tinyblocks-mcp/tb_mcp.h`](#librariestinyblocks-mcpincludetinyblocks-mcptb_mcph) +- [`libraries/tinyblocks-mcp/src/tb_mcp_py.h`](#librariestinyblocks-mcpsrctb_mcp_pyh) - [`libraries/tinyblocks-number/include/tb_number.h`](#librariestinyblocks-numberincludetb_numberh) - [`libraries/tinyblocks-opentype/include/tb_opentype.h`](#librariestinyblocks-opentypeincludetb_opentypeh) - [`libraries/tinyblocks-operators/include/tb_operators.h`](#librariestinyblocks-operatorsincludetb_operatorsh) @@ -90,6 +92,11 @@ Convenções que valem para toda a API: - [`libraries/tinyblocks-png/include/tb_png.h`](#librariestinyblocks-pngincludetb_pngh) - [`libraries/tinyblocks-ppm/include/tb_ppm.h`](#librariestinyblocks-ppmincludetb_ppmh) - [`libraries/tinyblocks-python/include/tinyblocks-python/tb_python.h`](#librariestinyblocks-pythonincludetinyblocks-pythontb_pythonh) +- [`libraries/tinyblocks-qr/include/tb_camera.h`](#librariestinyblocks-qrincludetb_camerah) +- [`libraries/tinyblocks-qr/include/tb_qr.h`](#librariestinyblocks-qrincludetb_qrh) +- [`libraries/tinyblocks-qr/src/qrcodegen.h`](#librariestinyblocks-qrsrcqrcodegenh) +- [`libraries/tinyblocks-qr/src/quirc.h`](#librariestinyblocks-qrsrcquirch) +- [`libraries/tinyblocks-qr/src/quirc_internal.h`](#librariestinyblocks-qrsrcquirc_internalh) - [`libraries/tinyblocks-regex/include/tb_regex.h`](#librariestinyblocks-regexincludetb_regexh) - [`libraries/tinyblocks-scratchblocks/include/tb_scratchblocks.h`](#librariestinyblocks-scratchblocksincludetb_scratchblocksh) - [`libraries/tinyblocks-sdl2/include/tb_sdl2.h`](#librariestinyblocks-sdl2includetb_sdl2h) @@ -694,6 +701,16 @@ Uso típico: | `void tb_draw_set_clip (TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h)` | Recorte: só desenha dentro do retângulo (coordenadas da tela). | | `void tb_draw_clear_clip (TinyBlocks_RenderableBlock* rb)` | Tira o recorte. | | `void tb_draw_text (TinyBlocks_RenderableBlock* rb, float x, float y, const char* text, float font_size, float r, float g, float b, float a)` | Texto com a linha de base em (x, y) e tamanho `font_size` em px. | +| `#define TB_FONT_REGULAR` = `0` | Roboto Regular | +| `#define TB_FONT_MEDIUM` = `1` | Roboto Medium (rotulos, titulos) | +| `#define TB_FONT_ICON` = `2` | Material Symbols Outlined | +| `#define TB_FONT_ICON_FILLED` = `3` | Material Symbols (preenchido) | +| `#define TB_FONT_COUNT` = `4` | | +| `#define TB_POLY_MAX` = `16` | Poligono convexo (ate TB_POLY_MAX pontos; xy = x0,y0,x1,y1,...). Formas inclinadas (hexagono, encaixe) ficam lisas em qualquer escala. | +| `void tb_draw_fill_poly (TinyBlocks_RenderableBlock* rb, const float* xy, int n, float r, float g, float b, float a)` | | +| `int tb_draw_poly_get (const TinyBlocks_DrawCmd* c, float* xy)` | Pontos de um TB_DRAW_FILL_POLY (quem transforma comandos usa os dois) | +| `void tb_draw_poly_set (TinyBlocks_DrawCmd* c, const float* xy, int n)` | | +| `void tb_draw_text_font (TinyBlocks_RenderableBlock* rb, float x, float y, const char* text, float font_size, int font, float r, float g, float b, float a)` | | | `void tb_draw_image (TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, const TinyBlocks_Image* image)` | Desenha a imagem escalada para o retângulo (x,y,w,h). A imagem é ref-counted; o comando apenas guarda um ponteiro não-owning, portanto a imagem precisa continuar viva até o backend renderizar o frame. | | `void tb_draw_merge_offset(TinyBlocks_RenderableBlock* dst, const TinyBlocks_RenderableBlock* src, float dx, float dy)` | Mescla src em dst deslocando todas as coordenadas por (dx, dy). Usado pelo editor para incorporar sub-renderables de blocos com on_draw. | | `float tb_measure_text(const char* text, float font_size)` | Estimativa de largura de texto (independente de fonte real). Precisa ser substituída por medição real pelo backend quando disponível. | @@ -1093,9 +1110,11 @@ OpenGL (clip z em -1..1, y para cima); o Vulkan ajusta por conta propria. | Declaração | Descrição | |---|---| | `#define TB_3D_LIB` = `"tinyblocks-3d"` | TinyBlocks - tb_3d.h Library tinyblocks-3d: uma cena 3D simples feita de blocos (categoria "3D") e o CONTRATO dos renderizadores. A cena tem objetos com nome (cubo, esfera, plano, cilindro), cada um com posicao, rotacao, escala e cor; uma camera; uma luz direcional. O bloco "imagem da cena" desenha tudo numa imagem RGBA, que vai para o palco com "desenhe (imagem da cena ...)". Quem desenha e um Tb3dRenderer. A propria 3d traz um rasterizador em software (sempre disponivel); tinyblocks-vk (Vulkan) e tinyblocks-gl (OpenGL) publicam o deles no lib_userdata, e a 3d procura pelo nome da library no runtime a cada quadro (sem linkar com elas): lib = tb_rt_find_library(rt, "tinyblocks-vk"); const Tb3dRenderer* r = lib ? lib->lib_userdata : NULL; if (r && r->version == TB_3D_RENDERER_VERSION && r->available()) ... A ordem automatica e Vulkan, OpenGL, software ("use o renderizador ..." escolhe um). As matrizes sao 4x4 em colunas (column-major) na convencao do OpenGL (clip z em -1..1, y para cima); o Vulkan ajusta por conta propria. | -| `#define TB_3D_RENDERER_VERSION` = `3` | Versão do contrato Tb3dRenderer (quem publica confere). | -| tipo `struct Tb3dMesh` | Malha: triangulos com posicao e normal (6 floats por vertice). As malhas da cena sao fixas (cubo, esfera, plano e cilindro de tamanho 1): o renderizador pode guarda-las na GPU pelo id. | -| `#define TB_3D_MAX_BINARIES` = `4` | Shader compilado: o valor que o repórter "compile o shader [pilha]" devolve (um bloco-handle; guarde numa variável) e que "use o shader" põe num objeto. A 3d compila os blocos para o corpo de uma funcao GLSL (330 e 450) e pede a cada renderizador disponivel o BINARIO dele (Tb3dRenderer.compile); o formato do binario so o renderizador conhece. vec3 tb_shade(vec3 P, vec3 N, vec3 base, float light, float time) P = ponto no mundo, N = normal (normalizada), base = cor do objeto, light = ambiente + (1 - ambiente) * max(N . luz, 0), time = segundos; devolve a cor do pixel (0..1). id e unico por compilacao (o renderizador guarda o programa da placa por ele) e vale enquanto alguem usar o shader. | +| `#define TB_3D_RENDERER_VERSION` = `5` | Versão do contrato Tb3dRenderer (quem publica confere). | +| tipo `struct Tb3dMesh` | Malha: triangulos com posicao, normal e uv (8 floats por vertice). Alem das malhas fixas (cubo, esfera, plano e cilindro de tamanho 1), o usuario monta malhas personalizadas com os blocos "crie a malha", "adicione o vertice/a normal/a texcoord" e "finalize a malha". O renderizador guarda a malha na GPU pelo id; quando o version muda, ele sobe de novo. | +| `#define TB_3D_STAGE_FRAGMENT` = `0` | Shader compilado: o valor que o repórter "compile o shader [pilha]" devolve (um bloco-handle; guarde numa variável) e que "use o shader" põe num objeto. A pilha é de VÉRTICE ou de FRAGMENTO, e o "compile o shader" descobre sozinho pelo que a pilha usa: vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) vec3 tb_vert (vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) No fragmento (estágio 0) P/N são o ponto e a normal no mundo e o shader devolve a COR do pixel (0..1); no vértice (estágio 1) P/N são a posição e a normal no espaço do objeto e o shader devolve a POSIÇÃO do vértice (ainda no espaço do objeto: a câmera e o mova/gire aplicam por cima). A 3d compila os blocos para o corpo da função GLSL (330 e 450) e pede a cada renderizador disponível o BINÁRIO dele (Tb3dRenderer.compile). light = ambiente + (1 - ambiente) * max(N . luz, 0); time = segundos. id e unico por compilacao (o renderizador guarda o programa da placa por ele) e vale enquanto alguem usar o shader. | +| `#define TB_3D_STAGE_VERTEX` = `1` | | +| `#define TB_3D_MAX_BINARIES` = `4` | Quantos binários (renderizadores) um shader compilado guarda. | | tipo `struct Tb3dBinary` | Binário de um shader para um renderizador (nome dele, dados com malloc, tamanho); o formato só o renderizador conhece. | | tipo `struct Tb3dShader` | Shader compilado (o valor de "compile o shader"): id único, a função GLSL tb_shade e os binários de cada renderizador. | | tipo `struct Tb3dDraw` | Um objeto a desenhar | @@ -1125,9 +1144,11 @@ compilador de shaders (d3_shader.c) e quem o usa (tb_3d.c). | tipo `struct D3Program` | TinyBlocks - d3_internal.h Partes internas da tinyblocks-3d compartilhadas entre os fontes: o compilador de shaders (d3_shader.c) e quem o usa (tb_3d.c). o shader compilado (opaco) | | `D3Program* d3_shader_compile(const TinyBlocks_JsonValue* stack, char* err, size_t cap)` | Compila a pilha (o codigo de um encaixe TB_SLOT_STACK, em JSON). NULL em erro, com a mensagem em err. | | `void d3_shader_free(D3Program* p)` | Libera o shader compilado. | -| `const char* d3_shader_glsl(const D3Program* p)` | a funcao tb_shade | -| tipo `struct D3Pixel` | Entradas de um pixel e a cor que sai (o interpretador do software) | +| `const char* d3_shader_glsl(const D3Program* p)` | tb_shade ou tb_vert | +| `int d3_shader_stage(const D3Program* p)` | D3_STAGE_* | +| tipo `struct D3Pixel` | Entradas de um pixel/vertice e a cor que sai (interpretador do software). No fragmento P/N sao o ponto e a normal no mundo; no vertice, P e a posicao local (a que o shader de vertice devolve) e N a normal do objeto. | | `void d3_shader_run(const D3Program* p, const D3Pixel* in, float out[3])` | Interpreta o shader para um pixel (renderizador em software). | +| `void d3_shader_run_vertex(const D3Program* p, const D3Pixel* in, float out[3])` | | | `bool d3_color_of(const char* name, float out[4])` | Cores por nome (vermelho, azul, dourado...) ou #rrggbb | ## libraries/tinyblocks-a11y/include/tb_a11y.h @@ -1219,6 +1240,7 @@ nome + ordem entre irmaos iguais), entao foco e selecao podem ser seguidos. | `void tb_a11y_set_name (TinyBlocks_A11yTree* tree, int node, const char* name)` | Troca o nome do nó. | | `void tb_a11y_set_key (TinyBlocks_A11yTree* tree, int node, const char* key)` | Chave estavel para o id quando o nome muda com o conteudo (ex.: um bloco "repita (10) vezes" usa o tipo como chave). Chame antes dos filhos. | | `void tb_a11y_set_point (TinyBlocks_A11yTree* tree, int node, float x, float y)` | Ponto onde as acoes agem (o centro pode cair num filho) | +| `void tb_a11y_scale_from (TinyBlocks_A11yTree* tree, int first, float ox, float oy, float s)` | Escala os nos a partir de `first` (ate o ultimo criado) em torno de (ox, oy): conteudo desenhado com zoom (ex.: a area de scripts) | | `void tb_a11y_announce(TinyBlocks_A11yTree* tree, const char* text)` | Aviso para o narrador ler (mensagens de status, erros) | ### Consulta @@ -1609,6 +1631,8 @@ Uso: | `void tb_editor_preload(const char* path)` | Enfileira um .so para ser carregado automaticamente ao abrir o editor | | tipo `struct TinyBlocks_A11yTree` | Interface de acessibilidade (tb_a11y.h, da tinyblocks-a11y): a arvore acessivel do ultimo quadro desenhado do bloco "Editor.Scene". Serve ao narrador (tb_a11y_set_bridge) e aos testes (tb_a11y_find + do_action). NULL se a acessibilidade estiver desligada (TINYBLOCKS_A11Y=0). | | `TinyBlocks_A11yTree* tb_editor_accessible(TinyBlocks_Block* scene)` | A árvore acessível do último quadro desenhado pela cena (NULL se desligada). | +| `void tb_editor_qr_feed(TinyBlocks_Block* scene, const char* text)` | Para testes: entrega ao leitor de QR aberto um texto como se a camera o tivesse lido ("Receber blocos") | +| `void tb_editor_qr_show_part(TinyBlocks_Block* scene, int i)` | Para testes: o painel "Compartilhar" mostra a parte i (0..n-1) em vez do loop de 1 s; -1 volta ao loop | | `struct TbMcpServer* tb_editor_mcp_server(TinyBlocks_Block* scene)` | O servidor MCP do editor dessa cena. | ## libraries/tinyblocks-editor/include/tb_editor_internal.h @@ -1639,6 +1663,7 @@ vem juntas com o editor e podem compartilhar este cabecalho. | `#define FLY_BTN_W` = `150` | Geometria do layout do editor (px). | | `#define PALETTE_W` = `(CAT_W + FLY_W)` | largura padrao da paleta | | `#define STAGE_W` = `360` | largura padrao da coluna do palco | +| `#define STAGE_TOP` = `(STAGE_BAR_H + 4)` | onde a vista do palco comeca | | `#define WIN_W` = `(ed->win_w)` | Geometria do layout do editor (px). | | `#define AREA(v)` = `(ed->area[(v)])` | 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 PAL_X` = `(AREA(V_PALETTE).x)` | Geometria do layout do editor (px). | @@ -1654,7 +1679,7 @@ vem juntas com o editor e podem compartilhar este cabecalho. | `#define TAB_W_MIN` = `84` | Largura mínima de uma aba (abaixo disso a barra rola). | | `#define TAB_W` = `(tab_width(ed))` | Geometria do layout do editor (px). | | `#define PLUS_W` = `28` | Geometria do layout do editor (px). | -| `#define PLUS_MENU_W` = `208` | Menu do botao "+" (nova aba) | +| `#define PLUS_MENU_W` = `260` | Menu do botao "+" (nova aba) | | `#define PLUS_MENU_N` = `4` | Itens do menu "+" (nova aba). | | `#define CODE_FS` = `13` | Editor de codigo (aba de codigo) | | `#define CODE_GUTTER_W` = `46` | Geometria do layout do editor (px). | @@ -1666,9 +1691,9 @@ vem juntas com o editor e podem compartilhar este cabecalho. | tipo `struct ImgLayer` | Camada do documento de imagem (rasterizada; SVG entra como vetor) | | tipo `struct ImgSel` | Selecao da ferramenta "selecionar" (mover/redimensionar pixels) | | tipo `struct MenuBtn` | Botão da barra de menu (o que não cabe vai para o menu de três traços). | -| `#define MENU_BTN_Y` = `7` | Geometria do layout do editor (px). | +| `#define MENU_BTN_Y` = `((MENU_H - MENU_BTN_H) / 2)` | Geometria do layout do editor (px). | | `#define MENU_MORE_W` = `40` | Geometria do layout do editor (px). | -| `#define COMPACT_W` = `1000` | Modo compacto (janela estreita / celular): uma area de cada vez. Scripts em tela cheia com a paleta em gaveta, ou palco sobre a saida. | +| `#define COMPACT_W` = `1000` | abaixo disso (janela estreita) uma area de cada vez | | `#define LAY_NARROW_W` = `1100` | abaixo disso os lados fixos (paleta, palco) ficam <= 40% | ### Geometria dos blocos @@ -1745,10 +1770,13 @@ vem juntas com o editor e podem compartilhar este cabecalho. | `#define REL_ARG0` = `4` | REL_ARG0 + i: campo de entrada i | | `#define MAX_MOUTHS` = `3` | bocas de um bloco C (tente/se der erro/finalmente) | | tipo `struct Part` | Pedaço do rótulo medido: texto ou campo, posição e largura. | +| tipo `struct ScrollAnim` | Rolagem animada: de `from` a `to` a partir de t0 (curva standard do M3) | +| `#define GHOST_MAX` = `8` | Bloco apagado saindo de cena: os comandos de desenho dele (na tela) | +| tipo `struct Ghost` | | | tipo `struct EdBlock` | Bloco no editor: tipo, posição, vínculos por índice, textos dos campos, layout do quadro e caches do executor. | | tipo `struct CodeTok` | Um trecho colorido do editor de codigo (vindo do tinyblocks-syntax). | | tipo `struct Tab` | Aba: pool de blocos, pilhas, rolagem, tipo (blocos, código, imagem) e o estado de cada tipo. | -| tipo `enum ParamKind` | Parte do protótipo: número/texto, booleano ou rótulo. | +| tipo `enum ParamKind` | PARAM_NAME marca onde o nome do bloco aparece; sem ela, o nome vai na frente | | tipo `struct UserParam` | Parte do protótipo (kind + nome). | | tipo `struct UserBlockDef` | Definição de um bloco do usuário: nome, entradas, saídas, partes, cópia do corpo, tipo registrado, aba e cor. | | tipo `struct CallFrame` | Chamada em andamento de um bloco do usuário: definição, entradas e saídas. | @@ -1780,8 +1808,12 @@ vem juntas com o editor e podem compartilhar este cabecalho. | `#define CT` = `(ed->tabs[ed->cur_tab])` | A aba atual (`ed->tabs[ed->cur_tab]`). | | `void bubble_clear(Ed* ed)` | Fecha o balão de resultado de um repórter. | | `void palette_rebuild(Ed* ed)` | Refaz as categorias e o flyout (libraries novas, variáveis novas). | +| `void ghost_capture(Ed* ed, Tab* T, int bi, bool chain, float wsx, float wsy, bool clip)` | Bloco (ou a pilha a partir dele) saindo de cena: fantasma animado | | `void utf8_pop(char* s)` | Apaga a última letra UTF-8 do texto. | | `void append_text(char* dst, size_t cap, const char* add)` | Acrescenta texto respeitando a capacidade. | +| `bool te_key(Ed* ed, char* buf, size_t cap, int sc, bool multi)` | Campo de texto em edicao (cursor, selecao, Ctrl+A/C/X/V): as teclas e o texto vao para te_key/te_insert e quem desenha chama te_draw depois do texto (x = inicio do texto, cy = centro da 1a linha, lh = altura da linha) | +| `void te_insert(Ed* ed, char* buf, size_t cap, const char* s, bool multi)` | | +| `void te_draw(Ed* ed, TinyBlocks_RenderableBlock* rb, char* buf, size_t cap, bool multi, float x, float cy, float lh, float fs, Col caret)` | | | `void dlg_open(Ed* ed, int def_idx)` | Abre o diálogo "Criar um Bloco" (`def_idx` -1 = novo) ou "Editar Bloco". | | `void dlg_render(Ed* ed, TinyBlocks_RenderableBlock* rb)` | Desenha o diálogo de bloco. | | `bool dlg_click(Ed* ed, float mx, float my)` | Clique no diálogo de bloco. | @@ -1893,6 +1925,201 @@ vem juntas com o editor e podem compartilhar este cabecalho. | `void settings_scroll_by(Ed* ed, float dy)` | Rola as configurações. | | `void settings_render(Ed* ed, TinyBlocks_RenderableBlock* rb)` | Desenha as configurações. | +## libraries/tinyblocks-editor/include/tb_editor_m3.h + +```text +Linguagem visual do editor: Material 3 (m3.material.io) com as cores que o +editor ja usava. Papeis de cor do M3 apontam para a paleta do TinyBlocks; +formas, tipografia (Roboto), icones (Material Symbols), camadas de estado +e elevacao seguem o M3. Densidade -2 do M3 (desktop): alturas 4 px menores. +Incluido por tb_editor_internal.h (usa Col, C(), COLA() e rb_*). +``` + +### Papeis de cor (M3) -> paleta do editor + +| Declaração | Descrição | +|---|---| +| `#define M3_PRIMARY` = `COL_MENU` | #4C97FF | +| `#define M3_ON_PRIMARY` = `COL_WHITE` | | +| `#define M3_PRIMARY_DARK` = `COL_MENU_DARK` | | +| `#define M3_PRIMARY_CONTAINER` = `COL_HOVER` | #D6E4F8 | +| `#define M3_SECONDARY_CONTAINER` = `COL_TAB_OFF` | #D9E3F2 | +| `#define M3_SURFACE` = `COL_PANEL` | branco | +| `#define M3_SURFACE_LOW` = `COL_FLY` | #F9F9F9 | +| `#define M3_SURFACE_CONTAINER` = `COL_UI_BG` | #E5F0FF | +| `#define M3_ON_SURFACE` = `COL_TEXT` | #575E75 | +| `#define M3_ON_SURFACE_VAR` = `COL_TEXT_DIM` | | +| `#define M3_OUTLINE` = `COL_TEXT_DIM` | | +| `#define M3_OUTLINE_VAR` = `COL_BORDER` | | +| `#define M3_INVERSE_SURFACE` = `COL_TIP_BG` | | +| `#define M3_INVERSE_ON_SURFACE` = `COL_CODE_TEXT` | | +| `#define M3_INVERSE_PRIMARY` = `COL_TIP_LINK` | | +| `#define M3_ERROR` = `COL_STOP` | | + +### Formas (raio dos cantos) + +| Declaração | Descrição | +|---|---| +| `#define M3_SHAPE_XS` = `4.f` | | +| `#define M3_SHAPE_S` = `8.f` | | +| `#define M3_SHAPE_M` = `12.f` | | +| `#define M3_SHAPE_L` = `16.f` | | +| `#define M3_SHAPE_XL` = `28.f` | | + +### Tipografia (tamanho em px; titulos e rotulos em Roboto Medium) + +| Declaração | Descrição | +|---|---| +| `#define M3_HEADLINE_S` = `24.f` | | +| `#define M3_TITLE_L` = `22.f` | | +| `#define M3_TITLE_M` = `16.f` | | +| `#define M3_TITLE_S` = `14.f` | | +| `#define M3_LABEL_L` = `14.f` | | +| `#define M3_LABEL_M` = `12.f` | | +| `#define M3_LABEL_S` = `11.f` | | +| `#define M3_BODY_L` = `16.f` | | +| `#define M3_BODY_M` = `14.f` | | +| `#define M3_BODY_S` = `12.f` | | + +### Camadas de estado (opacidade da cor do conteudo) + +| Declaração | Descrição | +|---|---| +| `#define M3_HOVER` = `0.08f` | | +| `#define M3_PRESSED` = `0.10f` | | +| `#define M3_DRAGGED` = `0.16f` | | + +### Componentes: alturas (densidade -2) + +| Declaração | Descrição | +|---|---| +| `#define M3_ICON_BTN` = `36.f` | icon button: alvo (40 no padrao) | +| `#define M3_ICON` = `20.f` | icone dentro de botoes | +| `#define M3_MENU_ITEM` = `40.f` | item de menu (48 no padrao) | + +### Icones (Material Symbols, codepoints) + +| Declaração | Descrição | +|---|---| +| `#define MI_ADD` = `0xe145` | | +| `#define MI_ARROW_BACK` = `0xe5c4` | | +| `#define MI_ARROW_FORWARD` = `0xe5c8` | | +| `#define MI_ARROW_UPWARD` = `0xe5d8` | | +| `#define MI_ARROW_RIGHT` = `0xe5df` | | +| `#define MI_BRUSH` = `0xe3ae` | | +| `#define MI_CANCEL` = `0xe888` | | +| `#define MI_CHECK` = `0xe668` | | +| `#define MI_CHECK_CIRCLE` = `0xf0be` | | +| `#define MI_CHEVRON_LEFT` = `0xe5cb` | | +| `#define MI_CHEVRON_RIGHT` = `0xe5cc` | | +| `#define MI_CIRCLE` = `0xef4a` | | +| `#define MI_CLOSE` = `0xe5cd` | | +| `#define MI_CODE` = `0xe86f` | | +| `#define MI_COLORIZE` = `0xe3b8` | | +| `#define MI_CONTENT_COPY` = `0xe14d` | | +| `#define MI_CONTENT_CUT` = `0xe14e` | | +| `#define MI_CONTENT_PASTE` = `0xe14f` | | +| `#define MI_CREATE_FOLDER` = `0xe2cc` | | +| `#define MI_DELETE` = `0xe92e` | | +| `#define MI_DESCRIPTION` = `0xe873` | | +| `#define MI_DRAFT` = `0xe66d` | | +| `#define MI_DRAG_INDICATOR` = `0xe945` | | +| `#define MI_EDIT` = `0xf097` | | +| `#define MI_ERROR` = `0xf8b6` | | +| `#define MI_EXPAND_MORE` = `0xe5cf` | | +| `#define MI_EXTENSION` = `0xe87b` | | +| `#define MI_FILL` = `0xe23a` | | +| `#define MI_FLAG` = `0xf0c6` | | +| `#define MI_FOLDER` = `0xe2c7` | | +| `#define MI_GRID_VIEW` = `0xe9b0` | | +| `#define MI_DATA_OBJECT` = `0xead3` | | +| `#define MI_TABLE` = `0xf191` | | +| `#define MI_ACCOUNT_TREE` = `0xe97a` | | +| `#define MI_SELECT_ALL` = `0xe162` | | +| `#define MI_ADD_BOX` = `0xe146` | | +| `#define MI_FOLDER_OPEN` = `0xe2c8` | | +| `#define MI_HOME` = `0xe9b2` | | +| `#define MI_IMAGE` = `0xe3f4` | | +| `#define MI_INFO` = `0xe88e` | | +| `#define MI_ERASER` = `0xe6d0` | | +| `#define MI_IOS_SHARE` = `0xe6b8` | | +| `#define MI_LIBRARY_ADD` = `0xe03c` | | +| `#define MI_LIBRARY_BOOKS` = `0xe02f` | | +| `#define MI_MENU` = `0xe5d2` | | +| `#define MI_MORE_VERT` = `0xe5d4` | | +| `#define MI_OPEN_IN_NEW` = `0xe89e` | | +| `#define MI_CLOSE_FULLSCR` = `0xf1cf` | | +| `#define MI_PALETTE` = `0xe40a` | | +| `#define MI_PAN_TOOL` = `0xe925` | | +| `#define MI_PLAY_ARROW` = `0xe037` | | +| `#define MI_RECTANGLE` = `0xeb54` | | +| `#define MI_REDO` = `0xe15a` | | +| `#define MI_REFRESH` = `0xe5d5` | | +| `#define MI_SAVE` = `0xe161` | | +| `#define MI_SEARCH` = `0xef7a` | | +| `#define MI_SHARE` = `0xe80d` | | +| `#define MI_QR_CODE` = `0xe00a` | | +| `#define MI_QR_SCANNER` = `0xf206` | | +| `#define MI_SOURCE` = `0xf1c8` | | +| `#define MI_SELECT` = `0xf74d` | | +| `#define MI_SETTINGS` = `0xe8b8` | | +| `#define MI_STOP` = `0xe047` | | +| `#define MI_STOP_CIRCLE` = `0xef71` | | +| `#define MI_SWAP_HORIZ` = `0xe8d4` | | +| `#define MI_TERMINAL` = `0xeb8e` | | +| `#define MI_TEXT_FIELDS` = `0xe262` | | +| `#define MI_UNDO` = `0xe166` | | +| `#define MI_UPLOAD_FILE` = `0xe9fc` | | +| `#define MI_WARNING` = `0xf083` | | +| `#define MI_WIDGETS` = `0xe1bd` | | +| `#define MI_ZOOM_IN` = `0xe8ff` | | +| `#define MI_ZOOM_OUT` = `0xe900` | | + +### Movimento: curvas do M3 (cubic-bezier, como no CSS) + +| Declaração | Descrição | +|---|---| +| `static inline float m3_bezier(float x1, float y1, float x2, float y2, float t) { if (t <= 0.f) return 0.f` | | +| `#define M3_EASE_STANDARD(t)` = `m3_bezier(0.2f, 0.f, 0.f, 1.f, (t))` | | +| `#define M3_EASE_EMPH_DECEL(t)` = `m3_bezier(0.05f, 0.7f, 0.1f, 1.f, (t))` | entrar | +| `#define M3_EASE_EMPH_ACCEL(t)` = `m3_bezier(0.3f, 0.f, 0.8f, 0.15f, (t))` | sair | +| `#define M3_DUR_SCROLL` = `260u` | ms | +| `#define M3_DUR_SLIDE` = `280u` | | +| `#define M3_DUR_APPEAR` = `380u` | | +| `#define M3_DUR_EXIT` = `220u` | | + +### Utilitarios + +| Declaração | Descrição | +|---|---| +| `static inline Col m3_alpha(Col c, float a) { c.a = a; return c; }` | | +| `static inline Col m3_mix(Col bg, Col c, float a) { Col r = { bg.r + (c.r - bg.r) * a, bg.g + (c.g - bg.g) * a, bg.b + (c.b - bg.b) * a, 1.f }` | c sobre o fundo bg com opacidade a (cor solida resultante) | +| `static inline float m3_tw_m(const char* s, float fs) { return tw(s, fs) * 1.04f; }` | Largura de um rotulo em Roboto Medium (a medicao do backend e da Regular) | +| `static inline void m3_state(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, float rad, Col on, bool hover, bool pressed) { float a = pressed ? M3_PRESSED : hover ? M3_HOVER : 0.f` | Camada de estado: a cor do conteudo, translucida, sobre o componente | + +### Botoes (pilula): filled, tonal, outlined, text + +| Declaração | Descrição | +|---|---| +| `static inline float m3_button_w(const char* label, unsigned icon) { return m3_tw_m(label, M3_LABEL_L) + (icon ? 16.f + 18.f + 8.f + 24.f : 48.f)` | | +| `static inline void m3_button(TinyBlocks_RenderableBlock* rb, int kind, float x, float y, float w, float h, const char* label, unsigned icon, Col accent, bool hover, bool pressed) { float r = h * 0.5f` | accent = cor do papel "primary" deste botao (a do editor ou a do dialogo) | +| `static inline void m3_icon_button(TinyBlocks_RenderableBlock* rb, float cx, float cy, unsigned icon, Col c, bool hover, bool selected) { float s = M3_ICON_BTN` | Icon button (padrao): so o icone; o circulo aparece no hover/pressionado. selected = toggle ligado (container tonal) | + +### Superficies + +| Declaração | Descrição | +|---|---| +| `static inline void m3_menu_surface(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h) { rb_shadow(rb, x, y, w, h, M3_SHAPE_XS, 2)` | Menu: canto XS, elevacao 2 | +| `static inline void m3_menu_item(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, const char* label, unsigned icon, bool hover, Col fg) { m3_state(rb, x, y, w, h, 0, M3_ON_SURFACE, hover, false)` | Item de menu: icone opcional a esquerda, rotulo Label Large | +| `static inline void m3_dialog_surface(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h) { rb_shadow(rb, x, y, w, h, M3_SHAPE_XL, 3)` | Dialogo: canto XL, elevacao 3 | +| `static inline void m3_scrim(TinyBlocks_RenderableBlock* rb, float w, float h) { rb_fill_rect(rb, 0, 0, w, h, COLA(0, 0, 0, 82))` | Scrim atras de dialogos modais | +| `static inline void m3_field(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, bool focused, Col accent) { if (focused) { rb_fill_rrect(rb, x, y, w, h, M3_SHAPE_XS, accent)` | Campo de texto "outlined": canto XS, contorno 1 px (2 px na cor primaria quando em foco) | +| `static inline void m3_search_bar(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, bool focused, Col accent) { rb_fill_rrect(rb, x, y, w, h, h * 0.5f, M3_SURFACE_CONTAINER)` | Barra de busca: pilula, icone de lupa a esquerda | +| `static inline void m3_tab_indicator(TinyBlocks_RenderableBlock* rb, float x, float y_bottom, float w, Col c) { rb_fill_rrect(rb, x, y_bottom - 3.f, w, 6.f, 3.f, c)` | Indicador da aba ativa (aba primaria): 3 px com cantos de cima redondos | +| `static inline void m3_chip(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h, const char* label, unsigned icon, bool selected, bool hover) { if (selected) rb_fill_rrect(rb, x, y, w, h, M3_SHAPE_S, M3_SECONDARY_CONTAINER)` | Chip (assist/filter): canto S, 32 px | +| `static inline void m3_snackbar_surface(TinyBlocks_RenderableBlock* rb, float x, float y, float w, float h) { rb_shadow(rb, x, y, w, h, M3_SHAPE_XS, 3)` | Snackbar: superficie inversa, canto XS, elevacao 3 | +| `static inline void m3_switch(TinyBlocks_RenderableBlock* rb, float x, float y, bool on, Col accent) { const float w = 52.f, h = 32.f` | Interruptor (switch) do M3: trilho 52x32, alca 16 (24 ligado) | + ## libraries/tinyblocks-editor/include/tb_editor_modules.h **Privado**: compile com `-DTB_EDITOR_PRIVATE_API`. @@ -2106,7 +2333,8 @@ Uso típico (host): | `#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` | Saídas do bloco `Graphics.Input`. | +| `#define GFX_IN_ZOOM` = `28 /* real: pinça do touchpad neste frame (fator; *` | | +| `#define GFX_IN_COUNT` = `29` | Saídas do bloco `Graphics.Input`. | | `#define GFX_MAX_TOUCHES` = `10` | Toques guardados por quadro. | | tipo `struct TinyBlocks_GfxInput` | Estado de entrada de uma janela em um frame (preenchido pelo backend) | @@ -2424,6 +2652,8 @@ endereco fica aberta entre as chamadas; tb_mcp_deinit fecha todas. | `char* tb_mcp_call_tool(const char* url, const char* tool, const char* args_json, bool* ok)` | conteudo em texto | | `const TinyBlocks_LibraryDescriptor* tb_mcp_get_library(void)` | Library de blocos (categoria "MCP") | +## libraries/tinyblocks-mcp/src/tb_mcp_py.h + ## libraries/tinyblocks-number/include/tb_number.h ```text @@ -2598,6 +2828,115 @@ como TinyBlocks_Image (TB_VALUE_IMAGE). Independente do editor. | `char* tb_python_run_with_vars(const char* code, const char* const* names, const double* vals, int n)` | Executa código passando variáveis como locais (nome=valor float). Equivalente a tb_python_run mas com namespace preenchido. | | `char* tb_python_exec_main(const char* code)` | Executa código no namespace __main__ (definições persistem entre chamadas). Retorna stdout+stderr capturado (caller frees). | +## libraries/tinyblocks-qr/include/tb_camera.h + +```text +Camera do aparelho, em tons de cinza (o que um leitor de QR precisa). +Linux: V4L2 (/dev/video0, YUYV: o canal Y ja e o cinza). Android: Camera2 +do NDK (camera2ndk + AImageReader, sem Java), com a permissao de camera +pedida na hora. Sem camera (ou no Windows): tb_camera_open falha e +tb_camera_error diz por que. +``` + +## libraries/tinyblocks-qr/include/tb_qr.h + +```text +QR code: gerar (qrcodegen, de Project Nayuki, MIT) e ler de uma imagem em +tons de cinza (quirc, de Daniel Beer, ISC). Mais a camera do aparelho para +o leitor (tb_camera.h). Usada pelo editor para mandar blocos de uma +instancia para outra por QR. +``` + +## libraries/tinyblocks-qr/src/qrcodegen.h + +```text +QR Code generator library (C) +Copyright (c) Project Nayuki. (MIT License) +https://www.nayuki.io/page/qr-code-generator-library +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: +- The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. +- The Software is provided "as is", without warranty of any kind, express or + implied, including but not limited to the warranties of merchantability, + fitness for a particular purpose and noninfringement. In no event shall the + authors or copyright holders be liable for any claim, damages or other + liability, whether in an action of contract, tort or otherwise, arising from, + out of or in connection with the Software or the use or other dealings in the + Software. +``` + +## libraries/tinyblocks-qr/src/quirc.h + +```text +quirc -- QR-code recognition library +Copyright (C) 2010-2012 Daniel Beer +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +``` + +| Declaração | Descrição | +|---|---| +| `#define QUIRC_H_` | quirc -- QR-code recognition library Copyright (C) 2010-2012 Daniel Beer Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | + +## libraries/tinyblocks-qr/src/quirc_internal.h + +```text +quirc -- QR-code recognition library +Copyright (C) 2010-2012 Daniel Beer +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +``` + +| Declaração | Descrição | +|---|---| +| `#define QUIRC_INTERNAL_H_` | quirc -- QR-code recognition library Copyright (C) 2010-2012 Daniel Beer Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | +| `#define QUIRC_ASSERT(a)` = `assert(a)` | | +| `#define QUIRC_PIXEL_WHITE` = `0` | | +| `#define QUIRC_PIXEL_BLACK` = `1` | | +| `#define QUIRC_PIXEL_REGION` = `2` | | +| `#define QUIRC_MAX_REGIONS` = `254` | | +| `#define QUIRC_MAX_CAPSTONES` = `32` | | +| `#define QUIRC_MAX_GRIDS` = `(QUIRC_MAX_CAPSTONES * 2)` | | +| `#define QUIRC_PERSPECTIVE_PARAMS` = `8` | | +| `#define QUIRC_PIXEL_ALIAS_IMAGE` = `1` | | +| tipo `typedef uint8_t quirc_pixel_t` | | +| `#define QUIRC_PIXEL_ALIAS_IMAGE` = `0` | | +| tipo `typedef uint16_t quirc_pixel_t` | | +| tipo `typedef QUIRC_FLOAT_TYPE quirc_float_t` | Quirc uses double precision floating point internally by default. On platforms with a single precision FPU but no double precision FPU, this can be changed to float by defining QUIRC_FLOAT_TYPE. When setting QUIRC_FLOAT_TYPE to 'float', consider also defining QUIRC_USE_TGMATH. This will use the type-generic math functions (tgmath.h, C99 or later) instead of the normal ones, which will allow the compiler to use the correct overloaded functions for the type. | +| tipo `typedef double quirc_float_t` | | +| tipo `struct quirc_region` | | +| tipo `struct quirc_capstone` | | +| tipo `struct quirc_grid` | | +| tipo `struct quirc_flood_fill_vars` | | +| tipo `struct quirc` | | +| `static inline size_t quirc_image_size(int w, int h) { return (size_t)w * (size_t)h` | | +| `static inline size_t quirc_pixel_count(const struct quirc *q) { return quirc_image_size(q->w, q->h)` | | +| `#define QUIRC_MAX_VERSION` = `40` | QR-code version information database | +| `#define QUIRC_MAX_ALIGNMENT` = `7` | | +| tipo `struct quirc_rs_params` | | +| tipo `struct quirc_version_info` | | + ## libraries/tinyblocks-regex/include/tb_regex.h ```text diff --git a/examples/jogo-3d/README.md b/examples/jogo-3d/README.md index 28d82a6..16f9571 100644 --- a/examples/jogo-3d/README.md +++ b/examples/jogo-3d/README.md @@ -59,6 +59,26 @@ Na notação do fórum, a pilha de um encaixe vem nas linhas de baixo, indentada e fechada com `end`, mesmo quando o bloco com o encaixe está dentro de outro (como o "compile o shader" dentro do "mude"). +## Shader de vértice (`onda.sb`) + +A mesma pilha pode ser um shader de **vértice** em vez de fragmento: use +`mude a posição do vértice para x ( ) y ( ) z ( )` no lugar de +`cor do pixel = ( )`. O `compile o shader` descobre o estágio sozinho (pelo +que a pilha usa) e o `use o shader` põe no objeto. + +``` +mude [onda v] para (compile o shader) + mude a posição do vértice para x ((x do vértice) * (1 + (0.25 * (seno de ((tempo) * (180)))))) y (...) z (...) +end +use o shader (onda) no objeto [bola] +``` + +A posição sai no espaço do objeto: a câmera e o `mova`/`gire` do objeto +aplicam por cima. Entradas úteis: `x/y/z do vértice` (a posição local), +`x/y/z da normal`, `u/v do uv` e `tempo`. Cada objeto usa um shader só (ou +de vértice, ou de fragmento); `GLSL do shader (onda)` mostra o `tb_vert` +gerado. + ## Malha personalizada e UV (`malha.sb`) Além das formas fixas (cubo, esfera, plano, cilindro), dá para montar uma diff --git a/examples/jogo-3d/onda.sb b/examples/jogo-3d/onda.sb new file mode 100644 index 0000000..2cd2a43 --- /dev/null +++ b/examples/jogo-3d/onda.sb @@ -0,0 +1,13 @@ +when flag clicked +nova cena 3D +crie esfera [bola] em x (0) y (0.5) z (0) +mude a cor de [bola] para [azul] +mude [onda v] para (compile o shader) + mude a posição do vértice para x ((x do vértice) * ((1) + ((0.25) * (seno de ((tempo) * (180)))))) y ((y do vértice) * ((1) + ((0.25) * (seno de ((tempo) * (180)))))) z ((z do vértice) * ((1) + ((0.25) * (seno de ((tempo) * (180)))))) +end +use o shader (onda) no objeto [bola] +câmera em x (0) y (3) z (6) olhando para x (0) y (0.5) z (0) +sempre + apague tudo + desenhe (imagem da cena de (480) por (360)) em x (0) y (0) escala (1) +end diff --git a/libraries/tinyblocks-3d/include/tb_3d.h b/libraries/tinyblocks-3d/include/tb_3d.h index 4dddb9d..72e5359 100644 --- a/libraries/tinyblocks-3d/include/tb_3d.h +++ b/libraries/tinyblocks-3d/include/tb_3d.h @@ -29,7 +29,7 @@ #include #define TB_3D_LIB "tinyblocks-3d" -#define TB_3D_RENDERER_VERSION 4 +#define TB_3D_RENDERER_VERSION 5 /* Malha: triangulos com posicao, normal e uv (8 floats por vertice). Alem das malhas fixas (cubo, esfera, plano e cilindro de tamanho 1), o usuario @@ -47,18 +47,24 @@ typedef struct Tb3dMesh { /* Shader compilado: o valor que o repórter "compile o shader [pilha]" devolve (um bloco-handle; guarde numa variável) e que "use o shader" põe - num objeto. A 3d compila os blocos para o corpo de uma funcao GLSL (330 - e 450) e pede a cada renderizador disponivel o BINARIO dele - (Tb3dRenderer.compile); o formato do binario so o renderizador conhece. + num objeto. A pilha é de VÉRTICE ou de FRAGMENTO, e o "compile o shader" + descobre sozinho pelo que a pilha usa: - vec3 tb_shade(vec3 P, vec3 N, vec3 base, float light, float time) + vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) + vec3 tb_vert (vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) - P = ponto no mundo, N = normal (normalizada), base = cor do objeto, - light = ambiente + (1 - ambiente) * max(N . luz, 0), time = segundos; - devolve a cor do pixel (0..1). + No fragmento (estágio 0) P/N são o ponto e a normal no mundo e o shader + devolve a COR do pixel (0..1); no vértice (estágio 1) P/N são a posição e + a normal no espaço do objeto e o shader devolve a POSIÇÃO do vértice + (ainda no espaço do objeto: a câmera e o mova/gire aplicam por cima). + A 3d compila os blocos para o corpo da função GLSL (330 e 450) e pede a + cada renderizador disponível o BINÁRIO dele (Tb3dRenderer.compile). + light = ambiente + (1 - ambiente) * max(N . luz, 0); time = segundos. id e unico por compilacao (o renderizador guarda o programa da placa por ele) e vale enquanto alguem usar o shader. */ +#define TB_3D_STAGE_FRAGMENT 0 +#define TB_3D_STAGE_VERTEX 1 #define TB_3D_MAX_BINARIES 4 typedef struct Tb3dBinary { char renderer[16]; /* Tb3dRenderer.name de quem compilou */ @@ -69,6 +75,7 @@ typedef struct Tb3dBinary { typedef struct Tb3dShader { int id; int version; /* sempre 1 (cada compilacao tem outro id) */ + int stage; /* TB_3D_STAGE_FRAGMENT ou _VERTEX */ const char* glsl; Tb3dBinary bin[TB_3D_MAX_BINARIES]; int bin_n; @@ -112,7 +119,7 @@ typedef struct Tb3dRenderer { /* Binario do shader para esta placa, a partir do GLSL (tb_shade). data com malloc (a 3d libera com free). NULL = o renderizador nao guarda binario (compila na hora de desenhar). */ - bool (*compile)(const char* glsl, void** data, size_t* size, char* err, size_t cap); + bool (*compile)(const char* glsl, int stage, void** data, size_t* size, char* err, size_t cap); } Tb3dRenderer; TB_API const TinyBlocks_LibraryDescriptor* tb_3d_get_library(void); diff --git a/libraries/tinyblocks-3d/src/d3_internal.h b/libraries/tinyblocks-3d/src/d3_internal.h index 56b0ca1..57b60ba 100644 --- a/libraries/tinyblocks-3d/src/d3_internal.h +++ b/libraries/tinyblocks-3d/src/d3_internal.h @@ -12,20 +12,28 @@ typedef struct D3Program D3Program; /* o shader compilado (opaco) */ +/* Estagio do shader: o "compile o shader" descobre sozinho (tem + "mude a posicao do vertice" = vertice; "cor do pixel" = fragmento). */ +enum { D3_STAGE_NONE, D3_STAGE_FRAGMENT, D3_STAGE_VERTEX }; + /* Compila a pilha (o codigo de um encaixe TB_SLOT_STACK, em JSON). NULL em erro, com a mensagem em err. */ D3Program* d3_shader_compile(const TinyBlocks_JsonValue* stack, char* err, size_t cap); void d3_shader_free(D3Program* p); -const char* d3_shader_glsl(const D3Program* p); /* a funcao tb_shade */ +const char* d3_shader_glsl(const D3Program* p); /* tb_shade ou tb_vert */ +int d3_shader_stage(const D3Program* p); /* D3_STAGE_* */ -/* Entradas de um pixel e a cor que sai (o interpretador do software) */ +/* Entradas de um pixel/vertice e a cor que sai (interpretador do software). + No fragmento P/N sao o ponto e a normal no mundo; no vertice, P e a + posicao local (a que o shader de vertice devolve) e N a normal do objeto. */ typedef struct { - float P[3], N[3], L[3]; /* ponto no mundo, normal, vertice local */ + float P[3], N[3], L[3]; /* ponto/vertice, normal, vertice local */ float uv[2]; /* coordenada de textura */ float base[3]; float light, time; } D3Pixel; void d3_shader_run(const D3Program* p, const D3Pixel* in, float out[3]); +void d3_shader_run_vertex(const D3Program* p, const D3Pixel* in, float out[3]); /* Cores por nome (vermelho, azul, dourado...) ou #rrggbb */ bool d3_color_of(const char* name, float out[4]); diff --git a/libraries/tinyblocks-3d/src/d3_shader.c b/libraries/tinyblocks-3d/src/d3_shader.c index e254d1f..2d3d9b0 100644 --- a/libraries/tinyblocks-3d/src/d3_shader.c +++ b/libraries/tinyblocks-3d/src/d3_shader.c @@ -5,8 +5,10 @@ * Entrada: o codigo de uma pilha (JSON de um encaixe TB_SLOT_STACK, ver * tb_defs.h). Saida: uma arvore compacta (nos num vetor) com o tipo de * cada expressao (numero, cor ou condicao), de onde saem - * - o GLSL da funcao tb_shade (OpenGL e Vulkan), e + * - o GLSL da funcao tb_shade (fragmento) ou tb_vert (vertice), e * - o interpretador usado pelo renderizador em software. + * O estagio sai sozinho: a pilha que usa "cor do pixel" e de fragmento; a + * que usa "mude a posicao do vertice" e de vertice. * * Valores: numero (F), cor (V, tres canais) e condicao (B). Uma conta entre * cor e numero vale para os tres canais (como no GLSL). No interpretador um @@ -33,7 +35,7 @@ enum { E_CHAN, E_GRAY, /* E_CHAN: canal em k[0] */ E_LT, E_EQ, E_GT, E_AND, E_OR, E_NOT, /* comandos */ - S_PIXEL, S_SET, S_IF, + S_PIXEL, S_VPOS, S_SET, S_IF, }; typedef struct { @@ -49,6 +51,7 @@ struct D3Program { Node* n; int nn, cap; int first; /* primeiro comando */ + int stage; /* D3_STAGE_* */ char local[MAX_LOCALS][32]; int ltype[MAX_LOCALS]; int nl; @@ -313,6 +316,8 @@ static int set_var(C* c, const TinyBlocks_JsonValue* j, bool change) { static int stmt(C* c, const TinyBlocks_JsonValue* j) { const char* t = jtype(j); if (!strcmp(t, "Shader.Pixel")) { + if (c->p->stage == D3_STAGE_VERTEX) { fail(c, "\"cor do pixel\" não vale num shader de vértice"); return -1; } + c->p->stage = D3_STAGE_FRAGMENT; int e = expr_in(c, j, 0); if (e < 0) return -1; if (c->p->n[e].type == TB) { fail(c, "\"cor do pixel =\" recebe uma cor ou um número"); return -1; } @@ -320,6 +325,22 @@ static int stmt(C* c, const TinyBlocks_JsonValue* j) { if (n >= 0) c->p->n[n].a = e; return n; } + if (!strcmp(t, "Shader.Vertex")) { + if (c->p->stage == D3_STAGE_FRAGMENT) { fail(c, "\"mude a posição do vértice\" não vale num shader de fragmento"); return -1; } + c->p->stage = D3_STAGE_VERTEX; + int a = expr_in(c, j, 0), b = expr_in(c, j, 1), d = expr_in(c, j, 2); + if (a < 0 || b < 0 || d < 0) return -1; + if (c->p->n[a].type != TF || c->p->n[b].type != TF || c->p->n[d].type != TF) { + fail(c, "\"mude a posição do vértice\" recebe três números"); + return -1; + } + int e = node(c, E_RGB, TV); + if (e < 0) return -1; + c->p->n[e].a = a; c->p->n[e].b = b; c->p->n[e].c = d; + int n = node(c, S_VPOS, -1); + if (n >= 0) c->p->n[n].a = e; + return n; + } if (!strcmp(t, "Variables.Set")) return set_var(c, j, false); if (!strcmp(t, "Variables.Change")) return set_var(c, j, true); if (!strcmp(t, "Control.If") || !strcmp(t, "Control.IfElse")) { @@ -443,6 +464,7 @@ static void gs(const D3Program* p, Str* o, int i, int depth) { const Node* x = &p->n[i]; put(o, "%*s", depth * 4, ""); if (x->op == S_PIXEL) { put(o, "pix = "); gv(p, o, x->a, true); put(o, ";\n"); } + else if (x->op == S_VPOS) { put(o, "vpos = "); gv(p, o, x->a, true); put(o, ";\n"); } else if (x->op == S_SET) { put(o, "l%d = ", x->var); gx(p, o, x->a); put(o, ";\n"); } else if (x->op == S_IF) { put(o, "if "); gx(p, o, x->a); put(o, " {\n"); @@ -456,12 +478,17 @@ static void gs(const D3Program* p, Str* o, int i, int depth) { static char* emit_glsl(const D3Program* p) { Str o = {0}; - put(&o, "vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) {\n"); - put(&o, " vec3 pix = base * light;\n"); + if (p->stage == D3_STAGE_VERTEX) { + put(&o, "vec3 tb_vert(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) {\n"); + put(&o, " vec3 vpos = P;\n"); + } else { + put(&o, "vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) {\n"); + put(&o, " vec3 pix = base * light;\n"); + } for (int i = 0; i < p->nl; i++) put(&o, p->ltype[i] == TV ? " vec3 l%d = vec3(0.0);\n" : " float l%d = 0.0;\n", i); gs(p, &o, p->first, 1); - put(&o, " return clamp(pix, 0.0, 1.0);\n}\n"); + put(&o, p->stage == D3_STAGE_VERTEX ? " return vpos;\n}\n" : " return clamp(pix, 0.0, 1.0);\n}\n"); return o.s; } @@ -473,7 +500,8 @@ D3Program* d3_shader_compile(const TinyBlocks_JsonValue* stack, char* err, size_ C c = { p, err, cap, false }; if (!stack || tb_json_kind(stack) != TB_JSON_ARRAY) fail(&c, "encaixe uma pilha de blocos de shader"); else p->first = stmts(&c, stack); - if (!c.failed && p->first < 0) fail(&c, "o shader está vazio (use \"cor do pixel = ...\")"); + if (!c.failed && p->stage == D3_STAGE_NONE) + fail(&c, "o shader está vazio (use \"cor do pixel = ...\" ou \"mude a posição do vértice para ...\")"); if (!c.failed) { p->glsl = emit_glsl(p); if (!p->glsl) fail(&c, "sem memória"); @@ -490,9 +518,10 @@ void d3_shader_free(D3Program* p) { } const char* d3_shader_glsl(const D3Program* p) { return p ? p->glsl : ""; } +int d3_shader_stage(const D3Program* p) { return p ? p->stage : D3_STAGE_NONE; } /* == Interpretador (software): cada valor e um float[3] ================ */ -typedef struct { const D3Pixel* in; float pix[3]; float loc[MAX_LOCALS][3]; } Run; +typedef struct { const D3Pixel* in; float pix[3]; float vpos[3]; float loc[MAX_LOCALS][3]; } Run; static float fmod_glsl(float a, float b) { return b == 0 ? 0 : a - b * floorf(a / b); } @@ -558,6 +587,7 @@ static void ex(const D3Program* p, Run* r, int i) { for (; i >= 0; i = p->n[i].next) { const Node* x = &p->n[i]; if (x->op == S_PIXEL) ev(p, r, x->a, r->pix); + else if (x->op == S_VPOS) ev(p, r, x->a, r->vpos); else if (x->op == S_SET) ev(p, r, x->a, r->loc[x->var]); else if (x->op == S_IF) { float c[3]; @@ -575,3 +605,13 @@ void d3_shader_run(const D3Program* p, const D3Pixel* in, float out[3]) { ex(p, &r, p->first); for (int k = 0; k < 3; k++) out[k] = fminf(fmaxf(r.pix[k], 0.f), 1.f); } + +void d3_shader_run_vertex(const D3Program* p, const D3Pixel* in, float out[3]) { + Run r; + r.in = in; + memcpy(r.vpos, in->P, sizeof(r.vpos)); + for (int k = 0; k < 3; k++) r.pix[k] = in->base[k] * in->light; + memset(r.loc, 0, sizeof(float) * 3 * (size_t)(p->nl ? p->nl : 1)); + ex(p, &r, p->first); + memcpy(out, r.vpos, sizeof(r.vpos)); +} diff --git a/libraries/tinyblocks-3d/src/tb_3d.c b/libraries/tinyblocks-3d/src/tb_3d.c index 1ea7228..38fb62b 100644 --- a/libraries/tinyblocks-3d/src/tb_3d.c +++ b/libraries/tinyblocks-3d/src/tb_3d.c @@ -388,6 +388,7 @@ typedef struct { float x, y, z, w, r, g, b, P[3], N[3], L[3], uv[2]; } CV; /* Quem o rasterizador esta desenhando agora (shader do objeto) */ static const D3Program* s_prog; +static const D3Program* s_vprog; /* shader de vertice (ou NULL) */ static const Tb3dFrame* s_frame; static float s_base[3]; @@ -476,7 +477,18 @@ static void clip_and_raster(const CV in[3], int W, int H, uint8_t* px) { /* Cor de um vertice: lambert por vertice (o GL e o Vulkan fazem igual) */ static void shade(const Tb3dFrame* f, const Tb3dDraw* d, const float* v, CV* o) { - float p[4] = { v[0], v[1], v[2], 1 }, c[4] = { 0 }; + float lp[3] = { v[0], v[1], v[2] }; + if (s_vprog) { /* shader de vertice: move o vertice */ + D3Pixel in; + in.P[0] = v[0]; in.P[1] = v[1]; in.P[2] = v[2]; + in.N[0] = v[3]; in.N[1] = v[4]; in.N[2] = v[5]; + in.L[0] = v[0]; in.L[1] = v[1]; in.L[2] = v[2]; + in.uv[0] = v[6]; in.uv[1] = v[7]; + in.base[0] = d->color[0]; in.base[1] = d->color[1]; in.base[2] = d->color[2]; + in.light = 1.f; in.time = f->time; + d3_shader_run_vertex(s_vprog, &in, lp); + } + float p[4] = { lp[0], lp[1], lp[2], 1 }, c[4] = { 0 }; for (int i = 0; i < 4; i++) for (int k = 0; k < 4; k++) c[i] += d->mvp[k * 4 + i] * p[k]; float n[3] = { 0 }; @@ -485,9 +497,9 @@ static void shade(const Tb3dFrame* f, const Tb3dDraw* d, const float* v, CV* o) v3_norm(n); for (int i = 0; i < 3; i++) { /* ponto no mundo (shader) */ o->P[i] = d->model[12 + i]; - for (int k = 0; k < 3; k++) o->P[i] += d->model[k * 4 + i] * v[k]; + for (int k = 0; k < 3; k++) o->P[i] += d->model[k * 4 + i] * lp[k]; o->N[i] = n[i]; - o->L[i] = v[i]; /* vertice local (shader) */ + o->L[i] = lp[i]; /* vertice local (shader) */ } o->uv[0] = v[6]; o->uv[1] = v[7]; float lam = v3_dot(n, f->light_dir); @@ -521,10 +533,12 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) { if (!p) { free(cv); return false; } cv = p; cv_cap = m->vcount; } - for (int i = 0; i < m->vcount; i++) shade(f, d, m->verts + (size_t)i * 8, &cv[i]); - s_prog = d->shader ? ((const Shd*)d->shader)->prog : NULL; /* pub e o 1o campo */ + const D3Program* prog = d->shader ? ((const Shd*)d->shader)->prog : NULL; /* pub e o 1o campo */ + s_vprog = (prog && d3_shader_stage(prog) == D3_STAGE_VERTEX) ? prog : NULL; + s_prog = (prog && d3_shader_stage(prog) == D3_STAGE_FRAGMENT) ? prog : NULL; s_frame = f; memcpy(s_base, d->color, sizeof(s_base)); + for (int i = 0; i < m->vcount; i++) shade(f, d, m->verts + (size_t)i * 8, &cv[i]); for (int t = 0; t + 2 < m->icount; t += 3) { CV tri[3] = { cv[m->index[t]], cv[m->index[t + 1]], cv[m->index[t + 2]] }; if (tri[0].z < -tri[0].w && tri[1].z < -tri[1].w && tri[2].z < -tri[2].w) continue; @@ -532,7 +546,7 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) { } } free(cv); - s_prog = NULL; + s_prog = s_vprog = NULL; return true; } @@ -922,7 +936,7 @@ static void shd_binaries(TinyBlocks* rt, Shd* sh) { if (!r || r->version != TB_3D_RENDERER_VERSION || !r->compile || !r->available() || !r->shaders()) continue; Tb3dBinary* b = &sh->pub.bin[sh->pub.bin_n]; char err[200]; - if (!r->compile(sh->pub.glsl, &b->data, &b->size, err, sizeof(err))) { + if (!r->compile(sh->pub.glsl, sh->pub.stage, &b->data, &b->size, err, sizeof(err))) { snprintf(S.err, sizeof(S.err), "%s: %.140s", r->name, err); continue; } @@ -946,6 +960,7 @@ static void eval_shader(TinyBlocks_Block* self, TinyBlocks* rt) { sh->refs = 1; sh->pub.id = ++s_shd_seq; sh->pub.version = 1; + sh->pub.stage = d3_shader_stage(prog) == D3_STAGE_VERTEX ? TB_3D_STAGE_VERTEX : TB_3D_STAGE_FRAGMENT; sh->pub.glsl = d3_shader_glsl(prog); shd_binaries(rt, sh); ShdProducer* p = self->userdata; diff --git a/libraries/tinyblocks-gl/src/tb_gl.c b/libraries/tinyblocks-gl/src/tb_gl.c index 8c6aef2..f8b2249 100644 --- a/libraries/tinyblocks-gl/src/tb_gl.c +++ b/libraries/tinyblocks-gl/src/tb_gl.c @@ -27,6 +27,7 @@ static struct { const Tb3dFrame* job; uint8_t* out; const char* glsl; /* != NULL: compilar */ + int stage; /* estagio do shader a compilar */ void** bin; size_t* bin_size; bool busy, ok; @@ -73,7 +74,7 @@ static const char* FS = "out vec4 o_color;\n" "void main() { o_color = vec4(min(v_col, vec3(1.0)), 1.0); }\n"; -static const char* VS_SHADER = +static const char* VS_VERT_HEAD = "#version 330 core\n" "layout(location = 0) in vec3 a_pos;\n" "layout(location = 1) in vec3 a_nrm;\n" @@ -81,17 +82,29 @@ static const char* VS_SHADER = "uniform mat4 u_mvp;\n" "uniform mat4 u_model;\n" "uniform mat3 u_nrm;\n" + "uniform vec4 u_color;\n" + "uniform vec3 u_light;\n" + "uniform float u_ambient;\n" + "uniform float u_time;\n" "out vec3 v_pos;\n" "out vec3 v_nrm;\n" "out vec3 v_local;\n" - "out vec2 v_uv;\n" + "out vec2 v_uv;\n"; +static const char* VS_VERT_MAIN = "void main() {\n" - " gl_Position = u_mvp * vec4(a_pos, 1.0);\n" - " v_pos = (u_model * vec4(a_pos, 1.0)).xyz;\n" + " vec3 n = normalize(u_nrm * a_nrm);\n" + " float light = u_ambient + (1.0 - u_ambient) * max(dot(n, u_light), 0.0);\n" + " vec3 P = tb_vert(a_pos, a_nrm, a_pos, a_uv, u_color.rgb, light, u_time);\n" + " gl_Position = u_mvp * vec4(P, 1.0);\n" + " v_pos = (u_model * vec4(P, 1.0)).xyz;\n" " v_nrm = u_nrm * a_nrm;\n" - " v_local = a_pos;\n" + " v_local = P;\n" " v_uv = a_uv;\n" "}\n"; +static const char* DEFAULT_VERT = + "vec3 tb_vert(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) { return P; }\n"; +static const char* DEFAULT_FRAG = + "vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) { return base * light; }\n"; static const char* FS_HEAD = "#version 330 core\n" "in vec3 v_pos;\n" @@ -141,13 +154,21 @@ static GLuint link_hint(GLuint vs, GLuint fs, bool retrievable) { return p; } -/* O programa do shader feito com blocos, compilado do GLSL */ -static GLuint program_from_glsl(const char* glsl, bool retrievable) { - size_t n = strlen(FS_HEAD) + strlen(glsl) + strlen(FS_MAIN) + 1; - char* fs = malloc(n); - if (!fs) return 0; - snprintf(fs, n, "%s%s%s", FS_HEAD, glsl, FS_MAIN); - GLuint p = link_hint(shader(GL_VERTEX_SHADER, VS_SHADER), shader(GL_FRAGMENT_SHADER, fs), retrievable); +/* O programa do shader feito com blocos, compilado do GLSL. O estagio diz + qual funcao o GLSL traz (tb_vert ou tb_shade); o outro estagio usa o + padrao (posicao intacta / cor do objeto com luz). */ +static GLuint program_from_glsl(const char* glsl, int stage, bool retrievable) { + bool vert = stage == TB_3D_STAGE_VERTEX; + const char* vb = vert ? glsl : DEFAULT_VERT; + const char* fb = vert ? DEFAULT_FRAG : glsl; + size_t nv = strlen(VS_VERT_HEAD) + strlen(vb) + strlen(VS_VERT_MAIN) + 1; + size_t nf = strlen(FS_HEAD) + strlen(fb) + strlen(FS_MAIN) + 1; + char* vs = malloc(nv), *fs = malloc(nf); + if (!vs || !fs) { free(vs); free(fs); return 0; } + snprintf(vs, nv, "%s%s%s", VS_VERT_HEAD, vb, VS_VERT_MAIN); + snprintf(fs, nf, "%s%s%s", FS_HEAD, fb, FS_MAIN); + GLuint p = link_hint(shader(GL_VERTEX_SHADER, vs), shader(GL_FRAGMENT_SHADER, fs), retrievable); + free(vs); free(fs); return p; } @@ -155,12 +176,12 @@ static GLuint program_from_glsl(const char* glsl, bool retrievable) { /* O binario do OpenGL e o programa ja ligado, como o driver o devolve (glGetProgramBinary): 4 bytes com o formato e os bytes do driver. So serve para a mesma placa e driver; se o driver o recusar, recompila. */ -static bool binary_compile(const char* glsl, void** data, size_t* size) { +static bool binary_compile(const char* glsl, int stage, void** data, size_t* size) { *data = NULL; *size = 0; GLint nfmt = 0; glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &nfmt); if (nfmt < 1) { fail("%s", "o driver não devolve binários de programa"); return false; } - GLuint p = program_from_glsl(glsl, true); + GLuint p = program_from_glsl(glsl, stage, true); if (!p) return false; GLint len = 0; glGetProgramiv(p, GL_PROGRAM_BINARY_LENGTH, &len); @@ -197,7 +218,7 @@ static GpuShader* gpu_shader(const Tb3dShader* sh) { memset(g, 0, sizeof(*g)); for (int i = 0; i < sh->bin_n && !g->prog; i++) if (!strcmp(sh->bin[i].renderer, "opengl")) g->prog = program_from_binary(sh->bin[i].data, sh->bin[i].size); - if (!g->prog) g->prog = program_from_glsl(sh->glsl, false); + if (!g->prog) g->prog = program_from_glsl(sh->glsl, sh->stage, false); if (!g->prog) return NULL; g->id = sh->id; g->mvp = glGetUniformLocation(g->prog, "u_mvp"); @@ -384,7 +405,7 @@ static void* gl_thread(void* arg) { uint8_t* out = G.out; const char* glsl = G.glsl; pthread_mutex_unlock(&G.mu); - bool r = glsl ? binary_compile(glsl, G.bin, G.bin_size) : draw(f, out); + bool r = glsl ? binary_compile(glsl, G.stage, G.bin, G.bin_size) : draw(f, out); pthread_mutex_lock(&G.mu); G.ok = r; G.busy = false; @@ -424,10 +445,10 @@ static const char* gl_error(void) { return G.err; } static bool gl_shaders(void) { return true; } /* Tb3dRenderer.compile: pede o binario a thread do OpenGL */ -static bool gl_compile(const char* glsl, void** data, size_t* size, char* err, size_t cap) { +static bool gl_compile(const char* glsl, int stage, void** data, size_t* size, char* err, size_t cap) { if (!gl_available()) { snprintf(err, cap, "%s", G.err); return false; } pthread_mutex_lock(&G.mu); - G.glsl = glsl; G.bin = data; G.bin_size = size; G.busy = true; + G.glsl = glsl; G.stage = stage; G.bin = data; G.bin_size = size; G.busy = true; pthread_cond_broadcast(&G.cv); while (G.busy) pthread_cond_wait(&G.cv, &G.mu); bool ok = G.ok; diff --git a/libraries/tinyblocks-shader/src/tb_shader.c b/libraries/tinyblocks-shader/src/tb_shader.c index c5e0a78..7d5bc91 100644 --- a/libraries/tinyblocks-shader/src/tb_shader.c +++ b/libraries/tinyblocks-shader/src/tb_shader.c @@ -15,7 +15,8 @@ static void eval_outside(TinyBlocks_Block* self, TinyBlocks* rt) { typedef struct { const char* name; const char* label; const char* defs; int nin; bool cmd; const char* doc; } Spec; static const Spec s_specs[] = { - { "Shader.Pixel", "cor do pixel = %1", "", 1, true, "Muda a cor do pixel (uma cor, ou um número para cinza)" }, + { "Shader.Pixel", "cor do pixel = %1", "", 1, true, "Muda a cor do pixel (uma cor, ou um número para cinza). Faz o shader ser de FRAGMENTO" }, + { "Shader.Vertex", "mude a posição do vértice para x %1 y %2 z %3", "|0|0", 3, true, "A posição do vértice no espaço do objeto (a câmera e o mova/gire aplicam por cima). Faz o shader ser de VÉRTICE" }, { "Shader.PixelColor", "cor do pixel", "", 0, false, "A cor do pixel até aqui (começa com a cor do objeto já iluminada)" }, { "Shader.ObjectColor", "cor do objeto", "", 0, false, "A cor dada ao objeto (\"mude a cor de\"), sem luz" }, { "Shader.Light", "luz", "", 0, false, "Claridade do ponto (luz ambiente + sol), de 0 a 1" }, diff --git a/libraries/tinyblocks-vk/src/tb_vk.c b/libraries/tinyblocks-vk/src/tb_vk.c index aa58143..88f9654 100644 --- a/libraries/tinyblocks-vk/src/tb_vk.c +++ b/libraries/tinyblocks-vk/src/tb_vk.c @@ -72,18 +72,49 @@ static const char* FS_MAIN = " o_color = vec4(tb_shade(v_pos, N, v_local, v_uv, pc.color.rgb, light, pc.light.w), 1.0);\n" "}\n"; -/* Tb3dRenderer.compile: o binario do shader para o Vulkan e o SPIR-V do - fragment inteiro (a interface com o vertice fixo esta em FS_HEAD) */ -static uint32_t* spirv_fragment(const char* glsl, size_t* words, char* err, size_t cap) { +/* Estagio de VERTICE: o VS chama tb_vert e sai a interface que o fragmento + espera (posicao no mundo, normal, vertice local e uv). */ +static const char* VS_VERT_HEAD = + "#version 450\n" + "layout(location = 0) in vec3 a_pos;\n" + "layout(location = 1) in vec3 a_nrm;\n" + "layout(location = 2) in vec2 a_uv;\n" + "layout(push_constant) uniform PC { mat4 mvp; mat4 model; vec4 color; vec4 light; } pc;\n" + "layout(location = 0) out vec3 v_pos;\n" + "layout(location = 1) out vec3 v_nrm;\n" + "layout(location = 2) out vec3 v_local;\n" + "layout(location = 3) out vec2 v_uv;\n"; +static const char* VS_VERT_MAIN = + "void main() {\n" + " vec3 n = normalize(transpose(inverse(mat3(pc.model))) * a_nrm);\n" + " float light = pc.color.a + (1.0 - pc.color.a) * max(dot(n, pc.light.xyz), 0.0);\n" + " vec3 P = tb_vert(a_pos, a_nrm, a_pos, a_uv, pc.color.rgb, light, pc.light.w);\n" + " vec4 p = pc.mvp * vec4(P, 1.0);\n" + " p.z = (p.z + p.w) * 0.5;\n" + " gl_Position = p;\n" + " v_pos = (pc.model * vec4(P, 1.0)).xyz;\n" + " v_nrm = transpose(inverse(mat3(pc.model))) * a_nrm;\n" + " v_local = P;\n" + " v_uv = a_uv;\n" + "}\n"; +/* Fragmento padrao de quem so tem shader de vertice (cor do objeto com luz) */ +static const char* DEFAULT_FRAG = + "vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) { return base * light; }\n"; + +/* Monta o fonte completo de um estagio (o corpo GLSL vem dos blocos) */ +static char* wrap(const char* head, const char* body, const char* tail, const char* fallback) { + const char* b = body ? body : fallback; + size_t n = strlen(head) + strlen(b) + strlen(tail) + 1; + char* s = malloc(n); + if (s) snprintf(s, n, "%s%s%s", head, b, tail); + return s; +} + +static uint32_t* spirv_stage(const char* src, int stage, size_t* words, char* err, size_t cap) { *words = 0; if (err && cap) err[0] = 0; if (!shaderc_load()) { snprintf(err, cap, "sem a libshaderc: shaders feitos com blocos não rodam no Vulkan"); return NULL; } - size_t n = strlen(FS_HEAD) + strlen(glsl) + strlen(FS_MAIN) + 1; - char* src = malloc(n); - if (!src) return NULL; - snprintf(src, n, "%s%s%s", FS_HEAD, glsl, FS_MAIN); - void* res = SC.compile(SC.compiler, src, strlen(src), 1 /* fragment */, "shader.frag", "main", NULL); - free(src); + void* res = SC.compile(SC.compiler, src, strlen(src), stage, stage == 0 ? "shader.vert" : "shader.frag", "main", NULL); if (!res || SC.status(res) != 0) { snprintf(err, cap, "shaderc: %.200s", res ? SC.error(res) : "falhou"); if (res) SC.release_result(res); @@ -96,10 +127,27 @@ static uint32_t* spirv_fragment(const char* glsl, size_t* words, char* err, size return spv; } +/* Tb3dRenderer.compile: o binario do shader para o Vulkan e o SPIR-V do + estagio inteiro (vertice: junta com o fragmento padrao ao desenhar; + fragmento: a interface com o vertice fixo esta em FS_HEAD) */ +static uint32_t* spirv_shader(const char* glsl, int stage, size_t* words, char* err, size_t cap) { + if (stage == TB_3D_STAGE_VERTEX) { + char* src = wrap(VS_VERT_HEAD, glsl, VS_VERT_MAIN, NULL); + if (!src) { snprintf(err, cap, "sem memória"); return NULL; } + uint32_t* spv = spirv_stage(src, 0, words, err, cap); + free(src); + return spv; + } + char* src = wrap(FS_HEAD, glsl, FS_MAIN, NULL); + if (!src) { snprintf(err, cap, "sem memória"); return NULL; } + uint32_t* spv = spirv_stage(src, 1, words, err, cap); + free(src); + return spv; +} -static bool vk_compile(const char* glsl, void** data, size_t* size, char* err, size_t cap) { +static bool vk_compile(const char* glsl, int stage, void** data, size_t* size, char* err, size_t cap) { size_t words = 0; - uint32_t* spv = spirv_fragment(glsl, &words, err, cap); + uint32_t* spv = spirv_shader(glsl, stage, &words, err, cap); *data = spv; *size = words * 4; return spv != NULL; @@ -395,6 +443,7 @@ static GpuMesh* gpu_mesh(const Tb3dMesh* m) { static GpuShader* gpu_shader(const Tb3dShader* sh) { GpuShader* g = &V.shd[(unsigned)sh->id % 64u]; if (g->pipe && g->id == sh->id) return g; + bool vert = sh->stage == TB_3D_STAGE_VERTEX; /* o binario que veio no shader ("compile o shader"); sem ele, compila agora */ const void* code = NULL; size_t size = 0; @@ -402,19 +451,41 @@ static GpuShader* gpu_shader(const Tb3dShader* sh) { for (int i = 0; i < sh->bin_n; i++) if (!strcmp(sh->bin[i].renderer, "vulkan")) { code = sh->bin[i].data; size = sh->bin[i].size; } if (!code) { - if (!vk_compile(sh->glsl, &own, &size, V.err, sizeof(V.err))) return NULL; + if (!vk_compile(sh->glsl, sh->stage, &own, &size, V.err, sizeof(V.err))) return NULL; code = own; } VkShaderModuleCreateInfo sm = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, size, code }; - VkShaderModule fs; - VkResult r = vkCreateShaderModule(V.dev, &sm, NULL, &fs); + VkShaderModule mod; + VkResult r = vkCreateShaderModule(V.dev, &sm, NULL, &mod); free(own); if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "binário do shader recusado (%d)", (int)r); return NULL; } + VkShaderModule vs, fs; + if (vert) { /* vertice: junta com o fragmento padrao */ + vs = mod; + void* def = NULL; + size_t dsz = 0; + if (!vk_compile(DEFAULT_FRAG, TB_3D_STAGE_FRAGMENT, &def, &dsz, V.err, sizeof(V.err))) { + vkDestroyShaderModule(V.dev, vs, NULL); + return NULL; + } + VkShaderModuleCreateInfo sf = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, dsz, def }; + VkResult r2 = vkCreateShaderModule(V.dev, &sf, NULL, &fs); + free(def); + if (r2 != VK_SUCCESS) { + vkDestroyShaderModule(V.dev, vs, NULL); + snprintf(V.err, sizeof(V.err), "binário do fragmento padrão recusado (%d)", (int)r2); + return NULL; + } + } else { + fs = mod; + vs = V.shd_vert; + } vkDeviceWaitIdle(V.dev); if (g->pipe) vkDestroyPipeline(V.dev, g->pipe, NULL); g->pipe = VK_NULL_HANDLE; - r = build_pipe(V.shd_vert, fs, V.shd_layout, &g->pipe); - vkDestroyShaderModule(V.dev, fs, NULL); + r = build_pipe(vs, fs, V.shd_layout, &g->pipe); + if (vert) vkDestroyShaderModule(V.dev, fs, NULL); + vkDestroyShaderModule(V.dev, mod, NULL); if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "pipeline do shader recusado (%d)", (int)r); return NULL; } g->id = sh->id; return g; diff --git a/tests/d3_test.c b/tests/d3_test.c index 9987577..6f644ec 100644 --- a/tests/d3_test.c +++ b/tests/d3_test.c @@ -261,6 +261,45 @@ int main(void) { } tb_image_release(ui); } + + /* -- shader de vertice: estica o triangulo no y -- */ + { + const char* vex = "[" BLK("Shader.Vertex", BLK0("Shader.VX") "," BLK("Math.Mul", BLK0("Shader.VY") "," "2") "," BLK0("Shader.VZ")) "]"; + TinyBlocks_Block* sv = compile_shader(vex); + CHECK(sv != NULL, "shader de vértice (\"mude a posição do vértice\") compila"); + CHECK(!compile_shader("[" BLK("Shader.Pixel", BLK("Shader.Color", "\"azul\"")) "," BLK("Shader.Vertex", BLK0("Shader.VX") "," BLK0("Shader.VY") "," BLK0("Shader.VZ")) "]"), + "não mistura \"cor do pixel\" com \"mude a posição do vértice\""); + tinyblocks_clear_error(rt); + if (sv) { + TinyBlocks_Block* g = run_with_shader("3D.ShaderGlsl", sv, NULL); + CHECK(g->outputs[0].kind == TB_VALUE_TEXT && strstr(g->outputs[0].as.text, "vec3 tb_vert("), + "o GLSL gerado pelo shader de vértice é tb_vert"); + run_with_shader("3D.ShaderUse", sv, "quad"); + TinyBlocks_Image* vi = render_with("software"); + CHECK(vi != NULL, "o shader de vértice desenha no software"); + if (vi) { + uint8_t t[4]; + tb_image_get_pixel(vi, 160, 40, &t[0], &t[1], &t[2], &t[3]); + printf(" vertice: topo y=40 rgb=(%d,%d,%d)\n", t[0], t[1], t[2]); + for (int i = 0; i < 2; i++) { + const char* lib = i ? "tinyblocks-vk" : "tinyblocks-gl"; + if (!tb_rt_find_library(rt, lib)) continue; + TinyBlocks_Image* gi = render_with(gpu[i]); + TinyBlocks_Block* gr = RUN("3D.Renderer", NULL); + const char* used = gr->outputs[0].kind == TB_VALUE_TEXT ? gr->outputs[0].as.text : ""; + if (strncmp(used, gpu[i], strlen(gpu[i])) != 0) { tb_image_release(gi); continue; } + double mean = 0, bad = 1; + if (gi) compare(vi, gi, &mean, &bad); + printf(" vértice %s x software: diferença média %.3f, pixels muito diferentes %.2f%%\n", gpu[i], mean, bad * 100); + char m[96]; + snprintf(m, sizeof(m), "o shader de vértice desenha igual no %s", gpu[i]); + CHECK(gi && mean < 4.0 && bad < 0.02, m); + tb_image_release(gi); + } + } + tb_image_release(vi); + } + } tb_image_release(sw); tinyblocks_deinit(&rt); if (fails) printf("\n%d FALHA(S)\n", fails);