Files
tinyblocks/libraries/tinyblocks-image/src/tb_imglib.c
T
mguinhosandClaude Opus 5 85bd6f7cf4 Editor/core: resolve caminhos relativos pela pasta do projeto
Blocos que abrem arquivo (carregue o PNG, Image.Load, FS.*) passam a
resolver caminhos relativos contra o diretorio-base do projeto, definido
pelo editor ao abrir um .sb. Assim exemplos acham atlas.png etc. mesmo
quando o editor roda de outro cwd (ex.: AppImage aberto pelo menu), sem
mudar o cwd global (que quebrava "Ver codigo-fonte" e o harness).

- tb_path_set_base / tb_path_resolve, na API publica (src/tinyblocks.c)
- editor: project_set_dir no project_load (sem chdir)
- tb_png, tb_fs e tb_imglib usam o resolvedor
- MAX_USER_BLOCKS 16 -> 8192 (documentado em docs/editor.md)

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

368 lines
17 KiB
C

/*
* TinyBlocks - tb_imglib.c
* Categoria "Imagem": operacoes genericas e Load/Save por extensao.
* Conversoes: imagem <-> lista de pixels ([r,g,b,a] linha a linha), tons de
* cinza e desenho em texto (letras mais "cheias" onde e mais escuro).
*/
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <tinyblocks/tinyblocks.h>
#include "tb_imglib.h"
TinyBlocks_Image* tb_imglib_fill(TinyBlocks_Image* img,
uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
if (!img) return NULL;
for (int y = 0; y < tb_image_height(img); y++)
for (int x = 0; x < tb_image_width(img); x++)
tb_image_set_pixel(img, x, y, r, g, b, a);
return img;
}
TinyBlocks_Image* tb_imglib_crop(const TinyBlocks_Image* img,
int x, int y, int w, int h) {
if (!img || w <= 0 || h <= 0) return NULL;
TinyBlocks_Image* out = tb_image_new(w, h, tb_image_channels(img));
if (!out) return NULL;
for (int j = 0; j < h; j++)
for (int i = 0; i < w; i++) {
uint8_t r, g, b, a;
if (tb_image_get_pixel(img, x + i, y + j, &r, &g, &b, &a))
tb_image_set_pixel(out, i, j, r, g, b, a);
}
return out;
}
TinyBlocks_Image* tb_imglib_scale(const TinyBlocks_Image* img,
int w, int h, bool smooth) {
if (!img || w <= 0 || h <= 0) return NULL;
int sw = tb_image_width(img), sh = tb_image_height(img);
if (sw <= 0 || sh <= 0) return NULL;
TinyBlocks_Image* out = tb_image_new(w, h, tb_image_channels(img));
if (!out) return NULL;
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
uint8_t r, g, b, a;
if (smooth) {
double sx = (i + 0.5) * sw / w - 0.5;
double sy = (j + 0.5) * sh / h - 0.5;
int x0 = (int)floor(sx), y0 = (int)floor(sy);
double fx = sx - x0, fy = sy - y0;
double ar = 0, ag = 0, ab = 0, aa = 0, wsum = 0;
for (int dy = 0; dy <= 1; dy++)
for (int dx = 0; dx <= 1; dx++) {
int xx = x0 + dx, yy = y0 + dy;
if (xx < 0) xx = 0;
if (xx >= sw) xx = sw - 1;
if (yy < 0) yy = 0;
if (yy >= sh) yy = sh - 1;
double ww = (dx ? fx : 1 - fx) * (dy ? fy : 1 - fy);
uint8_t rr, gg, bb, al;
if (tb_image_get_pixel(img, xx, yy, &rr, &gg, &bb, &al)) {
ar += rr*ww; ag += gg*ww; ab += bb*ww; aa += al*ww; wsum += ww;
}
}
if (wsum <= 0) wsum = 1;
r = (uint8_t)(ar/wsum); g = (uint8_t)(ag/wsum);
b = (uint8_t)(ab/wsum); a = (uint8_t)(aa/wsum);
} else {
int xx = i * sw / w, yy = j * sh / h;
if (!tb_image_get_pixel(img, xx, yy, &r, &g, &b, &a)) continue;
}
tb_image_set_pixel(out, i, j, r, g, b, a);
}
}
return out;
}
/* -- Helpers de entrada --- */
static TinyBlocks_Image* in_img(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
return v.kind == TB_VALUE_IMAGE ? v.as.image : NULL;
}
static uint8_t clamp8(double v) { return v < 0 ? 0 : v > 255 ? 255 : (uint8_t)(v + 0.5); }
static void out_img(TinyBlocks_Block* self, TinyBlocks_Image* img) {
if (!img) { self->dirty = false; return; }
tb_block_set_output(self, 0, tb_value_image(img));
tb_image_release(img);
self->dirty = false;
}
/* -- Blocos --- */
static void eval_new(TinyBlocks_Block* self, TinyBlocks* rt) {
int w = (int)tb_block_input_number(self, rt, 0, 0), h = (int)tb_block_input_number(self, rt, 1, 0);
TinyBlocks_Image* img = tb_image_new(w > 0 ? w : 1, h > 0 ? h : 1, 4);
if (!img) { tinyblocks_set_error(rt, "sem memoria"); self->dirty = false; return; }
tb_imglib_fill(img, clamp8(tb_block_input_number(self,rt,2, 0)), clamp8(tb_block_input_number(self,rt,3, 0)),
clamp8(tb_block_input_number(self,rt,4, 0)), 255);
out_img(self, img);
}
static void eval_width (TinyBlocks_Block* self, TinyBlocks* rt) { tb_block_set_output(self,0,tb_value_integer(tb_image_width (in_img(self,rt,0)))); self->dirty = false; }
static void eval_height(TinyBlocks_Block* self, TinyBlocks* rt) { tb_block_set_output(self,0,tb_value_integer(tb_image_height(in_img(self,rt,0)))); self->dirty = false; }
static void eval_getpixel(TinyBlocks_Block* self, TinyBlocks* rt) {
uint8_t r=0,g=0,b=0,a=0;
tb_image_get_pixel(in_img(self,rt,0), (int)tb_block_input_number(self,rt,1, 0), (int)tb_block_input_number(self,rt,2, 0), &r,&g,&b,&a);
TinyBlocks_JsonValue* arr = tb_json_array();
const uint8_t ch[4] = { r, g, b, a };
for (int i = 0; i < 4; i++) { /* push retem: solta a nossa referencia */
TinyBlocks_JsonValue* n = tb_json_number(ch[i]);
tb_json_array_push(arr, n);
tb_json_release(n);
}
tb_block_set_output(self, 0, tb_value_json(arr));
tb_json_release(arr);
self->dirty = false;
}
static void eval_setpixel(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Image* img = in_img(self,rt,0);
if (img) tb_image_set_pixel(img, (int)tb_block_input_number(self,rt,1, 0), (int)tb_block_input_number(self,rt,2, 0),
clamp8(tb_block_input_number(self,rt,3, 0)), clamp8(tb_block_input_number(self,rt,4, 0)),
clamp8(tb_block_input_number(self,rt,5, 0)), 255);
self->dirty = false;
}
static void eval_fill(TinyBlocks_Block* self, TinyBlocks* rt) {
tb_imglib_fill(in_img(self,rt,0), clamp8(tb_block_input_number(self,rt,1, 0)),
clamp8(tb_block_input_number(self,rt,2, 0)), clamp8(tb_block_input_number(self,rt,3, 0)), 255);
self->dirty = false;
}
static void eval_clone(TinyBlocks_Block* self, TinyBlocks* rt) { out_img(self, tb_image_clone(in_img(self,rt,0))); }
static void eval_crop(TinyBlocks_Block* self, TinyBlocks* rt) {
out_img(self, tb_imglib_crop(in_img(self,rt,0), (int)tb_block_input_number(self,rt,1, 0), (int)tb_block_input_number(self,rt,2, 0),
(int)tb_block_input_number(self,rt,3, 0), (int)tb_block_input_number(self,rt,4, 0)));
}
static void eval_scale(TinyBlocks_Block* self, TinyBlocks* rt) {
out_img(self, tb_imglib_scale(in_img(self,rt,0), (int)tb_block_input_number(self,rt,1, 0), (int)tb_block_input_number(self,rt,2, 0), true));
}
static void eval_load(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* path = tb_block_input_text(self, rt, 0);
char rpath[1100];
path = tb_path_resolve(path, rpath, sizeof(rpath));
TinyBlocks_Image* img = tb_image_load(path);
if (!img) { tinyblocks_set_error(rt, "nao carregou '%s' (formato?)", path); self->dirty = false; return; }
/* A imagem carregada ganha nome (nome do arquivo) e numero no armazem,
para os blocos "desenhe imagem nome/numero" acharem depois. */
const char* base = strrchr(path, '/');
base = base ? base + 1 : path;
tb_image_store_put(base, img);
out_img(self, img);
}
static void eval_save(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Image* img = in_img(self,rt,0);
if (!img || !tb_image_save(img, tb_block_input_text(self,rt,1)))
tinyblocks_set_error(rt, "nao gravou '%s' (formato?)", tb_block_input_text(self,rt,1));
self->dirty = false;
}
/* -- Conversoes --- */
#define IMG_MAX_PIXELS (4096 * 4096)
static TinyBlocks_JsonValue* json_rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
TinyBlocks_JsonValue* c = tb_json_array();
if (!c) return NULL;
uint8_t v[4] = { r, g, b, a };
for (int k = 0; k < 4; k++) {
TinyBlocks_JsonValue* n = tb_json_number(v[k]);
tb_json_array_push(c, n);
tb_json_release(n);
}
return c;
}
/* "pixels da imagem": [[r,g,b,a], ...] da esquerda p/ direita, de cima p/ baixo */
static void eval_to_list(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Image* img = in_img(self, rt, 0);
TinyBlocks_JsonValue* arr = tb_json_array();
int w = tb_image_width(img), h = tb_image_height(img);
for (int y = 0; img && arr && y < h; y++)
for (int x = 0; x < w; x++) {
uint8_t r, g, b, a;
if (!tb_image_get_pixel(img, x, y, &r, &g, &b, &a)) continue;
TinyBlocks_JsonValue* c = json_rgba(r, g, b, a);
if (c) { tb_json_array_push(arr, c); tb_json_release(c); }
}
tb_block_set_output(self, 0, tb_value_json(arr));
tb_json_release(arr);
self->dirty = false;
}
static double json_num(const TinyBlocks_JsonValue* j) {
const char* s = tb_json_as_string(j);
return s ? strtod(s, NULL) : tb_json_as_number(j, 0);
}
/* Lista de entrada: valor JSON ou texto "[...]" (ref nova ou NULL) */
static TinyBlocks_JsonValue* in_json_list(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
TinyBlocks_JsonValue* j = NULL;
if (v.kind == TB_VALUE_JSON && v.as.json) { j = v.as.json; tb_json_retain(j); }
else if (v.kind == TB_VALUE_TEXT && v.as.text) j = tb_json_parse(v.as.text, NULL, 0);
if (j && tb_json_kind(j) != TB_JSON_ARRAY) { tb_json_release(j); j = NULL; }
return j;
}
/* "imagem de largura (w) com os pixels (lista)": cada pixel e [r,g,b],
[r,g,b,a] ou um numero (cinza); a altura sai do tamanho da lista */
static void eval_from_list(TinyBlocks_Block* self, TinyBlocks* rt) {
int w = (int)(int)tb_block_input_number(self, rt, 0, 0);
TinyBlocks_JsonValue* list = in_json_list(self, rt, 1);
uint32_t n = list ? tb_json_array_length(list) : 0;
if (w <= 0 || !n) {
tinyblocks_set_error(rt, "precisa de largura > 0 e de uma lista de pixels");
if (list) tb_json_release(list);
self->dirty = false;
return;
}
int h = (int)((n + (uint32_t)w - 1) / (uint32_t)w);
if ((long long)w * h > IMG_MAX_PIXELS) {
tinyblocks_set_error(rt, "imagem grande demais (%d x %d)", w, h);
tb_json_release(list);
self->dirty = false;
return;
}
TinyBlocks_Image* img = tb_image_new(w, h, 4);
for (uint32_t i = 0; img && i < n; i++) {
TinyBlocks_JsonValue* p = tb_json_array_get(list, i);
uint8_t c[4] = { 0, 0, 0, 255 };
if (p && tb_json_kind(p) == TB_JSON_ARRAY) {
uint32_t m = tb_json_array_length(p);
for (uint32_t k = 0; k < m && k < 4; k++) {
TinyBlocks_JsonValue* e = tb_json_array_get(p, k);
c[k] = clamp8(json_num(e));
if (e) tb_json_release(e);
}
} else if (p) {
c[0] = c[1] = c[2] = clamp8(json_num(p));
}
if (p) tb_json_release(p);
tb_image_set_pixel(img, (int)(i % (uint32_t)w), (int)(i / (uint32_t)w), c[0], c[1], c[2], c[3]);
}
tb_json_release(list);
out_img(self, img);
}
static uint8_t luma(uint8_t r, uint8_t g, uint8_t b) {
return clamp8(0.299 * r + 0.587 * g + 0.114 * b);
}
/* "imagem (i) em tons de cinza": copia nova, mesma transparencia */
static void eval_gray(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Image* src = in_img(self, rt, 0);
TinyBlocks_Image* img = src ? tb_image_clone(src) : NULL;
for (int y = 0; img && y < tb_image_height(img); y++)
for (int x = 0; x < tb_image_width(img); x++) {
uint8_t r, g, b, a;
if (!tb_image_get_pixel(img, x, y, &r, &g, &b, &a)) continue;
uint8_t l = luma(r, g, b);
tb_image_set_pixel(img, x, y, l, l, l, a);
}
out_img(self, img);
}
/* "desenho em texto da imagem (i) com (n) colunas": arte ASCII. Cada letra
cobre um bloco de pixels; a altura e corrigida (letras sao ~2x altas). */
static void eval_to_text(TinyBlocks_Block* self, TinyBlocks* rt) {
static const char ramp[] = " .:-=+*#%@"; /* claro -> escuro */
TinyBlocks_Image* img = in_img(self, rt, 0);
int cols = (int)(int)tb_block_input_number(self, rt, 1, 0);
int w = tb_image_width(img), h = tb_image_height(img);
if (!img || w <= 0 || h <= 0) { tb_block_set_output(self, 0, tb_value_text("")); self->dirty = false; return; }
if (cols <= 0 || cols > w) cols = w;
if (cols > 400) cols = 400;
double cw = (double)w / cols, chh = cw * 2.0;
int rows = (int)ceil(h / chh);
if (rows < 1) rows = 1;
char* out = malloc((size_t)(cols + 1) * (size_t)rows + 1);
if (!out) { self->dirty = false; return; }
char* o = out;
for (int ry = 0; ry < rows; ry++) {
for (int cx = 0; cx < cols; cx++) {
int x0 = (int)(cx * cw), x1 = (int)((cx + 1) * cw), y0 = (int)(ry * chh), y1 = (int)((ry + 1) * chh);
if (x1 <= x0) x1 = x0 + 1;
if (y1 <= y0) y1 = y0 + 1;
double sum = 0; int cnt = 0;
for (int y = y0; y < y1 && y < h; y++)
for (int x = x0; x < x1 && x < w; x++) {
uint8_t r, g, b, a;
if (!tb_image_get_pixel(img, x, y, &r, &g, &b, &a)) continue;
/* transparente conta como claro (fundo branco) */
sum += 255 - (255 - luma(r, g, b)) * (a / 255.0);
cnt++;
}
double l = cnt ? sum / cnt : 255;
int k = (int)((255 - l) / 256.0 * (sizeof(ramp) - 1));
*o++ = ramp[k < 0 ? 0 : k > (int)sizeof(ramp) - 2 ? (int)sizeof(ramp) - 2 : k];
}
while (o > out && o[-1] == ' ') o--; /* sem espacos no fim */
*o++ = '\n';
}
*o = 0;
tb_block_set_output(self, 0, tb_value_text(out));
free(out);
self->dirty = false;
}
/* -- Registro --- */
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
const TinyBlocks_SlotDesc* in, uint32_t ni,
const TinyBlocks_SlotDesc* out, uint32_t no,
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
return t && tb_library_add(lib, &t->base);
}
static bool imglib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_Category cat = {
"Imagem",
{ 63/255.f, 81/255.f, 181/255.f, 1.f},
{ 40/255.f, 53/255.f, 147/255.f, 1.f},
};
tb_library_set_category(lib, &cat);
static const TinyBlocks_SlotDesc out_img[] = {{"imagem", TB_VALUE_IMAGE}};
static const TinyBlocks_SlotDesc n_out[] = {{"n", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc pix_out[] = {{"cor", TB_VALUE_JSON}};
static const TinyBlocks_SlotDesc new_in[] = {{"largura",TB_VALUE_REAL},{"altura",TB_VALUE_REAL},{"r",TB_VALUE_REAL},{"g",TB_VALUE_REAL},{"b",TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc wh_in[] = {{"imagem",TB_VALUE_IMAGE}};
static const TinyBlocks_SlotDesc getp_in[] = {{"imagem",TB_VALUE_IMAGE},{"x",TB_VALUE_INTEGER},{"y",TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc setp_in[] = {{"imagem",TB_VALUE_IMAGE},{"x",TB_VALUE_INTEGER},{"y",TB_VALUE_INTEGER},{"r",TB_VALUE_REAL},{"g",TB_VALUE_REAL},{"b",TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc fill_in[] = {{"imagem",TB_VALUE_IMAGE},{"r",TB_VALUE_REAL},{"g",TB_VALUE_REAL},{"b",TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc crop_in[] = {{"imagem",TB_VALUE_IMAGE},{"x",TB_VALUE_INTEGER},{"y",TB_VALUE_INTEGER},{"largura",TB_VALUE_INTEGER},{"altura",TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc scale_in[]= {{"imagem",TB_VALUE_IMAGE},{"largura",TB_VALUE_INTEGER},{"altura",TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc load_in[] = {{"caminho",TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc save_in[] = {{"imagem",TB_VALUE_IMAGE},{"caminho",TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc list_out[]= {{"pixels", TB_VALUE_JSON}};
static const TinyBlocks_SlotDesc text_out[]= {{"texto", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc fl_in[] = {{"largura",TB_VALUE_INTEGER},{"pixels",TB_VALUE_JSON}};
static const TinyBlocks_SlotDesc txt_in[] = {{"imagem",TB_VALUE_IMAGE},{"colunas",TB_VALUE_INTEGER}};
return reg(rt, lib, "Image.New", new_in, 5, out_img, 1, eval_new)
&& reg(rt, lib, "Image.Width", wh_in, 1, n_out, 1, eval_width)
&& reg(rt, lib, "Image.Height", wh_in, 1, n_out, 1, eval_height)
&& reg(rt, lib, "Image.GetPixel", getp_in, 3, pix_out, 1, eval_getpixel)
&& reg(rt, lib, "Image.SetPixel", setp_in, 6, NULL, 0, eval_setpixel)
&& reg(rt, lib, "Image.Fill", fill_in, 4, NULL, 0, eval_fill)
&& reg(rt, lib, "Image.Clone", wh_in, 1, out_img, 1, eval_clone)
&& reg(rt, lib, "Image.Crop", crop_in, 5, out_img, 1, eval_crop)
&& reg(rt, lib, "Image.Scale", scale_in,3, out_img, 1, eval_scale)
&& reg(rt, lib, "Image.Load", load_in, 1, out_img, 1, eval_load)
&& reg(rt, lib, "Image.Save", save_in, 2, NULL, 0, eval_save)
&& reg(rt, lib, "Image.ToList", wh_in, 1, list_out,1, eval_to_list)
&& reg(rt, lib, "Image.FromList", fl_in, 2, out_img, 1, eval_from_list)
&& reg(rt, lib, "Image.Gray", wh_in, 1, out_img, 1, eval_gray)
&& reg(rt, lib, "Image.ToText", txt_in, 2, text_out,1, eval_to_text);
}
TINYBLOCKS_DEFINE_LIBRARY(imglib, "tinyblocks-image", "1.0.0", imglib_init, NULL)
const TinyBlocks_LibraryDescriptor* tb_imglib_get_library(void) {
return &_tb_lib_desc_imglib;
}