Shader compilado como valor; binarios gerados pelos backends

"compile o shader [pilha]" vira um reporter: devolve o shader compilado,
um bloco-handle com referencias contadas que se guarda numa variavel
("mude [ondas] para (compile o shader ...)", "use o shader (ondas) no
objeto"); sai o registro de shaders por nome.

A 3d continua sem saber de backend: compila os blocos para GLSL e para o
interpretador do software e pede o binario a cada renderizador pelo
contrato (Tb3dRenderer.compile, versao 3). A vk gera SPIR-V (a libshaderc
e a interface do fragment voltam para ela); a gl liga o programa na thread
dela e devolve o binario do driver (glGetProgramBinary), que carrega com
glProgramBinary e, se recusado, recompila o GLSL. O monitor mostra
"shader compilado (vulkan: 2940 bytes, opengl: 10953 bytes)".

Notacao do forum: a pilha de um encaixe vem embaixo tambem quando o bloco
com o encaixe e um reporter dentro do bloco da linha.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-27 03:08:47 -03:00
1 parent 16009eca8e
commit 1c3103ec55
16 files changed
+1186 -608

No files matched your search

+26 -8
View File
@@ -29,7 +29,7 @@
#include <tinyblocks/tinyblocks.h>
#define TB_3D_LIB "tinyblocks-3d"
#define TB_3D_RENDERER_VERSION 2
#define TB_3D_RENDERER_VERSION 3
/* 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
@@ -42,19 +42,33 @@ typedef struct Tb3dMesh {
int icount;
} Tb3dMesh;
/* Shader compilado ("compile o shader [nome] com [pilha]"): o corpo de uma
funcao GLSL que o renderizador poe no fragment shader:
/* Shader compilado: o valor que o repórter "compile o shader [pilha]"
devolve (um bloco-handle; guarde numa variável) e que "use o shader" põe
num objeto. A 3d compila os blocos para o corpo de uma funcao GLSL (330
e 450) e pede a cada renderizador disponivel o BINARIO dele
(Tb3dRenderer.compile); o formato do binario so o renderizador conhece.
vec3 tb_shade(vec3 P, vec3 N, vec3 base, float light, float time)
P = ponto no mundo, N = normal (normalizada), base = cor do objeto,
light = ambiente + (1 - ambiente) * max(N . luz, 0), time = segundos.
Devolve a cor do pixel (0..1). id fica igual enquanto o nome existir;
version muda a cada compilacao (o renderizador recompila). */
light = ambiente + (1 - ambiente) * max(N . luz, 0), time = segundos;
devolve a cor do pixel (0..1).
id e unico por compilacao (o renderizador guarda o programa da placa por
ele) e vale enquanto alguem usar o shader. */
#define TB_3D_MAX_BINARIES 4
typedef struct Tb3dBinary {
char renderer[16]; /* Tb3dRenderer.name de quem compilou */
void* data; /* malloc do renderizador; a 3d da free */
size_t size;
} Tb3dBinary;
typedef struct Tb3dShader {
int id;
int version;
const char* glsl; /* a funcao tb_shade inteira (GLSL 330/450) */
int version; /* sempre 1 (cada compilacao tem outro id) */
const char* glsl;
Tb3dBinary bin[TB_3D_MAX_BINARIES];
int bin_n;
} Tb3dShader;
/* Um objeto a desenhar */
@@ -92,6 +106,10 @@ typedef struct Tb3dRenderer {
const char* (*error)(void); /* ultimo erro */
bool (*shaders)(void); /* desenha Tb3dDraw.shader? (false: a 3d
usa outro renderizador nesse quadro) */
/* Binario do shader para esta placa, a partir do GLSL (tb_shade). data
com malloc (a 3d libera com free). NULL = o renderizador nao guarda
binario (compila na hora de desenhar). */
bool (*compile)(const char* glsl, void** data, size_t* size, char* err, size_t cap);
} Tb3dRenderer;
TB_API const TinyBlocks_LibraryDescriptor* tb_3d_get_library(void);
+145 -50
View File
@@ -196,14 +196,25 @@ typedef struct {
int kind;
float pos[3], rot[3], scale[3], color[4];
bool visible;
int shader; /* indice em s_shd (-1 = luz padrao) */
struct Shd* shader; /* NULL = luz padrao */
} Obj;
/* Shaders compilados, pelo nome ("compile o shader [nome] com [pilha]") */
typedef struct { Tb3dShader pub; char name[48]; D3Program* prog; } Shd;
#define MAX_SHADERS 64
static Shd s_shd[MAX_SHADERS];
static int s_shd_n;
/* Shader compilado ("compile o shader [pilha]"): o valor que viaja num
bloco-handle; o handle e cada objeto que o usa guardam uma referencia. */
typedef struct Shd {
Tb3dShader pub; /* primeiro: o renderizador ve so isto */
D3Program* prog; /* nos (interpretador do software) */
int refs;
} Shd;
static int s_shd_seq; /* ids unicos por compilacao */
static Shd* shd_retain(Shd* s) { if (s) s->refs++; return s; }
static void shd_release(Shd* s) {
if (!s || --s->refs > 0) return;
d3_shader_free(s->prog);
for (int i = 0; i < s->pub.bin_n; i++) free(s->pub.bin[i].data);
free(s);
}
static double now_s(void) {
struct timespec ts;
@@ -223,6 +234,7 @@ static struct {
} S;
static void scene_reset(void) {
for (int i = 0; i < S.n; i++) shd_release(S.o[i].shader);
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;
@@ -318,7 +330,7 @@ static bool frame_build(Tb3dFrame* f, int w, int h) {
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));
d->shader = o->shader >= 0 && o->shader < s_shd_n && s_shd[o->shader].prog ? &s_shd[o->shader].pub : NULL;
d->shader = o->shader ? &o->shader->pub : NULL;
}
f->draws = s_draws;
f->draw_count = n;
@@ -462,7 +474,7 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
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]);
s_prog = d->shader ? s_shd[d->shader->id - 1].prog : NULL; /* id = indice + 1 */
s_prog = d->shader ? ((const Shd*)d->shader)->prog : NULL; /* pub e o 1o campo */
s_frame = f;
memcpy(s_base, d->color, sizeof(s_base));
for (int t = 0; t + 2 < m->icount; t += 3) {
@@ -479,7 +491,8 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
static bool sw_shaders(void) { return true; }
static const Tb3dRenderer s_software = {
TB_3D_RENDERER_VERSION, "software", sw_available, sw_render, sw_device, sw_error, sw_shaders };
TB_3D_RENDERER_VERSION, "software", sw_available, sw_render, sw_device, sw_error, sw_shaders,
NULL /* interpreta os nos do proprio shader: sem binario */ };
const Tb3dRenderer* tb_3d_software_renderer(void) { return &s_software; }
@@ -544,7 +557,8 @@ static void create(TinyBlocks_Block* self, TinyBlocks* rt, int kind) {
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;
o->shader = -1;
shd_release(o->shader);
o->shader = NULL;
}
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); }
@@ -567,7 +581,12 @@ OBJ_CMD(eval_color, if (!d3_color_of(name_in(self, rt, 1), o->color))
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--; }
if (o) {
shd_release(o->shader);
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) {
@@ -668,50 +687,119 @@ static void eval_image(TinyBlocks_Block* self, TinyBlocks* rt) {
tb_image_release(img);
}
static int shader_find(const char* name) {
for (int i = 0; i < s_shd_n; i++) if (!strcmp(s_shd[i].name, name)) return i;
return -1;
/* -- o bloco-handle do shader compilado --- */
typedef struct { Shd* s; TinyBlocks_Block* owner; } ShdHandle;
typedef struct { TinyBlocks_Block* handle; } ShdProducer;
static TinyBlocks_TypeBlock* s_t_shader;
static void shd_handle_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
ShdHandle* h = self->userdata;
if (!h) return;
shd_release(h->s);
h->s = NULL;
if (h->owner && h->owner->userdata && ((ShdProducer*)h->owner->userdata)->handle == self)
((ShdProducer*)h->owner->userdata)->handle = NULL;
}
static void eval_shader_compile(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
const char* nm = name_in(self, rt, 0);
if (!nm[0]) { tinyblocks_set_error(rt, "dê um nome ao shader"); return; }
TinyBlocks_Value v = tb_block_get_input(self, rt, 1);
const TinyBlocks_JsonValue* code = v.kind == TB_VALUE_JSON ? v.as.json : NULL;
char err[200];
D3Program* prog = d3_shader_compile(code, err, sizeof(err));
if (!prog) { tinyblocks_set_error(rt, "shader \"%s\": %s", nm, err); return; }
int i = shader_find(nm);
if (i < 0) {
if (s_shd_n == MAX_SHADERS) { d3_shader_free(prog); tinyblocks_set_error(rt, "shaders demais (máximo %d)", MAX_SHADERS); return; }
i = s_shd_n++;
memset(&s_shd[i], 0, sizeof(s_shd[i]));
snprintf(s_shd[i].name, sizeof(s_shd[i].name), "%s", nm);
s_shd[i].pub.id = i + 1;
static size_t shd_handle_text(TinyBlocks_Block* self, char* out, size_t cap) {
ShdHandle* h = self->userdata;
if (!h || !h->s) return (size_t)snprintf(out, cap, "shader vazio");
const Tb3dShader* p = &h->s->pub;
if (!p->bin_n) return (size_t)snprintf(out, cap, "shader compilado");
char buf[256]; /* o tamanho devolvido e o real, mesmo com cap 0 */
size_t n = (size_t)snprintf(buf, sizeof(buf), "shader compilado (");
for (int i = 0; i < p->bin_n && n < sizeof(buf); i++)
n += (size_t)snprintf(buf + n, sizeof(buf) - n, "%s%s: %zu bytes", i ? ", " : "", p->bin[i].renderer, p->bin[i].size);
if (n < sizeof(buf)) snprintf(buf + n, sizeof(buf) - n, ")");
return (size_t)snprintf(out, cap, "%s", buf);
}
static void shd_producer_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
ShdProducer* p = self->userdata;
if (p && p->handle) {
TinyBlocks_Block* h = p->handle;
p->handle = NULL;
((ShdHandle*)h->userdata)->owner = NULL;
tb_block_destroy(h, rt);
}
d3_shader_free(s_shd[i].prog);
s_shd[i].prog = prog;
s_shd[i].pub.glsl = d3_shader_glsl(prog);
s_shd[i].pub.version++;
}
static Shd* shd_of(TinyBlocks_Value v) {
if (v.kind != TB_VALUE_BLOCK || !v.as.block || v.as.block->type != s_t_shader) return NULL;
ShdHandle* h = v.as.block->userdata;
return h ? h->s : NULL;
}
/* Pede o binario a cada renderizador disponivel (o formato e dele: a 3d so
guarda). Quem nao compila antes desenha a partir do GLSL. */
static void shd_binaries(TinyBlocks* rt, Shd* sh) {
static const char* libs[] = { "tinyblocks-vk", "tinyblocks-gl" };
for (int i = 0; i < 2 && sh->pub.bin_n < TB_3D_MAX_BINARIES; i++) {
TinyBlocks_LibraryBlock* lib = tb_rt_find_library(rt, libs[i]);
const Tb3dRenderer* r = lib ? lib->lib_userdata : NULL;
if (!r || r->version != TB_3D_RENDERER_VERSION || !r->compile || !r->available() || !r->shaders()) continue;
Tb3dBinary* b = &sh->pub.bin[sh->pub.bin_n];
char err[200];
if (!r->compile(sh->pub.glsl, &b->data, &b->size, err, sizeof(err))) {
snprintf(S.err, sizeof(S.err), "%s: %.140s", r->name, err);
continue;
}
snprintf(b->renderer, sizeof(b->renderer), "%s", r->name);
sh->pub.bin_n++;
}
}
/* "compile o shader [pilha]": le o codigo da pilha (nao a executa) e
devolve o shader compilado: nos (software), GLSL e o binario de cada
renderizador */
static void eval_shader(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
char err[200];
D3Program* prog = d3_shader_compile(v.kind == TB_VALUE_JSON ? v.as.json : NULL, err, sizeof(err));
if (!prog) { tinyblocks_set_error(rt, "shader: %s", err); return; }
Shd* sh = calloc(1, sizeof(*sh));
if (!sh) { d3_shader_free(prog); tinyblocks_set_error(rt, "sem memória"); return; }
sh->prog = prog;
sh->refs = 1;
sh->pub.id = ++s_shd_seq;
sh->pub.version = 1;
sh->pub.glsl = d3_shader_glsl(prog);
shd_binaries(rt, sh);
ShdProducer* p = self->userdata;
if (!p->handle) { /* um handle por bloco: muda o conteudo */
p->handle = tb_block_create(rt, s_t_shader);
if (!p->handle) { shd_release(sh); return; }
((ShdHandle*)p->handle->userdata)->owner = self;
}
ShdHandle* h = p->handle->userdata;
shd_release(h->s);
h->s = sh;
tb_block_set_output(self, 0, tb_value_block(p->handle));
}
static void eval_shader_use(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = need(self, rt, 1);
if (!o) return;
const char* nm = name_in(self, rt, 0);
if (!nm[0] || !strcasecmp(nm, "nenhum")) { o->shader = -1; return; }
int i = shader_find(nm);
if (i < 0) { tinyblocks_set_error(rt, "não existe o shader '%s' (compile antes)", nm); return; }
o->shader = i;
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
Shd* sh = shd_of(v);
if (!sh) {
char* t = tb_value_to_string(v);
bool none = !t || !t[0] || !strcasecmp(t, "nenhum");
free(t);
if (!none) { tinyblocks_set_error(rt, "encaixe um shader compilado (\"compile o shader\" ou uma variável com ele)"); return; }
}
shd_release(o->shader);
o->shader = shd_retain(sh);
}
static void eval_shader_glsl(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
int i = shader_find(name_in(self, rt, 0));
if (i < 0) { tinyblocks_set_error(rt, "não existe o shader '%s'", name_in(self, rt, 0)); return; }
tb_block_set_output(self, 0, tb_value_text(s_shd[i].pub.glsl));
Shd* sh = shd_of(tb_block_get_input(self, rt, 0));
if (!sh) { tinyblocks_set_error(rt, "encaixe um shader compilado"); return; }
tb_block_set_output(self, 0, tb_value_text(sh->pub.glsl));
}
static void eval_renderer(TinyBlocks_Block* self, TinyBlocks* rt) {
@@ -726,7 +814,7 @@ static void eval_count(TinyBlocks_Block* self, TinyBlocks* rt) {
}
/* == Registro ========================================================= */
enum { O_NONE, O_IMAGE, O_REAL, O_BOOL, O_TEXT, O_INT };
enum { O_NONE, O_IMAGE, O_REAL, O_BOOL, O_TEXT, O_INT, O_SHADER };
typedef struct {
const char* name; const char* label; const char* defs;
@@ -771,11 +859,11 @@ static const Spec s_specs[] = {
{ "3D.Use", "use o renderizador %1", "automático", 1, {T}, O_NONE, -1, S_(eval_use), "vulkan, opengl, software ou automático" },
{ "3D.Renderer", "renderizador da cena", "", 0, {T}, O_TEXT, -1, S_(eval_renderer), "Quem desenhou o último quadro (e em qual placa)" },
{ "3D.Count", "número de objetos 3D", "", 0, {T}, O_INT, -1, S_(eval_count), "Quantos objetos a cena tem" },
{ "3D.ShaderCompile", "compile o shader %1 com %2", "ondas|", 2, {T,TB_VALUE_JSON}, O_NONE, 1, S_(eval_shader_compile),
"Compila a pilha de blocos de Shader encaixada (não executa: lê os blocos)" },
{ "3D.ShaderUse", "use o shader %1 no objeto %2", "ondas|chão", 2, {T,T}, O_NONE, -1, S_(eval_shader_use),
"O objeto passa a ser pintado pelo shader (\"nenhum\" volta ao normal)" },
{ "3D.ShaderGlsl", "GLSL do shader %1", "ondas", 1, {T}, O_TEXT, -1, S_(eval_shader_glsl),
{ "3D.Shader", "compile o shader %1", "", 1, {TB_VALUE_JSON}, O_SHADER, 0, S_(eval_shader),
"Compila a pilha de blocos de Shader encaixada (não a executa) e devolve o shader compilado, com o binário de cada renderizador" },
{ "3D.ShaderUse", "use o shader %1 no objeto %2", "|chão", 2, {TB_VALUE_NONE,T}, O_NONE, -1, S_(eval_shader_use),
"O objeto passa a ser pintado pelo shader (vazio ou \"nenhum\" volta ao normal)" },
{ "3D.ShaderGlsl", "GLSL do shader %1", "", 1, {TB_VALUE_NONE}, O_TEXT, -1, S_(eval_shader_glsl),
"O código GLSL que o shader virou (para ver ou estudar)" },
};
#undef T
@@ -788,6 +876,12 @@ static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
meshes_build();
scene_reset();
lib->lib_userdata = (void*)&s_software;
s_t_shader = tb_type_block_create(rt, "3D._Shader", NULL, 0, NULL, 0, NULL);
if (!s_t_shader) return false;
tb_type_block_set_flags(s_t_shader, TB_TYPE_HIDDEN);
tb_type_block_set_instance_hooks(s_t_shader, sizeof(ShdHandle), NULL, shd_handle_deinit);
tb_type_block_set_value_text(s_t_shader, shd_handle_text);
if (!tb_library_add(lib, &s_t_shader->base)) return false;
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];
@@ -799,6 +893,7 @@ static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
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;
case O_SHADER: out[0] = (TinyBlocks_SlotDesc){ "shader", TB_VALUE_BLOCK }; break;
default: break;
}
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, sp->name, sp->nin ? in : NULL, (uint32_t)sp->nin,
@@ -806,6 +901,7 @@ static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
if (!t) return false;
tb_type_block_set_label(t, sp->label, sp->defs);
if (sp->stack_slot >= 0) tb_type_block_set_input_flags(t, (uint32_t)sp->stack_slot, TB_SLOT_STACK);
if (sp->out == O_SHADER) tb_type_block_set_instance_hooks(t, sizeof(ShdProducer), NULL, shd_producer_deinit);
tb_meta_declare(sp->name, sp->fname, __FILE__, sp->doc);
if (!tb_library_add(lib, &t->base)) return false;
}
@@ -815,11 +911,10 @@ static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static void d3_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = NULL;
for (int i = 0; i < S.n; i++) shd_release(S.o[i].shader);
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;
for (int i = 0; i < s_shd_n; i++) d3_shader_free(s_shd[i].prog);
memset(s_shd, 0, sizeof(s_shd)); s_shd_n = 0;
meshes_free();
}
+83 -20
View File
@@ -23,9 +23,12 @@ static struct {
pthread_mutex_t mu;
pthread_cond_t cv;
bool started, ready, failed, quit;
/* um pedido por vez */
/* um pedido por vez: desenhar um quadro, ou compilar o binario de um shader */
const Tb3dFrame* job;
uint8_t* out;
const char* glsl; /* != NULL: compilar */
void** bin;
size_t* bin_size;
bool busy, ok;
char err[256], device[128];
} G = { .mu = PTHREAD_MUTEX_INITIALIZER, .cv = PTHREAD_COND_INITIALIZER };
@@ -41,9 +44,9 @@ static size_t s_rows_cap;
typedef struct { GLuint vao, vbo, ebo; int icount; } GpuMesh;
static GpuMesh s_mesh[32]; /* pelo id da malha */
/* Programas dos shaders feitos com blocos, pelo id (recompila se a versao muda) */
typedef struct { GLuint prog; int version; GLint mvp, model, nrm, color, light, ambient, time; } GpuShader;
static GpuShader s_shd[65];
/* Programas dos shaders feitos com blocos: cache pelo id (id % 64) */
typedef struct { GLuint prog; int id; GLint mvp, model, nrm, color, light, ambient, time; } GpuShader;
static GpuShader s_shd[64];
static void fail(const char* fmt, const char* a) { snprintf(G.err, sizeof(G.err), fmt, a); }
@@ -115,11 +118,12 @@ static GLuint shader(GLenum kind, const char* src) {
return s;
}
static GLuint link(GLuint vs, GLuint fs) {
static GLuint link_hint(GLuint vs, GLuint fs, bool retrievable) {
if (!vs || !fs) { if (vs) glDeleteShader(vs); if (fs) glDeleteShader(fs); return 0; }
GLuint p = glCreateProgram();
glAttachShader(p, vs);
glAttachShader(p, fs);
if (retrievable) glProgramParameteri(p, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);
glLinkProgram(p);
glDeleteShader(vs);
glDeleteShader(fs);
@@ -129,21 +133,65 @@ static GLuint link(GLuint vs, GLuint fs) {
return p;
}
/* O programa de um shader feito com blocos (compila na 1a vez e a cada versao) */
/* O programa do shader feito com blocos, compilado do GLSL */
static GLuint program_from_glsl(const char* glsl, bool retrievable) {
size_t n = strlen(FS_HEAD) + strlen(glsl) + strlen(FS_MAIN) + 1;
char* fs = malloc(n);
if (!fs) return 0;
snprintf(fs, n, "%s%s%s", FS_HEAD, glsl, FS_MAIN);
GLuint p = link_hint(shader(GL_VERTEX_SHADER, VS_SHADER), shader(GL_FRAGMENT_SHADER, fs), retrievable);
free(fs);
return p;
}
/* O binario do OpenGL e o programa ja ligado, como o driver o devolve
(glGetProgramBinary): 4 bytes com o formato e os bytes do driver. So
serve para a mesma placa e driver; se o driver o recusar, recompila. */
static bool binary_compile(const char* glsl, void** data, size_t* size) {
*data = NULL; *size = 0;
GLint nfmt = 0;
glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &nfmt);
if (nfmt < 1) { fail("%s", "o driver não devolve binários de programa"); return false; }
GLuint p = program_from_glsl(glsl, true);
if (!p) return false;
GLint len = 0;
glGetProgramiv(p, GL_PROGRAM_BINARY_LENGTH, &len);
uint8_t* buf = len > 0 ? malloc((size_t)len + 4) : NULL;
GLenum fmt = 0;
if (buf) glGetProgramBinary(p, len, &len, &fmt, buf + 4);
glDeleteProgram(p);
if (!buf || len <= 0) { free(buf); fail("%s", "o driver não devolveu o binário"); return false; }
uint32_t f = (uint32_t)fmt;
memcpy(buf, &f, 4);
*data = buf;
*size = (size_t)len + 4;
return true;
}
static GLuint program_from_binary(const void* data, size_t size) {
if (size <= 4) return 0;
uint32_t f;
memcpy(&f, data, 4);
GLuint p = glCreateProgram();
glProgramBinary(p, (GLenum)f, (const uint8_t*)data + 4, (GLsizei)(size - 4));
GLint ok = 0;
glGetProgramiv(p, GL_LINK_STATUS, &ok);
if (!ok) { glDeleteProgram(p); return 0; }
return p;
}
/* O programa de um shader feito com blocos (na 1a vez que o id aparece):
do binario que veio no shader, ou do GLSL */
static GpuShader* gpu_shader(const Tb3dShader* sh) {
if (sh->id <= 0 || sh->id >= 65) { fail("%s", "id de shader inválido"); return NULL; }
GpuShader* g = &s_shd[sh->id];
if (g->prog && g->version == sh->version) return g;
GpuShader* g = &s_shd[(unsigned)sh->id % 64u];
if (g->prog && g->id == sh->id) return g;
if (g->prog) glDeleteProgram(g->prog);
memset(g, 0, sizeof(*g));
size_t n = strlen(FS_HEAD) + strlen(sh->glsl) + strlen(FS_MAIN) + 1;
char* fs = malloc(n);
if (!fs) return NULL;
snprintf(fs, n, "%s%s%s", FS_HEAD, sh->glsl, FS_MAIN);
g->prog = link(shader(GL_VERTEX_SHADER, VS_SHADER), shader(GL_FRAGMENT_SHADER, fs));
free(fs);
for (int i = 0; i < sh->bin_n && !g->prog; i++)
if (!strcmp(sh->bin[i].renderer, "opengl")) g->prog = program_from_binary(sh->bin[i].data, sh->bin[i].size);
if (!g->prog) g->prog = program_from_glsl(sh->glsl, false);
if (!g->prog) return NULL;
g->version = sh->version;
g->id = sh->id;
g->mvp = glGetUniformLocation(g->prog, "u_mvp");
g->model = glGetUniformLocation(g->prog, "u_model");
g->nrm = glGetUniformLocation(g->prog, "u_nrm");
@@ -293,7 +341,7 @@ static void cleanup(void) {
glDeleteBuffers(1, &s_mesh[i].ebo);
}
memset(s_mesh, 0, sizeof(s_mesh));
for (int i = 0; i < 65; i++) if (s_shd[i].prog) glDeleteProgram(s_shd[i].prog);
for (int i = 0; i < 64; i++) if (s_shd[i].prog) glDeleteProgram(s_shd[i].prog);
memset(s_shd, 0, sizeof(s_shd));
if (s_prog) glDeleteProgram(s_prog);
if (s_fbo) { glDeleteFramebuffers(1, &s_fbo); glDeleteRenderbuffers(1, &s_color); glDeleteRenderbuffers(1, &s_depth); }
@@ -319,8 +367,9 @@ static void* gl_thread(void* arg) {
if (G.quit) break;
const Tb3dFrame* f = G.job;
uint8_t* out = G.out;
const char* glsl = G.glsl;
pthread_mutex_unlock(&G.mu);
bool r = draw(f, out);
bool r = glsl ? binary_compile(glsl, G.bin, G.bin_size) : draw(f, out);
pthread_mutex_lock(&G.mu);
G.ok = r;
G.busy = false;
@@ -347,7 +396,7 @@ static bool gl_available(void) {
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;
G.job = f; G.out = rgba; G.glsl = NULL; G.busy = true;
pthread_cond_broadcast(&G.cv);
while (G.busy) pthread_cond_wait(&G.cv, &G.mu);
bool ok = G.ok;
@@ -359,8 +408,22 @@ static const char* gl_device(void) { return G.device[0] ? G.device : "?"; }
static const char* gl_error(void) { return G.err; }
static bool gl_shaders(void) { return true; }
/* Tb3dRenderer.compile: pede o binario a thread do OpenGL */
static bool gl_compile(const char* glsl, void** data, size_t* size, char* err, size_t cap) {
if (!gl_available()) { snprintf(err, cap, "%s", G.err); return false; }
pthread_mutex_lock(&G.mu);
G.glsl = glsl; G.bin = data; G.bin_size = size; G.busy = true;
pthread_cond_broadcast(&G.cv);
while (G.busy) pthread_cond_wait(&G.cv, &G.mu);
bool ok = G.ok;
G.glsl = NULL;
if (!ok) snprintf(err, cap, "%s", G.err);
pthread_mutex_unlock(&G.mu);
return ok;
}
static const Tb3dRenderer s_renderer = {
TB_3D_RENDERER_VERSION, "opengl", gl_available, gl_render, gl_device, gl_error, gl_shaders };
TB_3D_RENDERER_VERSION, "opengl", gl_available, gl_render, gl_device, gl_error, gl_shaders, gl_compile };
static bool lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
@@ -331,6 +331,22 @@ static const Model* model_of(const Models* M, const char* type) {
return NULL;
}
/* O bloco da linha (ou um repórter encaixado nele, em profundidade) que tem
encaixe de pilha: a pilha dele vem nas linhas de baixo. -1 = nenhum.
Ex.: "mude [s v] para (compile o shader)" + a pilha + "end". */
static int stack_holder(const Models* M, const TbBpTab* tab, int bi, const Model** md) {
if (bi < 0 || bi >= tab->blocks_n || !tab->blocks[bi].used) return -1;
const Model* m = model_of(M, tab->blocks[bi].type);
if (m) { *md = m; return bi; }
for (int s = 0; s < TB_BP_MAX_INPUTS; s++) {
int c = tab->blocks[bi].args[s];
if (c < 0) continue;
int h = stack_holder(M, tab, c, md);
if (h >= 0) return h;
}
return -1;
}
/* "define nome (a) rotulo <b>": um bloco do usuario achado no texto */
#define PROTO_MAX 64
typedef struct {
@@ -609,9 +625,10 @@ static void render_chain(const Models* M, const TbBpTab* tab, int bi, int depth,
indent(out, depth);
render_block(M, tab, c, out, true);
sb_str(out, "\n");
const Model* md = model_of(M, b->type);
if (md && md->stack_slot >= 0 && md->stack_slot < TB_BP_MAX_INPUTS) {
render_chain(M, tab, b->args[md->stack_slot], depth + 1, out);
const Model* md = NULL;
int holder = stack_holder(M, tab, c, &md);
if (holder >= 0 && md->stack_slot < TB_BP_MAX_INPUTS) {
render_chain(M, tab, tab->blocks[holder].args[md->stack_slot], depth + 1, out);
indent(out, depth); sb_str(out, "end\n");
}
if (sh == TB_SB_C1 || sh == TB_SB_C2 || sh == TB_SB_CAP) {
@@ -920,10 +937,11 @@ int tb_scratchblocks_import(const char* text, TbBpTab* out, const TbSbContext* c
else if (depth > 0) tb_blueprint_link(out, L->cblock, TB_BP_REL_SUB0 + L->sub, bi);
L->last = bi;
}
const Model* md = outer ? NULL : model_of(&M, out->blocks[bi].type);
if (md && md->stack_slot >= 0 && depth + 1 < LEVEL_MAX) { /* encaixe de pilha: sub < 0 */
const Model* md = NULL;
int holder = outer ? -1 : stack_holder(&M, out, bi, &md);
if (holder >= 0 && depth + 1 < LEVEL_MAX) { /* encaixe de pilha (sub < 0): no bloco ou num repórter dele */
depth++;
lv[depth].cblock = bi; lv[depth].sub = -1 - md->stack_slot; lv[depth].last = -1;
lv[depth].cblock = holder; lv[depth].sub = -1 - md->stack_slot; lv[depth].last = -1;
} else if (!outer && (sh == TB_SB_C1 || sh == TB_SB_C2 || sh == TB_SB_CAP) && depth + 1 < LEVEL_MAX) {
depth++;
lv[depth].cblock = bi; lv[depth].sub = 0; lv[depth].last = -1;
+91 -64
View File
@@ -19,12 +19,11 @@
typedef struct { VkBuffer buf; VkDeviceMemory mem; void* map; VkDeviceSize size; } Buf;
typedef struct { Buf vb, ib; int icount; } GpuMesh;
/* Pipeline de um shader feito com blocos, pelo id (refeito se a versao muda) */
typedef struct { VkPipeline pipe; int version; } GpuShader;
/* Pipeline de um shader feito com blocos: cache pelo id (id % 64) */
typedef struct { VkPipeline pipe; int id; } GpuShader;
/* -- libshaderc (GLSL -> SPIR-V em execucao), carregada por dlopen --------
So as funcoes da API C usadas aqui (a API e estavel; nao precisa do
header). Sem a biblioteca, a vk so nao desenha shaders feitos com blocos. */
/* -- libshaderc (GLSL -> SPIR-V), carregada por dlopen -------------------- */
/* So as funcoes da API C usadas aqui (estavel; nao precisa do header) */
typedef void* (*ShcInit)(void);
typedef void (*ShcRelease)(void*);
typedef void* (*ShcCompile)(void*, const char*, size_t, int, const char*, const char*, const void*);
@@ -37,6 +36,73 @@ static struct {
ShcStatus status; ShcLength length; ShcBytes bytes, error;
} SC;
static bool shaderc_load(void) {
if (SC.tried) return SC.compiler != NULL;
SC.tried = true;
const char* names[] = { "libshaderc_shared.so.1", "libshaderc.so.1", "libshaderc_shared.so", "libshaderc.so" };
for (int i = 0; i < 4 && !SC.dl; i++) SC.dl = dlopen(names[i], RTLD_NOW | RTLD_LOCAL);
if (!SC.dl) return false;
#define SYM(field, name) do { void* p_ = dlsym(SC.dl, name); memcpy(&SC.field, &p_, sizeof(p_)); } while (0)
SYM(init, "shaderc_compiler_initialize");
SYM(release_compiler, "shaderc_compiler_release");
SYM(compile, "shaderc_compile_into_spv");
SYM(status, "shaderc_result_get_compilation_status");
SYM(length, "shaderc_result_get_length");
SYM(bytes, "shaderc_result_get_bytes");
SYM(error, "shaderc_result_get_error_message");
SYM(release_result, "shaderc_result_release");
#undef SYM
if (SC.init && SC.compile && SC.status && SC.length && SC.bytes && SC.error && SC.release_result)
SC.compiler = SC.init();
return SC.compiler != NULL;
}
static const char* FS_HEAD =
"#version 450\n"
"layout(location = 0) in vec3 v_pos;\n"
"layout(location = 1) in vec3 v_nrm;\n"
"layout(push_constant) uniform PC { mat4 mvp; mat4 model; vec4 color; vec4 light; } pc;\n"
"layout(location = 0) out vec4 o_color;\n";
static const char* FS_MAIN =
"void main() {\n"
" vec3 N = normalize(v_nrm);\n"
" float light = pc.color.a + (1.0 - pc.color.a) * max(dot(N, pc.light.xyz), 0.0);\n"
" o_color = vec4(tb_shade(v_pos, N, pc.color.rgb, light, pc.light.w), 1.0);\n"
"}\n";
/* Tb3dRenderer.compile: o binario do shader para o Vulkan e o SPIR-V do
fragment inteiro (a interface com o vertice fixo esta em FS_HEAD) */
static uint32_t* spirv_fragment(const char* glsl, size_t* words, char* err, size_t cap) {
*words = 0;
if (err && cap) err[0] = 0;
if (!shaderc_load()) { snprintf(err, cap, "sem a libshaderc: shaders feitos com blocos não rodam no Vulkan"); return NULL; }
size_t n = strlen(FS_HEAD) + strlen(glsl) + strlen(FS_MAIN) + 1;
char* src = malloc(n);
if (!src) return NULL;
snprintf(src, n, "%s%s%s", FS_HEAD, glsl, FS_MAIN);
void* res = SC.compile(SC.compiler, src, strlen(src), 1 /* fragment */, "shader.frag", "main", NULL);
free(src);
if (!res || SC.status(res) != 0) {
snprintf(err, cap, "shaderc: %.200s", res ? SC.error(res) : "falhou");
if (res) SC.release_result(res);
return NULL;
}
size_t len = SC.length(res);
uint32_t* spv = malloc(len ? len : 4);
if (spv) { memcpy(spv, SC.bytes(res), len); *words = len / 4; }
SC.release_result(res);
return spv;
}
static bool vk_compile(const char* glsl, void** data, size_t* size, char* err, size_t cap) {
size_t words = 0;
uint32_t* spv = spirv_fragment(glsl, &words, err, cap);
*data = spv;
*size = words * 4;
return spv != NULL;
}
static struct {
bool tried, ok;
char err[256], device[160];
@@ -56,7 +122,7 @@ static struct {
VkPipelineLayout shd_layout; /* 160 bytes de push constants */
VkShaderModule shd_vert;
bool shd_ok; /* da para usar shaders feitos com blocos */
GpuShader shd[65];
GpuShader shd[64];
/* alvo (recriado quando muda o tamanho) */
int w, h;
VkImage color, depth;
@@ -320,71 +386,32 @@ static GpuMesh* gpu_mesh(const Tb3dMesh* m) {
return g;
}
static bool shaderc_load(void) {
if (SC.tried) return SC.compiler != NULL;
SC.tried = true;
const char* names[] = { "libshaderc_shared.so.1", "libshaderc.so.1", "libshaderc_shared.so", "libshaderc.so" };
for (int i = 0; i < 4 && !SC.dl; i++) SC.dl = dlopen(names[i], RTLD_NOW | RTLD_LOCAL);
if (!SC.dl) { snprintf(V.err, sizeof(V.err), "sem a libshaderc: shaders feitos com blocos não rodam no Vulkan"); return false; }
#define SYM(field, name) do { void* p_ = dlsym(SC.dl, name); memcpy(&SC.field, &p_, sizeof(p_)); } while (0)
SYM(init, "shaderc_compiler_initialize");
SYM(release_compiler, "shaderc_compiler_release");
SYM(compile, "shaderc_compile_into_spv");
SYM(status, "shaderc_result_get_compilation_status");
SYM(length, "shaderc_result_get_length");
SYM(bytes, "shaderc_result_get_bytes");
SYM(error, "shaderc_result_get_error_message");
SYM(release_result, "shaderc_result_release");
#undef SYM
if (SC.init && SC.compile && SC.status && SC.length && SC.bytes && SC.error && SC.release_result)
SC.compiler = SC.init();
if (!SC.compiler) snprintf(V.err, sizeof(V.err), "a libshaderc não iniciou");
return SC.compiler != NULL;
}
static const char* FS_HEAD =
"#version 450\n"
"layout(location = 0) in vec3 v_pos;\n"
"layout(location = 1) in vec3 v_nrm;\n"
"layout(push_constant) uniform PC { mat4 mvp; mat4 model; vec4 color; vec4 light; } pc;\n"
"layout(location = 0) out vec4 o_color;\n";
static const char* FS_MAIN =
"void main() {\n"
" vec3 N = normalize(v_nrm);\n"
" float light = pc.color.a + (1.0 - pc.color.a) * max(dot(N, pc.light.xyz), 0.0);\n"
" o_color = vec4(tb_shade(v_pos, N, pc.color.rgb, light, pc.light.w), 1.0);\n"
"}\n";
/* O pipeline de um shader feito com blocos (compila na 1a vez e a cada versao) */
/* O pipeline de um shader feito com blocos (na 1a vez que o id aparece) */
static GpuShader* gpu_shader(const Tb3dShader* sh) {
if (sh->id <= 0 || sh->id >= 65) { snprintf(V.err, sizeof(V.err), "id de shader inválido"); return NULL; }
GpuShader* g = &V.shd[sh->id];
if (g->pipe && g->version == sh->version) return g;
if (!shaderc_load()) return NULL;
size_t n = strlen(FS_HEAD) + strlen(sh->glsl) + strlen(FS_MAIN) + 1;
char* src = malloc(n);
if (!src) return NULL;
snprintf(src, n, "%s%s%s", FS_HEAD, sh->glsl, FS_MAIN);
void* res = SC.compile(SC.compiler, src, strlen(src), 1 /* fragment */, "shader.frag", "main", NULL);
free(src);
if (!res || SC.status(res) != 0) {
snprintf(V.err, sizeof(V.err), "shaderc: %.200s", res ? SC.error(res) : "falhou");
if (res) SC.release_result(res);
return NULL;
GpuShader* g = &V.shd[(unsigned)sh->id % 64u];
if (g->pipe && g->id == sh->id) return g;
/* o binario que veio no shader ("compile o shader"); sem ele, compila agora */
const void* code = NULL;
size_t size = 0;
void* own = NULL;
for (int i = 0; i < sh->bin_n; i++)
if (!strcmp(sh->bin[i].renderer, "vulkan")) { code = sh->bin[i].data; size = sh->bin[i].size; }
if (!code) {
if (!vk_compile(sh->glsl, &own, &size, V.err, sizeof(V.err))) return NULL;
code = own;
}
VkShaderModuleCreateInfo sm = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, SC.length(res),
(const uint32_t*)(const void*)SC.bytes(res) };
VkShaderModuleCreateInfo sm = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, size, code };
VkShaderModule fs;
VkResult r = vkCreateShaderModule(V.dev, &sm, NULL, &fs);
SC.release_result(res);
if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "módulo do shader recusado (%d)", (int)r); return NULL; }
free(own);
if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "binário do shader recusado (%d)", (int)r); return NULL; }
vkDeviceWaitIdle(V.dev);
if (g->pipe) vkDestroyPipeline(V.dev, g->pipe, NULL);
g->pipe = VK_NULL_HANDLE;
r = build_pipe(V.shd_vert, fs, V.shd_layout, &g->pipe);
vkDestroyShaderModule(V.dev, fs, NULL);
if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "pipeline do shader recusado (%d)", (int)r); return NULL; }
g->version = sh->version;
g->id = sh->id;
return g;
}
@@ -419,7 +446,7 @@ static bool vk_draw(const Tb3dFrame* f, uint8_t* out) {
memcpy(pc + 16, d->model, sizeof(d->model));
pc[32] = d->color[0]; pc[33] = d->color[1]; pc[34] = d->color[2]; pc[35] = f->ambient;
pc[36] = f->light_dir[0]; pc[37] = f->light_dir[1]; pc[38] = f->light_dir[2]; pc[39] = f->time;
vkCmdBindPipeline(V.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, V.shd[d->shader->id].pipe);
vkCmdBindPipeline(V.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, V.shd[(unsigned)d->shader->id % 64u].pipe);
vkCmdPushConstants(V.cmd, V.shd_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
0, sizeof(pc), pc);
VkDeviceSize off = 0;
@@ -466,7 +493,7 @@ static void vk_cleanup(void) {
vkDeviceWaitIdle(V.dev);
for (int i = 0; i < 32; i++) { buf_free(&V.mesh[i].vb); buf_free(&V.mesh[i].ib); }
target_free();
for (int i = 0; i < 65; i++) if (V.shd[i].pipe) vkDestroyPipeline(V.dev, V.shd[i].pipe, NULL);
for (int i = 0; i < 64; i++) if (V.shd[i].pipe) vkDestroyPipeline(V.dev, V.shd[i].pipe, NULL);
if (V.shd_vert) vkDestroyShaderModule(V.dev, V.shd_vert, NULL);
if (V.shd_layout) vkDestroyPipelineLayout(V.dev, V.shd_layout, NULL);
if (V.pipe) vkDestroyPipeline(V.dev, V.pipe, NULL);
@@ -502,7 +529,7 @@ static const char* vk_error(void) { return V.err; }
static bool vk_shaders(void) { return V.ok && V.shd_ok && shaderc_load(); }
static const Tb3dRenderer s_renderer = {
TB_3D_RENDERER_VERSION, "vulkan", vk_available, vk_render, vk_device, vk_error, vk_shaders };
TB_3D_RENDERER_VERSION, "vulkan", vk_available, vk_render, vk_device, vk_error, vk_shaders, vk_compile };
static bool lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;