/* * celseed - Minecraft seed finder using cubiomes + CEL filter expressions * * Filter syntax (subset of Common Expression Language): * Literals: 42, 3.14, "text", true, false * Variable: seed * Operators: && || ! == != < <= > >= + - * / % * Functions: biome(x,z) biome_id(x,z) has_biome(name,x,z,r) * structure(type,rx,rz) struct_x(type,rx,rz) struct_z(type,rx,rz) * spawn_x() spawn_z() * * MIT License – see LICENSE */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #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" /* ============================================================ * 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; } Val; static Val vint(int64_t v) { Val r; memset(&r,0,sizeof(r)); r.type=VT_INT; r.i=v; return r; } static Val vfloat(double v) { Val r; memset(&r,0,sizeof(r)); r.type=VT_FLOAT; r.d=v; return r; } static Val vbool(bool v) { Val r; memset(&r,0,sizeof(r)); r.type=VT_BOOL; r.b=v; return r; } static Val vstr(const char *s) { Val r; memset(&r,0,sizeof(r)); r.type=VT_STR; r.s=s; return r; } static Val verr(const char *m) { Val r; memset(&r,0,sizeof(r)); r.type=VT_ERR; r.s=m; return r; } static bool vtrue(Val v) { switch (v.type) { case VT_BOOL: return v.b; case VT_INT: return v.i != 0; case VT_FLOAT: return v.d != 0.0; case VT_STR: return v.s && v.s[0]; 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.idb)-(dasrc=src; l->pos=0; l->peeked=false; l->err[0]='\0'; } static Tok lex_read(Lex *l) { 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(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 ((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(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; } /* ============================================================ * 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, } 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; }; 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; } static Node *parse_expr(Parser *p); static Node *parse_or(Parser *p); static Node *parse_and(Parser *p); static Node *parse_eq(Parser *p); static Node *parse_cmp(Parser *p); static Node *parse_add(Parser *p); static Node *parse_mul(Parser *p); 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;} 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;} 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;} 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;} 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;} 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;} 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);} 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; 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");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; } Ctx; static void ensure_gen(Ctx *c) { if(!c->gen_ready){applySeed(c->gen,c->dim,c->seed);c->gen_ready=true;} } static Val eval_node(const Node *n, Ctx *ctx); 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");} 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); 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-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},{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"); ensure_gen(ctx); 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;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); 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){ case ND_INT: return vint(n->ival); case ND_FLOAT: return vfloat(n->dval); case ND_STR: return vstr(n->name); 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); { 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_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("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"); } } /* ============================================================ * 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; } /* ============================================================ * Usage * ========================================================== */ static void usage(const char *prog) { printf( "Usage: %s [OPTIONS]\n\n" "Options:\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" " --output FILE, -o Write matched seeds to FILE (one per line)\n" " --append Append to output file instead of overwriting\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.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\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); } } /* ============================================================ * 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 log_level = LOG_INFO; const char *log_file = NULL; const char *out_file = NULL; bool out_append = false; int prog_force = 0; /* 0=auto, 1=on, -1=off */ for (int i=1; i0\n");return 1;} } else if (!strcmp(argv[i],"--random")) { random_m=true; } else if (!strcmp(argv[i],"--dim") &&i+1=argc) { fprintf(stderr,"--output requires a filename\n"); return 1; } out_file=argv[++i]; } else if (!strcmp(argv[i],"--append")) { out_append=true; } else if (!strcmp(argv[i],"--no-progress")) { prog_force=-1; } else if (!strcmp(argv[i],"--progress")) { prog_force=1; } else if (!strcmp(argv[i],"--list-versions")) { list_versions(); return 0; } else if (!strcmp(argv[i],"--help")||!strcmp(argv[i],"-h")) { usage(argv[0]); return 0; } else { fprintf(stderr,"Unknown option '%s'. Use --help.\n",argv[i]); return 1; } } /* Set up logging */ log_set_quiet(true); log_set_level(log_level); bool stderr_is_tty = isatty(STDERR_FILENO); log_add_callback(log_stderr_cb, stderr, log_level); FILE *log_fp = NULL; if (log_file) { log_fp = fopen(log_file, "a"); if (!log_fp) { perror(log_file); return 1; } log_add_callback(log_file_cb, log_fp, LOG_TRACE); } FILE *out_fp = NULL; if (out_file) { out_fp = fopen(out_file, out_append ? "a" : "w"); if (!out_fp) { perror(out_file); return 1; } log_debug("output file: %s (%s)", out_file, out_append ? "append" : "overwrite"); } /* Set up progress bar */ g_bar.is_tty = (prog_force == 1) || (prog_force == 0 && stderr_is_tty); g_bar.enabled = (prog_force >= 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; if (filter) { memset(&parser, 0, sizeof(parser)); lex_init(&parser.lex, filter); ast = parse_expr(&parser); if (!ast || parser.err[0]) { log_error("filter parse error: %s", parser.err[0]?parser.err:"unknown"); return 1; } if (lpeek(&parser.lex).k != TK_EOF) { log_error("filter parse error: unexpected trailing input"); return 1; } log_debug("filter parsed OK: %s", filter); } 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 */ Generator gen; setupGenerator(&gen, mc, flags); log_debug("generator ready: mc=%s flags=0x%x", mc2str(mc), flags); /* 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; /* 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; Val r = eval_node(ast, &ctx); if (r.type==VT_ERR) { log_warn("filter error seed=%"PRId64": %s", (int64_t)seed, r.s); match = false; } else { match = vtrue(r); } } 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); } if (out_fp) { fprintf(out_fp, "%"PRId64"\n", (int64_t)seed); fflush(out_fp); } log_info("found seed=%-20"PRId64" [%"PRIu64"/%"PRIu64"]", (int64_t)seed, found, count); g_bar.found = found; bar_draw(true); } tested++; 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); } } 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 (out_fp) { fclose(out_fp); log_info("seeds written to %s", out_file); } if (log_fp) fclose(log_fp); return 0; }