diff --git a/.gitmodules b/.gitmodules index aafaabf..fe2a449 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,3 +4,6 @@ [submodule "cubiomes"] path = cubiomes url = https://github.com/xpple/cubiomes.git +[submodule "deps/log.c"] + path = deps/log.c + url = https://github.com/rxi/log.c.git diff --git a/Makefile b/Makefile index 3e97669..b17e467 100644 --- a/Makefile +++ b/Makefile @@ -20,18 +20,23 @@ CUBIOMES_SRCS = \ CUBIOMES_OBJS = $(CUBIOMES_SRCS:.c=.o) +LOG_OBJ = deps/log.c/src/log.o + .PHONY: all clean all: celseed -celseed: celseed.o $(CUBIOMES_OBJS) +celseed: celseed.o $(CUBIOMES_OBJS) $(LOG_OBJ) $(CC) -o $@ $^ -lm celseed.o: celseed.c - $(CC) $(CFLAGS) -Wno-format-truncation -Wno-stringop-truncation -c -o $@ $< + $(CC) $(CFLAGS) -Wno-format-truncation -Wno-stringop-truncation -Wno-misleading-indentation -c -o $@ $< $(CUBIOMES_OBJS): %.o: %.c $(CC) $(CFLAGS) -Icubiomes -w -c -o $@ $< +$(LOG_OBJ): deps/log.c/src/log.c + $(CC) $(CFLAGS) -w -c -o $@ $< + clean: - rm -f celseed celseed.o $(CUBIOMES_OBJS) + rm -f celseed celseed.o $(CUBIOMES_OBJS) $(LOG_OBJ) diff --git a/README.md b/README.md index 64dbe8c..2431286 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,13 @@ make The binary `celseed` is created in the project root. +### Dependencies (included as git submodules) + +| Library | Purpose | +|---------|---------| +| [cubiomes](https://github.com/Cubitect/cubiomes) | Minecraft biome/structure generation | +| [log.c](https://github.com/rxi/log.c) | Structured leveled logging | + --- ## Usage @@ -39,6 +46,10 @@ celseed [OPTIONS] | `--large` | off | Enable large biomes | | `--quiet` | off | Print only seed values | | `--verbose` | off | Print index alongside value | +| `--log-level LEVEL` | `info` | Log verbosity: `trace` `debug` `info` `warn` `error` `off` | +| `--log-file FILE` | *(none)* | Write full logs to FILE (always includes DEBUG+) | +| `--no-progress` | off | Disable progress bar | +| `--progress` | off | Force-enable progress bar (e.g. for recording) | | `--list-versions` | — | List all supported versions | --- @@ -122,6 +133,11 @@ celseed --from -500000 --to 500000 --filter 'seed % 1000 == 0' --count 20 32 chunks, i.e. 512 blocks, depending on structure type). - The filter syntax follows CEL principles; the evaluator is implemented in C as part of this tool (the `cel-c` submodule is included for reference). +- The progress bar auto-enables when stderr is a terminal (TTY). It shows + a Unicode block bar (`██░░`), seeds/second speed, found count, and ETA. +- Logging uses [log.c](https://github.com/rxi/log.c) with timestamps and + colors. Use `--log-file` to persist logs. Use `--log-level debug` for + verbose output including expression parsing and generator setup. --- @@ -150,6 +166,13 @@ make В корне проекта появится исполняемый файл `celseed`. +### Зависимости (git submodule) + +| Библиотека | Назначение | +|------------|-----------| +| [cubiomes](https://github.com/Cubitect/cubiomes) | Генерация биомов и структур Minecraft | +| [log.c](https://github.com/rxi/log.c) | Структурированное логирование с уровнями | + --- ## Использование @@ -171,6 +194,10 @@ celseed [ОПЦИИ] | `--large` | выкл | Большие биомы | | `--quiet` | выкл | Печатать только значения сидов | | `--verbose` | выкл | Печатать индекс рядом со значением | +| `--log-level LEVEL` | `info` | Уровень логов: `trace` `debug` `info` `warn` `error` `off` | +| `--log-file FILE` | *(нет)* | Записывать логи в файл | +| `--no-progress` | выкл | Отключить прогресс бар | +| `--progress` | выкл | Принудительно включить прогресс бар | | `--list-versions` | — | Список поддерживаемых версий | --- @@ -246,6 +273,10 @@ celseed --filter 'spawn_x() > -200 && spawn_x() < 200 && spawn_z() > -200 && spa - `x`, `z` в `biome()` и `has_biome()` — блочные координаты. - `rx`, `rz` в `structure()` — индексы регионов (обычно 32 чанка = 512 блоков). - Синтаксис фильтра следует принципам CEL; вычислитель реализован на C. +- Прогресс бар автоматически включается когда stderr является терминалом. + Отображает Unicode-бар (`██░░`), скорость (сидов/сек), счётчик найденных и ETA. +- Логирование через [log.c](https://github.com/rxi/log.c): временные метки, + цветовые уровни. `--log-file` — лог в файл, `--log-level debug` — подробный вывод. --- diff --git a/celseed.c b/celseed.c index 0b1049d..b7a2a7a 100644 --- a/celseed.c +++ b/celseed.c @@ -20,26 +20,52 @@ #include #include #include +#include #include +#include +#include +#include "deps/log.c/src/log.h" #include "cubiomes/generator.h" #include "cubiomes/finders.h" #include "cubiomes/biomes.h" #include "cubiomes/util.h" /* ============================================================ - * Value type + * ANSI codes + Unicode glyphs * ========================================================== */ +#define C_RESET "\033[0m" +#define C_BOLD "\033[1m" +#define C_GREEN "\033[32m" +#define C_BGREEN "\033[1;32m" +#define C_CYAN "\033[36m" +#define C_YELLOW "\033[33m" +#define C_RED "\033[31m" +#define C_MAGENTA "\033[35m" +#define C_GRAY "\033[90m" +#define C_BLUE "\033[94m" +#define PIPE "\xe2\x94\x82" /* │ U+2502 */ +#define BAR_FULL "\xe2\x96\x88" /* █ U+2588 */ +#define BAR_LITE "\xe2\x96\x91" /* ░ U+2591 */ + +static const char *SPIN[] = { /* braille spinner */ + "\xe2\xa0\x8b", "\xe2\xa0\x99", "\xe2\xa0\xb9", "\xe2\xa0\xb8", + "\xe2\xa0\xbc", "\xe2\xa0\xb4", "\xe2\xa0\xa6", "\xe2\xa0\xa7", + "\xe2\xa0\x87", "\xe2\xa0\x8f" +}; +#define SPIN_N 10 + +/* ============================================================ + * CEL value type + * ========================================================== */ typedef enum { VT_NULL, VT_INT, VT_FLOAT, VT_STR, VT_BOOL, VT_ERR } VType; - typedef struct { VType type; int64_t i; double d; bool b; - const char *s; /* static string or points into sbuf */ - char sbuf[64]; + const char *s; } Val; static Val vint(int64_t v) { Val r; memset(&r,0,sizeof(r)); r.type=VT_INT; r.i=v; return r; } @@ -57,206 +83,98 @@ static bool vtrue(Val v) { default: return false; } } - static int vcmp(Val a, Val b) { - if (a.type == VT_INT && b.type == VT_INT) - return (a.i > b.i) - (a.i < b.i); - if ((a.type == VT_INT || a.type == VT_FLOAT) && - (b.type == VT_INT || b.type == VT_FLOAT)) { - double da = (a.type == VT_INT) ? (double)a.i : a.d; - double db = (b.type == VT_INT) ? (double)b.i : b.d; - return (da > db) - (da < db); + if (a.type==VT_INT && b.type==VT_INT) return (a.i>b.i)-(a.idb)-(dasrc = src; - l->pos = 0; - l->peeked = false; - l->err[0] = '\0'; -} +static void lex_init(Lex *l, const char *src) { l->src=src; l->pos=0; l->peeked=false; l->err[0]='\0'; } static Tok lex_read(Lex *l) { - Tok t; t.sval[0] = '\0'; - const char *s = l->src; - while (s[l->pos] == ' ' || s[l->pos] == '\t') l->pos++; - char c = s[l->pos]; - if (!c) { t.k = TK_EOF; return t; } - - if (c == '"') { - l->pos++; - int i = 0; - while (s[l->pos] && s[l->pos] != '"' && i < SMAX-1) - t.sval[i++] = s[l->pos++]; - t.sval[i] = '\0'; - if (s[l->pos] == '"') l->pos++; - t.k = TK_STR; - return t; + Tok t; t.sval[0]='\0'; + while (l->src[l->pos]==' '||l->src[l->pos]=='\t') l->pos++; + char c=l->src[l->pos]; + if (!c) { t.k=TK_EOF; return t; } + if (c=='"') { + l->pos++; int i=0; + while (l->src[l->pos]&&l->src[l->pos]!='"'&&isrc[l->pos++]; + t.sval[i]='\0'; if (l->src[l->pos]=='"') l->pos++; t.k=TK_STR; return t; } - - if (c >= '0' && c <= '9') { - char *end; - t.ival = strtoll(s + l->pos, &end, 10); - if (*end == '.' || *end == 'e' || *end == 'E') { - t.dval = strtod(s + l->pos, &end); - t.k = TK_FLOAT; - } else { - t.k = TK_INT; - } - l->pos = (int)(end - s); - return t; + if (c>='0'&&c<='9') { + char *end; t.ival=strtoll(l->src+l->pos,&end,10); + if (*end=='.'||*end=='e'||*end=='E') { t.dval=strtod(l->src+l->pos,&end); t.k=TK_FLOAT; } + else t.k=TK_INT; + l->pos=(int)(end-l->src); return t; } - - if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_') { - int i = 0; - while ((s[l->pos] >= 'a' && s[l->pos] <= 'z') || - (s[l->pos] >= 'A' && s[l->pos] <= 'Z') || - (s[l->pos] >= '0' && s[l->pos] <= '9') || - s[l->pos] == '_') - t.sval[i++] = s[l->pos++]; - t.sval[i] = '\0'; - t.k = TK_IDENT; - return t; + if ((c>='a'&&c<='z')||(c>='A'&&c<='Z')||c=='_') { + int i=0; + while ((l->src[l->pos]>='a'&&l->src[l->pos]<='z')||(l->src[l->pos]>='A'&&l->src[l->pos]<='Z')|| + (l->src[l->pos]>='0'&&l->src[l->pos]<='9')||l->src[l->pos]=='_') + t.sval[i++]=l->src[l->pos++]; + t.sval[i]='\0'; t.k=TK_IDENT; return t; } - l->pos++; switch (c) { - case '+': t.k = TK_PLUS; break; - case '-': t.k = TK_MINUS; break; - case '*': t.k = TK_STAR; break; - case '/': t.k = TK_SLASH; break; - case '%': t.k = TK_PCT; break; - case '(': t.k = TK_LP; break; - case ')': t.k = TK_RP; break; - case ',': t.k = TK_COMMA; break; - case '!': - if (s[l->pos]=='=') { l->pos++; t.k=TK_NEQ; } - else t.k = TK_BANG; - break; - case '<': - if (s[l->pos]=='=') { l->pos++; t.k=TK_LE; } - else t.k = TK_LT; - break; - case '>': - if (s[l->pos]=='=') { l->pos++; t.k=TK_GE; } - else t.k = TK_GT; - break; - case '=': - if (s[l->pos]=='=') { l->pos++; t.k=TK_EQ; } - else { snprintf(l->err,SMAX,"use '==' not '='"); t.k=TK_ERR; } - break; - case '&': - if (s[l->pos]=='&') { l->pos++; t.k=TK_AND; } - else { snprintf(l->err,SMAX,"use '&&' not '&'"); t.k=TK_ERR; } - break; - case '|': - if (s[l->pos]=='|') { l->pos++; t.k=TK_OR; } - else { snprintf(l->err,SMAX,"use '||' not '|'"); t.k=TK_ERR; } - break; - default: - snprintf(l->err, SMAX, "unexpected char '%c'", c); - t.k = TK_ERR; - break; + case '+': t.k=TK_PLUS; break; case '-': t.k=TK_MINUS; break; + case '*': t.k=TK_STAR; break; case '/': t.k=TK_SLASH; break; + case '%': t.k=TK_PCT; break; case '(': t.k=TK_LP; break; + case ')': t.k=TK_RP; break; case ',': t.k=TK_COMMA; break; + case '!': if(l->src[l->pos]=='='){l->pos++;t.k=TK_NEQ;}else t.k=TK_BANG; break; + case '<': if(l->src[l->pos]=='='){l->pos++;t.k=TK_LE;} else t.k=TK_LT; break; + case '>': if(l->src[l->pos]=='='){l->pos++;t.k=TK_GE;} else t.k=TK_GT; break; + case '=': if(l->src[l->pos]=='='){l->pos++;t.k=TK_EQ;} else{snprintf(l->err,SMAX,"use '=='");t.k=TK_ERR;} break; + case '&': if(l->src[l->pos]=='&'){l->pos++;t.k=TK_AND;}else{snprintf(l->err,SMAX,"use '&&'");t.k=TK_ERR;} break; + case '|': if(l->src[l->pos]=='|'){l->pos++;t.k=TK_OR;} else{snprintf(l->err,SMAX,"use '||'");t.k=TK_ERR;} break; + default: snprintf(l->err,SMAX,"unexpected char '%c'",c); t.k=TK_ERR; break; } return t; } - -static Tok lpeek(Lex *l) { - if (!l->peeked) { l->peek = lex_read(l); l->peeked = true; } - return l->peek; -} - -static Tok lconsume(Lex *l) { - Tok t = lpeek(l); - l->peeked = false; - return t; -} +static Tok lpeek(Lex *l) { if(!l->peeked){l->peek=lex_read(l);l->peeked=true;} return l->peek; } +static Tok lconsume(Lex *l) { Tok t=lpeek(l); l->peeked=false; return t; } /* ============================================================ * AST * ========================================================== */ - typedef enum { ND_INT, ND_FLOAT, ND_STR, ND_BOOL, ND_VAR, ND_CALL, - ND_NEG, ND_NOT, - ND_MUL, ND_DIV, ND_MOD, - ND_ADD, ND_SUB, - ND_LT, ND_LE, ND_GT, ND_GE, - ND_EQ, ND_NEQ, - ND_AND, ND_OR, + ND_NEG, ND_NOT, ND_MUL, ND_DIV, ND_MOD, ND_ADD, ND_SUB, + ND_LT, ND_LE, ND_GT, ND_GE, ND_EQ, ND_NEQ, ND_AND, ND_OR, } NKind; - #define MAX_NODES 512 #define MAX_ARGS 8 - typedef struct Node Node; struct Node { - NKind k; - int64_t ival; - double dval; - bool bval; - char name[SMAX]; - Node *lhs, *rhs; - Node *args[MAX_ARGS]; - int nargs; + NKind k; int64_t ival; double dval; bool bval; + char name[SMAX]; Node *lhs, *rhs; Node *args[MAX_ARGS]; int nargs; }; - -typedef struct { - Node pool[MAX_NODES]; - int used; - char err[SMAX]; - Lex lex; -} Parser; +typedef struct { Node pool[MAX_NODES]; int used; char err[SMAX]; Lex lex; } Parser; static Node *palloc(Parser *p) { - if (p->used >= MAX_NODES) { - snprintf(p->err, SMAX, "expression too complex"); - return NULL; - } - Node *n = &p->pool[p->used++]; - memset(n, 0, sizeof(*n)); - return n; + if (p->used>=MAX_NODES){snprintf(p->err,SMAX,"expression too complex");return NULL;} + Node *n=&p->pool[p->used++]; memset(n,0,sizeof(*n)); return n; } static Node *parse_expr(Parser *p); @@ -270,489 +188,441 @@ static Node *parse_unary(Parser *p); static Node *parse_primary(Parser *p); static Node *parse_expr(Parser *p) { return parse_or(p); } - static Node *parse_or(Parser *p) { - Node *n = parse_and(p); if (!n) return NULL; - while (lpeek(&p->lex).k == TK_OR) { - lconsume(&p->lex); - Node *r = parse_and(p); if (!r) return NULL; - Node *op = palloc(p); if (!op) return NULL; - op->k = ND_OR; op->lhs = n; op->rhs = r; n = op; - } - return n; -} - + Node *n=parse_and(p); if(!n) return NULL; + while(lpeek(&p->lex).k==TK_OR){lconsume(&p->lex);Node *r=parse_and(p);if(!r) return NULL; + Node *op=palloc(p);if(!op) return NULL;op->k=ND_OR;op->lhs=n;op->rhs=r;n=op;} return n;} static Node *parse_and(Parser *p) { - Node *n = parse_eq(p); if (!n) return NULL; - while (lpeek(&p->lex).k == TK_AND) { - lconsume(&p->lex); - Node *r = parse_eq(p); if (!r) return NULL; - Node *op = palloc(p); if (!op) return NULL; - op->k = ND_AND; op->lhs = n; op->rhs = r; n = op; - } - return n; -} - + Node *n=parse_eq(p); if(!n) return NULL; + while(lpeek(&p->lex).k==TK_AND){lconsume(&p->lex);Node *r=parse_eq(p);if(!r) return NULL; + Node *op=palloc(p);if(!op) return NULL;op->k=ND_AND;op->lhs=n;op->rhs=r;n=op;} return n;} static Node *parse_eq(Parser *p) { - Node *n = parse_cmp(p); if (!n) return NULL; - for (;;) { - TKind k = lpeek(&p->lex).k; - if (k != TK_EQ && k != TK_NEQ) break; - lconsume(&p->lex); - Node *r = parse_cmp(p); if (!r) return NULL; - Node *op = palloc(p); if (!op) return NULL; - op->k = (k == TK_EQ) ? ND_EQ : ND_NEQ; - op->lhs = n; op->rhs = r; n = op; - } - return n; -} - + Node *n=parse_cmp(p); if(!n) return NULL; + for(;;){TKind k=lpeek(&p->lex).k;if(k!=TK_EQ&&k!=TK_NEQ) break;lconsume(&p->lex); + Node *r=parse_cmp(p);if(!r) return NULL;Node *op=palloc(p);if(!op) return NULL; + op->k=(k==TK_EQ)?ND_EQ:ND_NEQ;op->lhs=n;op->rhs=r;n=op;} return n;} static Node *parse_cmp(Parser *p) { - Node *n = parse_add(p); if (!n) return NULL; - for (;;) { - TKind k = lpeek(&p->lex).k; - if (k!=TK_LT && k!=TK_LE && k!=TK_GT && k!=TK_GE) break; - lconsume(&p->lex); - Node *r = parse_add(p); if (!r) return NULL; - Node *op = palloc(p); if (!op) return NULL; - switch (k) { - case TK_LT: op->k=ND_LT; break; - case TK_LE: op->k=ND_LE; break; - case TK_GT: op->k=ND_GT; break; - default: op->k=ND_GE; break; - } - op->lhs = n; op->rhs = r; n = op; - } - return n; -} - + Node *n=parse_add(p); if(!n) return NULL; + for(;;){TKind k=lpeek(&p->lex).k;if(k!=TK_LT&&k!=TK_LE&&k!=TK_GT&&k!=TK_GE) break; + lconsume(&p->lex);Node *r=parse_add(p);if(!r) return NULL;Node *op=palloc(p);if(!op) return NULL; + switch(k){case TK_LT:op->k=ND_LT;break;case TK_LE:op->k=ND_LE;break; + case TK_GT:op->k=ND_GT;break;default:op->k=ND_GE;break;} + op->lhs=n;op->rhs=r;n=op;} return n;} static Node *parse_add(Parser *p) { - Node *n = parse_mul(p); if (!n) return NULL; - for (;;) { - TKind k = lpeek(&p->lex).k; - if (k!=TK_PLUS && k!=TK_MINUS) break; - lconsume(&p->lex); - Node *r = parse_mul(p); if (!r) return NULL; - Node *op = palloc(p); if (!op) return NULL; - op->k = (k==TK_PLUS) ? ND_ADD : ND_SUB; - op->lhs = n; op->rhs = r; n = op; - } - return n; -} - + Node *n=parse_mul(p); if(!n) return NULL; + for(;;){TKind k=lpeek(&p->lex).k;if(k!=TK_PLUS&&k!=TK_MINUS) break;lconsume(&p->lex); + Node *r=parse_mul(p);if(!r) return NULL;Node *op=palloc(p);if(!op) return NULL; + op->k=(k==TK_PLUS)?ND_ADD:ND_SUB;op->lhs=n;op->rhs=r;n=op;} return n;} static Node *parse_mul(Parser *p) { - Node *n = parse_unary(p); if (!n) return NULL; - for (;;) { - TKind k = lpeek(&p->lex).k; - if (k!=TK_STAR && k!=TK_SLASH && k!=TK_PCT) break; - lconsume(&p->lex); - Node *r = parse_unary(p); if (!r) return NULL; - Node *op = palloc(p); if (!op) return NULL; - switch (k) { - case TK_STAR: op->k=ND_MUL; break; - case TK_SLASH: op->k=ND_DIV; break; - default: op->k=ND_MOD; break; - } - op->lhs = n; op->rhs = r; n = op; - } - return n; -} - + Node *n=parse_unary(p); if(!n) return NULL; + for(;;){TKind k=lpeek(&p->lex).k;if(k!=TK_STAR&&k!=TK_SLASH&&k!=TK_PCT) break; + lconsume(&p->lex);Node *r=parse_unary(p);if(!r) return NULL;Node *op=palloc(p);if(!op) return NULL; + switch(k){case TK_STAR:op->k=ND_MUL;break;case TK_SLASH:op->k=ND_DIV;break;default:op->k=ND_MOD;break;} + op->lhs=n;op->rhs=r;n=op;} return n;} static Node *parse_unary(Parser *p) { - TKind k = lpeek(&p->lex).k; - if (k == TK_BANG || k == TK_MINUS) { - lconsume(&p->lex); - Node *op = palloc(p); if (!op) return NULL; - op->k = (k == TK_BANG) ? ND_NOT : ND_NEG; - op->lhs = parse_unary(p); - if (!op->lhs) return NULL; - return op; - } - return parse_primary(p); -} - + TKind k=lpeek(&p->lex).k; + if(k==TK_BANG||k==TK_MINUS){lconsume(&p->lex);Node *op=palloc(p);if(!op) return NULL; + op->k=(k==TK_BANG)?ND_NOT:ND_NEG;op->lhs=parse_unary(p);if(!op->lhs) return NULL;return op;} + return parse_primary(p);} static Node *parse_primary(Parser *p) { - Tok t = lconsume(&p->lex); - Node *n; - switch (t.k) { - case TK_INT: - n = palloc(p); if (!n) return NULL; - n->k = ND_INT; n->ival = t.ival; - return n; - case TK_FLOAT: - n = palloc(p); if (!n) return NULL; - n->k = ND_FLOAT; n->dval = t.dval; - return n; - case TK_STR: - n = palloc(p); if (!n) return NULL; - n->k = ND_STR; - strncpy(n->name, t.sval, SMAX-1); - return n; + Tok t=lconsume(&p->lex); Node *n; + switch(t.k){ + case TK_INT: n=palloc(p);if(!n) return NULL;n->k=ND_INT;n->ival=t.ival;return n; + case TK_FLOAT: n=palloc(p);if(!n) return NULL;n->k=ND_FLOAT;n->dval=t.dval;return n; + case TK_STR: n=palloc(p);if(!n) return NULL;n->k=ND_STR;strncpy(n->name,t.sval,SMAX-1);return n; case TK_IDENT: - if (!strcmp(t.sval,"true")) { n=palloc(p); if(!n) return NULL; n->k=ND_BOOL; n->bval=true; return n; } - if (!strcmp(t.sval,"false")) { n=palloc(p); if(!n) return NULL; n->k=ND_BOOL; n->bval=false; return n; } - if (lpeek(&p->lex).k == TK_LP) { - lconsume(&p->lex); - n = palloc(p); if (!n) return NULL; - n->k = ND_CALL; - strncpy(n->name, t.sval, SMAX-1); - if (lpeek(&p->lex).k != TK_RP) { - for (;;) { - if (n->nargs >= MAX_ARGS) { - snprintf(p->err, SMAX, "too many args to %s()", n->name); - return NULL; - } - Node *a = parse_expr(p); if (!a) return NULL; - n->args[n->nargs++] = a; - if (lpeek(&p->lex).k != TK_COMMA) break; - lconsume(&p->lex); - } - } - if (lpeek(&p->lex).k != TK_RP) { - snprintf(p->err, SMAX, "expected ')' after args to %s()", n->name); - return NULL; - } - lconsume(&p->lex); - return n; - } - n = palloc(p); if (!n) return NULL; - n->k = ND_VAR; - strncpy(n->name, t.sval, SMAX-1); - return n; - case TK_LP: { - Node *inner = parse_expr(p); if (!inner) return NULL; - if (lpeek(&p->lex).k != TK_RP) { - snprintf(p->err, SMAX, "expected ')'"); - return NULL; - } - lconsume(&p->lex); - return inner; - } - default: - snprintf(p->err, SMAX, "unexpected token (kind=%d sval='%s')", t.k, t.sval); - return NULL; + if(!strcmp(t.sval,"true")) {n=palloc(p);if(!n)return NULL;n->k=ND_BOOL;n->bval=true;return n;} + if(!strcmp(t.sval,"false")){n=palloc(p);if(!n)return NULL;n->k=ND_BOOL;n->bval=false;return n;} + if(lpeek(&p->lex).k==TK_LP){ + lconsume(&p->lex);n=palloc(p);if(!n) return NULL;n->k=ND_CALL;strncpy(n->name,t.sval,SMAX-1); + if(lpeek(&p->lex).k!=TK_RP){for(;;){ + if(n->nargs>=MAX_ARGS){snprintf(p->err,SMAX,"too many args");return NULL;} + Node *a=parse_expr(p);if(!a) return NULL;n->args[n->nargs++]=a; + if(lpeek(&p->lex).k!=TK_COMMA) break;lconsume(&p->lex);}} + if(lpeek(&p->lex).k!=TK_RP){snprintf(p->err,SMAX,"expected ')'");return NULL;} + lconsume(&p->lex);return n;} + n=palloc(p);if(!n) return NULL;n->k=ND_VAR;strncpy(n->name,t.sval,SMAX-1);return n; + case TK_LP:{Node *inner=parse_expr(p);if(!inner) return NULL; + if(lpeek(&p->lex).k!=TK_RP){snprintf(p->err,SMAX,"expected ')'");return NULL;} + lconsume(&p->lex);return inner;} + default:snprintf(p->err,SMAX,"unexpected token '%s' (kind=%d)",t.sval,t.k);return NULL; } } /* ============================================================ * Evaluation context * ========================================================== */ - typedef struct { - uint64_t seed; - int mc; - int dim; - uint32_t flags; - Generator *gen; - bool gen_ready; - bool spawn_ready; - Pos spawn; + uint64_t seed; int mc; int dim; uint32_t flags; + Generator *gen; bool gen_ready; bool spawn_ready; Pos spawn; } Ctx; - static void ensure_gen(Ctx *c) { - if (!c->gen_ready) { - applySeed(c->gen, c->dim, c->seed); - c->gen_ready = true; - } + if(!c->gen_ready){applySeed(c->gen,c->dim,c->seed);c->gen_ready=true;} } static Val eval_node(const Node *n, Ctx *ctx); -/* ============================================================ - * Built-in functions - * ========================================================== */ - -/* strip optional "minecraft:" prefix for comparison */ -static const char *strip_ns(const char *s) { - if (s && strncmp(s, "minecraft:", 10) == 0) return s + 10; - return s; -} - -static bool biome_name_eq(const char *query, const char *result) { - if (!result) return false; - return strcasecmp(strip_ns(query), strip_ns(result)) == 0; -} - -static bool arg_int(const Node *n, Ctx *ctx, int idx, int *out) { - Val v = eval_node(n->args[idx], ctx); - if (v.type == VT_INT) { *out = (int)v.i; return true; } - if (v.type == VT_FLOAT) { *out = (int)v.d; return true; } - return false; -} +static const char *strip_ns(const char *s){ return (s&&!strncmp(s,"minecraft:",10))?s+10:s; } +static bool biome_name_eq(const char *q,const char *r){ + if(!r) return false; return strcasecmp(strip_ns(q),strip_ns(r))==0;} +static bool arg_int(const Node *n,Ctx *ctx,int idx,int *out){ + Val v=eval_node(n->args[idx],ctx); + if(v.type==VT_INT){*out=(int)v.i;return true;} + if(v.type==VT_FLOAT){*out=(int)v.d;return true;} return false;} static Val fn_biome(const Node *n, Ctx *ctx) { - if (n->nargs != 2) return verr("biome(x,z) takes 2 args"); - int x, z; - if (!arg_int(n,ctx,0,&x) || !arg_int(n,ctx,1,&z)) - return verr("biome() args must be numbers"); - ensure_gen(ctx); - int id = getBiomeAt(ctx->gen, 4, x>>2, 0, z>>2); - if (id < 0) return vstr("none"); - const char *nm = biome2str(ctx->mc, id); - return vstr(nm ? strip_ns(nm) : "unknown"); -} - + if(n->nargs!=2) return verr("biome(x,z) takes 2 args"); + int x,z; if(!arg_int(n,ctx,0,&x)||!arg_int(n,ctx,1,&z)) return verr("biome() args must be numbers"); + ensure_gen(ctx); int id=getBiomeAt(ctx->gen,4,x>>2,0,z>>2); + if(id<0) return vstr("none"); const char *nm=biome2str(ctx->mc,id); + return vstr(nm?strip_ns(nm):"unknown");} static Val fn_biome_id(const Node *n, Ctx *ctx) { - if (n->nargs != 2) return verr("biome_id(x,z) takes 2 args"); - int x, z; - if (!arg_int(n,ctx,0,&x) || !arg_int(n,ctx,1,&z)) - return verr("biome_id() args must be numbers"); - ensure_gen(ctx); - int id = getBiomeAt(ctx->gen, 4, x>>2, 0, z>>2); - return vint(id); -} - + if(n->nargs!=2) return verr("biome_id(x,z) takes 2 args"); + int x,z; if(!arg_int(n,ctx,0,&x)||!arg_int(n,ctx,1,&z)) return verr("biome_id() args must be numbers"); + ensure_gen(ctx); return vint(getBiomeAt(ctx->gen,4,x>>2,0,z>>2));} static Val fn_has_biome(const Node *n, Ctx *ctx) { - if (n->nargs != 4) return verr("has_biome(name,x,z,r) takes 4 args"); - int cx, cz, cr; - if (!arg_int(n,ctx,1,&cx) || !arg_int(n,ctx,2,&cz) || !arg_int(n,ctx,3,&cr)) - return verr("has_biome() args 2,3,4 must be numbers"); - - Val bval = eval_node(n->args[0], ctx); - int target = -1; - - if (bval.type == VT_INT) { - target = (int)bval.i; - } else if (bval.type == VT_STR) { - /* search by name across all valid IDs */ - for (int id = 0; id < 256; id++) { - const char *nm = biome2str(ctx->mc, id); - if (biome_name_eq(bval.s, nm)) { target = id; break; } - } - /* fallback numeric lookup table for pre-1.13 */ - if (target < 0) { - static const struct { const char *name; int id; } tbl[] = { - {"ocean",0},{"plains",1},{"desert",2},{"mountains",3}, - {"forest",4},{"taiga",5},{"swamp",6},{"river",7}, - {"frozen_ocean",10},{"frozen_river",11},{"snowy_tundra",12}, - {"snowy_mountains",13},{"mushroom_fields",14},{"beach",16}, - {"desert_hills",17},{"wooded_hills",18},{"taiga_hills",19}, - {"jungle",21},{"jungle_hills",22},{"jungle_edge",23}, - {"deep_ocean",24},{"stone_shore",25},{"snowy_beach",26}, - {"birch_forest",27},{"birch_forest_hills",28},{"dark_forest",29}, - {"snowy_taiga",30},{"snowy_taiga_hills",31}, - {"giant_tree_taiga",32},{"giant_tree_taiga_hills",33}, - {"wooded_mountains",34},{"savanna",35},{"savanna_plateau",36}, - {"badlands",37},{"wooded_badlands_plateau",38}, + if(n->nargs!=4) return verr("has_biome(name,x,z,r) takes 4 args"); + int cx,cz,cr; + if(!arg_int(n,ctx,1,&cx)||!arg_int(n,ctx,2,&cz)||!arg_int(n,ctx,3,&cr)) + return verr("has_biome() args 2-4 must be numbers"); + Val bval=eval_node(n->args[0],ctx); int target=-1; + if(bval.type==VT_INT){target=(int)bval.i;} + else if(bval.type==VT_STR){ + for(int id=0;id<256;id++){const char *nm=biome2str(ctx->mc,id);if(biome_name_eq(bval.s,nm)){target=id;break;}} + if(target<0){ + static const struct{const char *n;int v;} tbl[]={ + {"ocean",0},{"plains",1},{"desert",2},{"mountains",3},{"forest",4}, + {"taiga",5},{"swamp",6},{"river",7},{"frozen_ocean",10},{"frozen_river",11}, + {"snowy_tundra",12},{"snowy_mountains",13},{"mushroom_fields",14},{"beach",16}, + {"desert_hills",17},{"wooded_hills",18},{"taiga_hills",19},{"jungle",21}, + {"jungle_hills",22},{"jungle_edge",23},{"deep_ocean",24},{"stone_shore",25}, + {"snowy_beach",26},{"birch_forest",27},{"birch_forest_hills",28},{"dark_forest",29}, + {"snowy_taiga",30},{"snowy_taiga_hills",31},{"giant_tree_taiga",32}, + {"giant_tree_taiga_hills",33},{"wooded_mountains",34},{"savanna",35}, + {"savanna_plateau",36},{"badlands",37},{"wooded_badlands_plateau",38}, {"badlands_plateau",39},{"warm_ocean",44},{"lukewarm_ocean",45}, - {"cold_ocean",46},{"deep_warm_ocean",47}, - {"deep_lukewarm_ocean",48},{"deep_cold_ocean",49}, - {"deep_frozen_ocean",50}, - {NULL,0} - }; - for (int i = 0; tbl[i].name; i++) - if (strcasecmp(tbl[i].name, bval.s)==0) { target=tbl[i].id; break; } + {"cold_ocean",46},{"deep_warm_ocean",47},{NULL,0}}; + for(int i=0;tbl[i].n;i++) if(strcasecmp(tbl[i].n,bval.s)==0){target=tbl[i].v;break;} } - if (target < 0) return verr("has_biome(): unknown biome name"); - } else { - return verr("has_biome() arg 1 must be string or int"); - } - + if(target<0) return verr("has_biome(): unknown biome name"); + } else return verr("has_biome() arg 1 must be string or int"); ensure_gen(ctx); - int r4 = (cr >> 2) + 1; - int cx4 = cx >> 2, cz4 = cz >> 2; - int step = (r4 / 32) + 1; - for (int z4 = cz4-r4; z4 <= cz4+r4; z4 += step) { - for (int x4 = cx4-r4; x4 <= cx4+r4; x4 += step) { - if (getBiomeAt(ctx->gen, 4, x4, 0, z4) == target) - return vbool(true); - } - } - return vbool(false); -} - -static int parse_stype(const char *s) { - static const struct { const char *n; int v; } map[] = { + int r4=(cr>>2)+1, cx4=cx>>2, cz4=cz>>2, step=(r4/32)+1; + for(int z4=cz4-r4;z4<=cz4+r4;z4+=step) + for(int x4=cx4-r4;x4<=cx4+r4;x4+=step) + if(getBiomeAt(ctx->gen,4,x4,0,z4)==target) return vbool(true); + return vbool(false);} +static int parse_stype(const char *s){ + static const struct{const char *n;int v;} m[]={ {"desert_pyramid",Desert_Pyramid},{"jungle_temple",Jungle_Temple}, {"swamp_hut",Swamp_Hut},{"igloo",Igloo},{"village",Village}, - {"ocean_ruin",Ocean_Ruin},{"shipwreck",Shipwreck}, - {"monument",Monument},{"mansion",Mansion},{"outpost",Outpost}, - {"ruined_portal",Ruined_Portal},{"ancient_city",Ancient_City}, - {"treasure",Treasure},{"fortress",Fortress},{"bastion",Bastion}, - {"end_city",End_City},{"stronghold",Stronghold}, - {"trail_ruins",Trail_Ruins},{"trial_chambers",Trial_Chambers}, - {NULL,0} - }; - for (int i = 0; map[i].n; i++) - if (strcasecmp(map[i].n, s)==0) return map[i].v; - return -1; -} - -static Val fn_structure(const Node *n, Ctx *ctx) { - if (n->nargs != 3) return verr("structure(type,rx,rz) takes 3 args"); - Val tv = eval_node(n->args[0], ctx); - if (tv.type != VT_STR) return verr("structure() arg 1 must be string"); - int stype = parse_stype(tv.s); - if (stype < 0) return verr("structure(): unknown structure type"); - int rx, rz; - if (!arg_int(n,ctx,1,&rx) || !arg_int(n,ctx,2,&rz)) - return verr("structure() args 2,3 must be numbers"); - StructureConfig sc; - if (!getStructureConfig(stype, ctx->mc, &sc)) return vbool(false); - Pos pos; - if (!getStructurePos(stype, ctx->mc, ctx->seed, rx, rz, &pos)) return vbool(false); + {"ocean_ruin",Ocean_Ruin},{"shipwreck",Shipwreck},{"monument",Monument}, + {"mansion",Mansion},{"outpost",Outpost},{"ruined_portal",Ruined_Portal}, + {"ancient_city",Ancient_City},{"treasure",Treasure},{"fortress",Fortress}, + {"bastion",Bastion},{"end_city",End_City},{"stronghold",Stronghold}, + {"trail_ruins",Trail_Ruins},{"trial_chambers",Trial_Chambers},{NULL,0}}; + for(int i=0;m[i].n;i++) if(strcasecmp(m[i].n,s)==0) return m[i].v; return -1;} +static Val fn_structure(const Node *n,Ctx *ctx){ + if(n->nargs!=3) return verr("structure(type,rx,rz) takes 3 args"); + Val tv=eval_node(n->args[0],ctx);if(tv.type!=VT_STR) return verr("structure() arg 1 must be string"); + int stype=parse_stype(tv.s);if(stype<0) return verr("structure(): unknown type"); + int rx,rz;if(!arg_int(n,ctx,1,&rx)||!arg_int(n,ctx,2,&rz)) return verr("structure() args 2,3 must be numbers"); + StructureConfig sc;if(!getStructureConfig(stype,ctx->mc,&sc)) return vbool(false); + Pos pos;if(!getStructurePos(stype,ctx->mc,ctx->seed,rx,rz,&pos)) return vbool(false); + ensure_gen(ctx);return vbool(isViableStructurePos(stype,ctx->gen,pos.x,pos.z,0)!=0);} +static Val fn_struct_coord(const Node *n,Ctx *ctx,bool want_z){ + if(n->nargs!=3) return verr("struct_x/z(type,rx,rz) takes 3 args"); + Val tv=eval_node(n->args[0],ctx);if(tv.type!=VT_STR) return verr("struct_x/z() arg 1 must be string"); + int stype=parse_stype(tv.s);if(stype<0) return verr("struct_x/z(): unknown type"); + int rx,rz;if(!arg_int(n,ctx,1,&rx)||!arg_int(n,ctx,2,&rz)) return verr("struct_x/z() args 2,3 must be numbers"); + StructureConfig sc;if(!getStructureConfig(stype,ctx->mc,&sc)) return vint(0); + Pos pos;if(!getStructurePos(stype,ctx->mc,ctx->seed,rx,rz,&pos)) return vint(0); + return vint(want_z?pos.z:pos.x);} +static Val fn_spawn(const Node *n,Ctx *ctx,bool want_z){ + if(n->nargs!=0) return verr("spawn_x/z() take no args"); ensure_gen(ctx); - return vbool(isViableStructurePos(stype, ctx->gen, pos.x, pos.z, 0) != 0); -} - -static Val fn_struct_x(const Node *n, Ctx *ctx) { - if (n->nargs != 3) return verr("struct_x(type,rx,rz) takes 3 args"); - Val tv = eval_node(n->args[0], ctx); - if (tv.type != VT_STR) return verr("struct_x() arg 1 must be string"); - int stype = parse_stype(tv.s); - if (stype < 0) return verr("struct_x(): unknown structure type"); - int rx, rz; - if (!arg_int(n,ctx,1,&rx) || !arg_int(n,ctx,2,&rz)) - return verr("struct_x() args 2,3 must be numbers"); - StructureConfig sc; - if (!getStructureConfig(stype, ctx->mc, &sc)) return vint(0); - Pos pos; - if (!getStructurePos(stype, ctx->mc, ctx->seed, rx, rz, &pos)) return vint(0); - return vint(pos.x); -} - -static Val fn_struct_z(const Node *n, Ctx *ctx) { - if (n->nargs != 3) return verr("struct_z(type,rx,rz) takes 3 args"); - Val tv = eval_node(n->args[0], ctx); - if (tv.type != VT_STR) return verr("struct_z() arg 1 must be string"); - int stype = parse_stype(tv.s); - if (stype < 0) return verr("struct_z(): unknown structure type"); - int rx, rz; - if (!arg_int(n,ctx,1,&rx) || !arg_int(n,ctx,2,&rz)) - return verr("struct_z() args 2,3 must be numbers"); - StructureConfig sc; - if (!getStructureConfig(stype, ctx->mc, &sc)) return vint(0); - Pos pos; - if (!getStructurePos(stype, ctx->mc, ctx->seed, rx, rz, &pos)) return vint(0); - return vint(pos.z); -} - -static Val fn_spawn(const Node *n, Ctx *ctx, bool want_z) { - if (n->nargs != 0) return verr("spawn_x()/spawn_z() take no args"); - ensure_gen(ctx); - if (!ctx->spawn_ready) { - ctx->spawn = getSpawn(ctx->gen); - ctx->spawn_ready = true; - } - return vint(want_z ? ctx->spawn.z : ctx->spawn.x); -} + if(!ctx->spawn_ready){ctx->spawn=getSpawn(ctx->gen);ctx->spawn_ready=true;} + return vint(want_z?ctx->spawn.z:ctx->spawn.x);} /* ============================================================ * AST evaluator * ========================================================== */ - static Val eval_node(const Node *n, Ctx *ctx) { - if (!n) return verr("null node"); - - switch (n->k) { + if(!n) return verr("null node"); + switch(n->k){ case ND_INT: return vint(n->ival); case ND_FLOAT: return vfloat(n->dval); case ND_STR: return vstr(n->name); - case ND_BOOL: return vbool(n->bval); - + case ND_BOOL: { Val r; memset(&r,0,sizeof(r)); r.type=VT_BOOL; r.b=n->bval; return r; } case ND_VAR: - if (!strcmp(n->name,"seed")) return vint((int64_t)ctx->seed); + if(!strcmp(n->name,"seed")) return vint((int64_t)ctx->seed); { char buf[SMAX]; snprintf(buf,SMAX,"unknown variable '%s'",n->name); return verr(buf); } - case ND_CALL: - if (!strcmp(n->name,"biome")) return fn_biome(n,ctx); - if (!strcmp(n->name,"biome_id")) return fn_biome_id(n,ctx); - if (!strcmp(n->name,"has_biome")) return fn_has_biome(n,ctx); - if (!strcmp(n->name,"structure")) return fn_structure(n,ctx); - if (!strcmp(n->name,"struct_x")) return fn_struct_x(n,ctx); - if (!strcmp(n->name,"struct_z")) return fn_struct_z(n,ctx); - if (!strcmp(n->name,"spawn_x")) return fn_spawn(n,ctx,false); - if (!strcmp(n->name,"spawn_z")) return fn_spawn(n,ctx,true); + if(!strcmp(n->name,"biome")) return fn_biome(n,ctx); + if(!strcmp(n->name,"biome_id")) return fn_biome_id(n,ctx); + if(!strcmp(n->name,"has_biome")) return fn_has_biome(n,ctx); + if(!strcmp(n->name,"structure")) return fn_structure(n,ctx); + if(!strcmp(n->name,"struct_x")) return fn_struct_coord(n,ctx,false); + if(!strcmp(n->name,"struct_z")) return fn_struct_coord(n,ctx,true); + if(!strcmp(n->name,"spawn_x")) return fn_spawn(n,ctx,false); + if(!strcmp(n->name,"spawn_z")) return fn_spawn(n,ctx,true); { char buf[SMAX]; snprintf(buf,SMAX,"unknown function '%s'",n->name); return verr(buf); } - - case ND_NOT: { - Val v = eval_node(n->lhs,ctx); - return (v.type==VT_ERR) ? v : vbool(!vtrue(v)); - } - case ND_NEG: { - Val v = eval_node(n->lhs,ctx); - if (v.type==VT_INT) return vint(-v.i); - if (v.type==VT_FLOAT) return vfloat(-v.d); - return verr("unary minus on non-numeric"); - } - - case ND_ADD: case ND_SUB: case ND_MUL: case ND_DIV: case ND_MOD: { - Val a=eval_node(n->lhs,ctx), b=eval_node(n->rhs,ctx); - if (a.type==VT_ERR) return a; - if (b.type==VT_ERR) return b; - if (a.type==VT_INT && b.type==VT_INT) { - int64_t ai=a.i, bi=b.i; - switch (n->k) { - case ND_ADD: return vint(ai+bi); - case ND_SUB: return vint(ai-bi); - case ND_MUL: return vint(ai*bi); - case ND_DIV: return bi ? vint(ai/bi) : verr("division by zero"); - default: return bi ? vint(ai%bi) : verr("modulo by zero"); - } - } - double da=(a.type==VT_INT)?(double)a.i:a.d; - double db=(b.type==VT_INT)?(double)b.i:b.d; - switch (n->k) { - case ND_ADD: return vfloat(da+db); - case ND_SUB: return vfloat(da-db); - case ND_MUL: return vfloat(da*db); - default: return db ? vfloat(da/db) : verr("division by zero"); - } - } - - case ND_LT: case ND_LE: case ND_GT: case ND_GE: { - Val a=eval_node(n->lhs,ctx), b=eval_node(n->rhs,ctx); - if (a.type==VT_ERR) return a; - if (b.type==VT_ERR) return b; - int c=vcmp(a,b); - switch (n->k) { - case ND_LT: return vbool(c<0); - case ND_LE: return vbool(c<=0); - case ND_GT: return vbool(c>0); - default: return vbool(c>=0); - } - } - case ND_EQ: { - Val a=eval_node(n->lhs,ctx), b=eval_node(n->rhs,ctx); - if (a.type==VT_ERR) return a; - if (b.type==VT_ERR) return b; - return vbool(veq(a,b)); - } - case ND_NEQ: { - Val a=eval_node(n->lhs,ctx), b=eval_node(n->rhs,ctx); - if (a.type==VT_ERR) return a; - if (b.type==VT_ERR) return b; - return vbool(!veq(a,b)); - } - - case ND_AND: { - Val a=eval_node(n->lhs,ctx); - if (a.type==VT_ERR) return a; - if (!vtrue(a)) return vbool(false); - Val b=eval_node(n->rhs,ctx); - return (b.type==VT_ERR) ? b : vbool(vtrue(b)); - } - case ND_OR: { - Val a=eval_node(n->lhs,ctx); - if (a.type==VT_ERR) return a; - if (vtrue(a)) return vbool(true); - Val b=eval_node(n->rhs,ctx); - return (b.type==VT_ERR) ? b : vbool(vtrue(b)); - } - - default: - return verr("unknown node kind"); + case ND_NOT:{Val v=eval_node(n->lhs,ctx);return(v.type==VT_ERR)?v:vbool(!vtrue(v));} + case ND_NEG:{Val v=eval_node(n->lhs,ctx); + if(v.type==VT_INT) return vint(-v.i);if(v.type==VT_FLOAT) return vfloat(-v.d); + return verr("unary minus on non-numeric");} + case ND_ADD: case ND_SUB: case ND_MUL: case ND_DIV: case ND_MOD:{ + Val a=eval_node(n->lhs,ctx),b=eval_node(n->rhs,ctx); + if(a.type==VT_ERR) return a; if(b.type==VT_ERR) return b; + if(a.type==VT_INT&&b.type==VT_INT){int64_t ai=a.i,bi=b.i; + switch(n->k){case ND_ADD:return vint(ai+bi);case ND_SUB:return vint(ai-bi); + case ND_MUL:return vint(ai*bi);case ND_DIV:return bi?vint(ai/bi):verr("div/0"); + default:return bi?vint(ai%bi):verr("mod/0");}} + double da=(a.type==VT_INT)?(double)a.i:a.d,db=(b.type==VT_INT)?(double)b.i:b.d; + switch(n->k){case ND_ADD:return vfloat(da+db);case ND_SUB:return vfloat(da-db); + case ND_MUL:return vfloat(da*db);default:return db?vfloat(da/db):verr("div/0");}} + case ND_LT: case ND_LE: case ND_GT: case ND_GE:{ + Val a=eval_node(n->lhs,ctx),b=eval_node(n->rhs,ctx); + if(a.type==VT_ERR) return a; if(b.type==VT_ERR) return b; int c=vcmp(a,b); + switch(n->k){case ND_LT:return vbool(c<0);case ND_LE:return vbool(c<=0); + case ND_GT:return vbool(c>0);default:return vbool(c>=0);}} + case ND_EQ:{Val a=eval_node(n->lhs,ctx),b=eval_node(n->rhs,ctx); + if(a.type==VT_ERR) return a;if(b.type==VT_ERR) return b;return vbool(veq(a,b));} + case ND_NEQ:{Val a=eval_node(n->lhs,ctx),b=eval_node(n->rhs,ctx); + if(a.type==VT_ERR) return a;if(b.type==VT_ERR) return b;return vbool(!veq(a,b));} + case ND_AND:{Val a=eval_node(n->lhs,ctx);if(a.type==VT_ERR) return a; + if(!vtrue(a)) return vbool(false);Val b=eval_node(n->rhs,ctx); + return(b.type==VT_ERR)?b:vbool(vtrue(b));} + case ND_OR:{Val a=eval_node(n->lhs,ctx);if(a.type==VT_ERR) return a; + if(vtrue(a)) return vbool(true);Val b=eval_node(n->rhs,ctx); + return(b.type==VT_ERR)?b:vbool(vtrue(b));} + default: return verr("unknown node kind"); } } /* ============================================================ - * xorshift64 for random seed generation + * Time utilities + * ========================================================== */ +static double now_s(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; +} + +static void fmt_speed(char *buf, int sz, double s) { + if (s>=1e9) snprintf(buf,sz,"%.2fG/s",s/1e9); + else if (s>=1e6) snprintf(buf,sz,"%.2fM/s",s/1e6); + else if (s>=1e3) snprintf(buf,sz,"%.1fK/s",s/1e3); + else snprintf(buf,sz,"%.0f/s",s); +} +static void fmt_count(char *buf, int sz, uint64_t n) { + if (n>=1000000000) snprintf(buf,sz,"%.2fB",n/1e9); + else if (n>=1000000) snprintf(buf,sz,"%.2fM",n/1e6); + else if (n>=1000) snprintf(buf,sz,"%.1fK",n/1e3); + else snprintf(buf,sz,"%"PRIu64,n); +} +static void fmt_eta(char *buf, int sz, double secs) { + if(secs<0||secs>86400*7){snprintf(buf,sz,"?");return;} + int h=(int)(secs/3600),m=(int)(secs/60)%60,s=(int)secs%60; + if(h>0) snprintf(buf,sz,"%d:%02d:%02d",h,m,s); + else snprintf(buf,sz,"%d:%02d",m,s); +} + +/* ============================================================ + * Progress bar + * ========================================================== */ +static struct { + bool enabled; + bool is_tty; + uint64_t count; /* target found (0 = unlimited) */ + uint64_t tested; + uint64_t found; + double t_start; + double t_last_draw; + double t_speed_t; /* time of last speed sample */ + uint64_t t_speed_n; /* tested count at last speed sample */ + double speed; /* seeds/sec (EMA) */ + int spin; + bool line_drawn; +} g_bar; + +static int term_width(void) { + struct winsize ws; + if (isatty(STDERR_FILENO) && ioctl(STDERR_FILENO, TIOCGWINSZ, &ws)==0 && ws.ws_col>0) + return ws.ws_col; + return 80; +} + +static void bar_clear(void) { + if (g_bar.line_drawn && g_bar.is_tty) { + fprintf(stderr, "\r\033[K"); fflush(stderr); + g_bar.line_drawn = false; + } +} + +static void bar_draw(bool force) { + if (!g_bar.enabled) return; + double now = now_s(); + if (!force && now - g_bar.t_last_draw < 0.08) return; /* ~12 fps */ + + /* update speed EMA every 250ms */ + double dt = now - g_bar.t_speed_t; + if (dt >= 0.25) { + double inst = (g_bar.tested - g_bar.t_speed_n) / dt; + g_bar.speed = (g_bar.speed == 0.0) ? inst : g_bar.speed*0.75 + inst*0.25; + g_bar.t_speed_n = g_bar.tested; + g_bar.t_speed_t = now; + } + + char spd[24], tst[16], fnd[24], eta[16]; + fmt_speed(spd, sizeof(spd), g_bar.speed); + fmt_count(tst, sizeof(tst), g_bar.tested); + + int tw = term_width(); + + if (g_bar.count > 0) { + /* determinate: show percentage bar */ + int pct = (int)(g_bar.found * 100 / g_bar.count); + if (pct > 100) pct = 100; + + /* ETA estimate */ + double eta_secs = -1.0; + if (g_bar.found > 0 && g_bar.speed > 0.0) { + double avg = (double)g_bar.tested / (double)g_bar.found; + eta_secs = (double)(g_bar.count - g_bar.found) * avg / g_bar.speed; + } + fmt_eta(eta, sizeof(eta), eta_secs); + snprintf(fnd, sizeof(fnd), "%"PRIu64"/%"PRIu64, g_bar.found, g_bar.count); + + /* fixed stats portion (visual width): " 100% │ Found XX/XX │ 99.99M/s │ ETA 9:99:99" */ + char stats_plain[80]; + snprintf(stats_plain, sizeof(stats_plain), + " %d%% " PIPE " Found %s " PIPE " %s " PIPE " ETA %s", + pct, fnd, spd, eta); + /* visual width: each │ is 3 bytes but 1 column, so subtract 2 per │ (3 occurrences) */ + int stats_vw = (int)strlen(stats_plain) - 2*3; + + int prefix_vw = 11; /* "Searching " */ + int bar_vw = tw - prefix_vw - stats_vw; + if (bar_vw < 6) bar_vw = 6; + if (bar_vw > 45) bar_vw = 45; + + int filled = (g_bar.count > 0) ? (int)((double)g_bar.found / g_bar.count * bar_vw) : 0; + if (filled > bar_vw) filled = bar_vw; + + /* build bar (each char = 3 UTF-8 bytes) */ + char bar_str[45*3+1]; int blen=0; + for (int i=0;i0 ? tested/elapsed : 0); + fmt_count(tst, sizeof(tst), tested); + int h=(int)(elapsed/3600),m=(int)(elapsed/60)%60,s=(int)elapsed%60; + if(h>0) snprintf(ela,sizeof(ela),"%d:%02d:%02d",h,m,s); + else snprintf(ela,sizeof(ela),"%d:%02d",m,s); + if (g_bar.is_tty) { + fprintf(stderr, + C_BGREEN "Done" C_RESET + " " C_BGREEN "✓" C_RESET + " Found " C_BGREEN "%"PRIu64 C_RESET + " " PIPE " Tested " C_CYAN "%s" C_RESET + " " PIPE " " C_CYAN "%s" C_RESET + " " PIPE " Elapsed " C_YELLOW "%s" C_RESET "\n", + found, tst, spd, ela); + } else { + fprintf(stderr, "Done Found %"PRIu64" Tested %s %s Elapsed %s\n", + found, tst, spd, ela); + } + fflush(stderr); +} + +/* ============================================================ + * log.c callback: clears progress bar before and redraws after + * ========================================================== */ +static void log_stderr_cb(log_Event *ev) { + static const char *colors[] = { + C_GRAY, C_BLUE, C_GREEN, C_YELLOW, C_RED, C_MAGENTA + }; + static const char *labels[] = { + "TRACE", "DEBUG", "INFO ", "WARN ", "ERROR", "FATAL" + }; + + bar_clear(); + + char ts[10]; + strftime(ts, sizeof(ts), "%H:%M:%S", ev->time); + + FILE *fp = (FILE *)ev->udata; + if (g_bar.is_tty) { + fprintf(fp, "%s %s%s" C_RESET " ", ts, colors[ev->level], labels[ev->level]); + } else { + fprintf(fp, "%s %s ", ts, labels[ev->level]); + } + vfprintf(fp, ev->fmt, ev->ap); + fputc('\n', fp); + fflush(fp); + + bar_draw(true); +} + +static void log_file_cb(log_Event *ev) { + static const char *labels[] = {"TRACE","DEBUG","INFO ","WARN ","ERROR","FATAL"}; + char ts[24]; + strftime(ts, sizeof(ts), "%Y-%m-%d %H:%M:%S", ev->time); + FILE *fp = (FILE *)ev->udata; + fprintf(fp, "%s %s ", ts, labels[ev->level]); + vfprintf(fp, ev->fmt, ev->ap); + fputc('\n', fp); + fflush(fp); +} + +/* ============================================================ + * xorshift64 * ========================================================== */ static uint64_t xorshift64(uint64_t s) { - s ^= s << 13; - s ^= s >> 7; - s ^= s << 17; - return s; + s ^= s << 13; s ^= s >> 7; s ^= s << 17; return s; } /* ============================================================ @@ -760,55 +630,44 @@ static uint64_t xorshift64(uint64_t s) { * ========================================================== */ static void usage(const char *prog) { printf( -"Usage: %s [OPTIONS]\n" -"\n" +"Usage: %s [OPTIONS]\n\n" "Options:\n" -" --mc VERSION Minecraft version (default: newest, e.g. 1.21, 1.18, 1.7, b1.8)\n" -" --filter EXPR CEL filter expression (default: accept all seeds)\n" -" --count N Stop after N matches (default: 10)\n" -" --from SEED Starting seed, signed int64 (default: 0)\n" -" --to SEED Ending seed exclusive (default: unlimited)\n" -" --step N Seed increment (default: 1)\n" -" --random Use random seeds instead of sequential\n" -" --dim DIM Dimension: overworld|nether|end (default: overworld)\n" -" --large Use large biomes flag\n" -" --quiet Print only seed values, no labels\n" -" --verbose Print seed index alongside value\n" -" --list-versions Print supported Minecraft versions and exit\n" -" --help, -h Show this help and exit\n" -"\n" -"Filter functions (x,z are block coordinates; rx,rz are region indices):\n" -" biome(x, z) biome name at block coords -> string\n" -" biome_id(x, z) biome numeric ID -> int\n" -" has_biome(name, x, z, r) biome present within r blocks -> bool\n" -" structure(type, rx, rz) viable structure at region -> bool\n" -" struct_x(type, rx, rz) structure block X coord -> int\n" -" struct_z(type, rx, rz) structure block Z coord -> int\n" -" spawn_x() world spawn X coordinate -> int\n" -" spawn_z() world spawn Z coordinate -> int\n" -"\n" -"Filter variable:\n" -" seed current seed (int64)\n" -"\n" -"Structure types:\n" -" village mansion monument outpost desert_pyramid jungle_temple\n" -" swamp_hut igloo ocean_ruin shipwreck ruined_portal ancient_city\n" -" fortress bastion end_city stronghold trail_ruins trial_chambers\n" -"\n" +" --mc VERSION Minecraft version (default: newest)\n" +" --filter EXPR CEL filter expression\n" +" --count N Stop after N matches (default: 10)\n" +" --from SEED Starting seed (signed int64, default: 0)\n" +" --to SEED Ending seed exclusive\n" +" --step N Seed increment (default: 1)\n" +" --random Random seeds instead of sequential\n" +" --dim overworld|nether|end Dimension (default: overworld)\n" +" --large Enable large biomes\n" +" --quiet Print only seed values to stdout\n" +" --verbose Print seed index alongside value\n" +" --log-level LEVEL trace|debug|info|warn|error|off (default: info)\n" +" --log-file FILE Write logs to FILE in addition to stderr\n" +" --no-progress Disable progress bar\n" +" --progress Force-enable progress bar\n" +" --list-versions Print supported MC versions and exit\n" +" --help, -h Show this help\n\n" +"Filter functions (x,z=block coords; rx,rz=region indices):\n" +" biome(x,z) biome name -> string\n" +" biome_id(x,z) biome ID -> int\n" +" has_biome(name,x,z,r) biome within r blocks -> bool\n" +" structure(type,rx,rz) viable structure -> bool\n" +" struct_x/z(type,rx,rz) structure coordinate -> int\n" +" spawn_x() / spawn_z() world spawn coords -> int\n\n" "Examples:\n" -" %s --mc 1.21 --filter 'biome(0,0) == \"jungle\"'\n" +" %s --mc 1.21 --filter 'biome(0,0)==\"jungle\"'\n" " %s --mc 1.18 --filter 'has_biome(\"mushroom_fields\",0,0,500)' --count 5\n" -" %s --mc 1.16 --filter 'structure(\"village\",0,0) && structure(\"mansion\",1,0)'\n" -" %s --random --filter 'spawn_x() > -100 && spawn_x() < 100'\n" -" %s --from -100000 --to 100000 --filter 'seed %% 7 == 0' --count 20\n" -"\n", prog, prog, prog, prog, prog, prog); +" %s --mc 1.16 --filter 'structure(\"village\",0,0)&&structure(\"mansion\",1,0)'\n" +" %s --random --filter 'spawn_x()>-100&&spawn_x()<100'\n\n", + prog,prog,prog,prog,prog); } static void list_versions(void) { printf("Supported Minecraft versions:\n"); - for (int mc = MC_B1_7; mc <= MC_NEWEST; mc++) { - const char *v = mc2str(mc); - if (v && strcmp(v,"?")!=0) printf(" %s\n", v); + for (int mc=MC_B1_7; mc<=MC_NEWEST; mc++) { + const char *v=mc2str(mc); if(v&&strcmp(v,"?")!=0) printf(" %s\n",v); } } @@ -816,64 +675,78 @@ static void list_versions(void) { * Main * ========================================================== */ int main(int argc, char **argv) { - int mc = MC_NEWEST; - const char *filter = NULL; - uint64_t count = 10; - int64_t from_s = 0; - int64_t to_s = 0; - bool has_to = false; - int64_t step = 1; - bool random_m = false; - int dim = DIM_OVERWORLD; - uint32_t flags = 0; - bool quiet = false; - bool verbose = false; + int mc = MC_NEWEST; + const char *filter = NULL; + uint64_t count = 10; + int64_t from_s = 0; + int64_t to_s = 0; + bool has_to = false; + int64_t step = 1; + bool random_m = false; + int dim = DIM_OVERWORLD; + uint32_t flags = 0; + bool quiet = false; + bool verbose = false; + int log_level = LOG_INFO; + const char *log_file = NULL; + int prog_force = 0; /* 0=auto, 1=on, -1=off */ - for (int i = 1; i < argc; i++) { - if (!strcmp(argv[i],"--mc") && i+1 0\n"); return 1; } - } else if (!strcmp(argv[i],"--random")) { - random_m = true; - } else if (!strcmp(argv[i],"--dim") && i+10\n");return 1;} } + else if (!strcmp(argv[i],"--random")) { random_m=true; } + else if (!strcmp(argv[i],"--dim") &&i+1= 0) && (prog_force == 1 || stderr_is_tty); + g_bar.count = count; + g_bar.t_start = now_s(); + g_bar.t_speed_t = g_bar.t_start; + /* Parse filter expression */ Parser parser; Node *ast = NULL; @@ -882,53 +755,48 @@ int main(int argc, char **argv) { lex_init(&parser.lex, filter); ast = parse_expr(&parser); if (!ast || parser.err[0]) { - fprintf(stderr,"Filter parse error: %s\n", - parser.err[0] ? parser.err : "unknown"); + log_error("filter parse error: %s", parser.err[0]?parser.err:"unknown"); return 1; } if (lpeek(&parser.lex).k != TK_EOF) { - fprintf(stderr,"Filter parse error: unexpected trailing input\n"); + log_error("filter parse error: unexpected trailing input"); return 1; } + log_debug("filter parsed OK: %s", filter); } - if (!quiet) { - fprintf(stderr,"# celseed mc=%s dim=%d count=%"PRIu64" filter=%s\n", - mc2str(mc), dim, count, filter ? filter : "(none)"); - } + log_info("mc=%s dim=%d count=%"PRIu64" filter=%s", + mc2str(mc), dim, count, filter?filter:"(none)"); + if (has_to) log_debug("range: [%"PRId64", %"PRId64")", from_s, to_s); + if (random_m) log_debug("mode: random"); - /* Set up generator (once for the mc version / flags) */ + /* Set up generator */ Generator gen; setupGenerator(&gen, mc, flags); + log_debug("generator ready: mc=%s flags=0x%x", mc2str(mc), flags); - /* Initialize RNG for random mode */ - uint64_t rng = (uint64_t)time(NULL) ^ (uint64_t)(uintptr_t)&rng; - if (rng == 0) rng = 1; - rng = xorshift64(rng); + /* RNG for random mode */ + uint64_t rng = (uint64_t)now_s() ^ (uint64_t)(uintptr_t)argv; + if (!rng) rng = 0xdeadbeefcafe1234ULL; + for (int i=0; i<8; i++) rng = xorshift64(rng); - uint64_t seed = (uint64_t)from_s; - uint64_t found = 0; - uint64_t tested = 0; + uint64_t seed = (uint64_t)from_s; + uint64_t found = 0; + uint64_t tested= 0; + /* Main search loop */ while (found < count) { if (!random_m && has_to && (int64_t)seed == to_s) break; bool match = true; if (ast) { Ctx ctx; - ctx.seed = seed; - ctx.mc = mc; - ctx.dim = dim; - ctx.flags = flags; - ctx.gen = &gen; - ctx.gen_ready = false; - ctx.spawn_ready = false; - ctx.spawn.x = ctx.spawn.z = 0; - + ctx.seed=seed; ctx.mc=mc; ctx.dim=dim; ctx.flags=flags; + ctx.gen=&gen; ctx.gen_ready=false; ctx.spawn_ready=false; + ctx.spawn.x=ctx.spawn.z=0; Val r = eval_node(ast, &ctx); - if (r.type == VT_ERR) { - fprintf(stderr,"# filter error seed=%"PRId64": %s\n", - (int64_t)seed, r.s); + if (r.type==VT_ERR) { + log_warn("filter error seed=%"PRId64": %s", (int64_t)seed, r.s); match = false; } else { match = vtrue(r); @@ -937,28 +805,38 @@ int main(int argc, char **argv) { if (match) { found++; + bar_clear(); if (quiet) { printf("%"PRId64"\n", (int64_t)seed); + fflush(stdout); } else if (verbose) { printf("%-22"PRId64" [%"PRIu64"/%"PRIu64"]\n", (int64_t)seed, found, count); + fflush(stdout); } else { printf("%"PRId64"\n", (int64_t)seed); + fflush(stdout); } - fflush(stdout); + log_info("found seed=%-20"PRId64" [%"PRIu64"/%"PRIu64"]", + (int64_t)seed, found, count); + g_bar.found = found; + bar_draw(true); } tested++; - if (random_m) { - rng = xorshift64(rng); - seed = rng; - } else { - seed = (uint64_t)((int64_t)seed + step); - } + g_bar.tested = tested; + + /* refresh bar every 4096 seeds */ + if ((tested & 0xFFF) == 0) bar_draw(false); + + if (random_m) { rng=xorshift64(rng); seed=rng; } + else { seed=(uint64_t)((int64_t)seed+step); } } - if (!quiet) - fprintf(stderr,"# done tested=%"PRIu64" found=%"PRIu64"\n", tested, found); + double elapsed = now_s() - g_bar.t_start; + log_info("done tested=%"PRIu64" found=%"PRIu64" elapsed=%.2fs", tested, found, elapsed); + bar_finish(tested, found, elapsed); + if (log_fp) fclose(log_fp); return 0; } diff --git a/deps/log.c b/deps/log.c new file mode 160000 index 0000000..f9ea349 --- /dev/null +++ b/deps/log.c @@ -0,0 +1 @@ +Subproject commit f9ea34994bd58ed342d2245cd4110bb5c6790153