Files
tinyblocks/tests/d3_test.c
T
mguinhosandClaude Opus 5 3f6015db2f 3D: normal map (relevo por pixel) nos 3 renderizadores
Fase 3: a textura "como normal" do material agora inclina a normal por
pixel. O frame de tangentes sai do uv no espaço do objeto (o software
pela face, o GL e o Vulkan pelos dFdx/dFdy da posição local), o normal
map é decodificado (2*rgb-1) e a luz passa a ser por pixel.

- O caminho padrão (objeto sem shader) deixou de usar luz por vértice nos
  três renderizadores: agora interpola cor base e normal e ilumina por
  pixel (com ou sem relevo). Isso muda a imagem de referência (o software
  é a referência e os três continuam batendo).
- OpenGL: o programa padrão virou VS (posição local/normal/uv) + FS
  (TBN + luz + albedo); o FS dos shaders também perturba a normal antes
  do tb_shade. Entra o sampler u_normalmap (unidade 1) e um normal map
  neutro 1x1 (128,128,255) para quem não tem relevo.
- Vulkan: os shaders d3.vert/d3.frag e o FS dos shaders ganham a normal
  local; o descritor ganhou o binding 1 (sampler), o range dos push
  constants do pipeline padrão inclui o fragmento, e o dFdy (que aponta
  para baixo, viewport com altura negativa) tem T e B negados para dar o
  mesmo frame do GL/software. SPIR-V regenerado.
- Software: CV leva a normal de objeto (No) além da de mundo; o
  rasterizador monta o TBN por triângulo, amostra o relevo e reluz por
  pixel. TB_3D_RENDERER_VERSION 6 -> 7.
- test-3d: novo caso de normal map (quad com relevo inclinando para a
  luz); os três batem (diferença média 0.001).
- Exemplo textura.sb com relevo.png e docs atualizadas.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-29 01:13:58 -03:00

463 lines
24 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 [pilha]" com o codigo (JSON) da pilha: o bloco (a saida
e o shader compilado), ou NULL em erro */
static TinyBlocks_Block* compile_shader(const char* json) {
TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, "3D.Shader"));
TinyBlocks_JsonValue* j = tb_json_parse(json, NULL, 0);
TinyBlocks_Value jv = tb_value_json(j);
tb_block_set_default(x, 0, jv);
tb_value_free(&jv);
tb_json_release(j);
tinyblocks_clear_error(rt);
tb_block_eval(x, rt);
return tinyblocks_last_error(rt)[0] ? NULL : x;
}
/* bloco com o shader (valor) na entrada 0 e um texto na 1 */
static TinyBlocks_Block* run_with_shader(const char* type, TinyBlocks_Block* sh, const char* obj) {
TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, type));
tb_block_set_default(x, 0, sh->outputs[0]);
if (obj) { TinyBlocks_Value t = tb_value_text(obj); tb_block_set_default(x, 1, t); tb_value_free(&t); }
tb_block_eval(x, rt);
return x;
}
#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"))) "]]}]";
TinyBlocks_Block* sx = compile_shader(xadrez);
CHECK(sx && sx->outputs[0].kind == TB_VALUE_BLOCK, "compila o xadrez (se/senão, resto, arredonde, cor, luz): um valor");
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"))) "]";
TinyBlocks_Block* sd = compile_shader(degrade);
CHECK(sd != NULL, "compila o degradê (variável local, misture)");
if (!sx || !sd) return 1;
char vt[128];
tb_value_to_text(sx->outputs[0], vt, sizeof(vt));
printf(" valor: %s\n", vt);
CHECK(strstr(vt, "vulkan: ") && strstr(vt, "opengl: "),
"o shader compilado leva o binário de cada renderizador (Vulkan: SPIR-V; OpenGL: o do driver)");
run_with_shader("3D.ShaderUse", sx, "chão");
run_with_shader("3D.ShaderUse", sd, "bola");
CHECK(!tinyblocks_last_error(rt)[0], "use o shader no objeto");
TinyBlocks_Block* g = run_with_shader("3D.ShaderGlsl", sx, NULL);
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("[" 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("[{\"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);
}
}
/* -- malha personalizada + uv: um quadrado pintado pelo uv -- */
{
RUN("3D.Scene", NULL);
RUN("3D.MeshCreate", "quad");
const char* vx[4][3] = { {"-1","-1","0"}, {"1","-1","0"}, {"1","1","0"}, {"-1","1","0"} };
const char* tx[4][2] = { {"0","0"}, {"1","0"}, {"1","1"}, {"0","1"} };
for (int i = 0; i < 4; i++) {
RUN("3D.MeshVertex", "quad", vx[i][0], vx[i][1], vx[i][2]);
RUN("3D.MeshUV", "quad", tx[i][0], tx[i][1]);
}
RUN("3D.MeshTri", "quad", "1", "2", "3");
RUN("3D.MeshTri", "quad", "1", "3", "4");
RUN("3D.MeshFinish", "quad");
CHECK(!tinyblocks_last_error(rt)[0], "malha personalizada: monta sem erro (normais calculadas)");
CHECK(RUN("3D.Count", NULL)->outputs[0].as.integer == 1, "a malha entra na cena como objeto");
CHECK(RUN("3D.X", "quad")->outputs[0].as.real == 0, "mova/gire valem para a malha também");
RUN("3D.Camera", "0", "0", "4", "0", "0", "0");
const char* uvsh = "[" BLK("Shader.Pixel", BLK("Shader.Rgb", BLK0("Shader.U") "," BLK0("Shader.V") "," "0")) "]";
TinyBlocks_Block* su = compile_shader(uvsh);
CHECK(su != NULL, "shader com u do uv / v do uv compila");
if (su) {
TinyBlocks_Block* g = run_with_shader("3D.ShaderGlsl", su, NULL);
CHECK(g->outputs[0].kind == TB_VALUE_TEXT && strstr(g->outputs[0].as.text, "UV.x") &&
strstr(g->outputs[0].as.text, "UV.y"), "o GLSL gerado usa o uv");
run_with_shader("3D.ShaderUse", su, "quad");
}
TinyBlocks_Image* ui = render_with("software");
CHECK(ui != NULL, "a malha personalizada desenha");
if (ui) {
uint8_t l[4], r[4];
tb_image_get_pixel(ui, 125, 120, &l[0], &l[1], &l[2], &l[3]);
tb_image_get_pixel(ui, 195, 120, &r[0], &r[1], &r[2], &r[3]);
printf(" quad por uv: esquerda r=%d direita r=%d\n", l[0], r[0]);
CHECK(r[0] > 150 && l[0] < 100, "o uv pinta da esquerda (u=0) para a direita (u=1)");
for (int i = 0; i < 2; i++) {
const char* lib = i ? "tinyblocks-vk" : "tinyblocks-gl";
if (!tb_rt_find_library(rt, lib)) continue;
TinyBlocks_Image* gi = render_with(gpu[i]);
TinyBlocks_Block* gr = RUN("3D.Renderer", NULL);
const char* used = gr->outputs[0].kind == TB_VALUE_TEXT ? gr->outputs[0].as.text : "";
if (strncmp(used, gpu[i], strlen(gpu[i])) != 0) { tb_image_release(gi); continue; }
double mean = 0, bad = 1;
if (gi) compare(ui, gi, &mean, &bad);
printf(" malha %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), "a malha personalizada com uv desenha igual no %s", gpu[i]);
CHECK(gi && mean < 4.0 && bad < 0.02, m);
tb_image_release(gi);
}
}
tb_image_release(ui);
}
/* -- shader de vertice: estica o triangulo no y -- */
{
const char* vex = "[" BLK("Shader.Vertex", BLK0("Shader.VX") "," BLK("Math.Mul", BLK0("Shader.VY") "," "2") "," BLK0("Shader.VZ")) "]";
TinyBlocks_Block* sv = compile_shader(vex);
CHECK(sv != NULL, "shader de vértice (\"mude a posição do vértice\") compila");
CHECK(!compile_shader("[" BLK("Shader.Pixel", BLK("Shader.Color", "\"azul\"")) "," BLK("Shader.Vertex", BLK0("Shader.VX") "," BLK0("Shader.VY") "," BLK0("Shader.VZ")) "]"),
"não mistura \"cor do pixel\" com \"mude a posição do vértice\"");
tinyblocks_clear_error(rt);
if (sv) {
TinyBlocks_Block* g = run_with_shader("3D.ShaderGlsl", sv, NULL);
CHECK(g->outputs[0].kind == TB_VALUE_TEXT && strstr(g->outputs[0].as.text, "vec3 tb_vert("),
"o GLSL gerado pelo shader de vértice é tb_vert");
run_with_shader("3D.ShaderUse", sv, "quad");
TinyBlocks_Image* vi = render_with("software");
CHECK(vi != NULL, "o shader de vértice desenha no software");
if (vi) {
uint8_t t[4];
tb_image_get_pixel(vi, 160, 40, &t[0], &t[1], &t[2], &t[3]);
printf(" vertice: topo y=40 rgb=(%d,%d,%d)\n", t[0], t[1], t[2]);
for (int i = 0; i < 2; i++) {
const char* lib = i ? "tinyblocks-vk" : "tinyblocks-gl";
if (!tb_rt_find_library(rt, lib)) continue;
TinyBlocks_Image* gi = render_with(gpu[i]);
TinyBlocks_Block* gr = RUN("3D.Renderer", NULL);
const char* used = gr->outputs[0].kind == TB_VALUE_TEXT ? gr->outputs[0].as.text : "";
if (strncmp(used, gpu[i], strlen(gpu[i])) != 0) { tb_image_release(gi); continue; }
double mean = 0, bad = 1;
if (gi) compare(vi, gi, &mean, &bad);
printf(" vértice %s x software: diferença média %.3f, pixels muito diferentes %.2f%%\n", gpu[i], mean, bad * 100);
char m[96];
snprintf(m, sizeof(m), "o shader de vértice desenha igual no %s", gpu[i]);
CHECK(gi && mean < 4.0 && bad < 0.02, m);
tb_image_release(gi);
}
}
tb_image_release(vi);
}
}
/* -- textura + material: um quad pintado por uma imagem 2x2 -- */
{
TinyBlocks_Image* tex = tb_image_new(2, 2, 4);
for (int y = 0; y < 2; y++) {
tb_image_set_pixel(tex, 0, y, 255, 0, 0, 255); /* esquerda: vermelho */
tb_image_set_pixel(tex, 1, y, 0, 0, 255, 255); /* direita: azul */
}
RUN("3D.Scene", NULL);
RUN("3D.MeshCreate", "quad");
const char* vx[4][3] = { {"-1","-1","0"}, {"1","-1","0"}, {"1","1","0"}, {"-1","1","0"} };
const char* tx[4][2] = { {"0","0"}, {"1","0"}, {"1","1"}, {"0","1"} };
for (int i = 0; i < 4; i++) {
RUN("3D.MeshVertex", "quad", vx[i][0], vx[i][1], vx[i][2]);
RUN("3D.MeshUV", "quad", tx[i][0], tx[i][1]);
}
RUN("3D.MeshTri", "quad", "1", "2", "3");
RUN("3D.MeshTri", "quad", "1", "3", "4");
RUN("3D.MeshFinish", "quad");
RUN("3D.Camera", "0", "0", "4", "0", "0", "0");
TinyBlocks_Block* tb = tb_block_create(rt, tb_type_block_find(rt, "3D.Texture"));
TinyBlocks_Value nm = tb_value_text("cores");
tb_block_set_default(tb, 0, nm); tb_value_free(&nm);
TinyBlocks_Value iv = tb_value_image(tex);
tb_block_set_default(tb, 1, iv); tb_value_free(&iv);
tb_block_eval(tb, rt);
CHECK(!tinyblocks_last_error(rt)[0], "3D.Texture: cria a textura a partir de uma imagem");
RUN("3D.Material", "mat");
RUN("3D.MaterialAlbedo", "mat", "cores");
RUN("3D.MaterialUse", "mat", "quad");
CHECK(!tinyblocks_last_error(rt)[0], "3D.Material + albedo + use: sem erro");
const char* tsh = "[" BLK("Shader.Pixel", BLK0("Shader.Texture")) "]";
TinyBlocks_Block* st = compile_shader(tsh);
CHECK(st != NULL, "shader com \"textura do pixel\" compila");
if (st) {
TinyBlocks_Block* g = run_with_shader("3D.ShaderGlsl", st, NULL);
CHECK(g->outputs[0].kind == TB_VALUE_TEXT && strstr(g->outputs[0].as.text, "tex"),
"o GLSL gerado usa a textura do pixel");
}
tb_image_release(tex);
TinyBlocks_Image* ti = render_with("software");
CHECK(ti != NULL, "o objeto com textura desenha");
if (ti) {
uint8_t l[4], r[4];
tb_image_get_pixel(ti, 125, 120, &l[0], &l[1], &l[2], &l[3]);
tb_image_get_pixel(ti, 195, 120, &r[0], &r[1], &r[2], &r[3]);
printf(" textura: esquerda rgb=(%d,%d,%d) direita rgb=(%d,%d,%d)\n", l[0], l[1], l[2], r[0], r[1], r[2]);
CHECK(l[0] > 80 && l[0] > 2 * l[2] && r[2] > 80 && r[2] > 2 * r[0],
"o albedo pinta a esquerda de vermelho e a direita de azul");
for (int i = 0; i < 2; i++) {
const char* lib = i ? "tinyblocks-vk" : "tinyblocks-gl";
if (!tb_rt_find_library(rt, lib)) continue;
TinyBlocks_Image* gi = render_with(gpu[i]);
TinyBlocks_Block* gr = RUN("3D.Renderer", NULL);
const char* used = gr->outputs[0].kind == TB_VALUE_TEXT ? gr->outputs[0].as.text : "";
if (strncmp(used, gpu[i], strlen(gpu[i])) != 0) { tb_image_release(gi); continue; }
double mean = 0, bad = 1;
if (gi) compare(ti, gi, &mean, &bad);
printf(" textura %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), "a textura desenha igual no %s", gpu[i]);
CHECK(gi && mean < 4.0 && bad < 0.02, m);
tb_image_release(gi);
}
}
tb_image_release(ti);
}
/* -- normal map: inclina a normal para a luz num lado do quad -- */
{
TinyBlocks_Image* nm = tb_image_new(2, 2, 4);
for (int y = 0; y < 2; y++) { /* n = (0.6,0,0.8) a esquerda; (-0.6,0,0.8) a direita */
tb_image_set_pixel(nm, 0, y, 204, 128, 230, 255);
tb_image_set_pixel(nm, 1, y, 51, 128, 230, 255);
}
RUN("3D.Scene", NULL);
RUN("3D.MeshCreate", "quad");
const char* vx[4][3] = { {"-1","-1","0"}, {"1","-1","0"}, {"1","1","0"}, {"-1","1","0"} };
const char* tx[4][2] = { {"0","0"}, {"1","0"}, {"1","1"}, {"0","1"} };
for (int i = 0; i < 4; i++) {
RUN("3D.MeshVertex", "quad", vx[i][0], vx[i][1], vx[i][2]);
RUN("3D.MeshUV", "quad", tx[i][0], tx[i][1]);
}
RUN("3D.MeshTri", "quad", "1", "2", "3");
RUN("3D.MeshTri", "quad", "1", "3", "4");
RUN("3D.MeshFinish", "quad");
RUN("3D.Camera", "0", "0", "4", "0", "0", "0");
TinyBlocks_Block* tb = tb_block_create(rt, tb_type_block_find(rt, "3D.Texture"));
TinyBlocks_Value nmv = tb_value_text("relevo");
tb_block_set_default(tb, 0, nmv); tb_value_free(&nmv);
TinyBlocks_Value iv = tb_value_image(nm);
tb_block_set_default(tb, 1, iv); tb_value_free(&iv);
tb_block_eval(tb, rt);
RUN("3D.Material", "pedra");
RUN("3D.MaterialNormal", "pedra", "relevo");
RUN("3D.MaterialUse", "pedra", "quad");
CHECK(!tinyblocks_last_error(rt)[0], "3D.MaterialNormal: sem erro");
tb_image_release(nm);
TinyBlocks_Image* ni = render_with("software");
CHECK(ni != NULL, "o objeto com normal map desenha");
if (ni) {
uint8_t l[4], r[4];
tb_image_get_pixel(ni, 125, 120, &l[0], &l[1], &l[2], &l[3]);
tb_image_get_pixel(ni, 195, 120, &r[0], &r[1], &r[2], &r[3]);
printf(" relevo: esquerda rgb=(%d,%d,%d) direita rgb=(%d,%d,%d)\n", l[0], l[1], l[2], r[0], r[1], r[2]);
CHECK(l[0] > r[0] + 20, "o normal map deixa o lado virado para a luz mais claro");
for (int i = 0; i < 2; i++) {
const char* lib = i ? "tinyblocks-vk" : "tinyblocks-gl";
if (!tb_rt_find_library(rt, lib)) continue;
TinyBlocks_Image* gi = render_with(gpu[i]);
TinyBlocks_Block* gr = RUN("3D.Renderer", NULL);
const char* used = gr->outputs[0].kind == TB_VALUE_TEXT ? gr->outputs[0].as.text : "";
if (strncmp(used, gpu[i], strlen(gpu[i])) != 0) { tb_image_release(gi); continue; }
double mean = 0, bad = 1;
if (gi) compare(ni, gi, &mean, &bad);
printf(" relevo %s x software: diferença média %.3f, pixels muito diferentes %.2f%%\n", gpu[i], mean, bad * 100);
char m[96];
snprintf(m, sizeof(m), "o normal map desenha igual no %s", gpu[i]);
CHECK(gi && mean < 4.0 && bad < 0.02, m);
tb_image_release(gi);
}
}
tb_image_release(ni);
/* o mesmo relevo num shader: a normal que o shader ve ja vem inclinada */
const char* nsh = "[" BLK("Shader.Pixel", BLK("Shader.Rgb", BLK0("Shader.NX") "," BLK0("Shader.NY") "," BLK0("Shader.NZ"))) "]";
TinyBlocks_Block* sn = compile_shader(nsh);
CHECK(sn != NULL, "shader que usa a normal compila com relevo");
if (sn) {
run_with_shader("3D.ShaderUse", sn, "quad");
TinyBlocks_Image* si = render_with("software");
CHECK(si != NULL, "o shader com relevo desenha");
for (int i = 0; si && i < 2; i++) {
const char* lib = i ? "tinyblocks-vk" : "tinyblocks-gl";
if (!tb_rt_find_library(rt, lib)) continue;
TinyBlocks_Image* gi = render_with(gpu[i]);
TinyBlocks_Block* gr = RUN("3D.Renderer", NULL);
const char* used = gr->outputs[0].kind == TB_VALUE_TEXT ? gr->outputs[0].as.text : "";
if (strncmp(used, gpu[i], strlen(gpu[i])) != 0) { tb_image_release(gi); continue; }
double mean = 0, bad = 1;
if (gi) compare(si, gi, &mean, &bad);
printf(" relevo+shader %s x software: diferença média %.3f, pixels muito diferentes %.2f%%\n", gpu[i], mean, bad * 100);
char m[96];
snprintf(m, sizeof(m), "o relevo com shader desenha igual no %s", gpu[i]);
CHECK(gi && mean < 4.0 && bad < 0.02, m);
tb_image_release(gi);
}
tb_image_release(si);
}
}
tb_image_release(sw);
tinyblocks_deinit(&rt);
if (fails) printf("\n%d FALHA(S)\n", fails);
else printf("\nTUDO OK\n");
return fails != 0;
}