tinyblocks-plot: graficos no estilo do matplotlib

Figura atual como no pyplot: linha, linha x-y, pontos, barras com nomes,
histograma, titulo, nomes dos eixos (y na vertical), legenda, grade,
limites e series com nome que crescem a cada passo (curvas de treino).
Desenha numa imagem (para o palco) ou grava em PNG/BMP/PPM. Valores de
lista, de texto ou de tensor. Paleta tab10; marcas "redondas" (1, 2, 5
x 10^n) com folga de 5%; linhas e pontos com antisserrilhado; fonte
DejaVu Sans 12 px embutida (tools/gen_font.c, via tinyblocks-opentype),
com os acentos do portugues.

Convolucoes da ai: "filtros de tamanho %3" (o rotulo repetia o campo).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-26 23:47:49 -03:00
1 parent 25bb30d12f
commit 2951535d93
10 files changed
+1957 -4

No files matched your search

+13 -2
View File
@@ -86,7 +86,7 @@ CAT_LDFLAGS := $(foreach l,$(CAT_LIBS),-ltinyblocks-$(l))
CAT_INCS := $(foreach l,$(CAT_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include) CAT_INCS := $(foreach l,$(CAT_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include)
# Libraries que o editor registra como as de categoria, mas com varios # Libraries que o editor registra como as de categoria, mas com varios
# fontes e o Makefile proprio (o harness nao as compila junto) # fontes e o Makefile proprio (o harness nao as compila junto)
APP_LIBS := socket ssl http archive tensor ai APP_LIBS := socket ssl http archive tensor ai plot
APP_A := $(foreach l,$(APP_LIBS),$(LIBDIR)/tinyblocks-$(l)/build/libtinyblocks-$(l).a) APP_A := $(foreach l,$(APP_LIBS),$(LIBDIR)/tinyblocks-$(l)/build/libtinyblocks-$(l).a)
APP_INCS := $(foreach l,$(APP_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include) APP_INCS := $(foreach l,$(APP_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include)
APP_LDLIBS := -lssl -lcrypto -lz -lpthread APP_LDLIBS := -lssl -lcrypto -lz -lpthread
@@ -111,7 +111,7 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \
editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \ editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \
appdir appimage run-appimage icon \ appdir appimage run-appimage icon \
test-toml test-plugin test-blueprint test-a11y test-mcp test-mcp-server test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \ test-toml test-plugin test-blueprint test-a11y test-mcp test-mcp-server test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \
test-tensor test-ai test-http test-archive test-syntax test-os test-value test-vars test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \ test-tensor test-ai test-http test-archive test-plot test-syntax test-os test-value test-vars test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \
category-libs category-sos libs app-libs \ category-libs category-sos libs app-libs \
lib-events lib-control lib-errors lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \ lib-events lib-control lib-errors lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \
lib-environ \ lib-environ \
@@ -648,6 +648,17 @@ $(BUILD)/archive_test: tests/archive_test.c $(LIBDIR)/tinyblocks-archive/src/tb_
test-archive: $(BUILD)/archive_test ## Roda o teste da archive (ASan/UBSan) test-archive: $(BUILD)/archive_test ## Roda o teste da archive (ASan/UBSan)
./$(BUILD)/archive_test ./$(BUILD)/archive_test
# -- Teste da library plot (figura -> imagem PNG) ---
PLOT_DIR := $(LIBDIR)/tinyblocks-plot
$(BUILD)/plot_test: tests/plot_test.c $(PLOT_DIR)/src/tb_plot.c $(PLOT_DIR)/src/plot_font.h $(TENSOR_SRCS) static
@mkdir -p $(BUILD)
$(CC) $(CFLAGS_DBG) -I$(TENSOR_DIR)/include -I$(PLOT_DIR)/include -I$(PNG_DIR)/include \
$(TENSOR_SRCS) $(PLOT_DIR)/src/tb_plot.c $(PNG_DIR)/src/tb_png.c tests/plot_test.c -o $@ \
-Wl,--start-group $(LIB_A) -Wl,--end-group -lpng -lm -lpthread
test-plot: $(BUILD)/plot_test ## Roda o teste da plot (ASan/UBSan; grava /tmp/tb_plot_*.png)
./$(BUILD)/plot_test
# -- Teste da library curves --- # -- Teste da library curves ---
$(BUILD)/curves_test: tests/curves_test.c $(CV_DIR)/src/tb_curves.c static $(BUILD)/curves_test: tests/curves_test.c $(CV_DIR)/src/tb_curves.c static
@mkdir -p $(BUILD) @mkdir -p $(BUILD)
+2
View File
@@ -41,6 +41,7 @@
#include <tb_archive.h> #include <tb_archive.h>
#include <tb_tensor.h> #include <tb_tensor.h>
#include <tb_ai.h> #include <tb_ai.h>
#include <tb_plot.h>
#include <tb_api.h> #include <tb_api.h>
/* Registra uma library de categoria: se existir o .so dela no disco, carrega /* Registra uma library de categoria: se existir o .so dela no disco, carrega
@@ -90,6 +91,7 @@ int main(int argc, char** argv) {
reg_core(rt, "tinyblocks-archive", tb_archive_get_library); reg_core(rt, "tinyblocks-archive", tb_archive_get_library);
reg_core(rt, "tinyblocks-tensor", tb_tensor_get_library); reg_core(rt, "tinyblocks-tensor", tb_tensor_get_library);
reg_core(rt, "tinyblocks-ai", tb_ai_get_library); reg_core(rt, "tinyblocks-ai", tb_ai_get_library);
reg_core(rt, "tinyblocks-plot", tb_plot_get_library);
/* Interface gráfica: o editor mede texto e cria o palco ao nascer */ /* Interface gráfica: o editor mede texto e cria o palco ao nascer */
tb_library_register(rt, tb_graphics_get_library()); tb_library_register(rt, tb_graphics_get_library());
+2 -2
View File
@@ -601,8 +601,8 @@ typedef struct {
static const Spec s_specs[] = { static const Spec s_specs[] = {
/* camadas */ /* camadas */
{ "AI.Linear", "camada linear de %1 com %2 saídas", "|10", 2, {N,I}, 0, 1, S(eval_linear), "x W + b (W [entradas, saídas]); os pesos nascem na primeira vez" }, { "AI.Linear", "camada linear de %1 com %2 saídas", "|10", 2, {N,I}, 0, 1, S(eval_linear), "x W + b (W [entradas, saídas]); os pesos nascem na primeira vez" },
{ "AI.Conv", "convolução de %1 com %2 filtros %3 x %3 passo %4 margem %5", "|16|3|1|1", 5, {N,I,I,I,I}, 0, 1, S(eval_conv), "Convolução 2D de [lote, canais, A, L]" }, { "AI.Conv", "convolução de %1 com %2 filtros de tamanho %3 passo %4 margem %5", "|16|3|1|1", 5, {N,I,I,I,I}, 0, 1, S(eval_conv), "Convolução 2D de [lote, canais, A, L]" },
{ "AI.ConvT", "convolução transposta de %1 com %2 filtros %3 x %3 passo %4 margem %5", "|16|4|2|1", 5, {N,I,I,I,I}, 0, 1, S(eval_conv_t), "Convolução transposta (aumenta a imagem): A' = (A-1) passo - 2 margem + filtro" }, { "AI.ConvT", "convolução transposta de %1 com %2 filtros de tamanho %3 passo %4 margem %5", "|16|4|2|1", 5, {N,I,I,I,I}, 0, 1, S(eval_conv_t), "Convolução transposta (aumenta a imagem): A' = (A-1) passo - 2 margem + filtro" },
{ "AI.MaxPool", "max pool de %1 com janela %2", "|2", 2, {N,I}, 0, 1, S(eval_pool), "Maior valor de cada janela (passo = janela)" }, { "AI.MaxPool", "max pool de %1 com janela %2", "|2", 2, {N,I}, 0, 1, S(eval_pool), "Maior valor de cada janela (passo = janela)" },
{ "AI.BatchNorm", "batch norm de %1", "", 1, {N}, 0, 1, S(eval_batchnorm), "Normaliza cada canal pelo lote (médias móveis no modo de avaliação)" }, { "AI.BatchNorm", "batch norm de %1", "", 1, {N}, 0, 1, S(eval_batchnorm), "Normaliza cada canal pelo lote (médias móveis no modo de avaliação)" },
{ "AI.LayerNorm", "layer norm de %1", "", 1, {N}, 0, 1, S(eval_layernorm), "Normaliza o último eixo (ganho e deslocamento treináveis)" }, { "AI.LayerNorm", "layer norm de %1", "", 1, {N}, 0, 1, S(eval_layernorm), "Normaliza o último eixo (ganho e deslocamento treináveis)" },
+30
View File
@@ -0,0 +1,30 @@
# Makefile da library plot (categoria "Gráficos")
# Constroi build/libtinyblocks-plot.a e build/libtinyblocks-plot.so
CC := gcc
BUILD := build
CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude -I../tinyblocks-tensor/include
SRCS := src/tb_plot.c
OBJS := $(BUILD)/tb_plot.o
LIB_A := $(BUILD)/libtinyblocks-plot.a
LIB_SO := $(BUILD)/libtinyblocks-plot.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)
@@ -0,0 +1,34 @@
/*
* TinyBlocks - tb_plot.h
* Library tinyblocks-plot: graficos no estilo do pyplot do matplotlib.
* Registra a categoria "Gráficos".
*
* Ha uma figura atual: "nova figura" a limpa; "plote", "pontos", "barras" e
* "histograma" acrescentam series; titulo, nomes dos eixos, limites,
* legenda e grade a enfeitam; "imagem da figura" a desenha numa imagem
* (para o palco: "desenhe (imagem da figura) ...") e "salve a figura" grava
* (.png, .bmp, .ppm, conforme os formatos carregados).
*
* Os valores podem vir de uma lista, de um texto "1, 2, 3" ou de um tensor
* (tinyblocks-tensor, se estiver carregada). Series com nome ("acrescente
* (perda) a serie [treino]") crescem a cada passo: boas para curvas de
* treino ao vivo.
*
* Cores: a paleta tab10 do matplotlib (azul, laranja, verde, vermelho, roxo,
* marrom, rosa, cinza, oliva, ciano), preto, branco ou "#rrggbb"; vazio =
* a proxima da paleta. O texto usa uma fonte embutida (DejaVu Sans 12 px).
*/
#ifndef TINYBLOCKS_PLOT_H
#define TINYBLOCKS_PLOT_H
#include <tinyblocks/tinyblocks.h>
TB_API const TinyBlocks_LibraryDescriptor* tb_plot_get_library(void);
/* -- API C: a figura atual --- */
TB_API void tb_plot_figure(int w, int h);
TB_API void tb_plot_line(const float* x, const float* y, int n, const char* color, const char* label);
TB_API void tb_plot_title(const char* title);
TB_API TinyBlocks_Image* tb_plot_render(void); /* imagem nova (ref = 1) */
#endif /* TINYBLOCKS_PLOT_H */
+15
View File
@@ -0,0 +1,15 @@
# Metadados da library plot. Lido pela UI/build sem recompilar o .so.
[library]
name = "tinyblocks-plot"
version = "1.0.0"
category = "Gráficos"
description = "Graficos no estilo do matplotlib: linhas, pontos, barras, histograma, legenda e series que crescem; desenha numa imagem"
color = [38, 158, 140, 255]
dark = [26, 120, 107, 255]
[build]
sources = ["src/tb_plot.c"]
includes = ["include"]
shared = "build/libtinyblocks-plot.so"
static = "build/libtinyblocks-plot.a"
depends = ["tensor"]
File diff suppressed because it is too large. Load diff
+665
View File
@@ -0,0 +1,665 @@
/*
* TinyBlocks - tb_plot.c
* A figura atual, o desenho dela numa imagem (linhas e pontos com
* antisserrilhado, barras, eixos com marcas "redondas", legenda, grade,
* texto com a fonte embutida) e os blocos da categoria "Gráficos".
*/
#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_json_block.h>
#include <tinyblocks/tb_image.h>
#include "tb_tensor.h"
#include "tb_plot.h"
#include "plot_font.h"
/* == Figura =========================================================== */
enum { S_LINE, S_SCATTER, S_BAR };
typedef struct {
int kind;
float* x;
float* y;
int n;
uint32_t color; /* 0xRRGGBB */
char label[64];
char** names; /* barras: nomes no eixo x (ou NULL) */
} Series;
static struct {
int w, h;
char title[128], xlabel[96], ylabel[96];
bool legend, grid;
bool xlim, ylim;
double x0, x1, y0, y1;
Series* s;
int n, cap, next_color;
} F = { 480, 320, "", "", "", false, false, false, false, 0, 1, 0, 1, NULL, 0, 0, 0 };
static const uint32_t s_tab10[10] = {
0x1f77b4, 0xff7f0e, 0x2ca02c, 0xd62728, 0x9467bd, 0x8c564b, 0xe377c2, 0x7f7f7f, 0xbcbd22, 0x17becf };
static const char* s_names[] = { "azul", "laranja", "verde", "vermelho", "roxo", "marrom", "rosa", "cinza", "oliva", "ciano" };
static uint32_t color_of(const char* c) {
while (c && isspace((unsigned char)*c)) c++;
if (!c || !*c) return s_tab10[F.next_color++ % 10];
if (c[0] == '#' && strlen(c) >= 7) return (uint32_t)strtoul(c + 1, NULL, 16) & 0xffffff;
for (int i = 0; i < 10; i++) if (!strcasecmp(c, s_names[i])) return s_tab10[i];
if (!strcasecmp(c, "preto")) return 0x000000;
if (!strcasecmp(c, "branco")) return 0xffffff;
return s_tab10[F.next_color++ % 10];
}
static void series_free(Series* s) {
free(s->x); free(s->y);
for (int i = 0; s->names && i < s->n; i++) free(s->names[i]);
free(s->names);
}
void tb_plot_figure(int w, int h) {
for (int i = 0; i < F.n; i++) series_free(&F.s[i]);
F.n = 0;
F.w = w < 64 ? 64 : w > 4096 ? 4096 : w;
F.h = h < 64 ? 64 : h > 4096 ? 4096 : h;
F.title[0] = F.xlabel[0] = F.ylabel[0] = 0;
F.legend = F.grid = F.xlim = F.ylim = false;
F.next_color = 0;
}
/* Acrescenta uma serie (copia os vetores; x NULL = 1..n) */
static Series* add(int kind, const float* x, const float* y, int n, const char* color, const char* label) {
if (F.n == F.cap) {
int nc = F.cap ? F.cap * 2 : 8;
Series* p = realloc(F.s, (size_t)nc * sizeof(*p));
if (!p) return NULL;
F.s = p; F.cap = nc;
}
Series* s = &F.s[F.n];
memset(s, 0, sizeof(*s));
s->x = malloc((size_t)(n ? n : 1) * sizeof(float));
s->y = malloc((size_t)(n ? n : 1) * sizeof(float));
if (!s->x || !s->y) { free(s->x); free(s->y); return NULL; }
for (int i = 0; i < n; i++) { s->x[i] = x ? x[i] : (float)(i + 1); s->y[i] = y[i]; }
s->n = n; s->kind = kind;
s->color = color_of(color);
snprintf(s->label, sizeof(s->label), "%s", label ? label : "");
F.n++;
return s;
}
void tb_plot_line(const float* x, const float* y, int n, const char* color, const char* label) {
add(S_LINE, x, y, n, color, label);
}
void tb_plot_title(const char* t) { snprintf(F.title, sizeof(F.title), "%s", t ? t : ""); }
/* == Desenho ========================================================== */
typedef struct { uint8_t* p; int w, h; int cx0, cy0, cx1, cy1; } Canvas; /* recorte [cx0,cx1) */
static void blend(Canvas* c, int x, int y, uint32_t rgb, float a) {
if (x < c->cx0 || y < c->cy0 || x >= c->cx1 || y >= c->cy1 || a <= 0) return;
if (a > 1) a = 1;
uint8_t* q = c->p + ((size_t)y * c->w + x) * 4;
float r = (float)((rgb >> 16) & 255), g = (float)((rgb >> 8) & 255), b = (float)(rgb & 255);
q[0] = (uint8_t)(q[0] + (r - q[0]) * a + .5f);
q[1] = (uint8_t)(q[1] + (g - q[1]) * a + .5f);
q[2] = (uint8_t)(q[2] + (b - q[2]) * a + .5f);
q[3] = 255;
}
static void fill_rect(Canvas* c, float x0, float y0, float x1, float y1, uint32_t rgb, float a) {
if (x1 < x0) { float t = x0; x0 = x1; x1 = t; }
if (y1 < y0) { float t = y0; y0 = y1; y1 = t; }
for (int y = (int)floorf(y0); y < (int)ceilf(y1); y++)
for (int x = (int)floorf(x0); x < (int)ceilf(x1); x++) {
float cx = fminf(x + 1.f, x1) - fmaxf((float)x, x0), cy = fminf(y + 1.f, y1) - fmaxf((float)y, y0);
if (cx > 0 && cy > 0) blend(c, x, y, rgb, a * cx * cy);
}
}
/* Segmento com espessura w: cobertura pela distancia ao segmento */
static void line(Canvas* c, float x0, float y0, float x1, float y1, float w, uint32_t rgb) {
float r = w * 0.5f;
int bx0 = (int)floorf(fminf(x0, x1) - r - 1), bx1 = (int)ceilf(fmaxf(x0, x1) + r + 1);
int by0 = (int)floorf(fminf(y0, y1) - r - 1), by1 = (int)ceilf(fmaxf(y0, y1) + r + 1);
if (bx0 < c->cx0) bx0 = c->cx0;
if (by0 < c->cy0) by0 = c->cy0;
if (bx1 > c->cx1) bx1 = c->cx1;
if (by1 > c->cy1) by1 = c->cy1;
float dx = x1 - x0, dy = y1 - y0, L2 = dx * dx + dy * dy;
for (int y = by0; y < by1; y++)
for (int x = bx0; x < bx1; x++) {
float px = x + .5f - x0, py = y + .5f - y0;
float t = L2 > 0 ? (px * dx + py * dy) / L2 : 0;
t = t < 0 ? 0 : t > 1 ? 1 : t;
float ex = px - t * dx, ey = py - t * dy;
float cov = r + 0.5f - sqrtf(ex * ex + ey * ey);
if (cov > 0) blend(c, x, y, rgb, cov);
}
}
static void disc(Canvas* c, float cx, float cy, float r, uint32_t rgb) {
for (int y = (int)(cy - r - 1); y <= (int)(cy + r + 1); y++)
for (int x = (int)(cx - r - 1); x <= (int)(cx + r + 1); x++) {
float d = sqrtf((x + .5f - cx) * (x + .5f - cx) + (y + .5f - cy) * (y + .5f - cy));
blend(c, x, y, rgb, r + 0.5f - d);
}
}
/* -- texto ---------------------------------------------------------------- */
static const PlotGlyph* glyph(unsigned cp) {
if (cp >= 32 && cp < 127) return &s_glyphs[cp - 32];
if (cp >= 160 && cp < 256) return &s_glyphs[95 + cp - 160];
return &s_glyphs['?' - 32];
}
static const char* next_cp(const char* p, unsigned* cp) {
unsigned char c = (unsigned char)*p;
if (c < 0x80) { *cp = c; return p + 1; }
if ((c & 0xE0) == 0xC0 && p[1]) { *cp = ((c & 0x1Fu) << 6) | ((unsigned char)p[1] & 0x3Fu); return p + 2; }
int n = (c & 0xF0) == 0xE0 ? 3 : (c & 0xF8) == 0xF0 ? 4 : 1;
for (int i = 1; i < n && p[i]; i++) p++;
*cp = '?';
return p + 1;
}
static int text_w(const char* s) {
int w = 0;
for (unsigned cp; *s; ) { s = next_cp(s, &cp); w += glyph(cp)->w; }
return w;
}
/* Texto com o topo em (x, y); vertical = de baixo para cima (eixo y) */
static void text(Canvas* c, int x, int y, const char* s, uint32_t rgb, bool vertical) {
int pen = 0;
for (unsigned cp; *s; ) {
s = next_cp(s, &cp);
const PlotGlyph* g = glyph(cp);
const uint8_t* a = s_font + g->off;
for (int gy = 0; gy < PLOT_FONT_H; gy++)
for (int gx = 0; gx < g->w; gx++) {
float al = a[gy * g->w + gx] / 255.f;
if (!al) continue;
if (vertical) blend(c, x + gy, y - pen - gx, rgb, al);
else blend(c, x + pen + gx, y + gy, rgb, al);
}
pen += g->w;
}
}
/* -- eixos ---------------------------------------------------------------- */
static double nice_step(double range, int want) {
double raw = range / (want > 0 ? want : 5);
if (raw <= 0 || !isfinite(raw)) return 1;
double p = pow(10, floor(log10(raw))), f = raw / p;
return (f < 1.5 ? 1 : f < 3 ? 2 : f < 7 ? 5 : 10) * p;
}
static void num_text(double v, double step, char* out, size_t cap) {
if (fabs(v) < step * 1e-6) v = 0;
int dec = step >= 1 ? 0 : (int)ceil(-log10(step) - 1e-9);
if (dec > 6) dec = 6;
if (fabs(v) >= 1e6 || (fabs(v) < 1e-4 && v != 0)) snprintf(out, cap, "%.2g", v);
else snprintf(out, cap, "%.*f", dec, v);
}
static void bounds(double* x0, double* x1, double* y0, double* y1) {
bool any = false, bars = false;
*x0 = *y0 = INFINITY; *x1 = *y1 = -INFINITY;
for (int i = 0; i < F.n; i++) {
const Series* s = &F.s[i];
if (s->kind == S_BAR) bars = true;
for (int k = 0; k < s->n; k++) {
if (!isfinite(s->x[k]) || !isfinite(s->y[k])) continue;
double bx = s->kind == S_BAR ? 0.4 : 0;
if (s->x[k] - bx < *x0) *x0 = s->x[k] - bx;
if (s->x[k] + bx > *x1) *x1 = s->x[k] + bx;
if (s->y[k] < *y0) *y0 = s->y[k];
if (s->y[k] > *y1) *y1 = s->y[k];
any = true;
}
}
if (!any) { *x0 = 0; *x1 = 1; *y0 = 0; *y1 = 1; }
if (bars && *y0 > 0) *y0 = 0;
if (*x1 - *x0 < 1e-12) { *x0 -= 0.5; *x1 += 0.5; }
if (*y1 - *y0 < 1e-12) { *y0 -= 0.5; *y1 += 0.5; }
double mx = (*x1 - *x0) * 0.05, my = (*y1 - *y0) * 0.05; /* folga, como no matplotlib */
*x0 -= mx; *x1 += mx;
if (!(bars && *y0 == 0)) *y0 -= my;
*y1 += my;
if (F.xlim) { *x0 = F.x0; *x1 = F.x1; }
if (F.ylim) { *y0 = F.y0; *y1 = F.y1; }
}
TinyBlocks_Image* tb_plot_render(void) {
int W = F.w, H = F.h;
TinyBlocks_Image* img = tb_image_new(W, H, 4);
if (!img) return NULL;
Canvas c = { tb_image_data(img), W, H, 0, 0, W, H };
memset(c.p, 255, (size_t)W * H * 4);
double x0, x1, y0, y1;
bounds(&x0, &x1, &y0, &y1);
double xs = nice_step(x1 - x0, W / 90), ys = nice_step(y1 - y0, H / 55);
/* margem esquerda pela largura das marcas do eixo y */
int ylw = 0;
char buf[64];
for (double v = ceil(y0 / ys) * ys; v <= y1 + ys * 1e-9; v += ys) {
num_text(v, ys, buf, sizeof(buf));
int w = text_w(buf);
if (w > ylw) ylw = w;
}
int L = 12 + ylw + 8 + (F.ylabel[0] ? PLOT_FONT_H + 4 : 0);
int T = F.title[0] ? PLOT_FONT_H + 14 : 12;
int R = 16, B = PLOT_FONT_H + 16 + (F.xlabel[0] ? PLOT_FONT_H + 4 : 0);
int px0 = L, px1 = W - R, py0 = T, py1 = H - B;
if (px1 - px0 < 20 || py1 - py0 < 20) return img;
#define SX(v) (px0 + (float)(((v) - x0) / (x1 - x0)) * (px1 - px0))
#define SY(v) (py1 - (float)(((v) - y0) / (y1 - y0)) * (py1 - py0))
const uint32_t axis = 0x333333, gridc = 0xdddddd;
/* barras com nomes: as marcas do x sao os nomes */
const Series* named = NULL;
for (int i = 0; i < F.n; i++) if (F.s[i].kind == S_BAR && F.s[i].names) named = &F.s[i];
/* grade e marcas */
for (double v = ceil(y0 / ys) * ys; v <= y1 + ys * 1e-9; v += ys) {
float y = SY(v);
if (F.grid) fill_rect(&c, px0, y - .5f, px1, y + .5f, gridc, 1);
fill_rect(&c, px0 - 4, y - .5f, px0, y + .5f, axis, 1);
num_text(v, ys, buf, sizeof(buf));
text(&c, px0 - 7 - text_w(buf), (int)(y - PLOT_FONT_BASE * 0.5f - 3), buf, axis, false);
}
if (named) {
float last = -1e9f; /* nomes que encostariam no anterior: pula */
for (int k = 0; k < named->n; k++) {
float x = SX(named->x[k]);
fill_rect(&c, x - .5f, py1, x + .5f, py1 + 4, axis, 1);
const char* nm = named->names[k] ? named->names[k] : "";
int w = text_w(nm);
if (!w || x - w * 0.5f < last + 6) continue;
text(&c, (int)(x - w * 0.5f), py1 + 6, nm, axis, false);
last = x + w * 0.5f;
}
} else {
for (double v = ceil(x0 / xs) * xs; v <= x1 + xs * 1e-9; v += xs) {
float x = SX(v);
if (F.grid) fill_rect(&c, x - .5f, py0, x + .5f, py1, gridc, 1);
fill_rect(&c, x - .5f, py1, x + .5f, py1 + 4, axis, 1);
num_text(v, xs, buf, sizeof(buf));
text(&c, (int)(x - text_w(buf) * 0.5f), py1 + 6, buf, axis, false);
}
}
/* series, recortadas na area do grafico */
Canvas in = c;
in.cx0 = px0; in.cy0 = py0; in.cx1 = px1; in.cy1 = py1;
for (int i = 0; i < F.n; i++) {
const Series* s = &F.s[i];
for (int k = 0; k < s->n; k++) {
if (!isfinite(s->x[k]) || !isfinite(s->y[k])) continue;
float x = SX(s->x[k]), y = SY(s->y[k]);
if (s->kind == S_BAR) {
float hw = (float)(0.4 / (x1 - x0) * (px1 - px0));
double base = y0 > 0 ? y0 : y1 < 0 ? y1 : 0; /* barras partem do zero (ou da borda) */
fill_rect(&in, x - hw, SY(base), x + hw, y, s->color, 1);
} else if (s->kind == S_SCATTER) {
disc(&in, x, y, 3.f, s->color);
} else if (k > 0 && isfinite(s->x[k - 1]) && isfinite(s->y[k - 1])) {
line(&in, SX(s->x[k - 1]), SY(s->y[k - 1]), x, y, 1.8f, s->color);
} else if (s->n == 1) disc(&in, x, y, 2.f, s->color);
}
}
/* moldura, titulo e nomes dos eixos */
fill_rect(&c, px0 - .5f, py0, px0 + .5f, py1, axis, 1);
fill_rect(&c, px0, py1 - .5f, px1, py1 + .5f, axis, 1);
fill_rect(&c, px1 - .5f, py0, px1 + .5f, py1, 0xbbbbbb, 1);
fill_rect(&c, px0, py0 - .5f, px1, py0 + .5f, 0xbbbbbb, 1);
if (F.title[0]) text(&c, (px0 + px1 - text_w(F.title)) / 2, 5, F.title, 0x111111, false);
if (F.xlabel[0]) text(&c, (px0 + px1 - text_w(F.xlabel)) / 2, H - PLOT_FONT_H - 4, F.xlabel, axis, false);
if (F.ylabel[0]) text(&c, 4, (py0 + py1 + text_w(F.ylabel)) / 2, F.ylabel, axis, true);
/* legenda: canto de cima a direita */
if (F.legend) {
int rows = 0, lw = 0;
for (int i = 0; i < F.n; i++) if (F.s[i].label[0]) { rows++; int w = text_w(F.s[i].label); if (w > lw) lw = w; }
if (rows) {
int bw = lw + 40, bh = rows * (PLOT_FONT_H + 2) + 8;
int bx = px1 - bw - 8, by = py0 + 8;
fill_rect(&c, bx, by, bx + bw, by + bh, 0xffffff, 0.9f);
fill_rect(&c, bx, by, bx + bw, by + 1, 0xcccccc, 1);
fill_rect(&c, bx, by + bh - 1, bx + bw, by + bh, 0xcccccc, 1);
fill_rect(&c, bx, by, bx + 1, by + bh, 0xcccccc, 1);
fill_rect(&c, bx + bw - 1, by, bx + bw, by + bh, 0xcccccc, 1);
int ry = by + 4;
for (int i = 0; i < F.n; i++) {
const Series* s = &F.s[i];
if (!s->label[0]) continue;
float cy = ry + PLOT_FONT_H * 0.5f;
if (s->kind == S_LINE) line(&c, bx + 6, cy, bx + 24, cy, 1.8f, s->color);
else if (s->kind == S_SCATTER) disc(&c, bx + 15, cy, 3.f, s->color);
else fill_rect(&c, bx + 8, cy - 4, bx + 22, cy + 4, s->color, 1);
text(&c, bx + 28, ry, s->label, 0x222222, false);
ry += PLOT_FONT_H + 2;
}
}
}
#undef SX
#undef SY
return img;
}
/* == Valores ========================================================== */
/* Numeros de um valor: tensor, lista ou texto "1, 2, 3"; malloc ou NULL */
static float* numbers(TinyBlocks* rt, TinyBlocks_Value v, int* n) {
*n = 0;
const TbTensorApi* api = tb_tensor_api(rt);
const TbTensor* t = api ? api->of_value(v) : NULL;
if (t) {
float* out = malloc((t->n ? t->n : 1) * sizeof(float));
if (out) { memcpy(out, t->d, t->n * sizeof(float)); *n = (int)t->n; }
return out;
}
TinyBlocks_JsonValue* j = v.kind == TB_VALUE_JSON ? v.as.json : NULL;
bool own = false;
if (!j && v.kind == TB_VALUE_TEXT && v.as.text) {
const char* s = v.as.text;
while (isspace((unsigned char)*s)) s++;
if (*s == '[') { j = tb_json_parse(s, NULL, 0); own = j != NULL; }
}
if (j && tb_json_kind(j) == TB_JSON_ARRAY) {
uint32_t len = tb_json_array_length(j);
float* out = malloc((len ? len : 1) * sizeof(float));
for (uint32_t i = 0; out && i < len; i++) {
TinyBlocks_JsonValue* e = tb_json_array_get(j, i);
const char* es = tb_json_as_string(e);
out[i] = es ? (float)strtod(es, NULL) : (float)tb_json_as_number(e, 0);
tb_json_release(e);
}
if (own) tb_json_release(j);
*n = out ? (int)len : 0;
return out;
}
if (own) tb_json_release(j);
double d;
if (v.kind != TB_VALUE_TEXT && tb_value_to_number(v, &d)) {
float* out = malloc(sizeof(float));
if (out) { out[0] = (float)d; *n = 1; }
return out;
}
char* s = tb_value_to_string(v); /* "1, 2, 3" ou "1 2 3" */
int cap = 64;
float* out = malloc((size_t)cap * sizeof(float));
for (char* p = s; out && p && *p; ) {
while (*p && !(isdigit((unsigned char)*p) || *p == '-' || *p == '.' || *p == '+')) p++;
if (!*p) break;
char* e;
double x = strtod(p, &e);
if (e == p) { p++; continue; }
if (*n == cap) { cap *= 2; float* q = realloc(out, (size_t)cap * sizeof(float)); if (!q) break; out = q; }
out[(*n)++] = (float)x;
p = e;
}
free(s);
return out;
}
/* Nomes (barras): lista JSON ou "a, b, c" */
static char** names_of(TinyBlocks_Value v, int n) {
char** out = calloc((size_t)(n ? n : 1), sizeof(char*));
if (!out) return NULL;
if (v.kind == TB_VALUE_JSON && tb_json_kind(v.as.json) == TB_JSON_ARRAY) {
for (int i = 0; i < n && i < (int)tb_json_array_length(v.as.json); i++) {
TinyBlocks_JsonValue* e = tb_json_array_get(v.as.json, (uint32_t)i);
TinyBlocks_Value ev = tb_value_json(e);
out[i] = tb_value_to_string(ev);
tb_value_free(&ev);
tb_json_release(e);
}
return out;
}
char* s = tb_value_to_string(v);
char* p = s;
for (int i = 0; p && *p && i < n; i++) {
char* e = strchr(p, ',');
size_t len = e ? (size_t)(e - p) : strlen(p);
while (len && isspace((unsigned char)*p)) { p++; len--; }
while (len && isspace((unsigned char)p[len - 1])) len--;
out[i] = strndup(p, len);
p = e ? e + 1 : NULL;
}
free(s);
return out;
}
/* == Series com nome (crescem a cada passo) =========================== */
typedef struct { char name[64]; float* v; int n, cap; } Named;
static Named* s_named;
static int s_named_n;
static Named* named(const char* name, bool create) {
for (int i = 0; i < s_named_n; i++) if (!strcmp(s_named[i].name, name)) return &s_named[i];
if (!create) return NULL;
Named* p = realloc(s_named, (size_t)(s_named_n + 1) * sizeof(*p));
if (!p) return NULL;
s_named = p;
Named* s = &s_named[s_named_n++];
memset(s, 0, sizeof(*s));
snprintf(s->name, sizeof(s->name), "%s", name);
return s;
}
/* == Blocos =========================================================== */
static void eval_figure(TinyBlocks_Block* self, TinyBlocks* rt) {
tb_plot_figure((int)tb_block_input_integer(self, rt, 0, 480), (int)tb_block_input_integer(self, rt, 1, 320));
self->dirty = false;
}
static void plot_xy(TinyBlocks_Block* self, TinyBlocks* rt, int kind, bool with_x) {
int nx = 0, ny = 0;
float* x = with_x ? numbers(rt, tb_block_get_input(self, rt, 0), &nx) : NULL;
float* y = numbers(rt, tb_block_get_input(self, rt, with_x ? 1 : 0), &ny);
uint32_t c0 = with_x ? 2 : 1;
if (with_x && nx != ny) tinyblocks_set_error(rt, "o x tem %d números e o y tem %d", nx, ny);
else if (y) add(kind, x, y, ny, tb_block_input_text(self, rt, c0), tb_block_input_text(self, rt, c0 + 1));
free(x); free(y);
self->dirty = false;
}
static void eval_line(TinyBlocks_Block* self, TinyBlocks* rt) { plot_xy(self, rt, S_LINE, false); }
static void eval_line_xy(TinyBlocks_Block* self, TinyBlocks* rt) { plot_xy(self, rt, S_LINE, true); }
static void eval_scatter(TinyBlocks_Block* self, TinyBlocks* rt) { plot_xy(self, rt, S_SCATTER, true); }
static void eval_bar(TinyBlocks_Block* self, TinyBlocks* rt) {
int n = 0;
float* y = numbers(rt, tb_block_get_input(self, rt, 0), &n);
Series* s = y ? add(S_BAR, NULL, y, n, tb_block_input_text(self, rt, 2), "") : NULL;
TinyBlocks_Value nv = tb_block_get_input(self, rt, 1);
if (s && nv.kind != TB_VALUE_NONE && tb_block_input_text(self, rt, 1)[0]) s->names = names_of(nv, n);
free(y);
self->dirty = false;
}
static void eval_hist(TinyBlocks_Block* self, TinyBlocks* rt) {
int n = 0, bins = (int)tb_block_input_integer(self, rt, 1, 10);
if (bins < 1) bins = 1;
if (bins > 1000) bins = 1000;
float* v = numbers(rt, tb_block_get_input(self, rt, 0), &n);
if (v && n) {
float lo = v[0], hi = v[0];
for (int i = 1; i < n; i++) { if (v[i] < lo) lo = v[i]; if (v[i] > hi) hi = v[i]; }
if (hi <= lo) hi = lo + 1;
float* cnt = calloc((size_t)bins, sizeof(float));
float* xs = malloc((size_t)bins * sizeof(float));
for (int i = 0; cnt && i < n; i++) {
int b = (int)((v[i] - lo) / (hi - lo) * bins);
if (b >= bins) b = bins - 1;
cnt[b] += 1;
}
for (int b = 0; xs && b < bins; b++) xs[b] = lo + (b + 0.5f) * (hi - lo) / bins;
if (cnt && xs) {
Series* s = add(S_BAR, NULL, cnt, bins, tb_block_input_text(self, rt, 2), "");
if (s) { /* barras no centro de cada faixa, numa escala 1..bins */
for (int b = 0; b < bins; b++) s->x[b] = (float)(b + 1);
s->names = calloc((size_t)bins, sizeof(char*));
for (int b = 0; s->names && b < bins; b++) {
char t[32];
snprintf(t, sizeof(t), "%.3g", xs[b]);
s->names[b] = strdup(t);
}
}
}
free(cnt); free(xs);
}
free(v);
self->dirty = false;
}
#define TEXT_SETTER(name, field) \
static void name(TinyBlocks_Block* self, TinyBlocks* rt) { \
snprintf(F.field, sizeof(F.field), "%s", tb_block_input_text(self, rt, 0)); \
self->dirty = false; }
TEXT_SETTER(eval_title, title)
TEXT_SETTER(eval_xlabel, xlabel)
TEXT_SETTER(eval_ylabel, ylabel)
static void eval_legend(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; F.legend = true; self->dirty = false; }
static void eval_grid(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; F.grid = true; self->dirty = false; }
static void eval_xlim(TinyBlocks_Block* self, TinyBlocks* rt) {
F.x0 = tb_block_input_number(self, rt, 0, 0); F.x1 = tb_block_input_number(self, rt, 1, 1);
F.xlim = F.x1 > F.x0;
self->dirty = false;
}
static void eval_ylim(TinyBlocks_Block* self, TinyBlocks* rt) {
F.y0 = tb_block_input_number(self, rt, 0, 0); F.y1 = tb_block_input_number(self, rt, 1, 1);
F.ylim = F.y1 > F.y0;
self->dirty = false;
}
static void eval_push(TinyBlocks_Block* self, TinyBlocks* rt) {
int n = 0;
float* v = numbers(rt, tb_block_get_input(self, rt, 0), &n);
Named* s = named(tb_block_input_text(self, rt, 1), true);
for (int i = 0; s && v && i < n; i++) {
if (s->n == s->cap) {
int nc = s->cap ? s->cap * 2 : 256;
float* p = realloc(s->v, (size_t)nc * sizeof(float));
if (!p) break;
s->v = p; s->cap = nc;
}
s->v[s->n++] = v[i];
}
free(v);
self->dirty = false;
}
static void eval_series_plot(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* nm = tb_block_input_text(self, rt, 0);
Named* s = named(nm, false);
if (s && s->n) add(S_LINE, NULL, s->v, s->n, tb_block_input_text(self, rt, 1), nm);
self->dirty = false;
}
static void eval_series_clear(TinyBlocks_Block* self, TinyBlocks* rt) {
Named* s = named(tb_block_input_text(self, rt, 0), false);
if (s) s->n = 0;
self->dirty = false;
}
static void eval_series_len(TinyBlocks_Block* self, TinyBlocks* rt) {
Named* s = named(tb_block_input_text(self, rt, 0), false);
tb_block_set_output(self, 0, tb_value_integer(s ? s->n : 0));
self->dirty = false;
}
static void eval_image(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
TinyBlocks_Image* img = tb_plot_render();
if (img) { tb_block_set_output(self, 0, tb_value_image(img)); tb_image_release(img); }
self->dirty = false;
}
static void eval_save(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* path = tb_block_input_text(self, rt, 0);
TinyBlocks_Image* img = tb_plot_render();
if (!img || !tb_image_save(img, path))
tinyblocks_set_error(rt, "não gravou '%s' (o formato da extensão está carregado?)", path);
tb_image_release(img);
self->dirty = false;
}
/* == Registro ========================================================= */
typedef struct {
const char* name; const char* label; const char* defs;
int nin; TinyBlocks_ValueKind in[4];
int out; /* 0 comando, 1 imagem, 2 numero */
void (*fn)(TinyBlocks_Block*, TinyBlocks*); const char* fname; const char* doc;
} Spec;
#define N TB_VALUE_NONE
#define T TB_VALUE_TEXT
#define I TB_VALUE_INTEGER
#define R TB_VALUE_REAL
#define S(fn) fn, #fn
static const Spec s_specs[] = {
{ "Plot.Figure", "nova figura de %1 por %2", "480|320", 2, {I,I}, 0, S(eval_figure), "Limpa a figura (largura e altura em pixels)" },
{ "Plot.Line", "plote %1 cor %2 rótulo %3", "1, 4, 2, 5||", 3, {N,T,T}, 0, S(eval_line), "Linha dos valores (x = 1, 2, 3...)" },
{ "Plot.LineXY", "plote %2 em função de %1 cor %3 rótulo %4", "1, 2, 3|1, 4, 9||", 4, {N,N,T,T}, 0, S(eval_line_xy), "Linha de y em função de x" },
{ "Plot.Scatter", "pontos %2 em função de %1 cor %3 rótulo %4", "1, 2, 3|1, 4, 9||", 4, {N,N,T,T}, 0, S(eval_scatter), "Um ponto para cada (x, y)" },
{ "Plot.Bar", "barras %1 com nomes %2 cor %3", "3, 5, 2|a, b, c|", 3, {N,N,T}, 0, S(eval_bar), "Barras dos valores, com nomes no eixo x" },
{ "Plot.Hist", "histograma de %1 com %2 faixas cor %3", "|10|", 3, {N,I,T}, 0, S(eval_hist), "Quantos valores caem em cada faixa" },
{ "Plot.Title", "título da figura %1", "Gráfico", 1, {T}, 0, S(eval_title), "Título no alto" },
{ "Plot.XLabel", "nome do eixo x %1", "x", 1, {T}, 0, S(eval_xlabel), "Texto embaixo do eixo x" },
{ "Plot.YLabel", "nome do eixo y %1", "y", 1, {T}, 0, S(eval_ylabel), "Texto ao lado do eixo y" },
{ "Plot.Legend", "mostre a legenda", "", 0, {N}, 0, S(eval_legend), "Caixa com o rótulo de cada série" },
{ "Plot.Grid", "mostre a grade", "", 0, {N}, 0, S(eval_grid), "Linhas de grade nas marcas" },
{ "Plot.XLim", "eixo x de %1 até %2", "0|10", 2, {R,R}, 0, S(eval_xlim), "Limites do eixo x" },
{ "Plot.YLim", "eixo y de %1 até %2", "0|10", 2, {R,R}, 0, S(eval_ylim), "Limites do eixo y" },
{ "Plot.Push", "acrescente %1 à série %2", "0|perda", 2, {N,T}, 0, S(eval_push), "Junta valores no fim de uma série com nome" },
{ "Plot.Series", "plote a série %1 cor %2", "perda|", 2, {T,T}, 0, S(eval_series_plot), "Linha da série com nome (rótulo = o nome)" },
{ "Plot.SeriesClear", "apague a série %1", "perda", 1, {T}, 0, S(eval_series_clear), "Esvazia a série" },
{ "Plot.SeriesLen", "tamanho da série %1", "perda", 1, {T}, 2, S(eval_series_len), "Quantos valores a série tem" },
{ "Plot.Image", "imagem da figura", "", 0, {N}, 1, S(eval_image), "Desenha a figura numa imagem" },
{ "Plot.Save", "salve a figura em %1", "grafico.png", 1, {T}, 0, S(eval_save), "Grava a figura (.png, .bmp ou .ppm)" },
};
#undef N
#undef T
#undef I
#undef R
static bool plot_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_Category cat = { "Gráficos", {0.15f, 0.62f, 0.55f, 1.f}, {0.10f, 0.47f, 0.42f, 1.f} };
tb_library_set_category(lib, &cat);
static const char* names[] = { "a", "b", "c", "d" };
static const TinyBlocks_SlotDesc out_img[] = {{"imagem", TB_VALUE_IMAGE}};
static const TinyBlocks_SlotDesc out_num[] = {{"valor", TB_VALUE_INTEGER}};
for (size_t i = 0; i < sizeof(s_specs) / sizeof(s_specs[0]); i++) {
const Spec* sp = &s_specs[i];
TinyBlocks_SlotDesc in[4];
for (int k = 0; k < sp->nin; k++) in[k] = (TinyBlocks_SlotDesc){ names[k], sp->in[k] };
const TinyBlocks_SlotDesc* out = sp->out == 1 ? out_img : sp->out == 2 ? out_num : NULL;
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, sp->name, sp->nin ? in : NULL, (uint32_t)sp->nin,
out, 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 plot_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt; (void)lib;
tb_plot_figure(480, 320);
free(F.s); F.s = NULL; F.cap = 0;
for (int i = 0; i < s_named_n; i++) free(s_named[i].v);
free(s_named); s_named = NULL; s_named_n = 0;
}
TINYBLOCKS_DEFINE_LIBRARY(plot, "tinyblocks-plot", "1.0.0", plot_init, plot_deinit)
const TinyBlocks_LibraryDescriptor* tb_plot_get_library(void) {
return &_tb_lib_desc_plot;
}
@@ -0,0 +1,64 @@
/*
* gen_font.c - gera src/plot_font.h: a fonte da tinyblocks-plot (DejaVu Sans
* 12 px, com antisserrilhado), renderizada pela tinyblocks-opentype. Assim a
* plot desenha texto sem depender de outra library em execucao.
*
* make -C libraries/tinyblocks-plot font (precisa da opentype compilada)
*
* Caracteres: ASCII 32..126 e Latin-1 160..255 (acentos do portugues).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
#include <tb_opentype.h>
static void utf8(unsigned cp, char* out) {
if (cp < 0x80) { out[0] = (char)cp; out[1] = 0; }
else { out[0] = (char)(0xC0 | (cp >> 6)); out[1] = (char)(0x80 | (cp & 0x3F)); out[2] = 0; }
}
int main(int argc, char** argv) {
const char* font = argc > 1 ? argv[1] : tb_opentype_default_font();
int px = argc > 2 ? atoi(argv[2]) : 12;
int h = tb_opentype_load(font);
if (!h) { fprintf(stderr, "fonte: %s\n", tb_opentype_last_error()); return 1; }
double asc, dsc, lh;
tb_opentype_metrics(h, px, &asc, &dsc, &lh);
unsigned cps[256]; int n = 0;
for (unsigned c = 32; c < 127; c++) cps[n++] = c;
for (unsigned c = 160; c < 256; c++) cps[n++] = c;
int H = 0;
printf("/* Gerado por tools/gen_font.c (%s, %d px). Nao editar. */\n", font, px);
printf("#ifndef TB_PLOT_FONT_H\n#define TB_PLOT_FONT_H\n#include <stdint.h>\n");
size_t total = 0;
TinyBlocks_Image* imgs[256];
for (int i = 0; i < n; i++) {
char s[4]; utf8(cps[i], s);
imgs[i] = tb_opentype_render(h, s, px, 255, 255, 255);
if (imgs[i]) { H = tb_image_height(imgs[i]); total += (size_t)tb_image_width(imgs[i]) * H; }
}
printf("#define PLOT_FONT_H %d\n#define PLOT_FONT_BASE %d\n#define PLOT_FONT_N %d\n", H, (int)(1 + asc + 0.5), n);
printf("typedef struct { uint16_t cp; uint8_t w; uint32_t off; } PlotGlyph;\n");
printf("static const PlotGlyph s_glyphs[PLOT_FONT_N] = {\n");
size_t off = 0;
for (int i = 0; i < n; i++) {
int w = imgs[i] ? tb_image_width(imgs[i]) - 2 : 4; /* sem a folga (o render poe 2 px) */
printf(" {%u,%d,%zu},%s", cps[i], w, off, i % 6 == 5 ? "\n" : "");
off += (size_t)w * H;
}
printf("};\nstatic const uint8_t s_font[%zu] = {\n", off);
size_t k = 0;
for (int i = 0; i < n; i++) {
int W = imgs[i] ? tb_image_width(imgs[i]) : 6, w = W - 2;
for (int y = 0; y < H; y++)
for (int x = 0; x < w; x++) {
uint8_t r, g, b, a = 0;
if (imgs[i]) tb_image_get_pixel(imgs[i], x, y, &r, &g, &b, &a);
printf("%d,%s", a, ++k % 24 == 0 ? "\n" : "");
}
}
printf("};\n#endif\n");
(void)total;
return 0;
}
+100
View File
@@ -0,0 +1,100 @@
/*
* plot_test.c - testa a tinyblocks-plot pelos blocos: linha, pontos,
* barras, histograma, serie com nome, legenda, grade e texto com acento;
* valores de lista, de texto e de tensor. Grava /tmp/tb_plot_*.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_tensor.h>
#include <tb_plot.h>
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* a, const char* b, const char* c, const char* d) {
TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, type));
const char* v[4] = { a, b, c, d };
for (int i = 0; i < 4; i++)
if (v[i]) { TinyBlocks_Value t = tb_value_text(v[i]); tb_block_set_default(x, (uint32_t)i, t); tb_value_free(&t); }
tb_block_eval(x, rt);
return x;
}
/* A cor do pixel e (quase) a pedida? */
static bool near_color(const TinyBlocks_Image* img, int x, int y, uint32_t rgb, int tol) {
uint8_t r, g, b, a;
if (!tb_image_get_pixel(img, x, y, &r, &g, &b, &a)) return false;
return abs(r - (int)(rgb >> 16 & 255)) <= tol && abs(g - (int)(rgb >> 8 & 255)) <= tol && abs(b - (int)(rgb & 255)) <= tol;
}
static int count_color(const TinyBlocks_Image* img, uint32_t rgb) {
int n = 0;
for (int y = 0; y < tb_image_height(img); y++)
for (int x = 0; x < tb_image_width(img); x++) n += near_color(img, x, y, rgb, 30);
return 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_tensor_get_library());
tb_library_register(rt, tb_plot_get_library());
run("Plot.Figure", "480", "320", NULL, NULL);
run("Plot.Line", "[1, 4, 2, 5, 3]", "azul", "treino", NULL);
run("Plot.Scatter", "1, 2, 3, 4, 5", "2, 3, 3.5, 4.5, 4", "laranja", "validação");
run("Plot.Title", "Perda por época", NULL, NULL, NULL);
run("Plot.XLabel", "época", NULL, NULL, NULL);
run("Plot.YLabel", "perda média", NULL, NULL, NULL);
run("Plot.Legend", NULL, NULL, NULL, NULL);
run("Plot.Grid", NULL, NULL, NULL, NULL);
TinyBlocks_Block* im = run("Plot.Image", NULL, NULL, NULL, NULL);
TinyBlocks_Image* img = im->outputs[0].kind == TB_VALUE_IMAGE ? im->outputs[0].as.image : NULL;
CHECK(img && tb_image_width(img) == 480 && tb_image_height(img) == 320, "imagem da figura 480x320");
CHECK(img && count_color(img, 0x1f77b4) > 150, "a linha azul (tab10) foi desenhada");
CHECK(img && count_color(img, 0xff7f0e) > 60, "os pontos laranja foram desenhados");
CHECK(img && near_color(img, 2, 2, 0xffffff, 0), "fundo branco");
run("Plot.Save", "/tmp/tb_plot_linha.png", NULL, NULL, NULL);
CHECK(!tinyblocks_last_error(rt)[0], "salva em PNG");
/* tensor, barras e serie com nome */
run("Plot.Figure", "400", "260", NULL, NULL);
TinyBlocks_Block* tz = run("Tensor.Randn", "500", NULL, NULL, NULL);
TinyBlocks_Block* h = tb_block_create(rt, tb_type_block_find(rt, "Plot.Hist"));
tb_block_connect(h, 0, tz, 0);
tz->dirty = false;
tb_block_set_default(h, 1, tb_value_integer(15));
tb_block_eval(h, rt);
run("Plot.Title", "Histograma de um tensor normal", NULL, NULL, NULL);
TinyBlocks_Block* im2 = run("Plot.Image", NULL, NULL, NULL, NULL);
CHECK(im2->outputs[0].kind == TB_VALUE_IMAGE && count_color(im2->outputs[0].as.image, 0x1f77b4) > 3000,
"histograma de um tensor (as barras aparecem)");
run("Plot.Save", "/tmp/tb_plot_hist.png", NULL, NULL, NULL);
run("Plot.Figure", "400", "260", NULL, NULL);
for (int i = 0; i < 50; i++) {
char v[32];
snprintf(v, sizeof(v), "%g", exp(-i / 12.0) + 0.05 * sin(i));
run("Plot.Push", v, "perda", NULL, NULL);
}
TinyBlocks_Block* len = run("Plot.SeriesLen", "perda", NULL, NULL, NULL);
CHECK(len->outputs[0].as.integer == 50, "a série com nome cresce (50 valores)");
run("Plot.Series", "perda", "vermelho", NULL, NULL);
run("Plot.Bar", "0.2, 0.4", "a, b", "verde", NULL);
run("Plot.Legend", NULL, NULL, NULL, NULL);
run("Plot.Save", "/tmp/tb_plot_serie.png", NULL, NULL, NULL);
CHECK(!tinyblocks_last_error(rt)[0], "série + barras na mesma figura");
tinyblocks_deinit(&rt);
if (fails) printf("\n%d FALHA(S)\n", fails);
else printf("\nTUDO OK\n");
return fails != 0;
}