Estado atual do TinyBlocks: editor estilo Scratch + graphics como interface

Snapshot do projeto antes de implementar o diálogo "Criar um Bloco":
- runtime C block-based (src/, include/)
- libraries: graphics (interface), sdl2 (backend), editor (estilo Scratch),
  python, mcp
- exemplos (hello, sdl2, editor, vector, json, customappearance, python, mcp)
- Makefile com alvo help e build do editor

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude committed 2026-10-20 19:10:43 -03:00
commit 4950ad6006
49 files changed
+10596

No files matched your search

+95
View File
@@ -0,0 +1,95 @@
/*
* TinyBlocks — tb_block.h
* Estrutura base de todo bloco e operações polimórficas via vtable.
*
* Todos os tipos concretos (TypeBlock, LibraryBlock, TextBlock…) começam com
* um campo `TinyBlocks_Block base` — herança em C via primeiro membro.
*/
#ifndef TINYBLOCKS_BLOCK_H
#define TINYBLOCKS_BLOCK_H
#include "tb_defs.h"
/* ── Vtable de bloco ─────────────────────────────────────────────────────── */
typedef struct TinyBlocks_BlockVTable {
/* Avalia o bloco: lê inputs, processa, escreve outputs */
void (*eval) (TinyBlocks_Block* self, TinyBlocks* rt);
/* Libera recursos internos (NÃO libera o ponteiro do bloco em si) */
void (*destroy) (TinyBlocks_Block* self, TinyBlocks* rt);
/* Representação textual; escreve em buf[0..buf_size-1], retorna len */
size_t (*to_string)(TinyBlocks_Block* self, TinyBlocks* rt,
char* buf, size_t buf_size);
/* Clona recursivamente o bloco (o runtime registra o clone) */
TinyBlocks_Block* (*clone) (const TinyBlocks_Block* self, TinyBlocks* rt);
} TinyBlocks_BlockVTable;
/* ── Estrutura base de todo bloco ────────────────────────────────────────── */
struct TinyBlocks_Block {
TinyBlocks_BlockKind kind;
const TinyBlocks_BlockVTable* vtable;
uint64_t id; /* ID único gerado pelo runtime */
char* name; /* rótulo opcional (heap-owned) */
TinyBlocks_TypeBlock* type; /* tipo/classe deste bloco; NULL *
* para blocos primitivos built-in */
/* Slots de entrada: connections[i] descreve de onde vem o input i */
TinyBlocks_Connection* inputs;
uint32_t input_count;
/* Slots de saída: valores computados pelo último eval */
TinyBlocks_Value* outputs;
uint32_t output_count;
TinyBlocks_Block* parent; /* bloco pai (se aninhado) */
void* userdata; /* dados extra por instância */
bool dirty; /* marcado quando inputs mudam */
bool in_eval; /* guard anti-ciclo */
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
/* Cria um bloco a partir de um TypeBlock; registra no runtime */
TB_API TinyBlocks_Block* tb_block_create (TinyBlocks* rt, TinyBlocks_TypeBlock* type);
/* Destrói e libera; remove do registro do runtime */
TB_API void tb_block_destroy(TinyBlocks_Block* block, TinyBlocks* rt);
/* Avalia o bloco (e seus inputs recursivamente se dirty) */
TB_API void tb_block_eval (TinyBlocks_Block* block, TinyBlocks* rt);
/* Clona o bloco e o registra no runtime */
TB_API TinyBlocks_Block* tb_block_clone (const TinyBlocks_Block* block, TinyBlocks* rt);
/* Representação textual */
TB_API size_t tb_block_to_string(TinyBlocks_Block* block, TinyBlocks* rt,
char* buf, size_t buf_size);
/* ── Conexões ────────────────────────────────────────────────────────────── */
TB_API bool tb_block_connect (TinyBlocks_Block* target, uint32_t input_idx,
TinyBlocks_Block* source, uint32_t output_idx);
TB_API void tb_block_disconnect(TinyBlocks_Block* target, uint32_t input_idx);
TB_API bool tb_block_set_default(TinyBlocks_Block* target, uint32_t input_idx,
TinyBlocks_Value default_value);
/* ── Acesso a valores (para uso dentro de eval_fn) ───────────────────────── */
/* Retorna o valor do input[idx]; resolve a conexão se necessário */
TB_API TinyBlocks_Value tb_block_get_input (TinyBlocks_Block* self, TinyBlocks* rt,
uint32_t input_idx);
/* Escreve no output[idx] */
TB_API void tb_block_set_output(TinyBlocks_Block* self,
uint32_t output_idx, TinyBlocks_Value v);
/* ── Downcasting seguro ──────────────────────────────────────────────────── */
TB_API TinyBlocks_TypeBlock* tb_block_as_type (TinyBlocks_Block* b);
TB_API TinyBlocks_LibraryBlock* tb_block_as_library(TinyBlocks_Block* b);
TB_API TinyBlocks_TextBlock* tb_block_as_text (TinyBlocks_Block* b);
TB_API TinyBlocks_IntegerBlock* tb_block_as_integer(TinyBlocks_Block* b);
TB_API TinyBlocks_RealBlock* tb_block_as_real (TinyBlocks_Block* b);
/* ── Helpers internos (usados por implementações de built-ins) ───────────── */
TB_API TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt,
TinyBlocks_BlockKind kind,
size_t struct_size,
uint32_t input_count,
uint32_t output_count,
const TinyBlocks_BlockVTable* vtable);
#endif /* TINYBLOCKS_BLOCK_H */
+116
View File
@@ -0,0 +1,116 @@
/*
* TinyBlocks — tb_defs.h
* Forward declarations, enums e tipos primitivos compartilhados por todo o runtime.
*/
#ifndef TINYBLOCKS_DEFS_H
#define TINYBLOCKS_DEFS_H
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
/* ── Visibilidade de API ─────────────────────────────────────────────────── */
#ifdef _WIN32
# define TB_API __declspec(dllexport)
#else
# define TB_API __attribute__((visibility("default")))
#endif
/* ── Forward declarations ────────────────────────────────────────────────── */
typedef struct TinyBlocks TinyBlocks;
typedef struct TinyBlocks_Block TinyBlocks_Block;
typedef struct TinyBlocks_TypeBlock TinyBlocks_TypeBlock;
typedef struct TinyBlocks_LibraryBlock TinyBlocks_LibraryBlock;
typedef struct TinyBlocks_TextBlock TinyBlocks_TextBlock;
typedef struct TinyBlocks_IntegerBlock TinyBlocks_IntegerBlock;
typedef struct TinyBlocks_RealBlock TinyBlocks_RealBlock;
typedef struct TinyBlocks_VectorBlock TinyBlocks_VectorBlock;
typedef struct TinyBlocks_VectorData TinyBlocks_VectorData;
typedef struct TinyBlocks_RenderableBlock TinyBlocks_RenderableBlock;
typedef struct TinyBlocks_JsonValue TinyBlocks_JsonValue;
/* ── Kinds de bloco ──────────────────────────────────────────────────────── */
typedef enum TinyBlocks_BlockKind {
TB_KIND_BLOCK = 0, /* bloco genérico / definido pelo usuário */
TB_KIND_TYPE = 1, /* TinyBlocks_TypeBlock */
TB_KIND_LIBRARY = 2, /* TinyBlocks_LibraryBlock */
TB_KIND_TEXT = 3, /* TinyBlocks_TextBlock */
TB_KIND_INTEGER = 4, /* TinyBlocks_IntegerBlock */
TB_KIND_REAL = 5, /* TinyBlocks_RealBlock */
TB_KIND_VECTOR = 6, /* TinyBlocks_VectorBlock */
} TinyBlocks_BlockKind;
/* ── Kinds de valor (para slots) ─────────────────────────────────────────── */
typedef enum TinyBlocks_ValueKind {
TB_VALUE_NONE = 0,
TB_VALUE_INTEGER = 1,
TB_VALUE_REAL = 2,
TB_VALUE_TEXT = 3,
TB_VALUE_BLOCK = 4, /* referência a qualquer bloco (handle opaco) */
TB_VALUE_VECTOR = 5, /* dados de vetor 2D (ref-counted) */
TB_VALUE_JSON = 6, /* valor JSON (ref-counted) */
} TinyBlocks_ValueKind;
/* ── Valor com tag (flui entre slots) ────────────────────────────────────── */
typedef struct TinyBlocks_Value {
TinyBlocks_ValueKind kind;
union {
int64_t integer;
double real;
char* text; /* heap-owned (tb_value_free) */
TinyBlocks_Block* block; /* ponteiro não-owning */
TinyBlocks_VectorData* vector; /* ref-counted (retain/release) */
TinyBlocks_JsonValue* json; /* ref-counted (retain/release) */
} as;
} TinyBlocks_Value;
/* ══════════════════════════════════════════════════════════════════════════
* Dados de vetor 2D (fluxo de comandos de desenho, ref-counted)
* ══════════════════════════════════════════════════════════════════════════ */
typedef enum TinyBlocks_VCmdKind {
TB_VCMD_BEGIN_PATH = 0, /* nenhum arg */
TB_VCMD_MOVE_TO, /* args[0]=x, args[1]=y */
TB_VCMD_LINE_TO, /* args[0]=x, args[1]=y */
TB_VCMD_CLOSE_PATH, /* nenhum arg */
TB_VCMD_STROKE, /* args[0..3]=r,g,b,a args[4]=width */
TB_VCMD_FILL, /* args[0..3]=r,g,b,a */
TB_VCMD_RECT, /* args[0..3]=x,y,w,h */
TB_VCMD_CIRCLE, /* args[0..2]=cx,cy,raio */
} TinyBlocks_VCmdKind;
typedef struct { TinyBlocks_VCmdKind kind; float args[5]; } TinyBlocks_VCmd;
struct TinyBlocks_VectorData {
TinyBlocks_VCmd* cmds;
uint32_t count, capacity;
int32_t ref;
};
/* ── Descritor de slot (em TypeBlock — descreve a forma dos inputs/outputs) ─ */
typedef struct TinyBlocks_SlotDesc {
const char* name;
TinyBlocks_ValueKind expected_kind; /* TB_VALUE_NONE = aceita qualquer tipo */
} TinyBlocks_SlotDesc;
/* ── Conexão de entrada (de qual bloco/slot este input lê) ───────────────── */
typedef struct TinyBlocks_Connection {
TinyBlocks_Block* source; /* bloco de origem (NULL se não conectado) */
uint32_t output_idx; /* qual output slot da origem */
TinyBlocks_Value default_value; /* valor quando não há conexão */
} TinyBlocks_Connection;
/* ── Alocador customizável ───────────────────────────────────────────────── */
typedef void* (*TinyBlocks_AllocFn)(size_t size, void* userdata);
typedef void (*TinyBlocks_FreeFn) (void* ptr, void* userdata);
/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */
TB_API TinyBlocks_Value tb_value_none(void);
TB_API TinyBlocks_Value tb_value_integer(int64_t v);
TB_API TinyBlocks_Value tb_value_real(double v);
TB_API TinyBlocks_Value tb_value_text(const char* v); /* copia a string */
TB_API TinyBlocks_Value tb_value_block(TinyBlocks_Block* v);
TB_API TinyBlocks_Value tb_value_clone(TinyBlocks_Value v); /* deep copy */
TB_API void tb_value_free(TinyBlocks_Value* v); /* libera text */
#endif /* TINYBLOCKS_DEFS_H */
+26
View File
@@ -0,0 +1,26 @@
/*
* TinyBlocks — tb_integer_block.h
* TinyBlocks_IntegerBlock: bloco primitivo que contém um inteiro de 64 bits.
*
* IntegerBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_INTEGER).
*/
#ifndef TINYBLOCKS_INTEGER_BLOCK_H
#define TINYBLOCKS_INTEGER_BLOCK_H
#include "tb_block.h"
struct TinyBlocks_IntegerBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
int64_t value;
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TB_API TinyBlocks_IntegerBlock* tb_integer_block_create (TinyBlocks* rt, int64_t value);
TB_API void tb_integer_block_destroy(TinyBlocks_IntegerBlock* ib,
TinyBlocks* rt);
/* ── Acesso ao valor ─────────────────────────────────────────────────────── */
TB_API int64_t tb_integer_block_get(const TinyBlocks_IntegerBlock* ib);
TB_API void tb_integer_block_set(TinyBlocks_IntegerBlock* ib, int64_t value);
#endif /* TINYBLOCKS_INTEGER_BLOCK_H */
+72
View File
@@ -0,0 +1,72 @@
/*
* TinyBlocks — tb_json_block.h
* TinyBlocks_JsonValue: árvore JSON imutável e ref-counted que flui como valor
* entre blocos (TB_VALUE_JSON).
*
* Fluxo típico de uso:
* TinyBlocks_JsonValue* root = tb_json_parse(text, NULL, 0);
* TinyBlocks_JsonValue* name = tb_json_object_get(root, "name"); // ref nova
* const char* s = tb_json_as_string(name);
* tb_json_release(name);
* tb_json_release(root);
*
* Mutações (array_push/object_set) são feitas em árvores recém-criadas (não
* compartilhadas); para "modificar" um valor já em uso, clone primeiro com
* tb_json_clone.
*/
#ifndef TINYBLOCKS_JSON_BLOCK_H
#define TINYBLOCKS_JSON_BLOCK_H
#include "tb_block.h"
typedef enum TinyBlocks_JsonKind {
TB_JSON_NULL = 0,
TB_JSON_BOOL = 1,
TB_JSON_NUMBER = 2,
TB_JSON_STRING = 3,
TB_JSON_ARRAY = 4,
TB_JSON_OBJECT = 5,
} TinyBlocks_JsonKind;
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TB_API TinyBlocks_JsonValue* tb_json_null (void);
TB_API TinyBlocks_JsonValue* tb_json_bool (bool b);
TB_API TinyBlocks_JsonValue* tb_json_number(double d);
TB_API TinyBlocks_JsonValue* tb_json_string(const char* s); /* copia a string */
TB_API TinyBlocks_JsonValue* tb_json_array (void); /* array vazio */
TB_API TinyBlocks_JsonValue* tb_json_object(void); /* objeto vazio */
TB_API void tb_json_retain (TinyBlocks_JsonValue* j);
TB_API void tb_json_release(TinyBlocks_JsonValue* j);
TB_API TinyBlocks_JsonValue* tb_json_clone (const TinyBlocks_JsonValue* j); /* deep copy */
/* ── Inspeção ────────────────────────────────────────────────────────────── */
TB_API TinyBlocks_JsonKind tb_json_kind (const TinyBlocks_JsonValue* j);
TB_API const char* tb_json_kind_name(const TinyBlocks_JsonValue* j);
TB_API bool tb_json_as_bool (const TinyBlocks_JsonValue* j, bool def);
TB_API double tb_json_as_number(const TinyBlocks_JsonValue* j, double def);
TB_API const char* tb_json_as_string(const TinyBlocks_JsonValue* j); /* NULL se não for string */
/* ── Arrays (mutação in-place; use em árvores não compartilhadas) ───────── */
TB_API bool tb_json_array_push (TinyBlocks_JsonValue* arr, TinyBlocks_JsonValue* item);
TB_API uint32_t tb_json_array_length(const TinyBlocks_JsonValue* arr);
TB_API TinyBlocks_JsonValue* tb_json_array_get(const TinyBlocks_JsonValue* arr, uint32_t idx); /* ref nova, ou NULL */
/* ── Objetos (mutação in-place; use em árvores não compartilhadas) ──────── */
TB_API bool tb_json_object_set (TinyBlocks_JsonValue* obj, const char* key, TinyBlocks_JsonValue* val);
TB_API uint32_t tb_json_object_length (const TinyBlocks_JsonValue* obj);
TB_API const char* tb_json_object_key_at (const TinyBlocks_JsonValue* obj, uint32_t idx);
TB_API TinyBlocks_JsonValue* tb_json_object_get(const TinyBlocks_JsonValue* obj, const char* key); /* ref nova, ou NULL */
/* ── Parsing / serialização ──────────────────────────────────────────────── */
/* Retorna NULL em erro de sintaxe; se errbuf não for NULL, escreve a mensagem. */
TB_API TinyBlocks_JsonValue* tb_json_parse(const char* text, char* errbuf, size_t errbuf_size);
/* Serializa para texto; retorna buffer heap-alocado (free() do chamador). */
TB_API char* tb_json_stringify(const TinyBlocks_JsonValue* j);
/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */
TB_API TinyBlocks_Value tb_value_json (TinyBlocks_JsonValue* j); /* retém ref */
TB_API TinyBlocks_JsonValue* tb_value_as_json(TinyBlocks_Value v);
#endif /* TINYBLOCKS_JSON_BLOCK_H */
+82
View File
@@ -0,0 +1,82 @@
/*
* TinyBlocks — tb_library_block.h
* TinyBlocks_LibraryBlock: contêiner que agrupa um conjunto de blocos.
*
* Libraries são o mecanismo de modularidade da linguagem. Uma library contém
* TypeBlocks (tipos/operações) e pode ser carregada dinamicamente via dlopen.
*
* Estrutura de uma library em C:
* 1. Exporte `const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void)`
* 2. Implemente `init` para criar TypeBlocks e adicioná-los com tb_library_add
* 3. Implemente `deinit` para limpeza
*/
#ifndef TINYBLOCKS_LIBRARY_BLOCK_H
#define TINYBLOCKS_LIBRARY_BLOCK_H
#include "tb_block.h"
struct TinyBlocks_LibraryBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
TinyBlocks_Block** blocks; /* blocos contidos (TypeBlocks, etc.) */
uint32_t block_count;
uint32_t block_capacity;
/* Hooks chamados pelo runtime ao carregar/descarregar (podem ser NULL) */
bool (*on_load )(TinyBlocks_LibraryBlock* self, TinyBlocks* rt);
void (*on_unload)(TinyBlocks_LibraryBlock* self, TinyBlocks* rt);
void* lib_userdata; /* dados privados da library */
};
/* ── Descritor exportado por cada library .so/.dll ───────────────────────── */
typedef struct TinyBlocks_LibraryDescriptor {
const char* name;
const char* version;
bool (*init )(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
void (*deinit)(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
} TinyBlocks_LibraryDescriptor;
/* Símbolo que cada library deve exportar */
#define TINYBLOCKS_LIBRARY_SYMBOL "tinyblocks_get_library"
/* Macro de conveniência para implementações de library */
#define TINYBLOCKS_DEFINE_LIBRARY(sym, name_, version_, init_, deinit_) \
static const TinyBlocks_LibraryDescriptor _tb_lib_desc_##sym = { \
.name = (name_), \
.version = (version_), \
.init = (init_), \
.deinit = (deinit_), \
}; \
TB_API __attribute__((weak)) \
const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void) { \
return &_tb_lib_desc_##sym; \
}
/* ── Operações em LibraryBlock ───────────────────────────────────────────── */
TB_API TinyBlocks_LibraryBlock* tb_library_block_create(TinyBlocks* rt,
const char* name);
TB_API void tb_library_block_destroy(TinyBlocks_LibraryBlock* lib, TinyBlocks* rt);
/* Adiciona um bloco à library (a library não toma ownership do bloco) */
TB_API bool tb_library_add(TinyBlocks_LibraryBlock* lib, TinyBlocks_Block* block);
/* Remove um bloco da library pelo índice */
TB_API bool tb_library_remove_at(TinyBlocks_LibraryBlock* lib, uint32_t index);
/* Busca um bloco pelo nome dentro da library */
TB_API TinyBlocks_Block* tb_library_find(TinyBlocks_LibraryBlock* lib,
const char* name);
/* ── Carregamento dinâmico de libraries ──────────────────────────────────── */
/* Carrega uma library a partir de um .so/.dll; retorna NULL em erro */
TB_API TinyBlocks_LibraryBlock* tb_library_load(TinyBlocks* rt, const char* path);
/* Descarrega uma library previamente carregada com tb_library_load */
TB_API void tb_library_unload(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
/* Registra um LibraryDescriptor estático (para libraries embutidas) */
TB_API TinyBlocks_LibraryBlock* tb_library_register(
TinyBlocks* rt, const TinyBlocks_LibraryDescriptor* desc);
#endif /* TINYBLOCKS_LIBRARY_BLOCK_H */
+26
View File
@@ -0,0 +1,26 @@
/*
* TinyBlocks — tb_real_block.h
* TinyBlocks_RealBlock: bloco primitivo que contém um número real (double).
*
* RealBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_REAL).
*/
#ifndef TINYBLOCKS_REAL_BLOCK_H
#define TINYBLOCKS_REAL_BLOCK_H
#include "tb_block.h"
struct TinyBlocks_RealBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
double value;
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TB_API TinyBlocks_RealBlock* tb_real_block_create (TinyBlocks* rt, double value);
TB_API void tb_real_block_destroy(TinyBlocks_RealBlock* rb,
TinyBlocks* rt);
/* ── Acesso ao valor ─────────────────────────────────────────────────────── */
TB_API double tb_real_block_get(const TinyBlocks_RealBlock* rb);
TB_API void tb_real_block_set(TinyBlocks_RealBlock* rb, double value);
#endif /* TINYBLOCKS_REAL_BLOCK_H */
+116
View File
@@ -0,0 +1,116 @@
/*
* TinyBlocks — tb_renderable_block.h
*
* TinyBlocks_RenderableBlock: lista de comandos de desenho produzida por on_draw.
* O backend (ex: SDL2.App) interpreta os comandos para renderizar na tela.
*
* Uso típico:
* bool my_on_draw(TinyBlocks_Block* self, TinyBlocks* rt,
* TinyBlocks_RenderableBlock** dst) {
* TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
* if (!rb) return false;
* tb_draw_clear(rb, 0.1f, 0.1f, 0.18f, 1.f);
* tb_draw_fill_rect(rb, 10, 10, 200, 100, 0.5f, 0.3f, 0.9f, 1.f);
* tb_draw_text(rb, 20, 50, "Olá", 13.f, 1,1,1,1);
* *dst = rb;
* return true;
* }
* // Após renderizar: tb_renderable_release_all();
*/
#ifndef TINYBLOCKS_RENDERABLE_BLOCK_H
#define TINYBLOCKS_RENDERABLE_BLOCK_H
#include "tb_defs.h"
/* ── Tipos de comando ──────────────────────────────────────────────────────── */
typedef enum {
TB_DRAW_CLEAR, /* limpa toda a área com uma cor */
TB_DRAW_FILL_RECT, /* retângulo preenchido */
TB_DRAW_FILL_RRECT, /* retângulo com cantos arredondados (param=radius) */
TB_DRAW_FILL_CIRCLE, /* círculo preenchido (x=cx, y=cy, param=radius) */
TB_DRAW_STROKE_LINE, /* linha (x,y → w,h como x2,y2; param=espessura) */
TB_DRAW_STROKE_RECT, /* contorno de retângulo (param=espessura) */
TB_DRAW_STROKE_CIRCLE, /* contorno de círculo (x=cx,y=cy,param=r,w=espessura)*/
TB_DRAW_SET_CLIP, /* define rect de clip (coordenadas tela) */
TB_DRAW_CLEAR_CLIP, /* remove clip */
TB_DRAW_TEXT, /* texto (x,y=baseline-left; font_size em px) */
} TinyBlocks_DrawCmdKind;
typedef struct {
TinyBlocks_DrawCmdKind kind;
float x, y, w, h; /* geometria (significado varia por kind) */
float r, g, b, a; /* cor RGBA [0..1] */
float param; /* radius (rrect/circle), espessura (linha/stroke) */
float font_size; /* tamanho da fonte em pixels (TB_DRAW_TEXT) */
char text[128]; /* conteúdo do texto (TB_DRAW_TEXT) */
} TinyBlocks_DrawCmd;
/* ── RenderableBlock ───────────────────────────────────────────────────────── */
#define TB_DRAW_CMD_CAP 8192
struct TinyBlocks_RenderableBlock {
TinyBlocks_DrawCmd cmds[TB_DRAW_CMD_CAP];
uint32_t count;
};
/* ── Pool de renderables (reset por frame, sem malloc durante o loop) ──────── */
/* Adquire um renderable limpo do pool. Retorna NULL se esgotado. */
TB_API TinyBlocks_RenderableBlock* tb_renderable_acquire(void);
/* Libera um renderable individual de volta ao pool (uso após merge). */
TB_API void tb_renderable_release(TinyBlocks_RenderableBlock* rb);
/* Libera todos os renderables de volta ao pool (chamar uma vez por frame,
depois que o backend terminar de renderizar). */
TB_API void tb_renderable_release_all(void);
/* ── Helpers para acrescentar comandos ────────────────────────────────────── */
TB_API void tb_draw_clear (TinyBlocks_RenderableBlock* rb,
float r, float g, float b, float a);
TB_API void tb_draw_fill_rect (TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h,
float r, float g, float b, float a);
TB_API void tb_draw_fill_rrect (TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h, float radius,
float r, float g, float b, float a);
TB_API void tb_draw_fill_circle(TinyBlocks_RenderableBlock* rb,
float cx, float cy, float radius,
float r, float g, float b, float a);
TB_API void tb_draw_stroke_line(TinyBlocks_RenderableBlock* rb,
float x1, float y1, float x2, float y2, float w,
float r, float g, float b, float a);
TB_API void tb_draw_stroke_rect (TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h, float stroke_w,
float r, float g, float b, float a);
TB_API void tb_draw_stroke_circle(TinyBlocks_RenderableBlock* rb,
float cx, float cy, float radius, float stroke_w,
float r, float g, float b, float a);
TB_API void tb_draw_set_clip (TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h);
TB_API void tb_draw_clear_clip (TinyBlocks_RenderableBlock* rb);
TB_API void tb_draw_text (TinyBlocks_RenderableBlock* rb,
float x, float y, const char* text, float font_size,
float r, float g, float b, float a);
/* Mescla src em dst deslocando todas as coordenadas por (dx, dy).
Usado pelo editor para incorporar sub-renderables de blocos com on_draw. */
TB_API void tb_draw_merge_offset(TinyBlocks_RenderableBlock* dst,
const TinyBlocks_RenderableBlock* src,
float dx, float dy);
/* Estimativa de largura de texto (independente de fonte real).
Precisa ser substituída por medição real pelo backend quando disponível. */
TB_API float tb_measure_text(const char* text, float font_size);
#endif /* TINYBLOCKS_RENDERABLE_BLOCK_H */
+30
View File
@@ -0,0 +1,30 @@
/*
* TinyBlocks — tb_text_block.h
* TinyBlocks_TextBlock: bloco primitivo que contém um valor textual.
*
* TextBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_TEXT).
* A string interna é heap-owned e gerenciada pelo bloco.
*/
#ifndef TINYBLOCKS_TEXT_BLOCK_H
#define TINYBLOCKS_TEXT_BLOCK_H
#include "tb_block.h"
struct TinyBlocks_TextBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
char* value; /* string heap-owned */
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TB_API TinyBlocks_TextBlock* tb_text_block_create (TinyBlocks* rt, const char* value);
TB_API void tb_text_block_destroy(TinyBlocks_TextBlock* tb,
TinyBlocks* rt);
/* ── Acesso ao valor ─────────────────────────────────────────────────────── */
TB_API const char* tb_text_block_get(const TinyBlocks_TextBlock* tb);
TB_API void tb_text_block_set(TinyBlocks_TextBlock* tb, const char* value);
/* Concatena value ao final da string atual */
TB_API void tb_text_block_append(TinyBlocks_TextBlock* tb, const char* suffix);
#endif /* TINYBLOCKS_TEXT_BLOCK_H */
+72
View File
@@ -0,0 +1,72 @@
/*
* TinyBlocks — tb_type_block.h
* TinyBlocks_TypeBlock: representa a "classe" de um bloco.
*
* Um TypeBlock define:
* • O nome do tipo
* • Os descritores de slots (inputs e outputs)
* • A função de avaliação para instâncias
* • Hooks de init/deinit por instância
* • Tamanho extra de userdata para instâncias
*
* TypeBlocks são eles mesmos blocos (base.kind == TB_KIND_TYPE).
*/
#ifndef TINYBLOCKS_TYPE_BLOCK_H
#define TINYBLOCKS_TYPE_BLOCK_H
#include "tb_block.h"
struct TinyBlocks_TypeBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
char* type_name; /* nome do tipo, e.g. "SDL2.Window" */
/* Descritores de slots */
TinyBlocks_SlotDesc* input_descs;
uint32_t input_desc_count;
TinyBlocks_SlotDesc* output_descs;
uint32_t output_desc_count;
/* Função de avaliação chamada para todas as instâncias deste tipo */
void (*eval_fn)(TinyBlocks_Block* self, TinyBlocks* rt);
/* Tamanho do bloco de userdata alocado em cada instância (pode ser 0) */
size_t instance_userdata_size;
/* Hooks de ciclo de vida por instância (podem ser NULL) */
bool (*instance_init )(TinyBlocks_Block* self, TinyBlocks* rt);
void (*instance_deinit)(TinyBlocks_Block* self, TinyBlocks* rt);
/* Renderização personalizada (opcional, NULL = aparência padrão do editor).
* Produz comandos de desenho em *dst (adquirido do pool ou passado pelo caller).
* Para blocos widget: coordenadas relativas à área de conteúdo (0,0=top-left).
* Para blocos de cena (ex: Editor.Scene): coordenadas absolutas de tela. */
bool (*on_draw)(TinyBlocks_Block* self, TinyBlocks* rt,
TinyBlocks_RenderableBlock** dst);
};
/* ── Criação de TypeBlock ────────────────────────────────────────────────── */
/* Cria e registra um TypeBlock no runtime */
TB_API TinyBlocks_TypeBlock* tb_type_block_create(
TinyBlocks* rt,
const char* type_name,
const TinyBlocks_SlotDesc* input_descs, uint32_t input_count,
const TinyBlocks_SlotDesc* output_descs, uint32_t output_count,
void (*eval_fn)(TinyBlocks_Block* self, TinyBlocks* rt)
);
TB_API void tb_type_block_destroy(TinyBlocks_TypeBlock* tb, TinyBlocks* rt);
/* Configura hooks de ciclo de vida e tamanho de userdata de instância */
TB_API void tb_type_block_set_instance_hooks(
TinyBlocks_TypeBlock* tb,
size_t instance_userdata_size,
bool (*init )(TinyBlocks_Block* self, TinyBlocks* rt),
void (*deinit)(TinyBlocks_Block* self, TinyBlocks* rt)
);
/* Localiza um TypeBlock por nome no runtime */
TB_API TinyBlocks_TypeBlock* tb_type_block_find(TinyBlocks* rt, const char* type_name);
#endif /* TINYBLOCKS_TYPE_BLOCK_H */
+65
View File
@@ -0,0 +1,65 @@
/*
* TinyBlocks — tb_vector_block.h
* TinyBlocks_VectorBlock: bloco que armazena dados de vetor 2D.
* TinyBlocks_VectorData: comandos de desenho ref-counted que fluem como valores.
*
* Fluxo típico de uso:
* v = tb_vector_data_create();
* tb_vector_begin_path(v);
* tb_vector_move_to(v, 0, 0);
* tb_vector_line_to(v, 100, 50);
* tb_vector_stroke(v, 1,0,0,1, 2.0f);
* TinyBlocks_Value val = tb_value_vector(v); // retém ref
* tb_vector_data_release(v); // libera ref local
* tb_block_set_output(self, 0, val); // set_output toma ownership
*
* Reprodução em RenderableBlock:
* tb_draw_ctx_play(rb, val.as.vector);
*/
#ifndef TINYBLOCKS_VECTOR_BLOCK_H
#define TINYBLOCKS_VECTOR_BLOCK_H
#include "tb_block.h"
#include "tb_renderable_block.h"
/* ── TinyBlocks_VectorBlock — bloco que contém VectorData ───────────────── */
struct TinyBlocks_VectorBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
TinyBlocks_VectorData* data;
};
/* ── Ciclo de vida de VectorData ────────────────────────────────────────── */
TB_API TinyBlocks_VectorData* tb_vector_data_create (void);
TB_API void tb_vector_data_retain (TinyBlocks_VectorData* v);
TB_API void tb_vector_data_release(TinyBlocks_VectorData* v);
TB_API TinyBlocks_VectorData* tb_vector_data_clone (const TinyBlocks_VectorData* v);
TB_API bool tb_vector_data_push (TinyBlocks_VectorData* v,
TinyBlocks_VCmd cmd);
/* ── Construtores de comandos ────────────────────────────────────────────── */
TB_API bool tb_vector_begin_path(TinyBlocks_VectorData* v);
TB_API bool tb_vector_move_to (TinyBlocks_VectorData* v, float x, float y);
TB_API bool tb_vector_line_to (TinyBlocks_VectorData* v, float x, float y);
TB_API bool tb_vector_close_path(TinyBlocks_VectorData* v);
TB_API bool tb_vector_stroke (TinyBlocks_VectorData* v,
float r, float g, float b, float a, float width);
TB_API bool tb_vector_fill (TinyBlocks_VectorData* v,
float r, float g, float b, float a);
TB_API bool tb_vector_rect (TinyBlocks_VectorData* v,
float x, float y, float w, float h);
TB_API bool tb_vector_circle (TinyBlocks_VectorData* v,
float cx, float cy, float radius);
/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */
TB_API TinyBlocks_Value tb_value_vector (TinyBlocks_VectorData* v);
TB_API TinyBlocks_VectorData* tb_value_as_vector(TinyBlocks_Value v);
/* ── VectorBlock (bloco no grafo) ────────────────────────────────────────── */
TB_API TinyBlocks_VectorBlock* tb_vector_block_create (TinyBlocks* rt);
TB_API void tb_vector_block_set_data (TinyBlocks_VectorBlock* b,
TinyBlocks_VectorData* v);
/* ── Reprodução de VectorData via RenderableBlock ───────────────────────── */
TB_API void tb_draw_ctx_play(TinyBlocks_RenderableBlock* rb, TinyBlocks_VectorData* v);
#endif /* TINYBLOCKS_VECTOR_BLOCK_H */
+113
View File
@@ -0,0 +1,113 @@
/*
* TinyBlocks — tinyblocks.h
* Cabeçalho principal do runtime. Inclua apenas este arquivo.
*
* O struct TinyBlocks é o runtime da linguagem. Ele é completamente separado
* de qualquer interface gráfica — GUIs são implementadas como LibraryBlocks.
*
* Fluxo de uso mínimo:
*
* TinyBlocks* rt = NULL;
* tinyblocks_init(&rt, NULL); // inicializa com alocador padrão
*
* // carrega uma library (estática ou dinâmica)
* tb_library_register(rt, my_library_descriptor());
*
* // cria blocos, conecta-os, avalia
* TinyBlocks_TypeBlock* t = tb_type_block_find(rt, "Math.Add");
* TinyBlocks_Block* b = tb_block_create(rt, t);
* tb_block_connect(b, 0, lit_a, 0);
* tb_block_connect(b, 1, lit_b, 0);
* tb_block_eval(b, rt);
* TinyBlocks_Value result = b->outputs[0];
*
* tinyblocks_deinit(&rt);
*/
#ifndef TINYBLOCKS_H
#define TINYBLOCKS_H
#include "tb_defs.h"
#include "tb_block.h"
#include "tb_type_block.h"
#include "tb_library_block.h"
#include "tb_text_block.h"
#include "tb_integer_block.h"
#include "tb_real_block.h"
#include "tb_vector_block.h"
#include "tb_json_block.h"
/* ── Runtime ─────────────────────────────────────────────────────────────── */
struct TinyBlocks {
/* Alocador (padrão: malloc/free) */
TinyBlocks_AllocFn alloc;
TinyBlocks_FreeFn free;
void* alloc_userdata;
/* Registro global de blocos vivos */
TinyBlocks_Block** blocks;
uint32_t block_count;
uint32_t block_capacity;
/* Registro de tipos */
TinyBlocks_TypeBlock** types;
uint32_t type_count;
uint32_t type_capacity;
/* Registro de libraries */
TinyBlocks_LibraryBlock** libraries;
uint32_t library_count;
uint32_t library_capacity;
/* Handles de bibliotecas carregadas dinamicamente (dlopen) */
void** dl_handles;
uint32_t dl_handle_count;
uint32_t dl_handle_capacity;
/* Gerador de IDs únicos */
uint64_t next_id;
/* Último erro em texto legível */
char error[512];
};
/* ── Opções de inicialização ─────────────────────────────────────────────── */
typedef struct TinyBlocks_InitOptions {
TinyBlocks_AllocFn alloc; /* NULL = malloc padrão */
TinyBlocks_FreeFn free_fn; /* NULL = free padrão */
void* alloc_userdata;
uint32_t initial_block_cap; /* 0 = 64 */
uint32_t initial_type_cap; /* 0 = 32 */
uint32_t initial_library_cap; /* 0 = 16 */
} TinyBlocks_InitOptions;
/* ── Ciclo de vida do runtime ────────────────────────────────────────────── */
TB_API bool tinyblocks_init (TinyBlocks** out_rt, const TinyBlocks_InitOptions* opts);
TB_API void tinyblocks_deinit(TinyBlocks** rt);
/* ── Registro interno (usado pelas implementações de bloco) ─────────────── */
TB_API bool tb_rt_register_block (TinyBlocks* rt, TinyBlocks_Block* block);
TB_API void tb_rt_unregister_block(TinyBlocks* rt, TinyBlocks_Block* block);
TB_API bool tb_rt_register_type (TinyBlocks* rt, TinyBlocks_TypeBlock* type);
TB_API void tb_rt_unregister_type (TinyBlocks* rt, TinyBlocks_TypeBlock* type);
TB_API bool tb_rt_register_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
TB_API void tb_rt_unregister_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
/* ── Alocação com o alocador do runtime ─────────────────────────────────── */
TB_API void* tb_alloc(TinyBlocks* rt, size_t size);
TB_API void tb_free (TinyBlocks* rt, void* ptr);
TB_API char* tb_strdup(TinyBlocks* rt, const char* str);
/* ── Diagnósticos ────────────────────────────────────────────────────────── */
TB_API const char* tinyblocks_last_error(TinyBlocks* rt);
TB_API void tinyblocks_set_error (TinyBlocks* rt, const char* fmt, ...);
TB_API void tinyblocks_clear_error(TinyBlocks* rt);
/* ── Busca no registro ───────────────────────────────────────────────────── */
TB_API TinyBlocks_Block* tb_rt_find_block (TinyBlocks* rt, uint64_t id);
TB_API TinyBlocks_TypeBlock* tb_rt_find_type (TinyBlocks* rt, const char* name);
TB_API TinyBlocks_LibraryBlock* tb_rt_find_library(TinyBlocks* rt, const char* name);
/* ── Geração de ID ───────────────────────────────────────────────────────── */
TB_API uint64_t tb_rt_next_id(TinyBlocks* rt);
#endif /* TINYBLOCKS_H */