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

+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;
}