"compile o shader [nome] com [pilha]" tem um encaixe de pilha: a pilha nao roda, a 3d le o codigo dela e o compila (d3_shader.c) em nos com tipo (numero, cor, condicao), de onde saem o GLSL da funcao tb_shade e um interpretador para o renderizador em software (ponto e normal com perspectiva, pixel a pixel). "use o shader [nome] no objeto" e "GLSL do shader" completam. tinyblocks-shader: o vocabulario (cor do pixel =, cor do pixel, cor do objeto, luz, tempo, x/y/z do ponto e da normal, cor r g b, cor [nome], misture, canais, brilho). Valem tambem as contas, comparacoes, o se/senao e as variaveis comuns (viram locais do shader). Contrato v2: Tb3dDraw.shader, Tb3dFrame.time, Tb3dRenderer.shaders. GL: um programa por shader. Vulkan: o fragment compilado em execucao pela libshaderc (dlopen) e push constants de 160 bytes; sem ela, a 3d usa o OpenGL ou o software nesses quadros. test-3d: xadrez e degrade iguais nos tres renderizadores (diferenca media 0,002), sem avisos da camada de validacao na NVIDIA, Intel e llvmpipe; erros claros para bloco que nao cabe e para comparar cores. examples/jogo-3d/shaders: ondas no chao e listras na bola. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
203 lines
9.4 KiB
C
203 lines
9.4 KiB
C
/*
|
|
* 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*)))
|
|
|
|
/* "compile o shader [nome] com [pilha]" com o codigo (JSON) da pilha */
|
|
static bool compile_shader(const char* name, const char* json) {
|
|
TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, "3D.ShaderCompile"));
|
|
TinyBlocks_Value nv = tb_value_text(name);
|
|
tb_block_set_default(x, 0, nv);
|
|
tb_value_free(&nv);
|
|
TinyBlocks_JsonValue* j = tb_json_parse(json, NULL, 0);
|
|
TinyBlocks_Value jv = tb_value_json(j);
|
|
tb_block_set_default(x, 1, jv);
|
|
tb_value_free(&jv);
|
|
tb_json_release(j);
|
|
tinyblocks_clear_error(rt);
|
|
tb_block_eval(x, rt);
|
|
return !tinyblocks_last_error(rt)[0];
|
|
}
|
|
|
|
#define BLK(t, ...) "{\"type\":\"" t "\",\"inputs\":[" __VA_ARGS__ "]}"
|
|
#define BLK0(t) "{\"type\":\"" t "\",\"inputs\":[]}"
|
|
|
|
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 pass = 0; pass < 2; pass++) {
|
|
if (pass == 1) {
|
|
/* -- shaders feitos com blocos: xadrez no chao, degrade na bola */
|
|
const char* xadrez = "[{\"type\":\"Control.IfElse\",\"inputs\":["
|
|
BLK("Operators.Eq", BLK("Math.Mod", BLK("Math.Add", BLK("Number.Floor", BLK0("Shader.X")) ","
|
|
BLK("Number.Floor", BLK0("Shader.Z"))) ",2") ",0")
|
|
"],\"mouths\":[[" BLK("Shader.Pixel", BLK("Math.Mul", BLK("Shader.Color", "\"branco\"") "," BLK0("Shader.Light")))
|
|
"],[" BLK("Shader.Pixel", BLK("Math.Mul", BLK("Shader.Color", "\"#333333\"") "," BLK0("Shader.Light"))) "]]}]";
|
|
CHECK(compile_shader("xadrez", xadrez), "compila o xadrez (se/senão, resto, arredonde, cor, luz)");
|
|
const char* degrade = "[" BLK("Variables.Set", "\"t\"," BLK("Math.Div", BLK("Math.Add", BLK0("Shader.NY") ",1") ",2"))
|
|
"," BLK("Shader.Pixel", BLK("Math.Mul", BLK("Shader.Mix", BLK("Shader.Color", "\"azul\"") ","
|
|
BLK("Shader.Color", "\"branco\"") "," BLK("Variables.Get", "\"t\"")) "," BLK0("Shader.Light"))) "]";
|
|
CHECK(compile_shader("degrade", degrade), "compila o degradê (variável local, misture)");
|
|
RUN("3D.ShaderUse", "xadrez", "chão");
|
|
RUN("3D.ShaderUse", "degrade", "bola");
|
|
CHECK(!tinyblocks_last_error(rt)[0], "use o shader no objeto");
|
|
TinyBlocks_Block* g = RUN("3D.ShaderGlsl", "xadrez");
|
|
CHECK(g->outputs[0].kind == TB_VALUE_TEXT && strstr(g->outputs[0].as.text, "vec3 tb_shade(") &&
|
|
strstr(g->outputs[0].as.text, "mod("), "GLSL gerado");
|
|
CHECK(!compile_shader("ruim", "[" BLK("Shader.Pixel", BLK0("Input.Timer")) "]") &&
|
|
strstr(tinyblocks_last_error(rt), "não pode ser usado num shader"), "bloco que não cabe num shader: erro claro");
|
|
CHECK(!compile_shader("ruim", "[{\"type\":\"Control.If\",\"inputs\":[" BLK("Operators.Lt", BLK0("Shader.PixelColor") ",1")
|
|
"],\"mouths\":[[]]}]") && strstr(tinyblocks_last_error(rt), "comparar números"), "comparar cor: erro claro");
|
|
tinyblocks_clear_error(rt);
|
|
tb_image_release(sw);
|
|
sw = render_with("software");
|
|
CHECK(sw != NULL, "cena com shaders pelo software");
|
|
if (sw) {
|
|
uint8_t r, g2, b, a, r2, g3, b2;
|
|
tb_image_get_pixel(sw, 40, 225, &r, &g2, &b, &a);
|
|
tb_image_get_pixel(sw, 75, 225, &r2, &g3, &b2, &a);
|
|
CHECK(abs(r - g2) < 4 && abs(r2 - g3) < 4 && abs(r - r2) > 60, "o chão virou xadrez (cinza claro e escuro)");
|
|
}
|
|
}
|
|
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), pass ? "%s com shaders desenha quase igual ao software" : "%s desenha quase igual ao software", gpu[i]);
|
|
CHECK(img && mean < 4.0 && bad < 0.02, m);
|
|
if (pass) {
|
|
char path[64];
|
|
snprintf(path, sizeof(path), "/tmp/tb_3d_%s_shader.png", gpu[i]);
|
|
tb_image_save(img, path);
|
|
}
|
|
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;
|
|
}
|