Files
tinyblocks/libraries/tinyblocks-ppm/src/tb_ppm.c
T
mguinhosandClaude Opus 5.5 63c8fb0c1c Listas com nome mutáveis no lugar (sem cópia); vazamento no "cor da imagem"
"lista [nome]" copiava a lista inteira a cada leitura e adicione / insira /
apague / substitua reconstruíam a lista a cada operação: um Z-buffer ou
qualquer lista grande ficava O(n) por acesso. Agora a lista com nome é um
objeto mutável, como no Scratch ("mude a lista para" continua copiando).
O JSON do core ganha tb_json_array_set / insert / remove / clear.
20 mil leituras + escritas numa lista de 10 mil: 13 ms (test-stdlib).

"cor da imagem" (Image e PPM) vazava os números de cada pixel lido.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:05:38 -03:00

239 lines
9.8 KiB
C

/*
* TinyBlocks - tb_ppm.c
* Categoria "PPM": PPM.Load / PPM.Save / PPM.New / PPM.Width / PPM.Height /
* PPM.SetPixel / PPM.GetPixel. Le e grava Netpbm (P6 binario e P3 ASCII).
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
#include <tinyblocks/tinyblocks.h>
#include "tb_ppm.h"
static char s_err[200] = "";
const char* tb_ppm_last_error(void) { return s_err; }
/* Le um token (inteiro ou magic) pulando espacos e comentarios '#'. */
static bool next_token(FILE* f, char* buf, size_t cap) {
int c;
/* pula espacos e comentarios */
for (;;) {
c = fgetc(f);
if (c == EOF) return false;
if (c == '#') { while ((c = fgetc(f)) != EOF && c != '\n') {} continue; }
if (!isspace(c)) break;
}
size_t n = 0;
while (c != EOF && !isspace(c)) {
if (n + 1 < cap) buf[n++] = (char)c;
c = fgetc(f);
}
buf[n] = 0;
return n > 0;
}
TinyBlocks_Image* tb_ppm_load(const char* path) {
s_err[0] = 0;
if (!path) { snprintf(s_err, sizeof(s_err), "caminho nulo"); return NULL; }
FILE* f = fopen(path, "rb");
if (!f) { snprintf(s_err, sizeof(s_err), "nao abriu '%s'", path); return NULL; }
char magic[8] = "", wbuf[24] = "", hbuf[24] = "", mbuf[24] = "";
if (!next_token(f, magic, sizeof(magic)) ||
(strcmp(magic, "P6") != 0 && strcmp(magic, "P3") != 0)) {
snprintf(s_err, sizeof(s_err), "formato PPM invalido (esperado P3/P6)");
fclose(f); return NULL;
}
if (!next_token(f, wbuf, sizeof(wbuf)) ||
!next_token(f, hbuf, sizeof(hbuf)) ||
!next_token(f, mbuf, sizeof(mbuf))) {
snprintf(s_err, sizeof(s_err), "cabecalho PPM incompleto");
fclose(f); return NULL;
}
int w = atoi(wbuf), h = atoi(hbuf), maxv = atoi(mbuf);
if (w <= 0 || h <= 0 || maxv <= 0 || maxv > 65535) {
snprintf(s_err, sizeof(s_err), "dimensoes/maxval invalidos");
fclose(f); return NULL;
}
TinyBlocks_Image* img = tb_image_new(w, h, 3);
if (!img) { snprintf(s_err, sizeof(s_err), "sem memoria"); fclose(f); return NULL; }
uint8_t* px = tb_image_data(img);
if (strcmp(magic, "P6") == 0) {
int bytes = maxv > 255 ? 2 : 1;
for (size_t i = 0; i < (size_t)w * h * 3; i++) {
int v;
if (bytes == 2) {
int hi = fgetc(f), lo = fgetc(f);
if (hi == EOF || lo == EOF) { snprintf(s_err, sizeof(s_err), "dados truncados"); tb_image_release(img); fclose(f); return NULL; }
v = (hi << 8) | lo;
} else {
v = fgetc(f);
if (v == EOF) { snprintf(s_err, sizeof(s_err), "dados truncados"); tb_image_release(img); fclose(f); return NULL; }
}
px[i] = (uint8_t)((v * 255 + maxv/2) / maxv);
}
} else {
for (size_t i = 0; i < (size_t)w * h * 3; i++) {
char tb[24];
if (!next_token(f, tb, sizeof(tb))) { snprintf(s_err, sizeof(s_err), "dados truncados"); tb_image_release(img); fclose(f); return NULL; }
int v = atoi(tb);
px[i] = (uint8_t)((v * 255 + maxv/2) / maxv);
}
}
fclose(f);
return img;
}
bool tb_ppm_save(const TinyBlocks_Image* img, const char* path) {
s_err[0] = 0;
if (!img || !path) { snprintf(s_err, sizeof(s_err), "imagem/caminho nulo"); return false; }
int w = tb_image_width(img), h = tb_image_height(img);
if (w <= 0 || h <= 0) { snprintf(s_err, sizeof(s_err), "imagem vazia"); return false; }
FILE* f = fopen(path, "wb");
if (!f) { snprintf(s_err, sizeof(s_err), "nao criou '%s'", path); return false; }
fprintf(f, "P6\n%d %d\n255\n", w, h);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
uint8_t r, g, b, a;
tb_image_get_pixel(img, x, y, &r, &g, &b, &a);
fputc(r, f); fputc(g, f); fputc(b, f);
}
}
bool ok = (ferror(f) == 0);
fclose(f);
if (!ok) snprintf(s_err, sizeof(s_err), "erro ao gravar");
return ok;
}
/* -- 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) {
if (v < 0) return 0;
if (v > 255) return 255;
return (uint8_t)(v + 0.5);
}
/* -- Blocos --- */
static void eval_load(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Image* img = tb_ppm_load(tb_block_input_text(self, rt, 0));
if (!img) { tinyblocks_set_error(rt, "%s", tb_ppm_last_error()); self->dirty = false; return; }
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) {
TinyBlocks_Image* img = in_img(self, rt, 0);
if (!img || !tb_ppm_save(img, tb_block_input_text(self, rt, 1)))
tinyblocks_set_error(rt, "%s", tb_ppm_last_error());
self->dirty = false;
}
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, 3);
if (!img) { tinyblocks_set_error(rt, "sem memoria"); self->dirty = false; return; }
uint8_t r = clamp8(tb_block_input_number(self, rt, 2, 0));
uint8_t g = clamp8(tb_block_input_number(self, rt, 3, 0));
uint8_t b = clamp8(tb_block_input_number(self, rt, 4, 0));
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
tb_image_set_pixel(img, x, y, r, g, b, 255);
tb_block_set_output(self, 0, tb_value_image(img));
tb_image_release(img);
self->dirty = false;
}
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_setpixel(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Image* img = in_img(self, rt, 0);
if (!img) { tinyblocks_set_error(rt, "imagem invalida"); self->dirty = false; return; }
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_getpixel(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Image* img = in_img(self, rt, 0);
uint8_t r = 0, g = 0, b = 0, a = 0;
tb_image_get_pixel(img, (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[3] = { r, g, b };
for (int i = 0; i < 3; 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;
}
/* -- 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 ppm_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_Category cat = {
"PPM",
{ 255/255.f, 167/255.f, 38/255.f, 1.f},
{ 245/255.f, 124/255.f, 0/255.f, 1.f},
};
tb_library_set_category(lib, &cat);
static const TinyBlocks_SlotDesc img_out[] = {{"imagem", TB_VALUE_IMAGE}};
static const TinyBlocks_SlotDesc n_out[] = {{"n", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc rgb_out[] = {{"cor", TB_VALUE_JSON}};
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 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 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 getp_in[] = {{"imagem",TB_VALUE_IMAGE},{"x",TB_VALUE_INTEGER},{"y",TB_VALUE_INTEGER}};
bool ok = reg(rt, lib, "PPM.Load", load_in, 1, img_out, 1, eval_load)
&& reg(rt, lib, "PPM.Save", save_in, 2, NULL, 0, eval_save)
&& reg(rt, lib, "PPM.New", new_in, 5, img_out, 1, eval_new)
&& reg(rt, lib, "PPM.Width", wh_in, 1, n_out, 1, eval_width)
&& reg(rt, lib, "PPM.Height", wh_in, 1, n_out, 1, eval_height)
&& reg(rt, lib, "PPM.SetPixel", setp_in, 6, NULL, 0, eval_setpixel)
&& reg(rt, lib, "PPM.GetPixel", getp_in, 3, rgb_out, 1, eval_getpixel);
if (ok) tb_image_register_format("ppm", tb_ppm_load, tb_ppm_save);
return ok;
}
TINYBLOCKS_DEFINE_LIBRARY(ppm, "tinyblocks-ppm", "1.0.0", ppm_init, NULL)
const TinyBlocks_LibraryDescriptor* tb_ppm_get_library(void) {
return &_tb_lib_desc_ppm;
}