Files
tinyblocks/libraries/tinyblocks-bmp/src/tb_bmp.c
T
mguinhosandClaude Opus 5.5 5ffc1741c2 Entradas convertidas no core: fim dos helpers de conversão repetidos
- tb_block_input_text / _number / _integer / _truthy: a entrada do bloco
  já convertida, despachando pela classe do valor. O texto de um valor
  que não é texto fica em cache na conexão (sem buffers nos blocos).
- Saída com nome terminado em '?' vira o traço TB_SLOT_BOOLEAN na criação
  do tipo (a convenção mora num lugar só; o editor só lê traços).
- Removidas ~35 funções locais (in_text, in_real, in_int, num, as_num,
  input_name, value_num, value_truthy, value_to_str, item_text) em 22
  libraries e no editor. Inteiros que truncavam (coordenadas de pixel)
  continuam truncando; um número ligado a um campo de texto agora vira
  texto ("42") em vez de "".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:59:14 -03:00

177 lines
6.6 KiB
C

/*
* TinyBlocks - tb_bmp.c
* Categoria "BMP": BMP.Load / BMP.Save. Le e grava BMP BI_RGB 24/32 bits.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <tinyblocks/tinyblocks.h>
#include "tb_bmp.h"
static char s_err[200] = "";
const char* tb_bmp_last_error(void) { return s_err; }
static uint16_t rd16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); }
static uint32_t rd32(const uint8_t* p) {
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
static void wr16(FILE* f, uint16_t v) { fputc(v & 0xff, f); fputc((v >> 8) & 0xff, f); }
static void wr32(FILE* f, uint32_t v) {
fputc(v & 0xff, f); fputc((v >> 8) & 0xff, f);
fputc((v >> 16) & 0xff, f); fputc((v >> 24) & 0xff, f);
}
TinyBlocks_Image* tb_bmp_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; }
uint8_t hdr[54];
if (fread(hdr, 1, 54, f) != 54 || hdr[0] != 'B' || hdr[1] != 'M') {
snprintf(s_err, sizeof(s_err), "nao e um BMP");
fclose(f); return NULL;
}
uint32_t data_off = rd32(hdr + 10);
uint32_t dib_size = rd32(hdr + 14);
int32_t w = (int32_t)rd32(hdr + 18);
int32_t h = (int32_t)rd32(hdr + 22);
uint16_t bpp = rd16(hdr + 28);
uint32_t comp = rd32(hdr + 30);
if (dib_size < 40 || w <= 0 || h == 0) {
snprintf(s_err, sizeof(s_err), "cabecalho BMP nao suportado");
fclose(f); return NULL;
}
if (bpp != 24 && bpp != 32) {
snprintf(s_err, sizeof(s_err), "somente BMP 24/32 bits (bpp=%u)", bpp);
fclose(f); return NULL;
}
if (comp != 0 && !(comp == 3 && bpp == 32)) {
snprintf(s_err, sizeof(s_err), "compressao BMP nao suportada (%u)", comp);
fclose(f); return NULL;
}
int topdown = h < 0;
int ih = topdown ? -h : h;
TinyBlocks_Image* img = tb_image_new(w, ih, 4);
if (!img) { snprintf(s_err, sizeof(s_err), "sem memoria"); fclose(f); return NULL; }
size_t stride = ((size_t)w * bpp / 8 + 3) / 4 * 4;
uint8_t* row = (uint8_t*)malloc(stride);
if (!row) { tb_image_release(img); snprintf(s_err, sizeof(s_err), "sem memoria"); fclose(f); return NULL; }
fseek(f, (long)data_off, SEEK_SET);
for (int y = 0; y < ih; y++) {
if (fread(row, 1, stride, f) != stride) {
snprintf(s_err, sizeof(s_err), "dados truncados");
free(row); tb_image_release(img); fclose(f); return NULL;
}
int dy = topdown ? y : (ih - 1 - y);
for (int x = 0; x < w; x++) {
const uint8_t* p = row + (size_t)x * (bpp / 8);
uint8_t a = (bpp == 32) ? p[3] : 255;
tb_image_set_pixel(img, x, dy, p[2], p[1], p[0], a);
}
}
free(row);
fclose(f);
return img;
}
bool tb_bmp_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; }
size_t stride = ((size_t)w * 3 + 3) / 4 * 4;
uint32_t data_size = (uint32_t)(stride * (size_t)h);
FILE* f = fopen(path, "wb");
if (!f) { snprintf(s_err, sizeof(s_err), "nao criou '%s'", path); return false; }
/* FILEHEADER (14) */
fputc('B', f); fputc('M', f);
wr32(f, 14 + 40 + data_size);
wr16(f, 0); wr16(f, 0);
wr32(f, 14 + 40);
/* BITMAPINFOHEADER (40) */
wr32(f, 40);
wr32(f, (uint32_t)w);
wr32(f, (uint32_t)h);
wr16(f, 1);
wr16(f, 24);
wr32(f, 0); /* BI_RGB */
wr32(f, data_size);
wr32(f, 2835); wr32(f, 2835);
wr32(f, 0); wr32(f, 0);
uint8_t pad[3] = {0, 0, 0};
for (int y = h - 1; y >= 0; y--) { /* BMP e' bottom-up */
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(b, f); fputc(g, f); fputc(r, f);
}
size_t wrote = (size_t)w * 3;
if (wrote < stride) fwrite(pad, 1, stride - wrote, f);
}
bool ok = (ferror(f) == 0);
fclose(f);
if (!ok) snprintf(s_err, sizeof(s_err), "erro ao gravar");
return ok;
}
/* -- Blocos -------------------------------------------------------------- */
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 void eval_load(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Image* img = tb_bmp_load(tb_block_input_text(self, rt, 0));
if (!img) { tinyblocks_set_error(rt, "%s", tb_bmp_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_bmp_save(img, tb_block_input_text(self, rt, 1)))
tinyblocks_set_error(rt, "%s", tb_bmp_last_error());
self->dirty = false;
}
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 bmp_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_Category cat = {
"BMP",
{ 126/255.f, 87/255.f, 194/255.f, 1.f},
{ 81/255.f, 45/255.f, 168/255.f, 1.f},
};
tb_library_set_category(lib, &cat);
static const TinyBlocks_SlotDesc out_img[] = {{"imagem", TB_VALUE_IMAGE}};
static const TinyBlocks_SlotDesc load_in[] = {{"caminho", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc save_in[] = {{"imagem", TB_VALUE_IMAGE}, {"caminho", TB_VALUE_TEXT}};
bool ok = reg(rt, lib, "BMP.Load", load_in, 1, out_img, 1, eval_load)
&& reg(rt, lib, "BMP.Save", save_in, 2, NULL, 0, eval_save);
if (ok) tb_image_register_format("bmp", tb_bmp_load, tb_bmp_save);
return ok;
}
TINYBLOCKS_DEFINE_LIBRARY(bmp, "tinyblocks-bmp", "1.0.0", bmp_init, NULL)
const TinyBlocks_LibraryDescriptor* tb_bmp_get_library(void) {
return &_tb_lib_desc_bmp;
}