3D: tinyblocks-3d com renderizadores Vulkan (vk) e OpenGL (gl); jogo das moedas

tinyblocks-3d (categoria 3D): cena com objetos com nome (cubo, esfera,
plano, cilindro), posicao/rotacao/escala/cor, colisao por caixas,
distancia, camera, luz direcional, ceu, e o bloco "imagem da cena" que
desenha numa imagem para o palco. Define o contrato Tb3dRenderer e traz um
rasterizador em software (z-buffer, corte no plano de perto, lambert por
vertice).

tinyblocks-gl: OpenGL 3.3 core por EGL sem janela (surfaceless), numa
thread propria dona do contexto (o SDL pode usar GL na thread do editor).
tinyblocks-vk: Vulkan 1.1 sem janela (render pass cor + profundidade,
viewport com altura negativa, z convertido no shader, push constants de 128
bytes, copia para buffer); SPIR-V embutido, gerado pelo glslc (make
shaders). Os dois publicam o renderizador no lib_userdata e nao dependem de
simbolos da 3d (o quadro leva a MVP pronta). Escolha automatica: Vulkan,
OpenGL, software.

test-3d: blocos, colisao e camera; as imagens de Vulkan e OpenGL ficam a
0,001 de diferenca media do software (testado na NVIDIA, na Intel e no
llvmpipe, com a camada de validacao). No Windows a 3d entra so com o
software.

examples/jogo-3d: "Pegue as moedas", todo em blocos.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-27 02:12:03 -03:00
1 parent 8f2c00693d
commit 5bae31edf3
29 files changed
+18420 -5

No files matched your search

+16 -3
View File
@@ -86,10 +86,10 @@ CAT_LDFLAGS := $(foreach l,$(CAT_LIBS),-ltinyblocks-$(l))
CAT_INCS := $(foreach l,$(CAT_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include) CAT_INCS := $(foreach l,$(CAT_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include)
# Libraries que o editor registra como as de categoria, mas com varios # Libraries que o editor registra como as de categoria, mas com varios
# fontes e o Makefile proprio (o harness nao as compila junto) # fontes e o Makefile proprio (o harness nao as compila junto)
APP_LIBS := socket ssl http archive tensor ai plot APP_LIBS := socket ssl http archive tensor ai plot 3d gl vk
APP_A := $(foreach l,$(APP_LIBS),$(LIBDIR)/tinyblocks-$(l)/build/libtinyblocks-$(l).a) APP_A := $(foreach l,$(APP_LIBS),$(LIBDIR)/tinyblocks-$(l)/build/libtinyblocks-$(l).a)
APP_INCS := $(foreach l,$(APP_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include) APP_INCS := $(foreach l,$(APP_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include)
APP_LDLIBS := -lssl -lcrypto -lz -lpthread APP_LDLIBS := -lssl -lcrypto -lz -lpthread -lEGL -lOpenGL -lvulkan
ED_A := $(ED_DIR)/build/libtinyblocks-editor.a ED_A := $(ED_DIR)/build/libtinyblocks-editor.a
GX_A := $(GX_DIR)/build/libtinyblocks-graphics.a GX_A := $(GX_DIR)/build/libtinyblocks-graphics.a
SD_A := $(SD_DIR)/build/libtinyblocks-sdl2.a SD_A := $(SD_DIR)/build/libtinyblocks-sdl2.a
@@ -111,7 +111,7 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \
editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \ editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \
appdir appimage run-appimage icon \ appdir appimage run-appimage icon \
test-toml test-plugin test-blueprint test-a11y test-mcp test-mcp-server test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \ test-toml test-plugin test-blueprint test-a11y test-mcp test-mcp-server test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \
test-tensor test-ai test-http test-archive test-plot test-syntax test-os test-value test-vars test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \ test-tensor test-ai test-http test-archive test-plot test-3d test-syntax test-os test-value test-vars test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \
category-libs category-sos libs app-libs \ category-libs category-sos libs app-libs \
lib-events lib-control lib-errors lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \ lib-events lib-control lib-errors lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \
lib-environ \ lib-environ \
@@ -651,6 +651,19 @@ $(BUILD)/archive_test: tests/archive_test.c $(LIBDIR)/tinyblocks-archive/src/tb_
test-archive: $(BUILD)/archive_test ## Roda o teste da archive (ASan/UBSan) test-archive: $(BUILD)/archive_test ## Roda o teste da archive (ASan/UBSan)
./$(BUILD)/archive_test ./$(BUILD)/archive_test
# -- Teste da 3d (cena e colisao; Vulkan e OpenGL comparados ao software) ---
D3_DIR := $(LIBDIR)/tinyblocks-3d
D3_SRCS := $(D3_DIR)/src/tb_3d.c $(LIBDIR)/tinyblocks-gl/src/tb_gl.c $(LIBDIR)/tinyblocks-vk/src/tb_vk.c
$(BUILD)/d3_test: tests/d3_test.c $(D3_SRCS) $(LIBDIR)/tinyblocks-vk/src/tb_vk_shaders.h static
@mkdir -p $(BUILD)
$(CC) $(CFLAGS_DBG) -DWITH_GL -DWITH_VK -I$(D3_DIR)/include -I$(LIBDIR)/tinyblocks-gl/include \
-I$(LIBDIR)/tinyblocks-vk/include -I$(PNG_DIR)/include \
$(D3_SRCS) $(PNG_DIR)/src/tb_png.c tests/d3_test.c -o $@ \
-Wl,--start-group $(LIB_A) -Wl,--end-group -lpng -lEGL -lOpenGL -lvulkan -lpthread -lm
test-3d: $(BUILD)/d3_test ## Roda o teste da 3d (sem os vazamentos dos drivers de GPU; grava /tmp/tb_3d_*.png)
ASAN_OPTIONS=detect_leaks=0 ./$(BUILD)/d3_test
# -- Teste da library plot (figura -> imagem PNG) --- # -- Teste da library plot (figura -> imagem PNG) ---
PLOT_DIR := $(LIBDIR)/tinyblocks-plot PLOT_DIR := $(LIBDIR)/tinyblocks-plot
$(BUILD)/plot_test: tests/plot_test.c $(PLOT_DIR)/src/tb_plot.c $(PLOT_DIR)/src/plot_font.h $(TENSOR_SRCS) static $(BUILD)/plot_test: tests/plot_test.c $(PLOT_DIR)/src/tb_plot.c $(PLOT_DIR)/src/plot_font.h $(TENSOR_SRCS) static
+38 -1
View File
@@ -23,7 +23,7 @@ ver [referencia-api.md](referencia-api.md)).
Para regerar: [ferramentas/README.md](ferramentas/README.md). Para regerar: [ferramentas/README.md](ferramentas/README.md).
Total: 372 tipos em 38 libraries. Total: 401 tipos em 39 libraries.
## Índice ## Índice
@@ -48,6 +48,7 @@ Total: 372 tipos em 38 libraries.
- [tinyblocks-tensor](#tinyblocks-tensor) (categoria "Tensores") - 51 blocos - [tinyblocks-tensor](#tinyblocks-tensor) (categoria "Tensores") - 51 blocos
- [tinyblocks-ai](#tinyblocks-ai) (categoria "IA") - 39 blocos - [tinyblocks-ai](#tinyblocks-ai) (categoria "IA") - 39 blocos
- [tinyblocks-plot](#tinyblocks-plot) (categoria "Gráficos") - 19 blocos - [tinyblocks-plot](#tinyblocks-plot) (categoria "Gráficos") - 19 blocos
- [tinyblocks-3d](#tinyblocks-3d) (categoria "3D") - 29 blocos
- [tinyblocks-toml](#tinyblocks-toml) (categoria "TOML") - 1 bloco - [tinyblocks-toml](#tinyblocks-toml) (categoria "TOML") - 1 bloco
- [tinyblocks-json](#tinyblocks-json) (categoria "JSON") - 2 blocos - [tinyblocks-json](#tinyblocks-json) (categoria "JSON") - 2 blocos
- [tinyblocks-xml](#tinyblocks-xml) (categoria "XML") - 2 blocos - [tinyblocks-xml](#tinyblocks-xml) (categoria "XML") - 2 blocos
@@ -511,6 +512,42 @@ Categoria na paleta: **Gráficos**.
| `Plot.Image` | imagem da figura | repórter | - | `imagem` (imagem) | Desenha a figura numa imagem | | `Plot.Image` | imagem da figura | repórter | - | `imagem` (imagem) | Desenha a figura numa imagem |
| `Plot.Save` | salve a figura em (a) <br>padrões: `grafico.png` | comando | `a` (texto) | - | Grava a figura (.png, .bmp ou .ppm) | | `Plot.Save` | salve a figura em (a) <br>padrões: `grafico.png` | comando | `a` (texto) | - | Grava a figura (.png, .bmp ou .ppm) |
## tinyblocks-3d
Categoria na paleta: **3D**.
| Tipo | Rótulo no editor | Forma | Entradas | Saídas | Descrição |
|---|---|---|---|---|---|
| `3D.Scene` | nova cena 3D | comando | - | - | Apaga os objetos e volta câmera, luz e céu ao padrão |
| `3D.Cube` | crie cubo (a) em x (b) y (c) z (d) <br>padrões: `jogador\|0\|0.5\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Cubo de lado 1 com esse nome (troca se já existir) |
| `3D.Sphere` | crie esfera (a) em x (b) y (c) z (d) <br>padrões: `bola\|0\|0.5\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Esfera de diâmetro 1 |
| `3D.Plane` | crie plano (a) em x (b) y (c) z (d) <br>padrões: `chão\|0\|0\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Plano deitado de 10 por 10 |
| `3D.Cylinder` | crie cilindro (a) em x (b) y (c) z (d) <br>padrões: `moeda\|0\|0.5\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Cilindro em pé, diâmetro 1 e altura 1 |
| `3D.MoveTo` | mova (a) para x (b) y (c) z (d) <br>padrões: `jogador\|0\|0.5\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Põe o objeto nessa posição |
| `3D.MoveBy` | mova (a) por x (b) y (c) z (d) <br>padrões: `jogador\|0\|0\|0.1` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Soma à posição do objeto |
| `3D.RotateTo` | gire (a) para x (b) y (c) z (d) graus <br>padrões: `jogador\|0\|45\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Rotação nos eixos x, y e z (em graus) |
| `3D.RotateBy` | gire (a) por x (b) y (c) z (d) graus <br>padrões: `jogador\|0\|5\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Soma à rotação do objeto |
| `3D.Scale` | mude o tamanho de (a) para x (b) y (c) z (d) <br>padrões: `chão\|20\|1\|20` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Escala do objeto em cada eixo |
| `3D.Color` | mude a cor de (a) para (b) <br>padrões: `jogador\|vermelho` | comando | `a` (texto), `b` (texto) | - | Cor por nome (vermelho, azul, dourado...) ou #rrggbb |
| `3D.Show` | mostre o objeto (a) <br>padrões: `jogador` | comando | `a` (texto) | - | Volta a desenhar o objeto |
| `3D.Hide` | esconda o objeto (a) <br>padrões: `jogador` | comando | `a` (texto) | - | Deixa de desenhar o objeto (e ele não encosta) |
| `3D.Delete` | apague o objeto (a) <br>padrões: `jogador` | comando | `a` (texto) | - | Tira o objeto da cena |
| `3D.X` | x do objeto (a) <br>padrões: `jogador` | repórter | `a` (texto) | `valor` (real) | Posição x |
| `3D.Y` | y do objeto (a) <br>padrões: `jogador` | repórter | `a` (texto) | `valor` (real) | Posição y |
| `3D.Z` | z do objeto (a) <br>padrões: `jogador` | repórter | `a` (texto) | `valor` (real) | Posição z |
| `3D.Exists` | existe o objeto (a)? <br>padrões: `jogador` | booleano | `a` (texto) | `sim?` (inteiro, booleano) | Verdadeiro se há um objeto com esse nome |
| `3D.Touching` | objeto (a) encosta em (b) <br>padrões: `jogador\|moeda` | booleano | `a` (texto), `b` (texto) | `sim?` (inteiro, booleano) | As caixas dos dois objetos se cruzam? |
| `3D.Distance` | distância entre (a) e (b) <br>padrões: `jogador\|moeda` | repórter | `a` (texto), `b` (texto) | `valor` (real) | Distância entre os centros |
| `3D.Camera` | câmera em x (a) y (b) z (c) olhando para x (d) y (e) z (f) <br>padrões: `0\|6\|10\|0\|0\|0` | comando | `a` (real), `b` (real), `c` (real), `d` (real), `e` (real), `f` (real) | - | Posição da câmera e o ponto para onde ela olha |
| `3D.Fov` | campo de visão da câmera (a) graus <br>padrões: `60` | comando | `a` (real) | - | Ângulo vertical que a câmera enxerga |
| `3D.Light` | luz vindo de x (a) y (b) z (c) <br>padrões: `0.4\|1\|0.6` | comando | `a` (real), `b` (real), `c` (real) | - | Direção de onde vem a luz do sol |
| `3D.Ambient` | luz ambiente (a) <br>padrões: `0.35` | comando | `a` (real) | - | Claridade das partes na sombra (0 a 1) |
| `3D.Sky` | cor do céu (a) <br>padrões: `#87c7fa` | comando | `a` (texto) | - | Cor do fundo |
| `3D.Image` | imagem da cena de (a) por (b) <br>padrões: `480\|360` | repórter | `a` (inteiro), `b` (inteiro) | `imagem` (imagem) | Desenha a cena numa imagem (use com "desenhe") |
| `3D.Use` | use o renderizador (a) <br>padrões: `automático` | comando | `a` (texto) | - | vulkan, opengl, software ou automático |
| `3D.Renderer` | renderizador da cena | repórter | - | `texto` (texto) | Quem desenhou o último quadro (e em qual placa) |
| `3D.Count` | número de objetos 3D | repórter | - | `valor` (inteiro) | Quantos objetos a cena tem |
## tinyblocks-toml ## tinyblocks-toml
Categoria na paleta: **TOML**. Categoria na paleta: **TOML**.
+1
View File
@@ -114,6 +114,7 @@ Todos compilam com ASan/UBSan (`CFLAGS_DBG`) e rodam sem janela.
| `test-scratchblocks` | `scratchblocks_test.c` | Notação do fórum, ida e volta. | | `test-scratchblocks` | `scratchblocks_test.c` | Notação do fórum, ida e volta. |
| `test-curves`, `test-ppm`, `test-bmp`, `test-png`, `test-jpg`, `test-image`, `test-vg`, `test-svg` | `*_test.c` | Curvas e imagens. | | `test-curves`, `test-ppm`, `test-bmp`, `test-png`, `test-jpg`, `test-image`, `test-vg`, `test-svg` | `*_test.c` | Curvas e imagens. |
| `test-syntax`, `test-regex`, `test-markdown`, `test-opentype` | `*_test.c` | Realce, regex, markdown, fontes. | | `test-syntax`, `test-regex`, `test-markdown`, `test-opentype` | `*_test.c` | Realce, regex, markdown, fontes. |
| `test-3d` | `d3_test.c` | Cena, colisão e câmera da `tinyblocks-3d`; desenha com software, OpenGL e Vulkan e compara as imagens (grava `/tmp/tb_3d_*.png`). |
| `test-a11y` | `a11y_test.c` | Árvore acessível. | | `test-a11y` | `a11y_test.c` | Árvore acessível. |
| `test-mcp-server`, `test-mcp` | `mcp_server_test.c`, `mcp_test.c` + `mcp_server.py` | Servidor MCP em C; cliente MCP (stdio, HTTP, SSE). | | `test-mcp-server`, `test-mcp` | `mcp_server_test.c`, `mcp_test.c` + `mcp_server.py` | Servidor MCP em C; cliente MCP (stdio, HTTP, SSE). |
| `test-plugin` | `plugin_test.c` | Carrega uma library `.so` por `dlopen` e testa. | | `test-plugin` | `plugin_test.c` | Carrega uma library `.so` por `dlopen` e testa. |
+16
View File
@@ -607,4 +607,20 @@ D = {
"TB_TENSOR_API_VERSION": "Versão da TbTensorApi.", "TB_TENSOR_API_VERSION": "Versão da TbTensorApi.",
"TbTensor": "Tensor com contagem de referências: forma, dados `d`, gradiente `g`, o nó do autograd e o estado do otimizador.", "TbTensor": "Tensor com contagem de referências: forma, dados `d`, gradiente `g`, o nó do autograd e o estado do otimizador.",
"TbTensorApi": "Tabela que a tinyblocks-tensor publica no lib_userdata: tensores, blocos-handle, autograd, parâmetros, operações e utilidades.", "TbTensorApi": "Tabela que a tinyblocks-tensor publica no lib_userdata: tensores, blocos-handle, autograd, parâmetros, operações e utilidades.",
# -- 3d / gl / vk
"TB_3D_LIB": "Nome da library 3d.",
"TB_3D_RENDERER_VERSION": "Versão do contrato Tb3dRenderer (quem publica confere).",
"Tb3dMesh": "Malha fixa: vértices (posição e normal) e índices dos triângulos, com um id estável para o renderizador guardar na GPU.",
"Tb3dDraw": "Um objeto a desenhar: malha, matriz do modelo, MVP já calculada, matriz das normais e cor.",
"Tb3dFrame": "Um quadro: tamanho, câmera (view, proj, viewproj), céu, luz e a lista de desenhos.",
"Tb3dRenderer": "Contrato de um renderizador: available (inicia na primeira vez), render (RGBA, linha 0 no alto), device e error.",
"tb_3d_get_library": "Descritor da library tinyblocks-3d.",
"tb_3d_software_renderer": "O rasterizador em software da 3d (sempre disponível; referência dos testes).",
"tb_3d_mat_identity": "Matriz identidade 4x4.",
"tb_3d_mat_mul": "out = a * b (4x4, em colunas).",
"tb_3d_mat_perspective": "Projeção perspectiva na convenção do OpenGL (z de -1 a 1).",
"tb_3d_mat_look_at": "Matriz da câmera olhando de eye para at.",
"tb_gl_get_library": "Descritor da tinyblocks-gl (publica o Tb3dRenderer \"opengl\").",
"tb_vk_get_library": "Descritor da tinyblocks-vk (publica o Tb3dRenderer \"vulkan\").",
} }
+26
View File
@@ -246,6 +246,27 @@ Usam isso: `TbTensorApi` (tensor), `TbSocketApi` (socket, com a interface
`TbStream`) e `TbSslApi` (ssl). A interface `TbStream` (read/write/close por `TbStream`) e `TbSslApi` (ssl). A interface `TbStream` (read/write/close por
classe) deixa a http falar com TCP ou TLS sem saber qual é. classe) deixa a http falar com TCP ou TLS sem saber qual é.
### O caminho inverso: renderizadores da 3D
Na `tinyblocks-3d` a direção é a contrária, como no `tinyblocks-graphics`
com os backends: a 3d define o contrato (`Tb3dRenderer` em `tb_3d.h`) e as
libraries `tinyblocks-vk` e `tinyblocks-gl` o implementam, publicando o
renderizador delas no próprio `lib_userdata`. A cada quadro a 3d procura
`tinyblocks-vk`, depois `tinyblocks-gl`, e usa o primeiro cujo
`available()` diga sim; se nenhum servir (ou o render falhar), usa o
rasterizador em software que ela mesma traz.
```
3d (cena, blocos, software) <-- tb_3d.h -- vk (Vulkan) / gl (OpenGL)
```
O `Tb3dFrame` leva tudo pronto (inclusive a MVP de cada objeto): o
renderizador não chama nenhuma função da 3d, então as `.so` da vk e da gl
não dependem de símbolos dela. Os dois desenham fora da tela e devolvem
RGBA; a gl tem uma thread própria para o contexto EGL (o SDL pode estar
usando OpenGL na thread do editor). O `test-3d` compara as imagens dos três
(diferença média por canal menor que 4).
## Arquivos de uma library ## Arquivos de uma library
``` ```
@@ -389,6 +410,11 @@ editor mostra em "Bibliotecas":
- **Estado global da library**: uma library carregada como `.so` e também - **Estado global da library**: uma library carregada como `.so` e também
linkada estaticamente em outro lugar teria dois estados. É por isso que linkada estaticamente em outro lugar teria dois estados. É por isso que
variáveis, palco, entrada e formatos de imagem moram no core. variáveis, palco, entrada e formatos de imagem moram no core.
- **Função exportada chamada de dentro do `.so`**: no editor a library
existe duas vezes (linkada no executável e carregada como `.so`); uma
chamada a uma função `TB_API` dela mesma pode ir para a cópia do
executável, com o outro estado. Chame as versões `static` por dentro
(foi o caso da `tinyblocks-plot`).
- **Hot reload**: tudo que a library guardou fora dela (ponteiros de - **Hot reload**: tudo que a library guardou fora dela (ponteiros de
`TypeBlock`, `FlowClass`, strings estáticas) fica inválido depois do `TypeBlock`, `FlowClass`, strings estáticas) fica inválido depois do
`dlclose`. `dlclose`.
+7
View File
@@ -107,6 +107,13 @@ a ser parâmetros sem gradiente, para irem junto no "salve os parâmetros".
O que ainda depende da instância é o estado que não passa por `tt_param` O que ainda depende da instância é o estado que não passa por `tt_param`
(ex.: buffers de outras libraries). (ex.: buffers de outras libraries).
### scratchblocks: `?` logo depois de um campo no fim do rótulo
Um rótulo como `%1 encosta em %2?` não é reconhecido na importação
(`<[a] encosta em (b)?>` vira "repórter desconhecido"); com o `?` depois
de uma palavra (`tecla %1 pressionada?`) funciona. A 3d usa
`objeto %1 encosta em %2` (o formato booleano vem do nome da saída).
### Campo de texto de um bloco corta em 63 caracteres ### Campo de texto de um bloco corta em 63 caracteres
`EdBlock.in_text[i]` tem 64 bytes: um texto maior colado ou importado `EdBlock.in_text[i]` tem 64 bytes: um texto maior colado ou importado
+83
View File
@@ -38,6 +38,7 @@ Convenções que valem para toda a API:
- [`include/tinyblocks/tb_vars.h`](#includetinyblockstb_varsh) - [`include/tinyblocks/tb_vars.h`](#includetinyblockstb_varsh)
- [`include/tinyblocks/tb_vector_block.h`](#includetinyblockstb_vector_blockh) - [`include/tinyblocks/tb_vector_block.h`](#includetinyblockstb_vector_blockh)
- [`include/tinyblocks/tinyblocks.h`](#includetinyblockstinyblocksh) - [`include/tinyblocks/tinyblocks.h`](#includetinyblockstinyblocksh)
- [`libraries/tinyblocks-3d/include/tb_3d.h`](#librariestinyblocks-3dincludetb_3dh)
- [`libraries/tinyblocks-a11y/include/tb_a11y.h`](#librariestinyblocks-a11yincludetb_a11yh) - [`libraries/tinyblocks-a11y/include/tb_a11y.h`](#librariestinyblocks-a11yincludetb_a11yh)
- [`libraries/tinyblocks-ai/include/tb_ai.h`](#librariestinyblocks-aiincludetb_aih) - [`libraries/tinyblocks-ai/include/tb_ai.h`](#librariestinyblocks-aiincludetb_aih)
- [`libraries/tinyblocks-ai/src/ai_internal.h`](#librariestinyblocks-aisrcai_internalh) - [`libraries/tinyblocks-ai/src/ai_internal.h`](#librariestinyblocks-aisrcai_internalh)
@@ -64,6 +65,7 @@ Convenções que valem para toda a API:
- [`libraries/tinyblocks-errors/include/tb_errors.h`](#librariestinyblocks-errorsincludetb_errorsh) - [`libraries/tinyblocks-errors/include/tb_errors.h`](#librariestinyblocks-errorsincludetb_errorsh)
- [`libraries/tinyblocks-events/include/tb_events.h`](#librariestinyblocks-eventsincludetb_eventsh) - [`libraries/tinyblocks-events/include/tb_events.h`](#librariestinyblocks-eventsincludetb_eventsh)
- [`libraries/tinyblocks-fs/include/tb_fs.h`](#librariestinyblocks-fsincludetb_fsh) - [`libraries/tinyblocks-fs/include/tb_fs.h`](#librariestinyblocks-fsincludetb_fsh)
- [`libraries/tinyblocks-gl/include/tb_gl.h`](#librariestinyblocks-glincludetb_glh)
- [`libraries/tinyblocks-graphics/include/tb_graphics.h`](#librariestinyblocks-graphicsincludetb_graphicsh) - [`libraries/tinyblocks-graphics/include/tb_graphics.h`](#librariestinyblocks-graphicsincludetb_graphicsh)
- [`libraries/tinyblocks-http/include/tb_http.h`](#librariestinyblocks-httpincludetb_httph) - [`libraries/tinyblocks-http/include/tb_http.h`](#librariestinyblocks-httpincludetb_httph)
- [`libraries/tinyblocks-image/include/tb_imglib.h`](#librariestinyblocks-imageincludetb_imglibh) - [`libraries/tinyblocks-image/include/tb_imglib.h`](#librariestinyblocks-imageincludetb_imglibh)
@@ -103,6 +105,8 @@ Convenções que valem para toda a API:
- [`libraries/tinyblocks-variables/include/tb_variables.h`](#librariestinyblocks-variablesincludetb_variablesh) - [`libraries/tinyblocks-variables/include/tb_variables.h`](#librariestinyblocks-variablesincludetb_variablesh)
- [`libraries/tinyblocks-vector/include/tb_vector.h`](#librariestinyblocks-vectorincludetb_vectorh) - [`libraries/tinyblocks-vector/include/tb_vector.h`](#librariestinyblocks-vectorincludetb_vectorh)
- [`libraries/tinyblocks-vg/include/tb_vg.h`](#librariestinyblocks-vgincludetb_vgh) - [`libraries/tinyblocks-vg/include/tb_vg.h`](#librariestinyblocks-vgincludetb_vgh)
- [`libraries/tinyblocks-vk/include/tb_vk.h`](#librariestinyblocks-vkincludetb_vkh)
- [`libraries/tinyblocks-vk/src/tb_vk_shaders.h`](#librariestinyblocks-vksrctb_vk_shadersh)
- [`libraries/tinyblocks-xml/include/ast.h`](#librariestinyblocks-xmlincludeasth) - [`libraries/tinyblocks-xml/include/ast.h`](#librariestinyblocks-xmlincludeasth)
- [`libraries/tinyblocks-xml/include/lexeme.h`](#librariestinyblocks-xmlincludelexemeh) - [`libraries/tinyblocks-xml/include/lexeme.h`](#librariestinyblocks-xmlincludelexemeh)
- [`libraries/tinyblocks-xml/include/tb_xml.h`](#librariestinyblocks-xmlincludetb_xmlh) - [`libraries/tinyblocks-xml/include/tb_xml.h`](#librariestinyblocks-xmlincludetb_xmlh)
@@ -1063,6 +1067,47 @@ Fluxo de uso mínimo:
|---|---| |---|---|
| `uint64_t tb_rt_next_id(TinyBlocks* rt)` | Próximo id único. | | `uint64_t tb_rt_next_id(TinyBlocks* rt)` | Próximo id único. |
## libraries/tinyblocks-3d/include/tb_3d.h
```text
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.
```
| 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` = `1` | 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. |
| tipo `struct Tb3dDraw` | Um objeto a desenhar |
| tipo `struct Tb3dFrame` | Um quadro: tudo o que o renderizador precisa |
| tipo `struct Tb3dRenderer` | Renderizador. render escreve width*height*4 bytes RGBA, linha 0 no ALTO. |
| `const TinyBlocks_LibraryDescriptor* tb_3d_get_library(void)` | Descritor da library tinyblocks-3d. |
| `const Tb3dRenderer* tb_3d_software_renderer(void)` | O rasterizador em software (tambem usado pelos testes como referencia) |
### matematica (column-major)
| Declaração | Descrição |
|---|---|
| `void tb_3d_mat_identity(float m[16])` | Matriz identidade 4x4. |
| `void tb_3d_mat_mul(float out[16], const float a[16], const float b[16])` | out = a * b (4x4, em colunas). |
| `void tb_3d_mat_perspective(float m[16], float fovy_deg, float aspect, float znear, float zfar)` | Projeção perspectiva na convenção do OpenGL (z de -1 a 1). |
| `void tb_3d_mat_look_at(float m[16], const float eye[3], const float at[3], const float up[3])` | Matriz da câmera olhando de eye para at. |
## libraries/tinyblocks-a11y/include/tb_a11y.h ## libraries/tinyblocks-a11y/include/tb_a11y.h
```text ```text
@@ -1946,6 +1991,22 @@ posicao). Independente do editor; registra a categoria "Arquivos".
|---|---| |---|---|
| `const TinyBlocks_LibraryDescriptor* tb_fs_get_library(void)` | TinyBlocks - tb_fs.h Library tinyblocks-fs: blocos de arquivo (abrir, ler, escrever, anexar, posicao). Independente do editor; registra a categoria "Arquivos". | | `const TinyBlocks_LibraryDescriptor* tb_fs_get_library(void)` | TinyBlocks - tb_fs.h Library tinyblocks-fs: blocos de arquivo (abrir, ler, escrever, anexar, posicao). Independente do editor; registra a categoria "Arquivos". |
## libraries/tinyblocks-gl/include/tb_gl.h
```text
Library tinyblocks-gl: renderizador OpenGL da tinyblocks-3d.
Nao tem blocos: publica um Tb3dRenderer ("opengl") no lib_userdata, que a
3d acha pelo nome. Desenha sem janela: contexto OpenGL 3.3 core pelo EGL
(plataforma surfaceless do Mesa, ou o display padrao), num framebuffer
fora da tela, e le os pixels de volta.
O contexto vive numa thread propria: assim ele nunca e o "corrente" da
thread do editor, onde o SDL pode estar usando o OpenGL dele.
```
| Declaração | Descrição |
|---|---|
| `const TinyBlocks_LibraryDescriptor* tb_gl_get_library(void)` | TinyBlocks - tb_gl.h Library tinyblocks-gl: renderizador OpenGL da tinyblocks-3d. Nao tem blocos: publica um Tb3dRenderer ("opengl") no lib_userdata, que a 3d acha pelo nome. Desenha sem janela: contexto OpenGL 3.3 core pelo EGL (plataforma surfaceless do Mesa, ou o display padrao), num framebuffer fora da tela, e le os pixels de volta. O contexto vive numa thread propria: assim ele nunca e o "corrente" da thread do editor, onde o SDL pode estar usando o OpenGL dele. |
## libraries/tinyblocks-graphics/include/tb_graphics.h ## libraries/tinyblocks-graphics/include/tb_graphics.h
```text ```text
@@ -2925,6 +2986,28 @@ palco por tb_draw_ctx_play.
| `bool tb_vg_circle (TinyBlocks_VectorData* v, float cx, float cy, float rad, float r, float g, float b, float a)` | Círculo preenchido. | | `bool tb_vg_circle (TinyBlocks_VectorData* v, float cx, float cy, float rad, float r, float g, float b, float a)` | Círculo preenchido. |
| `bool tb_vg_polygon(TinyBlocks_VectorData* v, const double* xy, int n, bool closed, float r, float g, float b, float a)` | Polígono/polilinha (`xy` = x0,y0,x1,y1...). | | `bool tb_vg_polygon(TinyBlocks_VectorData* v, const double* xy, int n, bool closed, float r, float g, float b, float a)` | Polígono/polilinha (`xy` = x0,y0,x1,y1...). |
## libraries/tinyblocks-vk/include/tb_vk.h
```text
Library tinyblocks-vk: renderizador Vulkan da tinyblocks-3d.
Nao tem blocos: publica um Tb3dRenderer ("vulkan") no lib_userdata, que a
3d acha pelo nome. Desenha sem janela: render pass com cor RGBA8 e
profundidade, os shaders em SPIR-V embutidos (src/tb_vk_shaders.h, gerado
pelo glslc a partir de src/shaders), e copia a imagem para a memoria.
Escolha da placa: a dedicada, depois a integrada, depois a de software
(llvmpipe). TINYBLOCKS_VK_DEVICE=<parte do nome> escolhe outra.
```
| Declaração | Descrição |
|---|---|
| `const TinyBlocks_LibraryDescriptor* tb_vk_get_library(void)` | TinyBlocks - tb_vk.h Library tinyblocks-vk: renderizador Vulkan da tinyblocks-3d. Nao tem blocos: publica um Tb3dRenderer ("vulkan") no lib_userdata, que a 3d acha pelo nome. Desenha sem janela: render pass com cor RGBA8 e profundidade, os shaders em SPIR-V embutidos (src/tb_vk_shaders.h, gerado pelo glslc a partir de src/shaders), e copia a imagem para a memoria. Escolha da placa: a dedicada, depois a integrada, depois a de software (llvmpipe). TINYBLOCKS_VK_DEVICE=<parte do nome> escolhe outra. |
## libraries/tinyblocks-vk/src/tb_vk_shaders.h
```text
Gerado por tools/spv2h.py a partir de src/shaders (glslc). Nao edite.
```
## libraries/tinyblocks-xml/include/ast.h ## libraries/tinyblocks-xml/include/ast.h
```text ```text
+10
View File
@@ -42,6 +42,11 @@
#include <tb_tensor.h> #include <tb_tensor.h>
#include <tb_ai.h> #include <tb_ai.h>
#include <tb_plot.h> #include <tb_plot.h>
#include <tb_3d.h>
#ifndef _WIN32
# include <tb_gl.h>
# include <tb_vk.h>
#endif
#include <tb_api.h> #include <tb_api.h>
#ifdef TB_STATIC_EXTRAS #ifdef TB_STATIC_EXTRAS
/* Build sem dlopen das libraries (Windows): as que no Linux vem como .so /* Build sem dlopen das libraries (Windows): as que no Linux vem como .so
@@ -107,6 +112,11 @@ int main(int argc, char** argv) {
reg_core(rt, "tinyblocks-tensor", tb_tensor_get_library); reg_core(rt, "tinyblocks-tensor", tb_tensor_get_library);
reg_core(rt, "tinyblocks-ai", tb_ai_get_library); reg_core(rt, "tinyblocks-ai", tb_ai_get_library);
reg_core(rt, "tinyblocks-plot", tb_plot_get_library); reg_core(rt, "tinyblocks-plot", tb_plot_get_library);
reg_core(rt, "tinyblocks-3d", tb_3d_get_library);
#ifndef _WIN32 /* no Windows a 3d desenha em software */
reg_core(rt, "tinyblocks-gl", tb_gl_get_library);
reg_core(rt, "tinyblocks-vk", tb_vk_get_library);
#endif
#ifdef TB_STATIC_EXTRAS #ifdef TB_STATIC_EXTRAS
{ {
const TinyBlocks_LibraryDescriptor* (*extras[])(void) = { const TinyBlocks_LibraryDescriptor* (*extras[])(void) = {
+29
View File
@@ -0,0 +1,29 @@
# Pegue as moedas (jogo 3D em blocos)
Um cubo azul anda numa arena com as setas do teclado; pegue as moedas
douradas (elas giram e reaparecem em outro lugar) e fuja das bolas
vermelhas, que andam mais rápido a cada moeda. Encostou numa bola: fim de
jogo.
- `moedas.sb`: o programa na notação do fórum (Abrir aceita `.sb`, ou
"Colar scratchblocks", ou o MCP com `add_scratchblocks`).
- `moedas.json`: o mesmo programa como projeto do editor.
## Como é feito
Tudo com os blocos da categoria **3D** (`tinyblocks-3d`):
- `nova cena 3D`, `crie cubo/esfera/plano/cilindro [nome] em x y z`,
`mude o tamanho de`, `mude a cor de`, `gire ... por/para`;
- `objeto [a] encosta em [b]` (caixas que se cruzam) para pegar moedas e
perder;
- `câmera em x y z olhando para x y z`, seguindo o jogador;
- a cada volta, `desenhe (imagem da cena de 480 por 360)` no palco.
Os laços de montagem e de atualização ficam em blocos próprios ("monte a
fase", "atualize as moedas", "atualize as bolas"): o corpo de um bloco
próprio roda de uma vez, então a cena inteira muda num quadro só.
O texto no canto de baixo mostra quem desenhou o quadro: `vulkan`,
`opengl` ou `software`, com a placa. A escolha é automática (Vulkan, depois
OpenGL, depois software); `use o renderizador [opengl]` força um.
File diff suppressed because it is too large. Load diff
+98
View File
@@ -0,0 +1,98 @@
when flag clicked
nova cena 3D
cor do céu [#87c7fa]
luz vindo de x (0.5) y (1) z (0.3)
monte a fase
mude [pontos v] para (0)
mude [vivo v] para (1)
zere o cronômetro
repita até que <(vivo) = (0)>
ande com as setas
atualize as moedas
atualize as bolas
câmera em x (x do objeto [jogador]) y (8) z ((z do objeto [jogador]) + (9)) olhando para x (x do objeto [jogador]) y (0) z ((z do objeto [jogador]) - (1))
apague tudo
desenhe (imagem da cena de (480) por (360)) em x (0) y (0) escala (1)
escreva (junte [moedas: ] com (pontos)) no palco em x (-220) y (160)
escreva (renderizador da cena) no palco em x (-220) y (-170)
end
mude a cor de [jogador] para [preto]
apague tudo
desenhe (imagem da cena de (480) por (360)) em x (0) y (0) escala (1)
escreva (junte [Fim de jogo! Moedas: ] com (pontos)) no palco em x (-110) y (0)
define monte a fase
crie plano [chão] em x (0) y (0) z (0)
mude o tamanho de [chão] para x (20) y (1) z (20)
mude a cor de [chão] para [#5aa05a]
crie cubo [parede1] em x (0) y (0.5) z (-10)
mude o tamanho de [parede1] para x (20.4) y (1) z (0.4)
crie cubo [parede2] em x (0) y (0.5) z (10)
mude o tamanho de [parede2] para x (20.4) y (1) z (0.4)
crie cubo [parede3] em x (-10) y (0.5) z (0)
mude o tamanho de [parede3] para x (0.4) y (1) z (20.4)
crie cubo [parede4] em x (10) y (0.5) z (0)
mude o tamanho de [parede4] para x (0.4) y (1) z (20.4)
mude [i v] para (1)
repita (4) vezes
mude a cor de (junte [parede] com (i)) para [cinza]
adicione (1) a [i v]
end
crie cubo [jogador] em x (0) y (0.5) z (8)
mude a cor de [jogador] para [azul]
mude [i v] para (1)
repita (6) vezes
crie cilindro (junte [moeda] com (i)) em x (0) y (0.6) z (0)
mude o tamanho de (junte [moeda] com (i)) para x (0.8) y (0.15) z (0.8)
gire (junte [moeda] com (i)) para x (90) y (0) z (0) graus
mude a cor de (junte [moeda] com (i)) para [dourado]
sorteie o lugar de (junte [moeda] com (i))
adicione (1) a [i v]
end
mude [i v] para (1)
repita (3) vezes
crie esfera (junte [bola] com (i)) em x (0) y (0.6) z (-6)
mude o tamanho de (junte [bola] com (i)) para x (1.2) y (1.2) z (1.2)
mude a cor de (junte [bola] com (i)) para [vermelho]
adicione (1) a [i v]
end
define sorteie o lugar de (nome)
mova (nome) para x (número aleatório entre (-8) e (8)) y (0.6) z (número aleatório entre (-8) e (8))
define ande com as setas
se <tecla [seta para esquerda] pressionada?> então
mova [jogador] por x (-0.2) y (0) z (0)
end
se <tecla [seta para direita] pressionada?> então
mova [jogador] por x (0.2) y (0) z (0)
end
se <tecla [seta para cima] pressionada?> então
mova [jogador] por x (0) y (0) z (-0.2)
end
se <tecla [seta para baixo] pressionada?> então
mova [jogador] por x (0) y (0) z (0.2)
end
mova [jogador] para x (limite (x do objeto [jogador]) entre (-9.2) e (9.2)) y (0.5) z (limite (z do objeto [jogador]) entre (-9.2) e (9.2))
define atualize as moedas
mude [i v] para (1)
repita (6) vezes
gire (junte [moeda] com (i)) por x (0) y (5) z (0) graus
se <objeto [jogador] encosta em (junte [moeda] com (i))> então
adicione (1) a [pontos v]
sorteie o lugar de (junte [moeda] com (i))
end
adicione (1) a [i v]
end
define atualize as bolas
mude [i v] para (1)
mude [t v] para ((cronômetro) * ((20) + ((5) * (pontos))))
repita (3) vezes
mova (junte [bola] com (i)) para x ((7) * (seno de ((t) + ((i) * (120))))) y (0.6) z ((7) * (cosseno de (((t) * (0.7)) + ((i) * (75)))))
se <objeto [jogador] encosta em (junte [bola] com (i))> então
mude [vivo v] para (0)
end
adicione (1) a [i v]
end
+30
View File
@@ -0,0 +1,30 @@
# Makefile da library 3d (categoria "3D")
# Constroi build/libtinyblocks-3d.a e build/libtinyblocks-3d.so
CC := gcc
BUILD := build
CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
SRCS := src/tb_3d.c
OBJS := $(BUILD)/tb_3d.o
LIB_A := $(BUILD)/libtinyblocks-3d.a
LIB_SO := $(BUILD)/libtinyblocks-3d.so
.PHONY: all static shared clean
all: static shared
static: $(LIB_A)
shared: $(LIB_SO)
$(BUILD)/%.o: src/%.c $(wildcard include/*.h) $(wildcard src/*.h)
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
$(LIB_A): $(OBJS)
ar rcs $@ $^
$(LIB_SO): $(OBJS)
$(CC) -shared -o $@ $^ -lm
clean:
$(RM) -r $(BUILD)
+89
View File
@@ -0,0 +1,89 @@
/*
* 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.
*/
#ifndef TINYBLOCKS_3D_H
#define TINYBLOCKS_3D_H
#include <stdbool.h>
#include <stdint.h>
#include <tinyblocks/tinyblocks.h>
#define TB_3D_LIB "tinyblocks-3d"
#define TB_3D_RENDERER_VERSION 1
/* 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. */
typedef struct Tb3dMesh {
int id; /* 1.. (estavel enquanto a library viver) */
const float* verts; /* x y z nx ny nz, vcount vezes */
int vcount;
const uint32_t* index; /* 3 por triangulo */
int icount;
} Tb3dMesh;
/* Um objeto a desenhar */
typedef struct Tb3dDraw {
const Tb3dMesh* mesh;
float model[16]; /* objeto -> mundo */
float mvp[16]; /* viewproj * model (ja calculada: os
renderizadores nao precisam de matematica) */
float normal[9]; /* matriz das normais (3x3, colunas) */
float color[4]; /* RGBA 0..1 */
} Tb3dDraw;
/* Um quadro: tudo o que o renderizador precisa */
typedef struct Tb3dFrame {
int width, height;
float view[16]; /* mundo -> camera */
float proj[16]; /* camera -> clip (convencao GL) */
float viewproj[16]; /* proj * view */
float sky[4]; /* cor de fundo */
float light_dir[3]; /* direcao PARA a luz, normalizada */
float ambient; /* 0..1 */
const Tb3dDraw* draws;
int draw_count;
} Tb3dFrame;
/* Renderizador. render escreve width*height*4 bytes RGBA, linha 0 no ALTO. */
typedef struct Tb3dRenderer {
int version; /* TB_3D_RENDERER_VERSION */
const char* name; /* "vulkan", "opengl", "software" */
bool (*available)(void); /* inicia na 1a vez; false = nao da */
bool (*render)(const Tb3dFrame* f, uint8_t* rgba);
const char* (*device)(void); /* placa/driver em uso (texto) */
const char* (*error)(void); /* ultimo erro */
} Tb3dRenderer;
TB_API const TinyBlocks_LibraryDescriptor* tb_3d_get_library(void);
/* O rasterizador em software (tambem usado pelos testes como referencia) */
TB_API const Tb3dRenderer* tb_3d_software_renderer(void);
/* -- matematica (column-major) --- */
TB_API void tb_3d_mat_identity(float m[16]);
TB_API void tb_3d_mat_mul(float out[16], const float a[16], const float b[16]);
TB_API void tb_3d_mat_perspective(float m[16], float fovy_deg, float aspect, float znear, float zfar);
TB_API void tb_3d_mat_look_at(float m[16], const float eye[3], const float at[3], const float up[3]);
#endif /* TINYBLOCKS_3D_H */
+14
View File
@@ -0,0 +1,14 @@
# Metadados da library 3d. Lido pela UI/build sem recompilar o .so.
[library]
name = "tinyblocks-3d"
version = "1.0.0"
category = "3D"
description = "Cena 3D com blocos: cubos, esferas, planos e cilindros, camera, luz e colisao; desenha numa imagem (Vulkan, OpenGL ou software)"
color = [92, 107, 219, 255]
dark = [64, 77, 168, 255]
[build]
sources = ["src/tb_3d.c"]
includes = ["include"]
shared = "build/libtinyblocks-3d.so"
static = "build/libtinyblocks-3d.a"
+712
View File
@@ -0,0 +1,712 @@
/*
* TinyBlocks - tb_3d.c
* A cena 3D (objetos com nome, camera, luz), as malhas fixas, o
* rasterizador em software, a escolha do renderizador e os blocos da
* categoria "3D".
*/
#define _POSIX_C_SOURCE 200809L
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_image.h>
#include "tb_3d.h"
#define PI_F 3.14159265358979f
/* == Matematica (column-major: m[col * 4 + row]) ====================== */
void tb_3d_mat_identity(float m[16]) {
memset(m, 0, 16 * sizeof(float));
m[0] = m[5] = m[10] = m[15] = 1.f;
}
void tb_3d_mat_mul(float out[16], const float a[16], const float b[16]) {
float r[16];
for (int c = 0; c < 4; c++)
for (int i = 0; i < 4; i++) {
float s = 0;
for (int k = 0; k < 4; k++) s += a[k * 4 + i] * b[c * 4 + k];
r[c * 4 + i] = s;
}
memcpy(out, r, sizeof(r));
}
void tb_3d_mat_perspective(float m[16], float fovy_deg, float aspect, float zn, float zf) {
float f = 1.f / tanf(fovy_deg * PI_F / 360.f);
memset(m, 0, 16 * sizeof(float));
m[0] = f / aspect;
m[5] = f;
m[10] = (zf + zn) / (zn - zf);
m[11] = -1.f;
m[14] = 2.f * zf * zn / (zn - zf);
}
static void v3_sub(float o[3], const float a[3], const float b[3]) { o[0] = a[0] - b[0]; o[1] = a[1] - b[1]; o[2] = a[2] - b[2]; }
static void v3_cross(float o[3], const float a[3], const float b[3]) {
float r[3] = { a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] };
memcpy(o, r, sizeof(r));
}
static float v3_dot(const float a[3], const float b[3]) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
static void v3_norm(float v[3]) {
float l = sqrtf(v3_dot(v, v));
if (l > 1e-12f) { v[0] /= l; v[1] /= l; v[2] /= l; }
}
void tb_3d_mat_look_at(float m[16], const float eye[3], const float at[3], const float up[3]) {
float f[3], s[3], u[3];
v3_sub(f, at, eye); v3_norm(f);
v3_cross(s, f, up);
if (v3_dot(s, s) < 1e-10f) { /* olhando reto para cima/baixo */
float alt[3] = { 0, 0, 1 };
v3_cross(s, f, alt);
}
v3_norm(s);
v3_cross(u, s, f);
tb_3d_mat_identity(m);
m[0] = s[0]; m[4] = s[1]; m[8] = s[2];
m[1] = u[0]; m[5] = u[1]; m[9] = u[2];
m[2] = -f[0]; m[6] = -f[1]; m[10] = -f[2];
m[12] = -v3_dot(s, eye); m[13] = -v3_dot(u, eye); m[14] = v3_dot(f, eye);
}
/* Rotacao Y (yaw) * X (pitch) * Z (roll), em graus: a 3x3 em colunas */
static void rot3(float r[9], const float deg[3]) {
float ax = deg[0] * PI_F / 180.f, ay = deg[1] * PI_F / 180.f, az = deg[2] * PI_F / 180.f;
float cx = cosf(ax), sx = sinf(ax), cy = cosf(ay), sy = sinf(ay), cz = cosf(az), sz = sinf(az);
/* Ry*Rx*Rz, linha i coluna j em r[j*3+i] */
float m[3][3] = {
{ cy * cz + sy * sx * sz, -cy * sz + sy * sx * cz, sy * cx },
{ cx * sz, cx * cz, -sx },
{ -sy * cz + cy * sx * sz, sy * sz + cy * sx * cz, cy * cx },
};
for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) r[j * 3 + i] = m[i][j];
}
/* == Malhas fixas (tamanho 1, centradas na origem) ===================== */
typedef struct { float* v; uint32_t* ix; int vn, in, vcap, icap; } MeshBuf;
static void mb_vert(MeshBuf* b, float x, float y, float z, float nx, float ny, float nz) {
if (b->vn == b->vcap) { b->vcap = b->vcap ? b->vcap * 2 : 64; b->v = realloc(b->v, (size_t)b->vcap * 6 * sizeof(float)); }
float* p = b->v + (size_t)b->vn * 6;
p[0] = x; p[1] = y; p[2] = z; p[3] = nx; p[4] = ny; p[5] = nz;
b->vn++;
}
static void mb_tri(MeshBuf* b, int i0, int i1, int i2) {
if (b->in + 3 > b->icap) { b->icap = b->icap ? b->icap * 2 : 96; b->ix = realloc(b->ix, (size_t)b->icap * sizeof(uint32_t)); }
b->ix[b->in++] = (uint32_t)i0; b->ix[b->in++] = (uint32_t)i1; b->ix[b->in++] = (uint32_t)i2;
}
enum { K_CUBE, K_SPHERE, K_PLANE, K_CYLINDER, K_COUNT };
static Tb3dMesh s_mesh[K_COUNT];
static MeshBuf s_mb[K_COUNT];
static void build_cube(MeshBuf* b) {
static const float n[6][3] = { {1,0,0}, {-1,0,0}, {0,1,0}, {0,-1,0}, {0,0,1}, {0,0,-1} };
for (int f = 0; f < 6; f++) {
float N[3] = { n[f][0], n[f][1], n[f][2] }, U[3], V[3];
float a[3] = { fabsf(N[1]) > 0.5f ? 1.f : 0.f, fabsf(N[1]) > 0.5f ? 0.f : 1.f, 0 };
v3_cross(U, N, a); v3_cross(V, N, U); /* U x V = N: frente para fora */
int base = b->vn;
for (int k = 0; k < 4; k++) {
float su = (k == 1 || k == 2) ? 0.5f : -0.5f, sv = (k >= 2) ? 0.5f : -0.5f;
mb_vert(b, N[0] * 0.5f + U[0] * su + V[0] * sv, N[1] * 0.5f + U[1] * su + V[1] * sv,
N[2] * 0.5f + U[2] * su + V[2] * sv, N[0], N[1], N[2]);
}
mb_tri(b, base, base + 1, base + 2);
mb_tri(b, base, base + 2, base + 3);
}
}
static void build_sphere(MeshBuf* b, int seg, int ring) {
for (int r = 0; r <= ring; r++) {
float th = PI_F * r / ring;
for (int s = 0; s <= seg; s++) {
float ph = 2 * PI_F * s / seg;
float x = sinf(th) * cosf(ph), y = cosf(th), z = sinf(th) * sinf(ph);
mb_vert(b, x * 0.5f, y * 0.5f, z * 0.5f, x, y, z);
}
}
for (int r = 0; r < ring; r++)
for (int s = 0; s < seg; s++) {
int a = r * (seg + 1) + s, c = a + seg + 1;
mb_tri(b, a, a + 1, c);
mb_tri(b, a + 1, c + 1, c);
}
}
static void build_plane(MeshBuf* b) {
mb_vert(b, -0.5f, 0, -0.5f, 0, 1, 0);
mb_vert(b, -0.5f, 0, 0.5f, 0, 1, 0);
mb_vert(b, 0.5f, 0, 0.5f, 0, 1, 0);
mb_vert(b, 0.5f, 0, -0.5f, 0, 1, 0);
mb_tri(b, 0, 1, 2);
mb_tri(b, 0, 2, 3);
}
static void build_cylinder(MeshBuf* b, int seg) {
for (int s = 0; s <= seg; s++) { /* lateral */
float ph = 2 * PI_F * s / seg, x = cosf(ph), z = sinf(ph);
mb_vert(b, x * 0.5f, -0.5f, z * 0.5f, x, 0, z);
mb_vert(b, x * 0.5f, 0.5f, z * 0.5f, x, 0, z);
}
for (int s = 0; s < seg; s++) {
int a = s * 2;
mb_tri(b, a, a + 1, a + 2);
mb_tri(b, a + 1, a + 3, a + 2);
}
for (int cap = 0; cap < 2; cap++) { /* tampas */
float y = cap ? 0.5f : -0.5f, ny = cap ? 1.f : -1.f;
int c = b->vn;
mb_vert(b, 0, y, 0, 0, ny, 0);
for (int s = 0; s <= seg; s++) {
float ph = 2 * PI_F * s / seg;
mb_vert(b, cosf(ph) * 0.5f, y, sinf(ph) * 0.5f, 0, ny, 0);
}
for (int s = 0; s < seg; s++) {
if (cap) mb_tri(b, c, c + 2 + s, c + 1 + s);
else mb_tri(b, c, c + 1 + s, c + 2 + s);
}
}
}
static void meshes_build(void) {
if (s_mesh[0].id) return;
build_cube(&s_mb[K_CUBE]);
build_sphere(&s_mb[K_SPHERE], 20, 14);
build_plane(&s_mb[K_PLANE]);
build_cylinder(&s_mb[K_CYLINDER], 24);
for (int k = 0; k < K_COUNT; k++)
s_mesh[k] = (Tb3dMesh){ k + 1, s_mb[k].v, s_mb[k].vn, s_mb[k].ix, s_mb[k].in };
}
static void meshes_free(void) {
for (int k = 0; k < K_COUNT; k++) { free(s_mb[k].v); free(s_mb[k].ix); memset(&s_mb[k], 0, sizeof(s_mb[k])); }
memset(s_mesh, 0, sizeof(s_mesh));
}
/* == Cena =============================================================== */
typedef struct {
char name[48];
int kind;
float pos[3], rot[3], scale[3], color[4];
bool visible;
} Obj;
#define MAX_OBJS 4096
static struct {
Obj* o;
int n, cap;
float eye[3], at[3], fov;
float light[3], ambient, sky[4];
char want[16]; /* "" = automatico */
char used[64], err[160];
} S;
static void scene_reset(void) {
S.n = 0;
S.eye[0] = 0; S.eye[1] = 6; S.eye[2] = 10;
S.at[0] = S.at[1] = S.at[2] = 0;
S.fov = 60;
S.light[0] = 0.4f; S.light[1] = 1.f; S.light[2] = 0.6f;
v3_norm(S.light);
S.ambient = 0.35f;
S.sky[0] = 0.53f; S.sky[1] = 0.78f; S.sky[2] = 0.98f; S.sky[3] = 1;
}
static Obj* find(const char* name) {
for (int i = 0; i < S.n; i++) if (!strcmp(S.o[i].name, name)) return &S.o[i];
return NULL;
}
/* Cores: nomes em portugues ou #rrggbb */
static bool color_of(const char* c, float out[4]) {
static const struct { const char* n; uint32_t rgb; } tab[] = {
{"vermelho", 0xe03131}, {"verde", 0x2f9e44}, {"azul", 0x1c7ed6}, {"amarelo", 0xfcc419},
{"laranja", 0xf76707}, {"roxo", 0x7048e8}, {"rosa", 0xe64980}, {"ciano", 0x15aabf},
{"marrom", 0x8b5a2b}, {"cinza", 0x868e96}, {"branco", 0xf8f9fa}, {"preto", 0x212529},
{"dourado", 0xf0b400},
};
while (c && isspace((unsigned char)*c)) c++;
if (!c || !*c) return false;
uint32_t rgb = 0;
bool ok = false;
if (c[0] == '#' && strlen(c) >= 7) { rgb = (uint32_t)strtoul(c + 1, NULL, 16); ok = true; }
for (size_t i = 0; !ok && i < sizeof(tab) / sizeof(tab[0]); i++)
if (!strcasecmp(c, tab[i].n)) { rgb = tab[i].rgb; ok = true; }
if (!ok) return false;
out[0] = ((rgb >> 16) & 255) / 255.f; out[1] = ((rgb >> 8) & 255) / 255.f;
out[2] = (rgb & 255) / 255.f; out[3] = 1;
return true;
}
/* model = T * R * S; normal = R * S^-1 */
static void obj_matrices(const Obj* o, float model[16], float normal[9]) {
float r[9];
rot3(r, o->rot);
tb_3d_mat_identity(model);
for (int j = 0; j < 3; j++)
for (int i = 0; i < 3; i++) model[j * 4 + i] = r[j * 3 + i] * o->scale[j];
model[12] = o->pos[0]; model[13] = o->pos[1]; model[14] = o->pos[2];
for (int j = 0; j < 3; j++) {
float inv = fabsf(o->scale[j]) > 1e-6f ? 1.f / o->scale[j] : 0.f;
for (int i = 0; i < 3; i++) normal[j * 3 + i] = r[j * 3 + i] * inv;
}
}
/* Caixa alinhada aos eixos do objeto no mundo (para "encosta em") */
static void obj_aabb(const Obj* o, float lo[3], float hi[3]) {
float r[9];
rot3(r, o->rot);
float h[3] = { fabsf(o->scale[0]) * 0.5f, fabsf(o->scale[1]) * 0.5f, fabsf(o->scale[2]) * 0.5f };
if (o->kind == K_PLANE) h[1] = 0.01f;
for (int i = 0; i < 3; i++) {
float e = 0;
for (int j = 0; j < 3; j++) e += fabsf(r[j * 3 + i]) * h[j];
lo[i] = o->pos[i] - e; hi[i] = o->pos[i] + e;
}
}
/* Monta o quadro (a lista de desenhos vive ate o proximo quadro) */
static Tb3dDraw* s_draws;
static int s_draws_cap;
static bool frame_build(Tb3dFrame* f, int w, int h) {
meshes_build();
memset(f, 0, sizeof(*f));
f->width = w; f->height = h;
float up[3] = { 0, 1, 0 };
tb_3d_mat_look_at(f->view, S.eye, S.at, up);
tb_3d_mat_perspective(f->proj, S.fov, (float)w / (float)h, 0.1f, 500.f);
tb_3d_mat_mul(f->viewproj, f->proj, f->view);
memcpy(f->sky, S.sky, sizeof(f->sky));
memcpy(f->light_dir, S.light, sizeof(f->light_dir));
f->ambient = S.ambient;
if (S.n > s_draws_cap) {
Tb3dDraw* d = realloc(s_draws, (size_t)S.n * sizeof(*d));
if (!d) return false;
s_draws = d; s_draws_cap = S.n;
}
int n = 0;
for (int i = 0; i < S.n; i++) {
const Obj* o = &S.o[i];
if (!o->visible) continue;
Tb3dDraw* d = &s_draws[n++];
d->mesh = &s_mesh[o->kind];
obj_matrices(o, d->model, d->normal);
tb_3d_mat_mul(d->mvp, f->viewproj, d->model);
memcpy(d->color, o->color, sizeof(d->color));
}
f->draws = s_draws;
f->draw_count = n;
return true;
}
/* == Rasterizador em software ======================================== */
typedef struct { float x, y, z, w, r, g, b; } CV; /* vertice no clip + cor */
static float* s_zbuf;
static size_t s_zcap;
static void raster_tri(const CV* a, const CV* b, const CV* c, int W, int H, uint8_t* px) {
float ax = (a->x / a->w * 0.5f + 0.5f) * W, ay = (0.5f - a->y / a->w * 0.5f) * H, az = a->z / a->w;
float bx = (b->x / b->w * 0.5f + 0.5f) * W, by = (0.5f - b->y / b->w * 0.5f) * H, bz = b->z / b->w;
float cx = (c->x / c->w * 0.5f + 0.5f) * W, cy = (0.5f - c->y / c->w * 0.5f) * H, cz = c->z / c->w;
float area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
if (fabsf(area) < 1e-8f) return;
int x0 = (int)floorf(fminf(ax, fminf(bx, cx))), x1 = (int)ceilf(fmaxf(ax, fmaxf(bx, cx)));
int y0 = (int)floorf(fminf(ay, fminf(by, cy))), y1 = (int)ceilf(fmaxf(ay, fmaxf(by, cy)));
if (x0 < 0) x0 = 0;
if (y0 < 0) y0 = 0;
if (x1 > W) x1 = W;
if (y1 > H) y1 = H;
float inv = 1.f / area;
for (int y = y0; y < y1; y++) {
float py = y + 0.5f;
for (int x = x0; x < x1; x++) {
float pxf = x + 0.5f;
float w0 = ((bx - pxf) * (cy - py) - (by - py) * (cx - pxf)) * inv;
float w1 = ((cx - pxf) * (ay - py) - (cy - py) * (ax - pxf)) * inv;
float w2 = 1.f - w0 - w1;
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
float z = w0 * az + w1 * bz + w2 * cz;
if (z < -1.f || z > 1.f) continue;
float* zb = &s_zbuf[(size_t)y * W + x];
if (z >= *zb) continue;
*zb = z;
uint8_t* p = px + ((size_t)y * W + x) * 4;
float r = w0 * a->r + w1 * b->r + w2 * c->r;
float g = w0 * a->g + w1 * b->g + w2 * c->g;
float bl = w0 * a->b + w1 * b->b + w2 * c->b;
p[0] = (uint8_t)(fminf(r, 1.f) * 255.f + .5f);
p[1] = (uint8_t)(fminf(g, 1.f) * 255.f + .5f);
p[2] = (uint8_t)(fminf(bl, 1.f) * 255.f + .5f);
p[3] = 255;
}
}
}
/* Corta o triangulo no plano de perto (z + w >= 0) e desenha o resultado */
static void clip_and_raster(const CV in[3], int W, int H, uint8_t* px) {
CV out[4];
int n = 0;
for (int i = 0; i < 3; i++) {
const CV* p = &in[i];
const CV* q = &in[(i + 1) % 3];
float dp = p->z + p->w, dq = q->z + q->w;
if (dp >= 0) out[n++] = *p;
if ((dp >= 0) != (dq >= 0)) {
float t = dp / (dp - dq);
CV m;
m.x = p->x + (q->x - p->x) * t; m.y = p->y + (q->y - p->y) * t;
m.z = p->z + (q->z - p->z) * t; m.w = p->w + (q->w - p->w) * t;
m.r = p->r + (q->r - p->r) * t; m.g = p->g + (q->g - p->g) * t; m.b = p->b + (q->b - p->b) * t;
out[n++] = m;
}
}
for (int i = 1; i + 1 < n; i++) raster_tri(&out[0], &out[i], &out[i + 1], W, H, 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 };
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 };
for (int i = 0; i < 3; i++)
for (int k = 0; k < 3; k++) n[i] += d->normal[k * 3 + i] * v[3 + k];
v3_norm(n);
float lam = v3_dot(n, f->light_dir);
float I = f->ambient + (1.f - f->ambient) * (lam > 0 ? lam : 0);
o->x = c[0]; o->y = c[1]; o->z = c[2]; o->w = c[3];
o->r = d->color[0] * I; o->g = d->color[1] * I; o->b = d->color[2] * I;
}
static bool sw_available(void) { return true; }
static const char* sw_device(void) { return "CPU"; }
static const char* sw_error(void) { return ""; }
static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
int W = f->width, H = f->height;
size_t np = (size_t)W * H;
if (np > s_zcap) {
float* z = realloc(s_zbuf, np * sizeof(float));
if (!z) return false;
s_zbuf = z; s_zcap = np;
}
uint8_t sky[4] = { (uint8_t)(f->sky[0] * 255.f + .5f), (uint8_t)(f->sky[1] * 255.f + .5f),
(uint8_t)(f->sky[2] * 255.f + .5f), 255 };
for (size_t i = 0; i < np; i++) { memcpy(px + i * 4, sky, 4); s_zbuf[i] = 1.f; }
CV* cv = NULL;
int cv_cap = 0;
for (int di = 0; di < f->draw_count; di++) {
const Tb3dDraw* d = &f->draws[di];
const Tb3dMesh* m = d->mesh;
if (m->vcount > cv_cap) {
CV* p = realloc(cv, (size_t)m->vcount * sizeof(CV));
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 * 6, &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;
clip_and_raster(tri, W, H, px);
}
}
free(cv);
return true;
}
static const Tb3dRenderer s_software = {
TB_3D_RENDERER_VERSION, "software", sw_available, sw_render, sw_device, sw_error };
const Tb3dRenderer* tb_3d_software_renderer(void) { return &s_software; }
/* == Escolha do renderizador ========================================= */
static const Tb3dRenderer* renderer_of(TinyBlocks* rt, const char* lib_name) {
TinyBlocks_LibraryBlock* lib = tb_rt_find_library(rt, lib_name);
const Tb3dRenderer* r = lib ? lib->lib_userdata : NULL;
if (!r || r->version != TB_3D_RENDERER_VERSION) return NULL;
return r->available() ? r : NULL;
}
/* Na ordem: o pedido (ou Vulkan, OpenGL), e o software se nada servir */
static const Tb3dRenderer* pick(TinyBlocks* rt) {
if (!strcmp(S.want, "software")) return &s_software;
if (!strcmp(S.want, "vulkan")) { const Tb3dRenderer* r = renderer_of(rt, "tinyblocks-vk"); return r ? r : &s_software; }
if (!strcmp(S.want, "opengl")) { const Tb3dRenderer* r = renderer_of(rt, "tinyblocks-gl"); return r ? r : &s_software; }
const Tb3dRenderer* r = renderer_of(rt, "tinyblocks-vk");
if (!r) r = renderer_of(rt, "tinyblocks-gl");
return r ? r : &s_software;
}
/* == Blocos =========================================================== */
static const char* name_in(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { return tb_block_input_text(self, rt, i); }
static Obj* need(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
const char* n = name_in(self, rt, i);
Obj* o = find(n);
if (!o) tinyblocks_set_error(rt, "não existe o objeto 3D '%s'", n);
return o;
}
static void vec_in(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t first, float v[3]) {
for (int k = 0; k < 3; k++) v[k] = (float)tb_block_input_number(self, rt, first + (uint32_t)k, 0);
}
static void eval_scene(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; scene_reset(); self->dirty = false; }
static void create(TinyBlocks_Block* self, TinyBlocks* rt, int kind) {
const char* n = name_in(self, rt, 0);
self->dirty = false;
if (!n[0]) { tinyblocks_set_error(rt, "dê um nome ao objeto 3D"); return; }
Obj* o = find(n);
if (!o) {
if (S.n >= MAX_OBJS) { tinyblocks_set_error(rt, "a cena já tem %d objetos", MAX_OBJS); return; }
if (S.n == S.cap) {
int nc = S.cap ? S.cap * 2 : 64;
Obj* p = realloc(S.o, (size_t)nc * sizeof(*p));
if (!p) { tinyblocks_set_error(rt, "sem memória"); return; }
S.o = p; S.cap = nc;
}
o = &S.o[S.n++];
memset(o, 0, sizeof(*o));
snprintf(o->name, sizeof(o->name), "%s", n);
}
o->kind = kind;
vec_in(self, rt, 1, o->pos);
o->rot[0] = o->rot[1] = o->rot[2] = 0;
o->scale[0] = o->scale[1] = o->scale[2] = 1;
if (kind == K_PLANE) { o->scale[0] = o->scale[2] = 10; }
o->color[0] = o->color[1] = o->color[2] = 0.8f; o->color[3] = 1;
o->visible = true;
}
static void eval_cube(TinyBlocks_Block* s, TinyBlocks* rt) { create(s, rt, K_CUBE); }
static void eval_sphere(TinyBlocks_Block* s, TinyBlocks* rt) { create(s, rt, K_SPHERE); }
static void eval_plane(TinyBlocks_Block* s, TinyBlocks* rt) { create(s, rt, K_PLANE); }
static void eval_cylinder(TinyBlocks_Block* s, TinyBlocks* rt) { create(s, rt, K_CYLINDER); }
#define OBJ_CMD(fname, body) \
static void fname(TinyBlocks_Block* self, TinyBlocks* rt) { \
self->dirty = false; Obj* o = need(self, rt, 0); if (!o) return; float v[3]; (void)v; body }
OBJ_CMD(eval_move_to, vec_in(self, rt, 1, v); memcpy(o->pos, v, sizeof(v));)
OBJ_CMD(eval_move_by, vec_in(self, rt, 1, v); for (int k = 0; k < 3; k++) o->pos[k] += v[k];)
OBJ_CMD(eval_rot_to, vec_in(self, rt, 1, v); memcpy(o->rot, v, sizeof(v));)
OBJ_CMD(eval_rot_by, vec_in(self, rt, 1, v); for (int k = 0; k < 3; k++) o->rot[k] = fmodf(o->rot[k] + v[k], 360.f);)
OBJ_CMD(eval_scale, vec_in(self, rt, 1, v); memcpy(o->scale, v, sizeof(v));)
OBJ_CMD(eval_show, o->visible = true;)
OBJ_CMD(eval_hide, o->visible = false;)
OBJ_CMD(eval_color, if (!color_of(name_in(self, rt, 1), o->color))
tinyblocks_set_error(rt, "cor desconhecida '%s' (use um nome ou #rrggbb)", name_in(self, rt, 1));)
static void eval_delete(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = find(name_in(self, rt, 0));
if (o) { int i = (int)(o - S.o); memmove(o, o + 1, (size_t)(S.n - i - 1) * sizeof(*o)); S.n--; }
}
static void coord(TinyBlocks_Block* self, TinyBlocks* rt, int axis) {
self->dirty = false;
Obj* o = need(self, rt, 0);
if (o) tb_block_set_output(self, 0, tb_value_real(o->pos[axis]));
}
static void eval_x(TinyBlocks_Block* s, TinyBlocks* rt) { coord(s, rt, 0); }
static void eval_y(TinyBlocks_Block* s, TinyBlocks* rt) { coord(s, rt, 1); }
static void eval_z(TinyBlocks_Block* s, TinyBlocks* rt) { coord(s, rt, 2); }
static void eval_exists(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
tb_block_set_output(self, 0, tb_value_integer(find(name_in(self, rt, 0)) != NULL));
}
static void eval_touching(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* a = need(self, rt, 0);
Obj* b = a ? need(self, rt, 1) : NULL;
if (!a || !b) return;
float al[3], ah[3], bl[3], bh[3];
obj_aabb(a, al, ah); obj_aabb(b, bl, bh);
bool hit = a != b && a->visible && b->visible;
for (int k = 0; hit && k < 3; k++) hit = al[k] <= bh[k] && bl[k] <= ah[k];
tb_block_set_output(self, 0, tb_value_integer(hit));
}
static void eval_distance(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* a = need(self, rt, 0);
Obj* b = a ? need(self, rt, 1) : NULL;
if (!a || !b) return;
float d[3];
v3_sub(d, a->pos, b->pos);
tb_block_set_output(self, 0, tb_value_real(sqrtf(v3_dot(d, d))));
}
static void eval_camera(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
vec_in(self, rt, 0, S.eye);
vec_in(self, rt, 3, S.at);
}
static void eval_fov(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
float f = (float)tb_block_input_number(self, rt, 0, 60);
S.fov = f < 5 ? 5 : f > 170 ? 170 : f;
}
static void eval_light(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
float v[3];
vec_in(self, rt, 0, v);
if (v3_dot(v, v) < 1e-12f) { tinyblocks_set_error(rt, "a direção da luz não pode ser (0, 0, 0)"); return; }
v3_norm(v);
memcpy(S.light, v, sizeof(v));
}
static void eval_ambient(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
float a = (float)tb_block_input_number(self, rt, 0, 0.35);
S.ambient = a < 0 ? 0 : a > 1 ? 1 : a;
}
static void eval_sky(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
if (!color_of(name_in(self, rt, 0), S.sky)) tinyblocks_set_error(rt, "cor desconhecida '%s'", name_in(self, rt, 0));
}
static void eval_use(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
const char* w = name_in(self, rt, 0);
if (!strcasecmp(w, "vulkan") || !strcasecmp(w, "vk")) snprintf(S.want, sizeof(S.want), "vulkan");
else if (!strcasecmp(w, "opengl") || !strcasecmp(w, "gl")) snprintf(S.want, sizeof(S.want), "opengl");
else if (!strcasecmp(w, "software")) snprintf(S.want, sizeof(S.want), "software");
else S.want[0] = 0;
}
static void eval_image(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
int w = (int)tb_block_input_integer(self, rt, 0, 480), h = (int)tb_block_input_integer(self, rt, 1, 360);
if (w < 8 || h < 8 || w > 4096 || h > 4096) { tinyblocks_set_error(rt, "tamanho da imagem fora de 8..4096"); return; }
Tb3dFrame f;
if (!frame_build(&f, w, h)) { tinyblocks_set_error(rt, "sem memória"); return; }
TinyBlocks_Image* img = tb_image_new(w, h, 4);
if (!img) { tinyblocks_set_error(rt, "sem memória"); return; }
const Tb3dRenderer* r = pick(rt);
if (!r->render(&f, tb_image_data(img))) {
snprintf(S.err, sizeof(S.err), "%s: %s", r->name, r->error());
r = &s_software; /* nao deixa o quadro vazio */
r->render(&f, tb_image_data(img));
}
snprintf(S.used, sizeof(S.used), "%s (%s)", r->name, r->device());
tb_block_set_output(self, 0, tb_value_image(img));
tb_image_release(img);
}
static void eval_renderer(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
if (!S.used[0]) { const Tb3dRenderer* r = pick(rt); snprintf(S.used, sizeof(S.used), "%s (%s)", r->name, r->device()); }
tb_block_set_output(self, 0, tb_value_text(S.used));
}
static void eval_count(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt; self->dirty = false;
tb_block_set_output(self, 0, tb_value_integer(S.n));
}
/* == Registro ========================================================= */
enum { O_NONE, O_IMAGE, O_REAL, O_BOOL, O_TEXT, O_INT };
typedef struct {
const char* name; const char* label; const char* defs;
int nin; TinyBlocks_ValueKind in[6];
int out;
void (*fn)(TinyBlocks_Block*, TinyBlocks*); const char* fname; const char* doc;
} Spec;
#define T TB_VALUE_TEXT
#define I TB_VALUE_INTEGER
#define R TB_VALUE_REAL
#define S_(fn) fn, #fn
#define XYZ "|0|0|0"
static const Spec s_specs[] = {
{ "3D.Scene", "nova cena 3D", "", 0, {T}, O_NONE, S_(eval_scene), "Apaga os objetos e volta câmera, luz e céu ao padrão" },
{ "3D.Cube", "crie cubo %1 em x %2 y %3 z %4", "jogador|0|0.5|0", 4, {T,R,R,R}, O_NONE, S_(eval_cube), "Cubo de lado 1 com esse nome (troca se já existir)" },
{ "3D.Sphere", "crie esfera %1 em x %2 y %3 z %4", "bola|0|0.5|0", 4, {T,R,R,R}, O_NONE, S_(eval_sphere), "Esfera de diâmetro 1" },
{ "3D.Plane", "crie plano %1 em x %2 y %3 z %4", "chão" XYZ, 4, {T,R,R,R}, O_NONE, S_(eval_plane), "Plano deitado de 10 por 10" },
{ "3D.Cylinder", "crie cilindro %1 em x %2 y %3 z %4", "moeda|0|0.5|0", 4, {T,R,R,R}, O_NONE, S_(eval_cylinder), "Cilindro em pé, diâmetro 1 e altura 1" },
{ "3D.MoveTo", "mova %1 para x %2 y %3 z %4", "jogador|0|0.5|0", 4, {T,R,R,R}, O_NONE, S_(eval_move_to), "Põe o objeto nessa posição" },
{ "3D.MoveBy", "mova %1 por x %2 y %3 z %4", "jogador|0|0|0.1", 4, {T,R,R,R}, O_NONE, S_(eval_move_by), "Soma à posição do objeto" },
{ "3D.RotateTo", "gire %1 para x %2 y %3 z %4 graus", "jogador|0|45|0", 4, {T,R,R,R}, O_NONE, S_(eval_rot_to), "Rotação nos eixos x, y e z (em graus)" },
{ "3D.RotateBy", "gire %1 por x %2 y %3 z %4 graus", "jogador|0|5|0", 4, {T,R,R,R}, O_NONE, S_(eval_rot_by), "Soma à rotação do objeto" },
{ "3D.Scale", "mude o tamanho de %1 para x %2 y %3 z %4", "chão|20|1|20", 4, {T,R,R,R}, O_NONE, S_(eval_scale), "Escala do objeto em cada eixo" },
{ "3D.Color", "mude a cor de %1 para %2", "jogador|vermelho", 2, {T,T}, O_NONE, S_(eval_color), "Cor por nome (vermelho, azul, dourado...) ou #rrggbb" },
{ "3D.Show", "mostre o objeto %1", "jogador", 1, {T}, O_NONE, S_(eval_show), "Volta a desenhar o objeto" },
{ "3D.Hide", "esconda o objeto %1", "jogador", 1, {T}, O_NONE, S_(eval_hide), "Deixa de desenhar o objeto (e ele não encosta)" },
{ "3D.Delete", "apague o objeto %1", "jogador", 1, {T}, O_NONE, S_(eval_delete), "Tira o objeto da cena" },
{ "3D.X", "x do objeto %1", "jogador", 1, {T}, O_REAL, S_(eval_x), "Posição x" },
{ "3D.Y", "y do objeto %1", "jogador", 1, {T}, O_REAL, S_(eval_y), "Posição y" },
{ "3D.Z", "z do objeto %1", "jogador", 1, {T}, O_REAL, S_(eval_z), "Posição z" },
{ "3D.Exists", "existe o objeto %1?", "jogador", 1, {T}, O_BOOL, S_(eval_exists), "Verdadeiro se há um objeto com esse nome" },
{ "3D.Touching", "objeto %1 encosta em %2", "jogador|moeda", 2, {T,T}, O_BOOL, S_(eval_touching), "As caixas dos dois objetos se cruzam?" },
{ "3D.Distance", "distância entre %1 e %2", "jogador|moeda", 2, {T,T}, O_REAL, S_(eval_distance), "Distância entre os centros" },
{ "3D.Camera", "câmera em x %1 y %2 z %3 olhando para x %4 y %5 z %6", "0|6|10|0|0|0", 6, {R,R,R,R,R,R}, O_NONE, S_(eval_camera), "Posição da câmera e o ponto para onde ela olha" },
{ "3D.Fov", "campo de visão da câmera %1 graus", "60", 1, {R}, O_NONE, S_(eval_fov), "Ângulo vertical que a câmera enxerga" },
{ "3D.Light", "luz vindo de x %1 y %2 z %3", "0.4|1|0.6", 3, {R,R,R}, O_NONE, S_(eval_light), "Direção de onde vem a luz do sol" },
{ "3D.Ambient", "luz ambiente %1", "0.35", 1, {R}, O_NONE, S_(eval_ambient), "Claridade das partes na sombra (0 a 1)" },
{ "3D.Sky", "cor do céu %1", "#87c7fa", 1, {T}, O_NONE, S_(eval_sky), "Cor do fundo" },
{ "3D.Image", "imagem da cena de %1 por %2", "480|360", 2, {I,I}, O_IMAGE, S_(eval_image), "Desenha a cena numa imagem (use com \"desenhe\")" },
{ "3D.Use", "use o renderizador %1", "automático", 1, {T}, O_NONE, S_(eval_use), "vulkan, opengl, software ou automático" },
{ "3D.Renderer", "renderizador da cena", "", 0, {T}, O_TEXT, S_(eval_renderer), "Quem desenhou o último quadro (e em qual placa)" },
{ "3D.Count", "número de objetos 3D", "", 0, {T}, O_INT, S_(eval_count), "Quantos objetos a cena tem" },
};
#undef T
#undef I
#undef R
static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_Category cat = { "3D", {0.36f, 0.42f, 0.86f, 1.f}, {0.25f, 0.30f, 0.66f, 1.f} };
tb_library_set_category(lib, &cat);
meshes_build();
scene_reset();
lib->lib_userdata = (void*)&s_software;
static const char* names[] = { "a", "b", "c", "d", "e", "f" };
for (size_t i = 0; i < sizeof(s_specs) / sizeof(s_specs[0]); i++) {
const Spec* sp = &s_specs[i];
TinyBlocks_SlotDesc in[6], out[1];
for (int k = 0; k < sp->nin; k++) in[k] = (TinyBlocks_SlotDesc){ names[k], sp->in[k] };
switch (sp->out) {
case O_IMAGE: out[0] = (TinyBlocks_SlotDesc){ "imagem", TB_VALUE_IMAGE }; break;
case O_REAL: out[0] = (TinyBlocks_SlotDesc){ "valor", TB_VALUE_REAL }; break;
case O_BOOL: out[0] = (TinyBlocks_SlotDesc){ "sim?", TB_VALUE_INTEGER }; break;
case O_TEXT: out[0] = (TinyBlocks_SlotDesc){ "texto", TB_VALUE_TEXT }; break;
case O_INT: out[0] = (TinyBlocks_SlotDesc){ "valor", TB_VALUE_INTEGER }; break;
default: break;
}
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, sp->name, sp->nin ? in : NULL, (uint32_t)sp->nin,
sp->out ? out : NULL, sp->out ? 1u : 0u, sp->fn);
if (!t) return false;
tb_type_block_set_label(t, sp->label, sp->defs);
tb_meta_declare(sp->name, sp->fname, __FILE__, sp->doc);
if (!tb_library_add(lib, &t->base)) return false;
}
return true;
}
static void d3_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = NULL;
free(S.o); S.o = NULL; S.n = S.cap = 0;
free(s_draws); s_draws = NULL; s_draws_cap = 0;
free(s_zbuf); s_zbuf = NULL; s_zcap = 0;
meshes_free();
}
TINYBLOCKS_DEFINE_LIBRARY(d3, "tinyblocks-3d", "1.0.0", d3_init, d3_deinit)
const TinyBlocks_LibraryDescriptor* tb_3d_get_library(void) {
return &_tb_lib_desc_d3;
}
+30
View File
@@ -0,0 +1,30 @@
# Makefile da library gl (renderizador OpenGL da 3d)
# Constroi build/libtinyblocks-gl.a e build/libtinyblocks-gl.so
CC := gcc
BUILD := build
CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude -I../tinyblocks-3d/include
SRCS := src/tb_gl.c
OBJS := $(BUILD)/tb_gl.o
LIB_A := $(BUILD)/libtinyblocks-gl.a
LIB_SO := $(BUILD)/libtinyblocks-gl.so
.PHONY: all static shared clean
all: static shared
static: $(LIB_A)
shared: $(LIB_SO)
$(BUILD)/%.o: src/%.c $(wildcard include/*.h) $(wildcard src/*.h)
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
$(LIB_A): $(OBJS)
ar rcs $@ $^
$(LIB_SO): $(OBJS)
$(CC) -shared -o $@ $^ -lEGL -lOpenGL -lpthread -lm
clean:
$(RM) -r $(BUILD)
+20
View File
@@ -0,0 +1,20 @@
/*
* TinyBlocks - tb_gl.h
* Library tinyblocks-gl: renderizador OpenGL da tinyblocks-3d.
*
* Nao tem blocos: publica um Tb3dRenderer ("opengl") no lib_userdata, que a
* 3d acha pelo nome. Desenha sem janela: contexto OpenGL 3.3 core pelo EGL
* (plataforma surfaceless do Mesa, ou o display padrao), num framebuffer
* fora da tela, e le os pixels de volta.
*
* O contexto vive numa thread propria: assim ele nunca e o "corrente" da
* thread do editor, onde o SDL pode estar usando o OpenGL dele.
*/
#ifndef TINYBLOCKS_GL_H
#define TINYBLOCKS_GL_H
#include <tinyblocks/tinyblocks.h>
TB_API const TinyBlocks_LibraryDescriptor* tb_gl_get_library(void);
#endif /* TINYBLOCKS_GL_H */
+15
View File
@@ -0,0 +1,15 @@
# Metadados da library gl. Lido pela UI/build sem recompilar o .so.
[library]
name = "tinyblocks-gl"
version = "1.0.0"
category = "3D"
description = "Renderizador OpenGL 3.3 (EGL, sem janela) para a tinyblocks-3d"
color = [92, 107, 219, 255]
dark = [64, 77, 168, 255]
[build]
sources = ["src/tb_gl.c"]
includes = ["include"]
shared = "build/libtinyblocks-gl.so"
static = "build/libtinyblocks-gl.a"
depends = ["3d"]
+295
View File
@@ -0,0 +1,295 @@
/*
* TinyBlocks - tb_gl.c
* Renderizador OpenGL (EGL sem janela) da tinyblocks-3d.
*/
#define _POSIX_C_SOURCE 200809L
#define GL_GLEXT_PROTOTYPES 1
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GL/glcorearb.h>
#include <tinyblocks/tinyblocks.h>
#include "tb_3d.h"
#include "tb_gl.h"
/* == Estado da thread do OpenGL ======================================== */
static struct {
pthread_t th;
pthread_mutex_t mu;
pthread_cond_t cv;
bool started, ready, failed, quit;
/* um pedido por vez */
const Tb3dFrame* job;
uint8_t* out;
bool busy, ok;
char err[256], device[128];
} G = { .mu = PTHREAD_MUTEX_INITIALIZER, .cv = PTHREAD_COND_INITIALIZER };
/* So a thread do OpenGL mexe nestes */
static EGLDisplay s_dpy = EGL_NO_DISPLAY;
static EGLContext s_ctx = EGL_NO_CONTEXT;
static GLuint s_prog, s_fbo, s_color, s_depth;
static GLint u_mvp, u_nrm, u_color, u_light, u_ambient;
static int s_w, s_h;
static uint8_t* s_rows; /* leitura (de baixo para cima) */
static size_t s_rows_cap;
typedef struct { GLuint vao, vbo, ebo; int icount; } GpuMesh;
static GpuMesh s_mesh[32]; /* pelo id da malha */
static void fail(const char* fmt, const char* a) { snprintf(G.err, sizeof(G.err), fmt, a); }
static const char* VS =
"#version 330 core\n"
"layout(location = 0) in vec3 a_pos;\n"
"layout(location = 1) in vec3 a_nrm;\n"
"uniform mat4 u_mvp;\n"
"uniform mat3 u_nrm;\n"
"uniform vec4 u_color;\n"
"uniform vec3 u_light;\n"
"uniform float u_ambient;\n"
"out vec3 v_col;\n"
"void main() {\n"
" gl_Position = u_mvp * vec4(a_pos, 1.0);\n"
" vec3 n = normalize(u_nrm * a_nrm);\n"
" float I = u_ambient + (1.0 - u_ambient) * max(dot(n, u_light), 0.0);\n"
" v_col = u_color.rgb * I;\n"
"}\n";
static const char* FS =
"#version 330 core\n"
"in vec3 v_col;\n"
"out vec4 o_color;\n"
"void main() { o_color = vec4(min(v_col, vec3(1.0)), 1.0); }\n";
static GLuint shader(GLenum kind, const char* src) {
GLuint s = glCreateShader(kind);
glShaderSource(s, 1, &src, NULL);
glCompileShader(s);
GLint ok = 0;
glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[200];
glGetShaderInfoLog(s, sizeof(log), NULL, log);
fail("shader: %s", log);
glDeleteShader(s);
return 0;
}
return s;
}
static bool gl_setup(void) {
PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform =
(PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
if (get_platform) s_dpy = get_platform(EGL_PLATFORM_SURFACELESS_MESA, EGL_DEFAULT_DISPLAY, NULL);
EGLint maj, min;
if (s_dpy == EGL_NO_DISPLAY || !eglInitialize(s_dpy, &maj, &min)) {
s_dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (s_dpy == EGL_NO_DISPLAY || !eglInitialize(s_dpy, &maj, &min)) { fail("%s", "o EGL não iniciou"); return false; }
}
if (!eglBindAPI(EGL_OPENGL_API)) { fail("%s", "o EGL não oferece OpenGL"); return false; }
static const EGLint cfg_attr[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_SURFACE_TYPE, 0, EGL_NONE };
EGLConfig cfg = NULL;
EGLint n = 0;
if (!eglChooseConfig(s_dpy, cfg_attr, &cfg, 1, &n) || n < 1) cfg = NULL; /* EGL_KHR_no_config_context */
static const EGLint ctx_attr[] = { EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3,
EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL_NONE };
s_ctx = eglCreateContext(s_dpy, cfg, EGL_NO_CONTEXT, ctx_attr);
if (s_ctx == EGL_NO_CONTEXT) { fail("%s", "não criou um contexto OpenGL 3.3"); return false; }
if (!eglMakeCurrent(s_dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, s_ctx)) { fail("%s", "contexto sem janela recusado"); return false; }
snprintf(G.device, sizeof(G.device), "%s", (const char*)glGetString(GL_RENDERER));
GLuint vs = shader(GL_VERTEX_SHADER, VS), fs = shader(GL_FRAGMENT_SHADER, FS);
if (!vs || !fs) return false;
s_prog = glCreateProgram();
glAttachShader(s_prog, vs);
glAttachShader(s_prog, fs);
glLinkProgram(s_prog);
glDeleteShader(vs);
glDeleteShader(fs);
GLint ok = 0;
glGetProgramiv(s_prog, GL_LINK_STATUS, &ok);
if (!ok) { fail("%s", "o programa de shaders não ligou"); return false; }
u_mvp = glGetUniformLocation(s_prog, "u_mvp");
u_nrm = glGetUniformLocation(s_prog, "u_nrm");
u_color = glGetUniformLocation(s_prog, "u_color");
u_light = glGetUniformLocation(s_prog, "u_light");
u_ambient = glGetUniformLocation(s_prog, "u_ambient");
glGenFramebuffers(1, &s_fbo);
glGenRenderbuffers(1, &s_color);
glGenRenderbuffers(1, &s_depth);
return true;
}
static bool target(int w, int h) {
if (w == s_w && h == s_h) return true;
glBindRenderbuffer(GL_RENDERBUFFER, s_color);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, w, h);
glBindRenderbuffer(GL_RENDERBUFFER, s_depth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, w, h);
glBindFramebuffer(GL_FRAMEBUFFER, s_fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, s_color);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, s_depth);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { fail("%s", "framebuffer incompleto"); return false; }
s_w = w; s_h = h;
return true;
}
static GpuMesh* gpu_mesh(const Tb3dMesh* m) {
if (m->id <= 0 || m->id >= 32) return NULL;
GpuMesh* g = &s_mesh[m->id];
if (g->vao) return g;
glGenVertexArrays(1, &g->vao);
glGenBuffers(1, &g->vbo);
glGenBuffers(1, &g->ebo);
glBindVertexArray(g->vao);
glBindBuffer(GL_ARRAY_BUFFER, g->vbo);
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)m->vcount * 6 * sizeof(float), m->verts, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g->ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)m->icount * sizeof(uint32_t), m->index, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
g->icount = m->icount;
return g;
}
static bool draw(const Tb3dFrame* f, uint8_t* out) {
if (!target(f->width, f->height)) return false;
glBindFramebuffer(GL_FRAMEBUFFER, s_fbo);
glViewport(0, 0, f->width, f->height);
glClearColor(f->sky[0], f->sky[1], f->sky[2], 1.f);
glClearDepth(1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glDisable(GL_CULL_FACE);
glUseProgram(s_prog);
glUniform3fv(u_light, 1, f->light_dir);
glUniform1f(u_ambient, f->ambient);
for (int i = 0; i < f->draw_count; i++) {
const Tb3dDraw* d = &f->draws[i];
GpuMesh* g = gpu_mesh(d->mesh);
if (!g) continue;
glUniformMatrix4fv(u_mvp, 1, GL_FALSE, d->mvp);
glUniformMatrix3fv(u_nrm, 1, GL_FALSE, d->normal);
glUniform4fv(u_color, 1, d->color);
glBindVertexArray(g->vao);
glDrawElements(GL_TRIANGLES, g->icount, GL_UNSIGNED_INT, (void*)0);
}
size_t row = (size_t)f->width * 4, n = row * (size_t)f->height;
if (n > s_rows_cap) {
uint8_t* p = realloc(s_rows, n);
if (!p) { fail("%s", "sem memória"); return false; }
s_rows = p; s_rows_cap = n;
}
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, f->width, f->height, GL_RGBA, GL_UNSIGNED_BYTE, s_rows);
for (int y = 0; y < f->height; y++) /* o GL comeca de baixo */
memcpy(out + (size_t)y * row, s_rows + (size_t)(f->height - 1 - y) * row, row);
GLenum e = glGetError();
if (e != GL_NO_ERROR) { char t[32]; snprintf(t, sizeof(t), "0x%x", e); fail("erro do OpenGL %s", t); return false; }
return true;
}
static void cleanup(void) {
for (int i = 0; i < 32; i++)
if (s_mesh[i].vao) {
glDeleteVertexArrays(1, &s_mesh[i].vao);
glDeleteBuffers(1, &s_mesh[i].vbo);
glDeleteBuffers(1, &s_mesh[i].ebo);
}
memset(s_mesh, 0, sizeof(s_mesh));
if (s_prog) glDeleteProgram(s_prog);
if (s_fbo) { glDeleteFramebuffers(1, &s_fbo); glDeleteRenderbuffers(1, &s_color); glDeleteRenderbuffers(1, &s_depth); }
s_prog = s_fbo = s_color = s_depth = 0;
s_w = s_h = 0;
if (s_dpy != EGL_NO_DISPLAY) {
eglMakeCurrent(s_dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (s_ctx != EGL_NO_CONTEXT) eglDestroyContext(s_dpy, s_ctx);
eglTerminate(s_dpy);
}
s_dpy = EGL_NO_DISPLAY; s_ctx = EGL_NO_CONTEXT;
free(s_rows); s_rows = NULL; s_rows_cap = 0;
}
static void* gl_thread(void* arg) {
(void)arg;
bool ok = gl_setup();
pthread_mutex_lock(&G.mu);
G.ready = ok; G.failed = !ok;
pthread_cond_broadcast(&G.cv);
while (ok && !G.quit) {
while (!G.busy && !G.quit) pthread_cond_wait(&G.cv, &G.mu);
if (G.quit) break;
const Tb3dFrame* f = G.job;
uint8_t* out = G.out;
pthread_mutex_unlock(&G.mu);
bool r = draw(f, out);
pthread_mutex_lock(&G.mu);
G.ok = r;
G.busy = false;
pthread_cond_broadcast(&G.cv);
}
pthread_mutex_unlock(&G.mu);
cleanup();
return NULL;
}
/* == Tb3dRenderer ===================================================== */
static bool gl_available(void) {
pthread_mutex_lock(&G.mu);
if (!G.started) {
G.started = true;
if (pthread_create(&G.th, NULL, gl_thread, NULL) != 0) { G.failed = true; fail("%s", "sem thread"); }
}
while (!G.ready && !G.failed) pthread_cond_wait(&G.cv, &G.mu);
bool ok = G.ready;
pthread_mutex_unlock(&G.mu);
return ok;
}
static bool gl_render(const Tb3dFrame* f, uint8_t* rgba) {
if (!gl_available()) return false;
pthread_mutex_lock(&G.mu);
G.job = f; G.out = rgba; G.busy = true;
pthread_cond_broadcast(&G.cv);
while (G.busy) pthread_cond_wait(&G.cv, &G.mu);
bool ok = G.ok;
pthread_mutex_unlock(&G.mu);
return ok;
}
static const char* gl_device(void) { return G.device[0] ? G.device : "?"; }
static const char* gl_error(void) { return G.err; }
static const Tb3dRenderer s_renderer = {
TB_3D_RENDERER_VERSION, "opengl", gl_available, gl_render, gl_device, gl_error };
static bool lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = (void*)&s_renderer; /* a thread so nasce no 1o uso */
return true;
}
static void lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = NULL;
pthread_mutex_lock(&G.mu);
bool started = G.started;
G.quit = true;
pthread_cond_broadcast(&G.cv);
pthread_mutex_unlock(&G.mu);
if (started) pthread_join(G.th, NULL);
G.started = G.ready = G.failed = G.quit = false;
}
TINYBLOCKS_DEFINE_LIBRARY(gl, "tinyblocks-gl", "1.0.0", lib_init, lib_deinit)
const TinyBlocks_LibraryDescriptor* tb_gl_get_library(void) {
return &_tb_lib_desc_gl;
}
+38
View File
@@ -0,0 +1,38 @@
# Makefile da library vk (renderizador Vulkan da 3d)
# Constroi build/libtinyblocks-vk.a e build/libtinyblocks-vk.so
CC := gcc
BUILD := build
CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude -I../tinyblocks-3d/include
SRCS := src/tb_vk.c
OBJS := $(BUILD)/tb_vk.o
LIB_A := $(BUILD)/libtinyblocks-vk.a
LIB_SO := $(BUILD)/libtinyblocks-vk.so
.PHONY: all static shared clean
all: static shared
static: $(LIB_A)
shared: $(LIB_SO)
$(BUILD)/%.o: src/%.c $(wildcard include/*.h) $(wildcard src/*.h)
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
$(LIB_A): $(OBJS)
ar rcs $@ $^
$(LIB_SO): $(OBJS)
$(CC) -shared -o $@ $^ -lvulkan -lm
clean:
$(RM) -r $(BUILD)
# Regera os shaders embutidos (precisa do glslc; o header gerado vai no git)
shaders: src/shaders/d3.vert src/shaders/d3.frag
@mkdir -p $(BUILD)
glslc -O src/shaders/d3.vert -o $(BUILD)/d3.vert.spv
glslc -O src/shaders/d3.frag -o $(BUILD)/d3.frag.spv
python3 -I tools/spv2h.py src/tb_vk_shaders.h s_vert_spv=$(BUILD)/d3.vert.spv s_frag_spv=$(BUILD)/d3.frag.spv
.PHONY: shaders
+20
View File
@@ -0,0 +1,20 @@
/*
* TinyBlocks - tb_vk.h
* Library tinyblocks-vk: renderizador Vulkan da tinyblocks-3d.
*
* Nao tem blocos: publica um Tb3dRenderer ("vulkan") no lib_userdata, que a
* 3d acha pelo nome. Desenha sem janela: render pass com cor RGBA8 e
* profundidade, os shaders em SPIR-V embutidos (src/tb_vk_shaders.h, gerado
* pelo glslc a partir de src/shaders), e copia a imagem para a memoria.
*
* Escolha da placa: a dedicada, depois a integrada, depois a de software
* (llvmpipe). TINYBLOCKS_VK_DEVICE=<parte do nome> escolhe outra.
*/
#ifndef TINYBLOCKS_VK_H
#define TINYBLOCKS_VK_H
#include <tinyblocks/tinyblocks.h>
TB_API const TinyBlocks_LibraryDescriptor* tb_vk_get_library(void);
#endif /* TINYBLOCKS_VK_H */
+15
View File
@@ -0,0 +1,15 @@
# Metadados da library vk. Lido pela UI/build sem recompilar o .so.
[library]
name = "tinyblocks-vk"
version = "1.0.0"
category = "3D"
description = "Renderizador Vulkan 1.1 (sem janela) para a tinyblocks-3d"
color = [92, 107, 219, 255]
dark = [64, 77, 168, 255]
[build]
sources = ["src/tb_vk.c"]
includes = ["include"]
shared = "build/libtinyblocks-vk.so"
static = "build/libtinyblocks-vk.a"
depends = ["3d"]
@@ -0,0 +1,5 @@
#version 450
layout(location = 0) in vec3 v_col;
layout(location = 0) out vec4 o_color;
void main() { o_color = vec4(min(v_col, vec3(1.0)), 1.0); }
@@ -0,0 +1,20 @@
#version 450
// Vertice da tinyblocks-vk: o mesmo calculo do GL e do software (lambert
// por vertice). Push constants (128 bytes, o minimo garantido):
// mvp; n0..n2 = colunas da matriz das normais, com a direcao da luz nos .w;
// color.rgb = cor do objeto, color.a = luz ambiente.
layout(location = 0) in vec3 a_pos;
layout(location = 1) in vec3 a_nrm;
layout(push_constant) uniform PC { mat4 mvp; vec4 n0; vec4 n1; vec4 n2; vec4 color; } pc;
layout(location = 0) out vec3 v_col;
void main() {
vec4 p = pc.mvp * vec4(a_pos, 1.0);
p.z = (p.z + p.w) * 0.5; // z do GL (-1..1) para o do Vulkan (0..1)
gl_Position = p;
mat3 N = mat3(pc.n0.xyz, pc.n1.xyz, pc.n2.xyz);
vec3 L = vec3(pc.n0.w, pc.n1.w, pc.n2.w);
vec3 n = normalize(N * a_nrm);
float I = pc.color.a + (1.0 - pc.color.a) * max(dot(n, L), 0.0);
v_col = pc.color.rgb * I;
}
+392
View File
@@ -0,0 +1,392 @@
/*
* TinyBlocks - tb_vk.c
* Renderizador Vulkan (sem janela) da tinyblocks-3d.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <vulkan/vulkan.h>
#include <tinyblocks/tinyblocks.h>
#include "tb_3d.h"
#include "tb_vk.h"
#include "tb_vk_shaders.h"
typedef struct { VkBuffer buf; VkDeviceMemory mem; void* map; VkDeviceSize size; } Buf;
typedef struct { Buf vb, ib; int icount; } GpuMesh;
static struct {
bool tried, ok;
char err[256], device[160];
VkInstance inst;
VkPhysicalDevice phys;
VkPhysicalDeviceMemoryProperties memp;
VkDevice dev;
VkQueue queue;
uint32_t qfam;
VkCommandPool pool;
VkCommandBuffer cmd;
VkFence fence;
VkFormat depth_fmt;
VkRenderPass pass;
VkPipelineLayout layout;
VkPipeline pipe;
/* alvo (recriado quando muda o tamanho) */
int w, h;
VkImage color, depth;
VkDeviceMemory color_mem, depth_mem;
VkImageView color_view, depth_view;
VkFramebuffer fb;
Buf readback;
GpuMesh mesh[32];
} V;
#define CK(x, what) do { VkResult r_ = (x); if (r_ != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "%s (VkResult %d)", what, (int)r_); return false; } } while (0)
static bool mem_type(uint32_t bits, VkMemoryPropertyFlags want, uint32_t* out) {
for (uint32_t i = 0; i < V.memp.memoryTypeCount; i++)
if ((bits & (1u << i)) && (V.memp.memoryTypes[i].propertyFlags & want) == want) { *out = i; return true; }
return false;
}
/* Buffer visivel pela CPU (simples: as malhas sao pequenas) */
static bool buf_new(Buf* b, VkDeviceSize size, VkBufferUsageFlags usage) {
VkBufferCreateInfo bi = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, NULL, 0, size, usage, VK_SHARING_MODE_EXCLUSIVE, 0, NULL };
CK(vkCreateBuffer(V.dev, &bi, NULL, &b->buf), "vkCreateBuffer");
VkMemoryRequirements req;
vkGetBufferMemoryRequirements(V.dev, b->buf, &req);
uint32_t t;
if (!mem_type(req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &t)) {
snprintf(V.err, sizeof(V.err), "sem memória visível pela CPU");
return false;
}
VkMemoryAllocateInfo ai = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, req.size, t };
CK(vkAllocateMemory(V.dev, &ai, NULL, &b->mem), "vkAllocateMemory");
CK(vkBindBufferMemory(V.dev, b->buf, b->mem, 0), "vkBindBufferMemory");
CK(vkMapMemory(V.dev, b->mem, 0, size, 0, &b->map), "vkMapMemory");
b->size = size;
return true;
}
static void buf_free(Buf* b) {
if (b->mem) { vkUnmapMemory(V.dev, b->mem); vkFreeMemory(V.dev, b->mem, NULL); }
if (b->buf) vkDestroyBuffer(V.dev, b->buf, NULL);
memset(b, 0, sizeof(*b));
}
/* "nome" contem "parte", sem diferenciar maiusculas */
static bool has_ci(const char* nome, const char* parte) {
size_t n = strlen(parte);
for (; *nome; nome++) if (!strncasecmp(nome, parte, n)) return true;
return n == 0;
}
static int dev_rank(VkPhysicalDeviceType t) {
return t == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU ? 3 : t == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU ? 2
: t == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU ? 1 : 0;
}
static bool pick_device(void) {
uint32_t n = 0;
vkEnumeratePhysicalDevices(V.inst, &n, NULL);
if (!n) { snprintf(V.err, sizeof(V.err), "nenhuma placa com Vulkan"); return false; }
VkPhysicalDevice* list = calloc(n, sizeof(*list));
if (!list) return false;
vkEnumeratePhysicalDevices(V.inst, &n, list);
const char* want = getenv("TINYBLOCKS_VK_DEVICE");
int best = -1, best_rank = -1;
for (uint32_t i = 0; i < n; i++) {
VkPhysicalDeviceProperties p;
vkGetPhysicalDeviceProperties(list[i], &p);
uint32_t qn = 0;
vkGetPhysicalDeviceQueueFamilyProperties(list[i], &qn, NULL);
VkQueueFamilyProperties q[16];
if (qn > 16) qn = 16;
vkGetPhysicalDeviceQueueFamilyProperties(list[i], &qn, q);
int fam = -1;
for (uint32_t k = 0; k < qn && fam < 0; k++) if (q[k].queueFlags & VK_QUEUE_GRAPHICS_BIT) fam = (int)k;
if (fam < 0 || p.apiVersion < VK_API_VERSION_1_1) continue;
int rank = dev_rank(p.deviceType);
if (want && want[0] && has_ci(p.deviceName, want)) rank = 100;
if (rank > best_rank) { best_rank = rank; best = (int)i; V.qfam = (uint32_t)fam; }
}
if (best < 0) { free(list); snprintf(V.err, sizeof(V.err), "nenhuma placa com Vulkan 1.1 e fila gráfica"); return false; }
V.phys = list[best];
free(list);
VkPhysicalDeviceProperties p;
vkGetPhysicalDeviceProperties(V.phys, &p);
snprintf(V.device, sizeof(V.device), "%.150s", p.deviceName);
vkGetPhysicalDeviceMemoryProperties(V.phys, &V.memp);
static const VkFormat cand[] = { VK_FORMAT_D32_SFLOAT, VK_FORMAT_X8_D24_UNORM_PACK32, VK_FORMAT_D16_UNORM };
for (int i = 0; i < 3; i++) {
VkFormatProperties fp;
vkGetPhysicalDeviceFormatProperties(V.phys, cand[i], &fp);
if (fp.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { V.depth_fmt = cand[i]; return true; }
}
snprintf(V.err, sizeof(V.err), "a placa não tem formato de profundidade");
return false;
}
static bool make_pipeline(void) {
VkAttachmentDescription att[2] = {
{ 0, VK_FORMAT_R8G8B8A8_UNORM, VK_SAMPLE_COUNT_1_BIT, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL },
{ 0, V.depth_fmt, VK_SAMPLE_COUNT_1_BIT, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE,
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL },
};
VkAttachmentReference cref = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
VkAttachmentReference dref = { 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
VkSubpassDescription sub = { 0, VK_PIPELINE_BIND_POINT_GRAPHICS, 0, NULL, 1, &cref, NULL, &dref, 0, NULL };
/* a copia para o buffer espera a escrita da cor terminar */
VkSubpassDependency dep = { 0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_ACCESS_TRANSFER_READ_BIT, 0 };
VkRenderPassCreateInfo rp = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, NULL, 0, 2, att, 1, &sub, 1, &dep };
CK(vkCreateRenderPass(V.dev, &rp, NULL, &V.pass), "vkCreateRenderPass");
VkPushConstantRange pcr = { VK_SHADER_STAGE_VERTEX_BIT, 0, 128 };
VkPipelineLayoutCreateInfo pl = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, NULL, 0, 0, NULL, 1, &pcr };
CK(vkCreatePipelineLayout(V.dev, &pl, NULL, &V.layout), "vkCreatePipelineLayout");
VkShaderModule vs, fs;
VkShaderModuleCreateInfo sm = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, sizeof(s_vert_spv), s_vert_spv };
CK(vkCreateShaderModule(V.dev, &sm, NULL, &vs), "shader de vértice");
sm.codeSize = sizeof(s_frag_spv); sm.pCode = s_frag_spv;
CK(vkCreateShaderModule(V.dev, &sm, NULL, &fs), "shader de fragmento");
VkPipelineShaderStageCreateInfo st[2] = {
{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_VERTEX_BIT, vs, "main", NULL },
{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_FRAGMENT_BIT, fs, "main", NULL },
};
VkVertexInputBindingDescription bind = { 0, 6 * sizeof(float), VK_VERTEX_INPUT_RATE_VERTEX };
VkVertexInputAttributeDescription attr[2] = { { 0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0 },
{ 1, 0, VK_FORMAT_R32G32B32_SFLOAT, 3 * sizeof(float) } };
VkPipelineVertexInputStateCreateInfo vi = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, NULL, 0, 1, &bind, 2, attr };
VkPipelineInputAssemblyStateCreateInfo ia = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, NULL, 0,
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, VK_FALSE };
VkPipelineViewportStateCreateInfo vp = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, NULL, 0, 1, NULL, 1, NULL };
VkPipelineRasterizationStateCreateInfo rs = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, NULL, 0,
VK_FALSE, VK_FALSE, VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, VK_FALSE, 0, 0, 0, 1.f };
VkPipelineMultisampleStateCreateInfo ms = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, NULL, 0,
VK_SAMPLE_COUNT_1_BIT, VK_FALSE, 0, NULL, VK_FALSE, VK_FALSE };
VkPipelineDepthStencilStateCreateInfo ds = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, NULL, 0,
VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS, VK_FALSE, VK_FALSE, {0}, {0}, 0, 1 };
VkPipelineColorBlendAttachmentState cba = { VK_FALSE, 0, 0, 0, 0, 0, 0, 0xf };
VkPipelineColorBlendStateCreateInfo cb = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0,
VK_FALSE, 0, 1, &cba, {0} };
VkDynamicState dyn_s[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dyn = { VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, NULL, 0, 2, dyn_s };
VkGraphicsPipelineCreateInfo gp = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, NULL, 0, 2, st, &vi, &ia, NULL,
&vp, &rs, &ms, &ds, &cb, &dyn, V.layout, V.pass, 0, VK_NULL_HANDLE, -1 };
VkResult r = vkCreateGraphicsPipelines(V.dev, VK_NULL_HANDLE, 1, &gp, NULL, &V.pipe);
vkDestroyShaderModule(V.dev, vs, NULL);
vkDestroyShaderModule(V.dev, fs, NULL);
CK(r, "vkCreateGraphicsPipelines");
return true;
}
static bool vk_setup(void) {
VkApplicationInfo app = { VK_STRUCTURE_TYPE_APPLICATION_INFO, NULL, "TinyBlocks", 1, "tinyblocks-vk", 1, VK_API_VERSION_1_1 };
const char* layers[] = { "VK_LAYER_KHRONOS_validation" };
bool validate = getenv("TINYBLOCKS_VK_VALIDATION") != NULL;
VkInstanceCreateInfo ii = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, NULL, 0, &app, validate ? 1u : 0u, layers, 0, NULL };
CK(vkCreateInstance(&ii, NULL, &V.inst), "vkCreateInstance (há driver Vulkan?)");
if (!pick_device()) return false;
float prio = 1.f;
VkDeviceQueueCreateInfo qi = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, NULL, 0, V.qfam, 1, &prio };
VkDeviceCreateInfo di = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, NULL, 0, 1, &qi, 0, NULL, 0, NULL, NULL };
CK(vkCreateDevice(V.phys, &di, NULL, &V.dev), "vkCreateDevice");
vkGetDeviceQueue(V.dev, V.qfam, 0, &V.queue);
VkCommandPoolCreateInfo cp = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, NULL,
VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, V.qfam };
CK(vkCreateCommandPool(V.dev, &cp, NULL, &V.pool), "vkCreateCommandPool");
VkCommandBufferAllocateInfo ca = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, NULL, V.pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1 };
CK(vkAllocateCommandBuffers(V.dev, &ca, &V.cmd), "vkAllocateCommandBuffers");
VkFenceCreateInfo fi = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, NULL, 0 };
CK(vkCreateFence(V.dev, &fi, NULL, &V.fence), "vkCreateFence");
return make_pipeline();
}
static void target_free(void) {
if (V.fb) vkDestroyFramebuffer(V.dev, V.fb, NULL);
if (V.color_view) vkDestroyImageView(V.dev, V.color_view, NULL);
if (V.depth_view) vkDestroyImageView(V.dev, V.depth_view, NULL);
if (V.color) vkDestroyImage(V.dev, V.color, NULL);
if (V.depth) vkDestroyImage(V.dev, V.depth, NULL);
if (V.color_mem) vkFreeMemory(V.dev, V.color_mem, NULL);
if (V.depth_mem) vkFreeMemory(V.dev, V.depth_mem, NULL);
buf_free(&V.readback);
V.fb = VK_NULL_HANDLE; V.color_view = V.depth_view = VK_NULL_HANDLE;
V.color = V.depth = VK_NULL_HANDLE; V.color_mem = V.depth_mem = VK_NULL_HANDLE;
V.w = V.h = 0;
}
static bool image_new(VkFormat fmt, VkImageUsageFlags usage, VkImageAspectFlags aspect,
VkImage* img, VkDeviceMemory* mem, VkImageView* view, int w, int h) {
VkImageCreateInfo ic = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, NULL, 0, VK_IMAGE_TYPE_2D, fmt,
{ (uint32_t)w, (uint32_t)h, 1 }, 1, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL,
usage, VK_SHARING_MODE_EXCLUSIVE, 0, NULL, VK_IMAGE_LAYOUT_UNDEFINED };
CK(vkCreateImage(V.dev, &ic, NULL, img), "vkCreateImage");
VkMemoryRequirements req;
vkGetImageMemoryRequirements(V.dev, *img, &req);
uint32_t t;
if (!mem_type(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &t) && !mem_type(req.memoryTypeBits, 0, &t)) {
snprintf(V.err, sizeof(V.err), "sem memória para a imagem");
return false;
}
VkMemoryAllocateInfo ai = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, req.size, t };
CK(vkAllocateMemory(V.dev, &ai, NULL, mem), "vkAllocateMemory (imagem)");
CK(vkBindImageMemory(V.dev, *img, *mem, 0), "vkBindImageMemory");
VkImageViewCreateInfo vc = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, NULL, 0, *img, VK_IMAGE_VIEW_TYPE_2D, fmt,
{ VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY },
{ aspect, 0, 1, 0, 1 } };
CK(vkCreateImageView(V.dev, &vc, NULL, view), "vkCreateImageView");
return true;
}
static bool target(int w, int h) {
if (w == V.w && h == V.h) return true;
vkDeviceWaitIdle(V.dev);
target_free();
if (!image_new(VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
VK_IMAGE_ASPECT_COLOR_BIT, &V.color, &V.color_mem, &V.color_view, w, h)) return false;
if (!image_new(V.depth_fmt, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_IMAGE_ASPECT_DEPTH_BIT,
&V.depth, &V.depth_mem, &V.depth_view, w, h)) return false;
VkImageView views[2] = { V.color_view, V.depth_view };
VkFramebufferCreateInfo fc = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, NULL, 0, V.pass, 2, views, (uint32_t)w, (uint32_t)h, 1 };
CK(vkCreateFramebuffer(V.dev, &fc, NULL, &V.fb), "vkCreateFramebuffer");
if (!buf_new(&V.readback, (VkDeviceSize)w * h * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT)) return false;
V.w = w; V.h = h;
return true;
}
static GpuMesh* gpu_mesh(const Tb3dMesh* m) {
if (m->id <= 0 || m->id >= 32) return NULL;
GpuMesh* g = &V.mesh[m->id];
if (g->vb.buf) return g;
if (!buf_new(&g->vb, (VkDeviceSize)m->vcount * 6 * sizeof(float), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) ||
!buf_new(&g->ib, (VkDeviceSize)m->icount * sizeof(uint32_t), VK_BUFFER_USAGE_INDEX_BUFFER_BIT)) {
buf_free(&g->vb); buf_free(&g->ib);
return NULL;
}
memcpy(g->vb.map, m->verts, (size_t)m->vcount * 6 * sizeof(float));
memcpy(g->ib.map, m->index, (size_t)m->icount * sizeof(uint32_t));
g->icount = m->icount;
return g;
}
static bool vk_draw(const Tb3dFrame* f, uint8_t* out) {
if (!target(f->width, f->height)) return false;
/* as malhas antes de gravar os comandos */
for (int i = 0; i < f->draw_count; i++) if (!gpu_mesh(f->draws[i].mesh)) return false;
CK(vkResetCommandBuffer(V.cmd, 0), "vkResetCommandBuffer");
VkCommandBufferBeginInfo bi = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, NULL };
CK(vkBeginCommandBuffer(V.cmd, &bi), "vkBeginCommandBuffer");
VkClearValue clear[2];
clear[0].color = (VkClearColorValue){ { f->sky[0], f->sky[1], f->sky[2], 1.f } };
clear[1].depthStencil = (VkClearDepthStencilValue){ 1.f, 0 };
VkRenderPassBeginInfo rb = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, NULL, V.pass, V.fb,
{ {0, 0}, { (uint32_t)f->width, (uint32_t)f->height } }, 2, clear };
vkCmdBeginRenderPass(V.cmd, &rb, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(V.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, V.pipe);
/* altura negativa: y para cima, como no GL (e a linha 0 da imagem e o alto) */
VkViewport vp = { 0, (float)f->height, (float)f->width, -(float)f->height, 0.f, 1.f };
VkRect2D sc = { {0, 0}, { (uint32_t)f->width, (uint32_t)f->height } };
vkCmdSetViewport(V.cmd, 0, 1, &vp);
vkCmdSetScissor(V.cmd, 0, 1, &sc);
for (int i = 0; i < f->draw_count; i++) {
const Tb3dDraw* d = &f->draws[i];
GpuMesh* g = gpu_mesh(d->mesh);
float pc[32];
memcpy(pc, d->mvp, sizeof(d->mvp));
for (int c = 0; c < 3; c++) {
pc[16 + c * 4 + 0] = d->normal[c * 3 + 0];
pc[16 + c * 4 + 1] = d->normal[c * 3 + 1];
pc[16 + c * 4 + 2] = d->normal[c * 3 + 2];
pc[16 + c * 4 + 3] = f->light_dir[c];
}
pc[28] = d->color[0]; pc[29] = d->color[1]; pc[30] = d->color[2]; pc[31] = f->ambient;
vkCmdPushConstants(V.cmd, V.layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(pc), pc);
VkDeviceSize off = 0;
vkCmdBindVertexBuffers(V.cmd, 0, 1, &g->vb.buf, &off);
vkCmdBindIndexBuffer(V.cmd, g->ib.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(V.cmd, (uint32_t)g->icount, 1, 0, 0, 0);
}
vkCmdEndRenderPass(V.cmd);
VkBufferImageCopy copy = { 0, 0, 0, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, {0, 0, 0},
{ (uint32_t)f->width, (uint32_t)f->height, 1 } };
vkCmdCopyImageToBuffer(V.cmd, V.color, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, V.readback.buf, 1, &copy);
VkBufferMemoryBarrier bar = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, NULL, VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_HOST_READ_BIT, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED,
V.readback.buf, 0, VK_WHOLE_SIZE };
vkCmdPipelineBarrier(V.cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 0, NULL, 1, &bar, 0, NULL);
CK(vkEndCommandBuffer(V.cmd), "vkEndCommandBuffer");
VkSubmitInfo si = { VK_STRUCTURE_TYPE_SUBMIT_INFO, NULL, 0, NULL, NULL, 1, &V.cmd, 0, NULL };
CK(vkResetFences(V.dev, 1, &V.fence), "vkResetFences");
CK(vkQueueSubmit(V.queue, 1, &si, V.fence), "vkQueueSubmit");
CK(vkWaitForFences(V.dev, 1, &V.fence, VK_TRUE, 5000000000ull), "vkWaitForFences");
memcpy(out, V.readback.map, (size_t)f->width * f->height * 4);
return true;
}
static void vk_cleanup(void) {
if (V.dev) {
vkDeviceWaitIdle(V.dev);
for (int i = 0; i < 32; i++) { buf_free(&V.mesh[i].vb); buf_free(&V.mesh[i].ib); }
target_free();
if (V.pipe) vkDestroyPipeline(V.dev, V.pipe, NULL);
if (V.layout) vkDestroyPipelineLayout(V.dev, V.layout, NULL);
if (V.pass) vkDestroyRenderPass(V.dev, V.pass, NULL);
if (V.fence) vkDestroyFence(V.dev, V.fence, NULL);
if (V.pool) vkDestroyCommandPool(V.dev, V.pool, NULL);
vkDestroyDevice(V.dev, NULL);
}
if (V.inst) vkDestroyInstance(V.inst, NULL);
memset(&V, 0, sizeof(V));
}
/* == Tb3dRenderer ===================================================== */
static bool vk_available(void) {
if (!V.tried) {
V.tried = true;
V.ok = vk_setup();
if (!V.ok) {
char err[256];
snprintf(err, sizeof(err), "%s", V.err);
vk_cleanup(); /* zera V (e o err): guarda e repoe */
V.tried = true;
snprintf(V.err, sizeof(V.err), "%s", err);
}
}
return V.ok;
}
static bool vk_render(const Tb3dFrame* f, uint8_t* rgba) { return vk_available() && vk_draw(f, rgba); }
static const char* vk_device(void) { return V.device[0] ? V.device : "?"; }
static const char* vk_error(void) { return V.err; }
static const Tb3dRenderer s_renderer = {
TB_3D_RENDERER_VERSION, "vulkan", vk_available, vk_render, vk_device, vk_error };
static bool lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = (void*)&s_renderer; /* o Vulkan so inicia no 1o uso */
return true;
}
static void lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = NULL;
vk_cleanup();
}
TINYBLOCKS_DEFINE_LIBRARY(vk, "tinyblocks-vk", "1.0.0", lib_init, lib_deinit)
const TinyBlocks_LibraryDescriptor* tb_vk_get_library(void) {
return &_tb_lib_desc_vk;
}
@@ -0,0 +1,94 @@
/* Gerado por tools/spv2h.py a partir de src/shaders (glslc). Nao edite. */
#ifndef TB_VK_SHADERS_H
#define TB_VK_SHADERS_H
#include <stdint.h>
static const uint32_t s_vert_spv[528] = {
0x07230203, 0x00010000, 0x000d000b, 0x00000077, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0009000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x00000015, 0x0000002d, 0x0000005b,
0x0000006d, 0x00040048, 0x0000000b, 0x00000000, 0x00000005, 0x00050048, 0x0000000b, 0x00000000,
0x00000023, 0x00000000, 0x00050048, 0x0000000b, 0x00000000, 0x00000007, 0x00000010, 0x00050048,
0x0000000b, 0x00000001, 0x00000023, 0x00000040, 0x00050048, 0x0000000b, 0x00000002, 0x00000023,
0x00000050, 0x00050048, 0x0000000b, 0x00000003, 0x00000023, 0x00000060, 0x00050048, 0x0000000b,
0x00000004, 0x00000023, 0x00000070, 0x00030047, 0x0000000b, 0x00000002, 0x00040047, 0x00000015,
0x0000001e, 0x00000000, 0x00050048, 0x0000002b, 0x00000000, 0x0000000b, 0x00000000, 0x00050048,
0x0000002b, 0x00000001, 0x0000000b, 0x00000001, 0x00050048, 0x0000002b, 0x00000002, 0x0000000b,
0x00000003, 0x00050048, 0x0000002b, 0x00000003, 0x0000000b, 0x00000004, 0x00030047, 0x0000002b,
0x00000002, 0x00040047, 0x0000005b, 0x0000001e, 0x00000001, 0x00040047, 0x0000006d, 0x0000001e,
0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006,
0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040018, 0x0000000a, 0x00000007,
0x00000004, 0x0007001e, 0x0000000b, 0x0000000a, 0x00000007, 0x00000007, 0x00000007, 0x00000007,
0x00040020, 0x0000000c, 0x00000009, 0x0000000b, 0x0004003b, 0x0000000c, 0x0000000d, 0x00000009,
0x00040015, 0x0000000e, 0x00000020, 0x00000001, 0x0004002b, 0x0000000e, 0x0000000f, 0x00000000,
0x00040020, 0x00000010, 0x00000009, 0x0000000a, 0x00040017, 0x00000013, 0x00000006, 0x00000003,
0x00040020, 0x00000014, 0x00000001, 0x00000013, 0x0004003b, 0x00000014, 0x00000015, 0x00000001,
0x0004002b, 0x00000006, 0x00000017, 0x3f800000, 0x00040015, 0x0000001d, 0x00000020, 0x00000000,
0x0004002b, 0x0000001d, 0x00000022, 0x00000003, 0x0004002b, 0x00000006, 0x00000026, 0x3f000000,
0x0004002b, 0x0000001d, 0x00000029, 0x00000001, 0x0004001c, 0x0000002a, 0x00000006, 0x00000029,
0x0006001e, 0x0000002b, 0x00000007, 0x00000006, 0x0000002a, 0x0000002a, 0x00040020, 0x0000002c,
0x00000003, 0x0000002b, 0x0004003b, 0x0000002c, 0x0000002d, 0x00000003, 0x00040020, 0x0000002f,
0x00000003, 0x00000007, 0x00040018, 0x00000031, 0x00000013, 0x00000003, 0x0004002b, 0x0000000e,
0x00000034, 0x00000001, 0x00040020, 0x00000035, 0x00000009, 0x00000007, 0x0004002b, 0x0000000e,
0x00000039, 0x00000002, 0x0004002b, 0x0000000e, 0x0000003d, 0x00000003, 0x0004002b, 0x00000006,
0x00000041, 0x00000000, 0x00040020, 0x00000051, 0x00000009, 0x00000006, 0x0004003b, 0x00000014,
0x0000005b, 0x00000001, 0x0004002b, 0x0000000e, 0x00000060, 0x00000004, 0x00040020, 0x0000006c,
0x00000003, 0x00000013, 0x0004003b, 0x0000006c, 0x0000006d, 0x00000003, 0x00050036, 0x00000002,
0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x00050041, 0x00000010, 0x00000011,
0x0000000d, 0x0000000f, 0x0004003d, 0x0000000a, 0x00000012, 0x00000011, 0x0004003d, 0x00000013,
0x00000016, 0x00000015, 0x00050051, 0x00000006, 0x00000018, 0x00000016, 0x00000000, 0x00050051,
0x00000006, 0x00000019, 0x00000016, 0x00000001, 0x00050051, 0x00000006, 0x0000001a, 0x00000016,
0x00000002, 0x00070050, 0x00000007, 0x0000001b, 0x00000018, 0x00000019, 0x0000001a, 0x00000017,
0x00050091, 0x00000007, 0x0000001c, 0x00000012, 0x0000001b, 0x00050051, 0x00000006, 0x00000021,
0x0000001c, 0x00000002, 0x00050051, 0x00000006, 0x00000024, 0x0000001c, 0x00000003, 0x00050081,
0x00000006, 0x00000025, 0x00000021, 0x00000024, 0x00050085, 0x00000006, 0x00000027, 0x00000025,
0x00000026, 0x00060052, 0x00000007, 0x00000076, 0x00000027, 0x0000001c, 0x00000002, 0x00050041,
0x0000002f, 0x00000030, 0x0000002d, 0x0000000f, 0x0003003e, 0x00000030, 0x00000076, 0x00050041,
0x00000035, 0x00000036, 0x0000000d, 0x00000034, 0x0004003d, 0x00000007, 0x00000037, 0x00000036,
0x00050041, 0x00000035, 0x0000003a, 0x0000000d, 0x00000039, 0x0004003d, 0x00000007, 0x0000003b,
0x0000003a, 0x00050041, 0x00000035, 0x0000003e, 0x0000000d, 0x0000003d, 0x0004003d, 0x00000007,
0x0000003f, 0x0000003e, 0x00050051, 0x00000006, 0x00000042, 0x00000037, 0x00000000, 0x00050051,
0x00000006, 0x00000043, 0x00000037, 0x00000001, 0x00050051, 0x00000006, 0x00000044, 0x00000037,
0x00000002, 0x00050051, 0x00000006, 0x00000045, 0x0000003b, 0x00000000, 0x00050051, 0x00000006,
0x00000046, 0x0000003b, 0x00000001, 0x00050051, 0x00000006, 0x00000047, 0x0000003b, 0x00000002,
0x00050051, 0x00000006, 0x00000048, 0x0000003f, 0x00000000, 0x00050051, 0x00000006, 0x00000049,
0x0000003f, 0x00000001, 0x00050051, 0x00000006, 0x0000004a, 0x0000003f, 0x00000002, 0x00060050,
0x00000013, 0x0000004b, 0x00000042, 0x00000043, 0x00000044, 0x00060050, 0x00000013, 0x0000004c,
0x00000045, 0x00000046, 0x00000047, 0x00060050, 0x00000013, 0x0000004d, 0x00000048, 0x00000049,
0x0000004a, 0x00060050, 0x00000031, 0x0000004e, 0x0000004b, 0x0000004c, 0x0000004d, 0x00060041,
0x00000051, 0x00000052, 0x0000000d, 0x00000034, 0x00000022, 0x0004003d, 0x00000006, 0x00000053,
0x00000052, 0x00060041, 0x00000051, 0x00000054, 0x0000000d, 0x00000039, 0x00000022, 0x0004003d,
0x00000006, 0x00000055, 0x00000054, 0x00060041, 0x00000051, 0x00000056, 0x0000000d, 0x0000003d,
0x00000022, 0x0004003d, 0x00000006, 0x00000057, 0x00000056, 0x00060050, 0x00000013, 0x00000058,
0x00000053, 0x00000055, 0x00000057, 0x0004003d, 0x00000013, 0x0000005c, 0x0000005b, 0x00050091,
0x00000013, 0x0000005d, 0x0000004e, 0x0000005c, 0x0006000c, 0x00000013, 0x0000005e, 0x00000001,
0x00000045, 0x0000005d, 0x00060041, 0x00000051, 0x00000061, 0x0000000d, 0x00000060, 0x00000022,
0x0004003d, 0x00000006, 0x00000062, 0x00000061, 0x00050083, 0x00000006, 0x00000065, 0x00000017,
0x00000062, 0x00050094, 0x00000006, 0x00000068, 0x0000005e, 0x00000058, 0x0007000c, 0x00000006,
0x00000069, 0x00000001, 0x00000028, 0x00000068, 0x00000041, 0x0008000c, 0x00000006, 0x0000006b,
0x00000001, 0x00000032, 0x00000065, 0x00000069, 0x00000062, 0x00050041, 0x00000035, 0x0000006e,
0x0000000d, 0x00000060, 0x0004003d, 0x00000007, 0x0000006f, 0x0000006e, 0x0008004f, 0x00000013,
0x00000070, 0x0000006f, 0x0000006f, 0x00000000, 0x00000001, 0x00000002, 0x0005008e, 0x00000013,
0x00000072, 0x00000070, 0x0000006b, 0x0003003e, 0x0000006d, 0x00000072, 0x000100fd, 0x00010038,
};
static const uint32_t s_frag_spv[121] = {
0x07230203, 0x00010000, 0x000d000b, 0x00000015, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0007000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x00000009, 0x0000000c, 0x00030010,
0x00000004, 0x00000007, 0x00040047, 0x00000009, 0x0000001e, 0x00000000, 0x00040047, 0x0000000c,
0x0000001e, 0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016,
0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040020, 0x00000008,
0x00000003, 0x00000007, 0x0004003b, 0x00000008, 0x00000009, 0x00000003, 0x00040017, 0x0000000a,
0x00000006, 0x00000003, 0x00040020, 0x0000000b, 0x00000001, 0x0000000a, 0x0004003b, 0x0000000b,
0x0000000c, 0x00000001, 0x0004002b, 0x00000006, 0x0000000e, 0x3f800000, 0x0006002c, 0x0000000a,
0x0000000f, 0x0000000e, 0x0000000e, 0x0000000e, 0x00050036, 0x00000002, 0x00000004, 0x00000000,
0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x0000000a, 0x0000000d, 0x0000000c, 0x0007000c,
0x0000000a, 0x00000010, 0x00000001, 0x00000025, 0x0000000d, 0x0000000f, 0x00050051, 0x00000006,
0x00000011, 0x00000010, 0x00000000, 0x00050051, 0x00000006, 0x00000012, 0x00000010, 0x00000001,
0x00050051, 0x00000006, 0x00000013, 0x00000010, 0x00000002, 0x00070050, 0x00000007, 0x00000014,
0x00000011, 0x00000012, 0x00000013, 0x0000000e, 0x0003003e, 0x00000009, 0x00000014, 0x000100fd,
0x00010038,
};
#endif
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
"""spv2h.py <saida.h> <nome>=<arquivo.spv> ...: SPIR-V como arrays uint32_t em C."""
import struct, sys
out = ["/* Gerado por tools/spv2h.py a partir de src/shaders (glslc). Nao edite. */",
"#ifndef TB_VK_SHADERS_H", "#define TB_VK_SHADERS_H", "#include <stdint.h>", ""]
for arg in sys.argv[2:]:
name, path = arg.split("=", 1)
data = open(path, "rb").read()
words = struct.unpack("<%dI" % (len(data) // 4), data)
out.append("static const uint32_t %s[%d] = {" % (name, len(words)))
for i in range(0, len(words), 8):
out.append(" " + ", ".join("0x%08x" % w for w in words[i:i + 8]) + ",")
out.append("};")
out.append("")
out.append("#endif")
open(sys.argv[1], "w").write("\n".join(out) + "\n")
+2 -1
View File
@@ -39,7 +39,8 @@ WIN_DEP_PKGS := SDL2 SDL2_ttf libpng freetype openssl zlib libsystre ca-certific
# Libraries que entram no .exe: as de categoria e de app (como no Linux), # Libraries que entram no .exe: as de categoria e de app (como no Linux),
# as que o editor ja linka, e as de extensao (no Linux viriam como .so) # as que o editor ja linka, e as de extensao (no Linux viriam como .so)
WIN_EXTRA_LIBS := base64 curves ppm bmp png image vg svg regex markdown opentype WIN_EXTRA_LIBS := base64 curves ppm bmp png image vg svg regex markdown opentype
WIN_LIB_DIRS := $(foreach l,$(CAT_LIBS) $(APP_LIBS) $(WIN_EXTRA_LIBS) \ # gl e vk ficam de fora: no Windows a 3d usa o renderizador em software
WIN_LIB_DIRS := $(foreach l,$(CAT_LIBS) $(filter-out gl vk,$(APP_LIBS)) $(WIN_EXTRA_LIBS) \
editor a11y mcp-server graphics sdl2 toml json xml csv blueprint scratchblocks api libman syntax, \ editor a11y mcp-server graphics sdl2 toml json xml csv blueprint scratchblocks api libman syntax, \
$(LIBDIR)/tinyblocks-$(l)) \ $(LIBDIR)/tinyblocks-$(l)) \
$(ED_DIR)/libraries/tinyblocks-editor-widgets \ $(ED_DIR)/libraries/tinyblocks-editor-widgets \
+143
View File
@@ -0,0 +1,143 @@
/*
* d3_test.c - testa a tinyblocks-3d pelos blocos (cena, objetos, colisao,
* camera) e compara os renderizadores: o software e a referencia; o Vulkan
* (tinyblocks-vk) e o OpenGL (tinyblocks-gl), se estiverem compilados e
* houver placa/driver, precisam dar quase a mesma imagem. Grava
* /tmp/tb_3d_<renderizador>.png.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_image.h>
#include <tb_png.h>
#include <tb_3d.h>
#ifdef WITH_GL
#include <tb_gl.h>
#endif
#ifdef WITH_VK
#include <tb_vk.h>
#endif
static int fails = 0;
#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0)
static TinyBlocks* rt;
static TinyBlocks_Block* run(const char* type, const char* const* args, int n) {
TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, type));
for (int i = 0; i < n; i++)
if (args[i]) { TinyBlocks_Value t = tb_value_text(args[i]); tb_block_set_default(x, (uint32_t)i, t); tb_value_free(&t); }
tb_block_eval(x, rt);
return x;
}
#define RUN(type, ...) run(type, (const char* const[]){ __VA_ARGS__ }, (int)(sizeof((const char* const[]){ __VA_ARGS__ }) / sizeof(char*)))
static TinyBlocks_Image* render_with(const char* who) {
RUN("3D.Use", who);
TinyBlocks_Block* b = RUN("3D.Image", "320", "240");
if (b->outputs[0].kind != TB_VALUE_IMAGE) return NULL;
TinyBlocks_Image* img = b->outputs[0].as.image;
tb_image_retain(img);
TinyBlocks_Block* r = RUN("3D.Renderer", NULL);
printf(" renderizador: %s\n", r->outputs[0].kind == TB_VALUE_TEXT ? r->outputs[0].as.text : "?");
char path[64];
snprintf(path, sizeof(path), "/tmp/tb_3d_%s.png", who);
tb_image_save(img, path);
return img;
}
/* Diferenca media por canal (0..255) e fracao de pixels muito diferentes */
static void compare(const TinyBlocks_Image* a, const TinyBlocks_Image* b, double* mean, double* bad) {
const uint8_t* p = tb_image_data_const(a);
const uint8_t* q = tb_image_data_const(b);
size_t n = (size_t)tb_image_width(a) * tb_image_height(a);
double s = 0;
size_t nb = 0;
for (size_t i = 0; i < n; i++) {
int d = 0;
for (int c = 0; c < 3; c++) { int e = abs(p[i * 4 + c] - q[i * 4 + c]); s += e; if (e > d) d = e; }
if (d > 40) nb++;
}
*mean = s / (n * 3.0);
*bad = (double)nb / n;
}
int main(void) {
setvbuf(stdout, NULL, _IOLBF, 0);
tinyblocks_init(&rt, NULL);
tb_library_register(rt, tb_png_get_library());
tb_library_register(rt, tb_3d_get_library());
#ifdef WITH_GL
tb_library_register(rt, tb_gl_get_library());
#endif
#ifdef WITH_VK
tb_library_register(rt, tb_vk_get_library());
#endif
RUN("3D.Scene", NULL);
RUN("3D.Plane", "chão", "0", "0", "0");
RUN("3D.Scale", "chão", "12", "1", "12");
RUN("3D.Color", "chão", "verde");
RUN("3D.Cube", "jogador", "0", "0.5", "0");
RUN("3D.Color", "jogador", "vermelho");
RUN("3D.RotateTo", "jogador", "0", "30", "0");
RUN("3D.Sphere", "bola", "2", "0.5", "-1");
RUN("3D.Color", "bola", "azul");
RUN("3D.Cylinder", "moeda", "-2", "0.6", "1");
RUN("3D.Scale", "moeda", "0.8", "0.15", "0.8");
RUN("3D.RotateTo", "moeda", "90", "0", "0");
RUN("3D.Color", "moeda", "dourado");
RUN("3D.Camera", "0", "4", "7", "0", "0.5", "0");
CHECK(RUN("3D.Count", NULL)->outputs[0].as.integer == 4, "4 objetos na cena");
/* colisao e posicao */
CHECK(!RUN("3D.Touching", "jogador", "bola")->outputs[0].as.integer, "jogador longe da bola não encosta");
RUN("3D.MoveTo", "bola", "0.6", "0.5", "0");
CHECK(RUN("3D.Touching", "jogador", "bola")->outputs[0].as.integer, "jogador encosta na bola depois de movê-la");
CHECK(RUN("3D.Touching", "jogador", "chão")->outputs[0].as.integer, "cubo apoiado encosta no chão");
RUN("3D.MoveBy", "bola", "1.4", "0", "-1");
CHECK(fabs(RUN("3D.X", "bola")->outputs[0].as.real - 2.0) < 1e-5, "mova por soma à posição");
CHECK(fabs(RUN("3D.Distance", "jogador", "bola")->outputs[0].as.real - sqrt(5.0)) < 1e-4, "distância entre os centros");
TinyBlocks_Block* e = RUN("3D.Hide", "nada");
(void)e;
CHECK(tinyblocks_last_error(rt)[0], "objeto que não existe dá erro");
tinyblocks_clear_error(rt);
/* software: a referencia */
TinyBlocks_Image* sw = render_with("software");
CHECK(sw != NULL, "imagem da cena pelo software");
if (sw) {
uint8_t r, g, b, a;
tb_image_get_pixel(sw, 2, 2, &r, &g, &b, &a);
CHECK(abs(r - 135) < 3 && abs(g - 199) < 3 && abs(b - 250) < 3, "o céu no canto");
tb_image_get_pixel(sw, 160, 118, &r, &g, &b, &a);
CHECK(r > 120 && g < 80 && b < 80, "o cubo vermelho no meio");
tb_image_get_pixel(sw, 160, 230, &r, &g, &b, &a);
CHECK(g > r && g > b, "o chão verde embaixo");
}
const char* gpu[] = { "opengl", "vulkan" };
for (int i = 0; i < 2; i++) {
const char* lib = i ? "tinyblocks-vk" : "tinyblocks-gl";
if (!tb_rt_find_library(rt, lib)) { printf("-- %s não compilado neste teste\n", gpu[i]); continue; }
TinyBlocks_Image* img = render_with(gpu[i]);
TinyBlocks_Block* r = RUN("3D.Renderer", NULL);
const char* used = r->outputs[0].kind == TB_VALUE_TEXT ? r->outputs[0].as.text : "";
if (strncmp(used, gpu[i], strlen(gpu[i])) != 0) { printf("-- %s indisponível aqui (%s)\n", gpu[i], used); tb_image_release(img); continue; }
double mean = 0, bad = 1;
if (img && sw) compare(sw, img, &mean, &bad);
printf(" %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), "%s desenha quase igual ao software", gpu[i]);
CHECK(img && mean < 4.0 && bad < 0.02, m);
tb_image_release(img);
}
tb_image_release(sw);
tinyblocks_deinit(&rt);
if (fails) printf("\n%d FALHA(S)\n", fails);
else printf("\nTUDO OK\n");
return fails != 0;
}