diff --git a/libraries/tinyblocks-image/src/tb_imglib.c b/libraries/tinyblocks-image/src/tb_imglib.c index a288f27..da231da 100644 --- a/libraries/tinyblocks-image/src/tb_imglib.c +++ b/libraries/tinyblocks-image/src/tb_imglib.c @@ -1,6 +1,8 @@ /* * 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 @@ -165,6 +167,155 @@ static void eval_save(TinyBlocks_Block* self, TinyBlocks* rt) { 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)in_int(self, rt, 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)in_int(self, rt, 1); + 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, @@ -195,6 +346,10 @@ static bool imglib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { 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) @@ -206,7 +361,11 @@ static bool imglib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { && 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.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) diff --git a/libraries/tinyblocks-number/include/tb_number.h b/libraries/tinyblocks-number/include/tb_number.h index 0bb9785..8ddb22e 100644 --- a/libraries/tinyblocks-number/include/tb_number.h +++ b/libraries/tinyblocks-number/include/tb_number.h @@ -20,4 +20,7 @@ TB_API bool tb_number_is_prime(long long n); /* Formata com `places` casas, sem zeros a direita se places < 0 */ TB_API void tb_number_format (double x, int places, char* out, size_t cap); +/* Texto -> numero (espacos nas pontas, virgula decimal "3,5"); false se nao for */ +TB_API bool tb_number_parse(const char* s, double* out); + #endif /* TINYBLOCKS_NUMBER_H */ diff --git a/libraries/tinyblocks-number/src/tb_number.c b/libraries/tinyblocks-number/src/tb_number.c index 675f2ac..955c379 100644 --- a/libraries/tinyblocks-number/src/tb_number.c +++ b/libraries/tinyblocks-number/src/tb_number.c @@ -2,8 +2,9 @@ * TinyBlocks - tb_number.c * Categoria "Números": matematica com numeros reais. Number.Div / Pow / * Sqrt / Round / Floor / Ceil / RoundTo / Sin / Cos / Tan / Asin / Acos / - * Atan / Log10 / Ln / Exp / Pi / Random / Clamp / Format e os booleanos - * Number.IsEven / IsPrime / IsInteger. + * Atan / Log10 / Ln / Exp / Pi / Random / Clamp / Format, os booleanos + * Number.IsEven / IsPrime / IsInteger e as conversoes Number.From (qualquer + * valor -> numero), Number.ToBase / FromBase (binario, hexadecimal, ...). * * Angulos em GRAUS, como no Scratch. Resultados inteiros saem como inteiro * ("3", nao "3.0"); trigonometria e arredondada em 10 casas (sen 180 = 0). @@ -16,7 +17,9 @@ #include #include +#include #include +#include #include "tb_number.h" #ifndef M_PI @@ -152,6 +155,86 @@ static void eval_is_int(TinyBlocks_Block* self, TinyBlocks* rt) { out_bool(self, isfinite(x) && x == floor(x)); } +/* -- Conversoes ----------------------------------------------------------- */ + +/* Texto -> numero. Aceita espacos nas pontas e virgula decimal ("3,5"). + false se nao for numero. */ +TB_API bool tb_number_parse(const char* s, double* out) { + if (!s) return false; + while (isspace((unsigned char)*s)) s++; + char buf[128]; + size_t n = strlen(s); + while (n && isspace((unsigned char)s[n - 1])) n--; + if (!n || n >= sizeof(buf)) return false; + memcpy(buf, s, n); buf[n] = 0; + char* comma = strchr(buf, ','); + if (comma && !strchr(buf, '.') && !strchr(comma + 1, ',')) *comma = '.'; + char* e; + double d = strtod(buf, &e); + if (e == buf || *e || !isfinite(d)) return false; + *out = d; + return true; +} + +/* "número de (x)": texto vira numero (0 se nao for), verdadeiro = 1 */ +static void eval_from(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + double d = 0; + switch (v.kind) { + case TB_VALUE_INTEGER: d = (double)v.as.integer; break; + case TB_VALUE_REAL: d = v.as.real; break; + case TB_VALUE_TEXT: + if (!tb_number_parse(v.as.text, &d)) { + const char* t = v.as.text ? v.as.text : ""; + d = (!strcmp(t, "verdadeiro") || !strcmp(t, "true")) ? 1 : 0; + } + break; + case TB_VALUE_JSON: { + const char* s = tb_json_as_string(v.as.json); + if (s) { if (!tb_number_parse(s, &d)) d = 0; } + else if (tb_json_kind(v.as.json) == TB_JSON_BOOL) d = tb_json_as_bool(v.as.json, false); + else d = tb_json_as_number(v.as.json, 0); + break; + } + default: break; + } + out_num(self, d); +} + +static int in_base(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + int b = (int)llround(num(self, rt, i)); + return b < 2 ? 2 : b > 36 ? 36 : b; +} + +/* "(255) na base (16)" -> "ff" */ +static void eval_to_base(TinyBlocks_Block* self, TinyBlocks* rt) { + long long x = llround(num(self, rt, 0)); + int b = in_base(self, rt, 1); + char buf[72], *p = buf + sizeof(buf) - 1; + *p = 0; + unsigned long long u = x < 0 ? 0ull - (unsigned long long)x : (unsigned long long)x; + do { *--p = "0123456789abcdefghijklmnopqrstuvwxyz"[u % (unsigned)b]; u /= (unsigned)b; } while (u); + if (x < 0) *--p = '-'; + tb_block_set_output(self, 0, tb_value_text(p)); + self->dirty = false; +} + +/* "(ff) da base (16)" -> 255; digito invalido = erro */ +static void eval_from_base(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + char buf[72]; + const char* s = buf; + if (v.kind == TB_VALUE_TEXT) s = v.as.text ? v.as.text : ""; + else snprintf(buf, sizeof(buf), "%lld", llround(num(self, rt, 0))); + int b = in_base(self, rt, 1); + while (isspace((unsigned char)*s)) s++; + char* e; + long long r = strtoll(s, &e, b); + while (isspace((unsigned char)*e)) e++; + if (e == s || *e) tinyblocks_set_error(rt, "'%s' não é um número na base %d", s, b); + out_num(self, (double)r); +} + /* -- Registro ------------------------------------------------------------- */ static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, @@ -194,11 +277,17 @@ static bool number_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { TB_BLOCK_META("Number.IsEven", "eval_is_even", "Verdadeiro se o numero for par"); TB_BLOCK_META("Number.IsPrime", "tb_number_is_prime", "Verdadeiro se o numero for primo"); TB_BLOCK_META("Number.IsInteger", "eval_is_int", "Verdadeiro se o numero nao tiver casas decimais"); + TB_BLOCK_META("Number.From", "tb_number_parse", "Converte texto (ou outro valor) em numero; aceita virgula decimal"); + TB_BLOCK_META("Number.ToBase", "eval_to_base", "Texto do numero em outra base (2 = binario, 16 = hexadecimal)"); + TB_BLOCK_META("Number.FromBase", "eval_from_base", "Numero a partir de um texto escrito em outra base"); static const TinyBlocks_SlotDesc n1[] = {{"x", TB_VALUE_REAL}}; static const TinyBlocks_SlotDesc n2[] = {{"a", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}}; static const TinyBlocks_SlotDesc n3[] = {{"x", TB_VALUE_REAL}, {"min", TB_VALUE_REAL}, {"max", TB_VALUE_REAL}}; static const TinyBlocks_SlotDesc nk[] = {{"x", TB_VALUE_REAL}, {"casas", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc any1[] = {{"valor", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc nb[] = {{"x", TB_VALUE_REAL}, {"base", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc tb[] = {{"texto", TB_VALUE_TEXT}, {"base", TB_VALUE_INTEGER}}; /* saida "qualquer": inteiro quando exato, senao real */ static const TinyBlocks_SlotDesc out[] = {{"numero", TB_VALUE_NONE}}; static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}}; @@ -229,7 +318,10 @@ static bool number_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { && reg(rt, lib, "Number.Format", nk, 2, text_out, 1, eval_format) && reg(rt, lib, "Number.IsEven", n1, 1, even_out, 1, eval_is_even) && reg(rt, lib, "Number.IsPrime", n1, 1, prime_out, 1, eval_is_prime) - && reg(rt, lib, "Number.IsInteger", n1, 1, int_out, 1, eval_is_int); + && reg(rt, lib, "Number.IsInteger", n1, 1, int_out, 1, eval_is_int) + && reg(rt, lib, "Number.From", any1, 1, out, 1, eval_from) + && reg(rt, lib, "Number.ToBase", nb, 2, text_out, 1, eval_to_base) + && reg(rt, lib, "Number.FromBase", tb, 2, out, 1, eval_from_base); } static void number_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { diff --git a/libraries/tinyblocks-string/src/tb_string.c b/libraries/tinyblocks-string/src/tb_string.c index 9c2752e..4883488 100644 --- a/libraries/tinyblocks-string/src/tb_string.c +++ b/libraries/tinyblocks-string/src/tb_string.c @@ -2,7 +2,8 @@ * TinyBlocks - tb_string.c * Categoria "Texto": String.Upper / Lower / Sub / Letter / Length / Find / * Replace / Trim / Repeat / Reverse / Split e os booleanos String.Contains / - * StartsWith / EndsWith / IsNumber / IsEmpty. + * StartsWith / EndsWith / IsNumber / IsEmpty e as conversoes String.From + * (qualquer valor -> texto), String.Code / FromCode (letra <-> codigo). * * Tudo conta LETRAS (pontos de codigo UTF-8), nao bytes: "maçã" tem 4. * Maiusculas/minusculas cobrem ASCII e Latin-1 (á, ç, õ, ...), o que basta @@ -312,6 +313,68 @@ static void eval_isempty(TinyBlocks_Block* self, TinyBlocks* rt) { free(t); } +/* -- Conversoes ----------------------------------------------------------- */ + +/* "texto de (x)": numero sem ".0", lista/JSON como JSON, imagem descrita */ +static void eval_from(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + char buf[64]; + switch (v.kind) { + case TB_VALUE_TEXT: out_owned(self, dup_n(v.as.text ? v.as.text : "", strlen(v.as.text ? v.as.text : ""))); return; + case TB_VALUE_INTEGER: snprintf(buf, sizeof(buf), "%lld", (long long)v.as.integer); break; + case TB_VALUE_REAL: snprintf(buf, sizeof(buf), "%.15g", v.as.real); break; + case TB_VALUE_JSON: { + const char* s = tb_json_as_string(v.as.json); /* texto JSON sai sem aspas */ + out_owned(self, s ? dup_n(s, strlen(s)) : tb_json_stringify(v.as.json)); + return; + } + case TB_VALUE_IMAGE: + snprintf(buf, sizeof(buf), "imagem %dx%d", tb_image_width(v.as.image), tb_image_height(v.as.image)); + break; + default: buf[0] = 0; break; + } + out_owned(self, dup_n(buf, strlen(buf))); +} + +/* Ponto de codigo da primeira letra (UTF-8); 0 se vazio */ +static long u8_decode(const char* s) { + const unsigned char* p = (const unsigned char*)s; + size_t l = u8_len(*p); + if (!*p) return 0; + if (l == 1) return *p; + long c = *p & (0xFF >> (l + 1)); + for (size_t i = 1; i < l; i++) { + if ((p[i] & 0xC0) != 0x80) return *p; + c = (c << 6) | (p[i] & 0x3F); + } + return c; +} + +static size_t u8_encode(long c, char* out) { + if (c < 0 || c > 0x10FFFF || (c >= 0xD800 && c <= 0xDFFF)) return 0; + if (c < 0x80) { out[0] = (char)c; return 1; } + if (c < 0x800) { out[0] = (char)(0xC0 | (c >> 6)); out[1] = (char)(0x80 | (c & 0x3F)); return 2; } + if (c < 0x10000) { out[0] = (char)(0xE0 | (c >> 12)); out[1] = (char)(0x80 | ((c >> 6) & 0x3F)); + out[2] = (char)(0x80 | (c & 0x3F)); return 3; } + out[0] = (char)(0xF0 | (c >> 18)); out[1] = (char)(0x80 | ((c >> 12) & 0x3F)); + out[2] = (char)(0x80 | ((c >> 6) & 0x3F)); out[3] = (char)(0x80 | (c & 0x3F)); + return 4; +} + +/* "código da letra (A)" -> 65 (Unicode, "ç" = 231) */ +static void eval_code(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64]; + tb_block_set_output(self, 0, tb_value_integer(u8_decode(TXT(0)))); + self->dirty = false; +} + +/* "letra do código (65)" -> "A" */ +static void eval_from_code(TinyBlocks_Block* self, TinyBlocks* rt) { + char buf[5]; + size_t n = u8_encode((long)in_int(self, rt, 0), buf); + out_owned(self, dup_n(buf, n)); +} + /* -- Registro ------------------------------------------------------------- */ static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, @@ -346,6 +409,9 @@ static bool string_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { TB_BLOCK_META("String.EndsWith", "eval_ends", "Verdadeiro se o texto termina com o trecho"); TB_BLOCK_META("String.IsNumber", "tb_string_is_number", "Verdadeiro se o texto for um numero"); TB_BLOCK_META("String.IsEmpty", "eval_isempty", "Verdadeiro se o texto estiver vazio (ou so espacos)"); + TB_BLOCK_META("String.From", "eval_from", "Converte qualquer valor em texto (lista vira JSON)"); + TB_BLOCK_META("String.Code", "eval_code", "Codigo Unicode da primeira letra (A = 65)"); + TB_BLOCK_META("String.FromCode", "eval_from_code", "Letra com o codigo Unicode dado (65 = A)"); static const TinyBlocks_SlotDesc t1[] = {{"texto", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc t2[] = {{"texto", TB_VALUE_TEXT}, {"trecho", TB_VALUE_TEXT}}; @@ -353,6 +419,8 @@ static bool string_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_SlotDesc sub[] = {{"texto", TB_VALUE_TEXT}, {"de", TB_VALUE_INTEGER}, {"ate", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc tn[] = {{"texto", TB_VALUE_TEXT}, {"n", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc split[]= {{"texto", TB_VALUE_TEXT}, {"separador", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc any1[] = {{"valor", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc n1[] = {{"código", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc int_out[] = {{"numero", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc list_out[] = {{"lista", TB_VALUE_JSON}}; @@ -378,7 +446,10 @@ static bool string_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { && reg(rt, lib, "String.StartsWith", t2, 2, beg_out, 1, eval_starts) && reg(rt, lib, "String.EndsWith", t2, 2, end_out, 1, eval_ends) && reg(rt, lib, "String.IsNumber", t1, 1, num_out, 1, eval_isnum) - && reg(rt, lib, "String.IsEmpty", t1, 1, emp_out, 1, eval_isempty); + && reg(rt, lib, "String.IsEmpty", t1, 1, emp_out, 1, eval_isempty) + && reg(rt, lib, "String.From", any1, 1, text_out, 1, eval_from) + && reg(rt, lib, "String.Code", t1, 1, int_out, 1, eval_code) + && reg(rt, lib, "String.FromCode", n1, 1, text_out, 1, eval_from_code); } static void string_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { diff --git a/libraries/tinyblocks-vector/src/tb_vector.c b/libraries/tinyblocks-vector/src/tb_vector.c index bd92437..a16dfe6 100644 --- a/libraries/tinyblocks-vector/src/tb_vector.c +++ b/libraries/tinyblocks-vector/src/tb_vector.c @@ -563,6 +563,20 @@ static void eval_assign(TinyBlocks_Block* self, TinyBlocks* rt) { self->dirty = false; } +/* "lista de (x)": texto "a, b" ou "[1,2]" vira lista, numero vira [n], + objeto JSON vira a lista dos valores, lista continua lista */ +static void eval_from(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + if (v.kind == TB_VALUE_JSON && v.as.json && tb_json_kind(v.as.json) == TB_JSON_OBJECT) { + TinyBlocks_JsonValue* arr = tb_json_array(); + for (uint32_t i = 0; arr && i < tb_json_object_length(v.as.json); i++) + push_owned(arr, tb_json_object_get(v.as.json, tb_json_object_key_at(v.as.json, i))); + out_list(self, arr); + return; + } + out_list(self, tb_vector_from_value(v)); +} + /* -- Registro ------------------------------------------------------------- */ static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, @@ -631,7 +645,8 @@ static bool vector_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { /* saida terminada em '?' = bloco booleano (hexagonal no editor) */ static const TinyBlocks_SlotDesc has_out[] = {{"contém?", TB_VALUE_INTEGER}}; - return reg(rt, lib, "List.Empty", NULL, 0, list_out, 1, eval_empty) + return reg(rt, lib, "List.From", l1, 1, list_out, 1, eval_from) + && reg(rt, lib, "List.Empty", NULL, 0, list_out, 1, eval_empty) && reg(rt, lib, "List.Of", of_in, 3, list_out, 1, eval_of) && reg(rt, lib, "List.Range", rng, 2, list_out, 1, eval_range) && reg(rt, lib, "List.Add", li, 2, list_out, 1, eval_add) diff --git a/tests/image_test.c b/tests/image_test.c index 6ad3c4b..11cb101 100644 --- a/tests/image_test.c +++ b/tests/image_test.c @@ -94,6 +94,51 @@ int main(void) { tb_block_destroy(bn, rt); tb_block_destroy(bc, rt); tinyblocks_deinit(&rt); + /* -- Conversoes: lista de pixels, tons de cinza, desenho em texto -- */ + { + TinyBlocks* rt2; + tinyblocks_init(&rt2, NULL); + tb_library_register(rt2, tb_imglib_get_library()); + TinyBlocks_Block* fl = tb_block_create(rt2, tb_rt_find_type(rt2, "Image.FromList")); + TinyBlocks_Value w = tb_value_integer(2); + TinyBlocks_Value px = tb_value_text("[[255,0,0],[0,0,255,128],0,255]"); + tb_block_set_default(fl, 0, w); + tb_block_set_default(fl, 1, px); + tb_value_free(&px); + tb_block_eval(fl, rt2); + TinyBlocks_Image* im = fl->outputs[0].kind == TB_VALUE_IMAGE ? fl->outputs[0].as.image : NULL; + uint8_t r2 = 0, g2 = 0, b2 = 0, a2 = 0; + if (im) tb_image_get_pixel(im, 1, 0, &r2, &g2, &b2, &a2); + CHECK(im && tb_image_width(im) == 2 && tb_image_height(im) == 2 && b2 == 255 && a2 == 128, + "imagem de largura 2 com 4 pixels (rgb, rgba e cinza)"); + + TinyBlocks_Block* tl = tb_block_create(rt2, tb_rt_find_type(rt2, "Image.ToList")); + tb_block_connect(tl, 0, fl, 0); + tb_block_eval(tl, rt2); + char* js = tl->outputs[0].kind == TB_VALUE_JSON ? tb_json_stringify(tl->outputs[0].as.json) : NULL; + CHECK(js && !strcmp(js, "[[255,0,0,255],[0,0,255,128],[0,0,0,255],[255,255,255,255]]"), + "pixels da imagem voltam como lista [r,g,b,a]"); + free(js); + + TinyBlocks_Block* gr = tb_block_create(rt2, tb_rt_find_type(rt2, "Image.Gray")); + tb_block_connect(gr, 0, fl, 0); + tb_block_eval(gr, rt2); + TinyBlocks_Image* gi = gr->outputs[0].kind == TB_VALUE_IMAGE ? gr->outputs[0].as.image : NULL; + if (gi) tb_image_get_pixel(gi, 0, 0, &r2, &g2, &b2, &a2); + CHECK(gi && r2 == 76 && g2 == 76 && b2 == 76, "tons de cinza (vermelho puro = 76)"); + + TinyBlocks_Block* tt = tb_block_create(rt2, tb_rt_find_type(rt2, "Image.ToText")); + TinyBlocks_Value cols = tb_value_integer(2); + tb_block_connect(tt, 0, fl, 0); + tb_block_set_default(tt, 1, cols); + tb_block_eval(tt, rt2); + const char* art = tt->outputs[0].kind == TB_VALUE_TEXT ? tt->outputs[0].as.text : ""; + CHECK(art[0] && art[0] != ' ' && strchr(art, '\n'), "desenho em texto da imagem"); + printf(" desenho: [%s]\n", art); + tb_block_destroy(tt, rt2); tb_block_destroy(gr, rt2); tb_block_destroy(tl, rt2); tb_block_destroy(fl, rt2); + tinyblocks_deinit(&rt2); + } + if (fails) printf("\n%d FALHA(S)\n", fails); else printf("\nTUDO OK\n"); return fails != 0; diff --git a/tests/stdlib_test.c b/tests/stdlib_test.c index 26680bb..73769ee 100644 --- a/tests/stdlib_test.c +++ b/tests/stdlib_test.c @@ -198,6 +198,40 @@ int main(void) { tb_block_destroy(bs, rt); } + /* -- Conversoes de tipo ------------------------------------------------ */ + CHECK(is_real(run("Number.From", " 3,5 ", NULL, NULL), 3.5), "número de \" 3,5 \" (vírgula decimal)"); + CHECK(is_int(run("Number.From", "42", NULL, NULL), 42) && is_int(run("Number.From", "abc", NULL, NULL), 0), + "número de texto: inteiro sai inteiro, não-número vira 0"); + CHECK(is_text(run("Number.ToBase", "255", "16", NULL), "ff") && is_text(run("Number.ToBase", "-5", "2", NULL), "-101"), + "número na base 16 e na base 2"); + CHECK(is_int(run("Number.FromBase", "ff", "16", NULL), 255) && is_int(run("Number.FromBase", "1010", "2", NULL), 10), + "texto de outra base para número"); + CHECK(is_int(run("String.Code", "ç", NULL, NULL), 231) && is_text(run("String.FromCode", "231", NULL, NULL), "ç"), + "código da letra / letra do código (Unicode)"); + CHECK(is_text(run("String.From", "olá", NULL, NULL), "olá"), "texto de texto"); + CHECK(is_list(run("List.From", "maçã, 2", NULL, NULL), "[\"maçã\",2]") && + is_list(run("List.From", "[1,[2]]", NULL, NULL), "[1,[2]]"), "lista de texto (vírgulas ou JSON)"); + { + /* lista -> texto -> lista; numero real -> texto */ + TinyBlocks_Block* lo = tb_block_create(rt, tb_rt_find_type(rt, "List.Of")); + TinyBlocks_Block* st = tb_block_create(rt, tb_rt_find_type(rt, "String.From")); + TinyBlocks_Block* li = tb_block_create(rt, tb_rt_find_type(rt, "List.From")); + const char* it[3] = { "a", "1", "2.5" }; + for (int k = 0; k < 3; k++) { TinyBlocks_Value v = tb_value_text(it[k]); tb_block_set_default(lo, k, v); tb_value_free(&v); } + tb_block_connect(st, 0, lo, 0); + tb_block_connect(li, 0, st, 0); + tb_block_eval(li, rt); + CHECK(is_text(&st->outputs[0], "[\"a\",\"1\",\"2.5\"]"), "texto de uma lista é o JSON dela"); + CHECK(is_list(&li->outputs[0], "[\"a\",\"1\",\"2.5\"]"), "lista de (texto de lista) volta à lista"); + TinyBlocks_Value r = tb_value_real(0.1); + tb_block_disconnect(st, 0); + tb_block_set_default(st, 0, r); + st->dirty = true; + tb_block_eval(st, rt); + CHECK(is_text(&st->outputs[0], "0.1"), "texto de 0.1 é \"0.1\""); + tb_block_destroy(li, rt); tb_block_destroy(st, rt); tb_block_destroy(lo, rt); + } + if (last) tb_block_destroy(last, rt); tinyblocks_deinit(&rt); if (fails) printf("\n%d FALHA(S)\n", fails);