From 0a1172b75f571685c264a8b9d8ee224bbf11381f Mon Sep 17 00:00:00 2001 From: xolatile Date: Wed, 6 Aug 2025 22:54:55 +0200 Subject: Please do not hate me, it makes sense... --- src/shared/command.h | 128 +++---- src/shared/crypto.cpp | 383 ++++++--------------- src/shared/cube2font.c | 192 +++++------ src/shared/ents.h | 76 ++--- src/shared/geom.cpp | 43 +-- src/shared/geom.h | 884 ++++++++++++++----------------------------------- src/shared/glemu.cpp | 173 +++------- src/shared/glemu.h | 54 +-- src/shared/iengine.h | 79 ++--- src/shared/igame.h | 14 +- src/shared/stream.cpp | 489 ++++++++------------------- src/shared/tools.cpp | 90 ++--- src/shared/tools.h | 565 +++++++++---------------------- src/shared/zip.cpp | 241 ++++---------- 14 files changed, 994 insertions(+), 2417 deletions(-) (limited to 'src/shared') diff --git a/src/shared/command.h b/src/shared/command.h index ffb2115..1c6a95c 100644 --- a/src/shared/command.h +++ b/src/shared/command.h @@ -2,8 +2,7 @@ enum { VAL_NULL = 0, VAL_INT, VAL_FLOAT, VAL_STR, VAL_ANY, VAL_CODE, VAL_MACRO, VAL_IDENT }; -enum -{ +enum { CODE_START = 0, CODE_OFFSET, CODE_POP, @@ -26,11 +25,9 @@ enum CODE_LOOKUP, CODE_LOOKUPU, CODE_LOOKUPARG, CODE_ALIAS, CODE_ALIASU, CODE_ALIASARG, CODE_CALL, CODE_CALLU, CODE_CALLARG, CODE_PRINT, CODE_LOCAL, - CODE_OP_MASK = 0x3F, CODE_RET = 6, CODE_RET_MASK = 0xC0, - /* return type flags */ RET_NULL = VAL_NULL< x ? IDF_READONLY : 0)), name(n), minval(m), maxval(x), fun((identfun)f) - { storage.i = s; } + : type(t), flags(flags | (m > x ? IDF_READONLY : 0)), name(n), minval(m), maxval(x), fun((identfun)f) { + storage.i = s; } // ID_FVAR ident(int t, const char *n, float m, float x, float *s, void *f = NULL, int flags = 0) - : type(t), flags(flags | (m > x ? IDF_READONLY : 0)), name(n), minvalf(m), maxvalf(x), fun((identfun)f) - { storage.f = s; } + : type(t), flags(flags | (m > x ? IDF_READONLY : 0)), name(n), minvalf(m), maxvalf(x), fun((identfun)f) { + storage.f = s; } // ID_SVAR ident(int t, const char *n, char **s, void *f = NULL, int flags = 0) - : type(t), flags(flags), name(n), fun((identfun)f) - { storage.s = s; } + : type(t), flags(flags), name(n), fun((identfun)f) { + storage.s = s; } // ID_ALIAS ident(int t, const char *n, char *a, int flags) - : type(t), valtype(VAL_STR), flags(flags), name(n), code(NULL), stack(NULL) - { val.s = a; } + : type(t), valtype(VAL_STR), flags(flags), name(n), code(NULL), stack(NULL) { + val.s = a; } ident(int t, const char *n, int a, int flags) - : type(t), valtype(VAL_INT), flags(flags), name(n), code(NULL), stack(NULL) - { val.i = a; } + : type(t), valtype(VAL_INT), flags(flags), name(n), code(NULL), stack(NULL) { + val.i = a; } ident(int t, const char *n, float a, int flags) - : type(t), valtype(VAL_FLOAT), flags(flags), name(n), code(NULL), stack(NULL) - { val.f = a; } + : type(t), valtype(VAL_FLOAT), flags(flags), name(n), code(NULL), stack(NULL) { + val.f = a; } ident(int t, const char *n, int flags) - : type(t), valtype(VAL_NULL), flags(flags), name(n), code(NULL), stack(NULL) - {} + : type(t), valtype(VAL_NULL), flags(flags), name(n), code(NULL), stack(NULL) { + } ident(int t, const char *n, const tagval &v, int flags) - : type(t), valtype(v.type), flags(flags), name(n), code(NULL), stack(NULL) - { val = v; } + : type(t), valtype(v.type), flags(flags), name(n), code(NULL), stack(NULL) { + val = v; } // ID_COMMAND ident(int t, const char *n, const char *args, uint argmask, int numargs, void *f = NULL, int flags = 0) - : type(t), numargs(numargs), flags(flags), name(n), args(args), argmask(argmask), fun((identfun)f) - {} - + : type(t), numargs(numargs), flags(flags), name(n), args(args), argmask(argmask), fun((identfun)f) { + } void changed() { if(fun) fun(); } - - void setval(const tagval &v) - { + void setval(const tagval &v) { valtype = v.type; val = v; } - - void setval(const identstack &v) - { + void setval(const identstack &v) { valtype = v.valtype; val = v.val; } - - void forcenull() - { + void forcenull() { if(valtype==VAL_STR) delete[] val.s; valtype = VAL_NULL; } - float getfloat() const; int getint() const; const char *getstr() const; @@ -200,13 +173,11 @@ extern void stringret(char *s); extern void result(tagval &v); extern void result(const char *s); -static inline int parseint(const char *s) -{ +static inline int parseint(const char *s) { return int(strtoul(s, NULL, 0)); } -static inline float parsefloat(const char *s) -{ +static inline float parsefloat(const char *s) { // not all platforms (windows) can parse hexadecimal integers via strtod char *end; double val = strtod(s, &end); @@ -216,10 +187,8 @@ static inline float parsefloat(const char *s) static inline void intformat(char *buf, int v, int len = 20) { nformatstring(buf, len, "%d", v); } static inline void floatformat(char *buf, float v, int len = 20) { nformatstring(buf, len, v==int(v) ? "%.1f" : "%.6g", v); } -static inline const char *getstr(const identval &v, int type) -{ - switch(type) - { +static inline const char *getstr(const identval &v, int type) { + switch(type) { case VAL_STR: case VAL_MACRO: return v.s; case VAL_INT: return intstr(v.i); case VAL_FLOAT: return floatstr(v.f); @@ -229,10 +198,8 @@ static inline const char *getstr(const identval &v, int type) inline const char *tagval::getstr() const { return ::getstr(*this, type); } inline const char *ident::getstr() const { return ::getstr(val, valtype); } -static inline int getint(const identval &v, int type) -{ - switch(type) - { +static inline int getint(const identval &v, int type) { + switch(type) { case VAL_INT: return v.i; case VAL_FLOAT: return int(v.f); case VAL_STR: case VAL_MACRO: return parseint(v.s); @@ -242,10 +209,8 @@ static inline int getint(const identval &v, int type) inline int tagval::getint() const { return ::getint(*this, type); } inline int ident::getint() const { return ::getint(val, valtype); } -static inline float getfloat(const identval &v, int type) -{ - switch(type) - { +static inline float getfloat(const identval &v, int type) { + switch(type) { case VAL_FLOAT: return v.f; case VAL_INT: return float(v.i); case VAL_STR: case VAL_MACRO: return parsefloat(v.s); @@ -255,10 +220,8 @@ static inline float getfloat(const identval &v, int type) inline float tagval::getfloat() const { return ::getfloat(*this, type); } inline float ident::getfloat() const { return ::getfloat(val, valtype); } -inline void ident::getval(tagval &v) const -{ - switch(valtype) - { +inline void ident::getval(tagval &v) const { + switch(valtype) { case VAL_STR: case VAL_MACRO: v.setstr(newstring(val.s)); break; case VAL_INT: v.setint(val.i); break; case VAL_FLOAT: v.setfloat(val.f); break; @@ -325,8 +288,7 @@ inline void ident::getval(tagval &v) const #define SVARFR(name, cur, body) _SVARF(name, name, cur, body, IDF_OVERRIDE) // anonymous inline commands, uses nasty template trick with line numbers to keep names unique -#define ICOMMANDNS(name, cmdname, nargs, proto, b) template struct cmdname; template<> struct cmdname<__LINE__> { static bool init; static void run proto; }; bool cmdname<__LINE__>::init = addcommand(name, (identfun)cmdname<__LINE__>::run, nargs); void cmdname<__LINE__>::run proto \ - { b; } +#define ICOMMANDNS(name, cmdname, nargs, proto, b) template struct cmdname; template<> struct cmdname<__LINE__> { static bool init; static void run proto; }; bool cmdname<__LINE__>::init = addcommand(name, (identfun)cmdname<__LINE__>::run, nargs); void cmdname<__LINE__>::run proto { b; } #define ICOMMANDN(name, cmdname, nargs, proto, b) ICOMMANDNS(#name, cmdname, nargs, proto, b) #define ICOMMANDNAME(name) _icmd_##name #define ICOMMAND(name, nargs, proto, b) ICOMMANDN(name, ICOMMANDNAME(name), nargs, proto, b) diff --git a/src/shared/crypto.cpp b/src/shared/crypto.cpp index fd0a950..3b56904 100644 --- a/src/shared/crypto.cpp +++ b/src/shared/crypto.cpp @@ -9,39 +9,27 @@ #define TIGER_PASSES 3 -namespace tiger -{ +namespace tiger { typedef unsigned long long int chunk; - - union hashval - { + union hashval { uchar bytes[3*8]; chunk chunks[3]; }; - chunk sboxes[4*256]; - - void compress(const chunk *str, chunk state[3]) - { + void compress(const chunk *str, chunk state[3]) { chunk a, b, c; chunk aa, bb, cc; chunk x0, x1, x2, x3, x4, x5, x6, x7; - a = state[0]; b = state[1]; c = state[2]; - x0=str[0]; x1=str[1]; x2=str[2]; x3=str[3]; x4=str[4]; x5=str[5]; x6=str[6]; x7=str[7]; - aa = a; bb = b; cc = c; - - loop(pass_no, TIGER_PASSES) - { - if(pass_no) - { + loop(pass_no, TIGER_PASSES) { + if(pass_no) { x0 -= x7 ^ 0xA5A5A5A5A5A5A5A5ULL; x1 ^= x0; x2 += x1; x3 -= x2 ^ ((~x1)<<19); x4 ^= x3; x5 += x4; x6 -= x5 ^ ((~x4)>>23); x7 ^= x6; x0 += x7; x1 -= x0 ^ ((~x7)<<19); x2 ^= x1; x3 += x2; @@ -60,85 +48,63 @@ namespace tiger b += sb4[((c)>>(1*8))&0xFF] ^ sb3[((c)>>(3*8))&0xFF] ^ \ sb2[((c)>>(5*8))&0xFF] ^ sb1[((c)>>(7*8))&0xFF] ; \ b *= mul; - uint mul = !pass_no ? 5 : (pass_no==1 ? 7 : 9); round(a, b, c, x0) round(b, c, a, x1) round(c, a, b, x2) round(a, b, c, x3) round(b, c, a, x4) round(c, a, b, x5) round(a, b, c, x6) round(b, c, a, x7) - chunk tmp = a; a = c; c = b; b = tmp; } - a ^= aa; b -= bb; c += cc; - state[0] = a; state[1] = b; state[2] = c; } - - void gensboxes() - { + void gensboxes() { const char *str = "Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham"; chunk state[3] = { 0x0123456789ABCDEFULL, 0xFEDCBA9876543210ULL, 0xF096A5B4C3B2E187ULL }; uchar temp[64]; - if(!*(const uchar *)&islittleendian) loopj(64) temp[j^7] = str[j]; else loopj(64) temp[j] = str[j]; loopi(1024) loop(col, 8) ((uchar *)&sboxes[i])[col] = i&0xFF; - int abc = 2; - loop(pass, 5) loopi(256) for(int sb = 0; sb < 1024; sb += 256) - { + loop(pass, 5) loopi(256) for(int sb = 0; sb < 1024; sb += 256) { abc++; if(abc >= 3) { abc = 0; compress((chunk *)temp, state); } - loop(col, 8) - { + loop(col, 8) { uchar val = ((uchar *)&sboxes[sb+i])[col]; ((uchar *)&sboxes[sb+i])[col] = ((uchar *)&sboxes[sb + ((uchar *)&state[abc])[col]])[col]; ((uchar *)&sboxes[sb + ((uchar *)&state[abc])[col]])[col] = val; } } } - - void hash(const uchar *str, int length, hashval &val) - { + void hash(const uchar *str, int length, hashval &val) { static bool init = false; if(!init) { gensboxes(); init = true; } - uchar temp[65]; - val.chunks[0] = 0x0123456789ABCDEFULL; val.chunks[1] = 0xFEDCBA9876543210ULL; val.chunks[2] = 0xF096A5B4C3B2E187ULL; - int i = length; - for(; i >= 64; i -= 64, str += 64) - { - if(!*(const uchar *)&islittleendian) - { + for(; i >= 64; i -= 64, str += 64) { + if(!*(const uchar *)&islittleendian) { loopj(64) temp[j^7] = str[j]; compress((chunk *)temp, val.chunks); } else compress((chunk *)str, val.chunks); } - int j; - if(!*(const uchar *)&islittleendian) - { + if(!*(const uchar *)&islittleendian) { for(j = 0; j < i; j++) temp[j^7] = str[j]; temp[j^7] = 0x01; while(++j&7) temp[j^7] = 0; } - else - { + else { for(j = 0; j < i; j++) temp[j] = str[j]; temp[j] = 0x01; while(++j&7) temp[j] = 0; } - - if(j > 56) - { + if(j > 56) { while(j < 64) temp[j++] = 0; compress((chunk *)temp, val.chunks); j = 0; @@ -146,10 +112,8 @@ namespace tiger while(j < 56) temp[j++] = 0; *(chunk *)(temp+56) = (chunk)length<<3; compress((chunk *)temp, val.chunks); - if(!*(const uchar *)&islittleendian) - { - loopk(3) - { + if(!*(const uchar *)&islittleendian) { + loopk(3) { uchar *c = &val.bytes[k*sizeof(chunk)]; loopl(sizeof(chunk)/2) swap(c[l], c[sizeof(chunk)-1-l]); } @@ -162,28 +126,22 @@ namespace tiger #define BI_DIGIT_BITS 16 #define BI_DIGIT_MASK ((1< struct bigint -{ +template struct bigint { typedef ushort digit; typedef uint dbldigit; - int len; digit digits[BI_DIGITS]; - bigint() {} bigint(digit n) { if(n) { len = 1; digits[0] = n; } else len = 0; } bigint(const char *s) { parse(s); } template bigint(const bigint &y) { *this = y; } - - static int parsedigits(ushort *digits, int maxlen, const char *s) - { + static int parsedigits(ushort *digits, int maxlen, const char *s) { int slen = 0; while(isxdigit(s[slen])) slen++; int len = (slen+2*sizeof(ushort)-1)/(2*sizeof(ushort)); if(len>maxlen) return 0; memset(digits, 0, len*sizeof(ushort)); - loopi(slen) - { + loopi(slen) { int c = s[slen-i-1]; if(isalpha(c)) c = toupper(c) - 'A' + 10; else if(isdigit(c)) c -= '0'; @@ -192,29 +150,20 @@ template struct bigint } return len; } - - void parse(const char *s) - { + void parse(const char *s) { len = parsedigits(digits, BI_DIGITS, s); shrink(); } - void zero() { len = 0; } - - void print(stream *out) const - { + void print(stream *out) const { vector buf; printdigits(buf); out->write(buf.getbuf(), buf.length()); } - - void printdigits(vector &buf) const - { - loopi(len) - { + void printdigits(vector &buf) const { + loopi(len) { digit d = digits[len-i-1]; - loopj(BI_DIGIT_BITS/4) - { + loopj(BI_DIGIT_BITS/4) { uint shift = BI_DIGIT_BITS - (j+1)*4; int val = (d >> shift) & 0xF; if(val < 10) buf.add('0' + val); @@ -222,41 +171,30 @@ template struct bigint } } } - - template bigint &operator=(const bigint &y) - { + template bigint &operator=(const bigint &y) { len = y.len; memcpy(digits, y.digits, len*sizeof(digit)); return *this; } - bool iszero() const { return !len; } bool isone() const { return len==1 && digits[0]==1; } - - int numbits() const - { + int numbits() const { if(!len) return 0; int bits = len*BI_DIGIT_BITS; digit last = digits[len-1], mask = 1<<(BI_DIGIT_BITS-1); - while(mask) - { + while(mask) { if(last&mask) return bits; bits--; mask >>= 1; } return 0; } - bool hasbit(int n) const { return n/BI_DIGIT_BITS < len && ((digits[n/BI_DIGIT_BITS]>>(n%BI_DIGIT_BITS))&1); } - bool morebits(int n) const { return len > n/BI_DIGIT_BITS; } - - template bigint &add(const bigint &x, const bigint &y) - { + template bigint &add(const bigint &x, const bigint &y) { dbldigit carry = 0; int maxlen = max(x.len, y.len), i; - for(i = 0; i < y.len || carry; i++) - { + for(i = 0; i < y.len || carry; i++) { carry += (i < x.len ? (dbldigit)x.digits[i] : 0) + (i < y.len ? (dbldigit)y.digits[i] : 0); digits[i] = (digit)carry; carry >>= BI_DIGIT_BITS; @@ -266,14 +204,11 @@ template struct bigint return *this; } template bigint &add(const bigint &y) { return add(*this, y); } - - template bigint &sub(const bigint &x, const bigint &y) - { + template bigint &sub(const bigint &x, const bigint &y) { ASSERT(x >= y); dbldigit borrow = 0; int i; - for(i = 0; i < y.len || borrow; i++) - { + for(i = 0; i < y.len || borrow; i++) { borrow = (1<>BI_DIGIT_BITS)^1; @@ -284,31 +219,23 @@ template struct bigint return *this; } template bigint &sub(const bigint &y) { return sub(*this, y); } - void shrink() { while(len > 0 && !digits[len-1]) len--; } void shrinkdigits(int n) { len = n; shrink(); } void shrinkbits(int n) { shrinkdigits(n/BI_DIGIT_BITS); } - - template void copyshrinkdigits(const bigint &y, int n) - { + template void copyshrinkdigits(const bigint &y, int n) { len = clamp(y.len, 0, n); memcpy(digits, y.digits, len*sizeof(digit)); shrink(); } - template void copyshrinkbits(const bigint &y, int n) - { + template void copyshrinkbits(const bigint &y, int n) { copyshrinkdigits(y, n/BI_DIGIT_BITS); } - - template bigint &mul(const bigint &x, const bigint &y) - { + template bigint &mul(const bigint &x, const bigint &y) { if(!x.len || !y.len) { len = 0; return *this; } memset(digits, 0, y.len*sizeof(digit)); - loopi(x.len) - { + loopi(x.len) { dbldigit carry = 0; - loopj(y.len) - { + loopj(y.len) { carry += (dbldigit)x.digits[i] * (dbldigit)y.digits[j] + (dbldigit)digits[i+j]; digits[i+j] = (digit)carry; carry >>= BI_DIGIT_BITS; @@ -319,17 +246,14 @@ template struct bigint shrink(); return *this; } - - bigint &rshift(int n) - { + bigint &rshift(int n) { assert(len <= BI_DIGITS); if(!len || n<=0) return *this; if(n >= len*BI_DIGIT_BITS) { len = 0; return *this; } int dig = (n-1)/BI_DIGIT_BITS; n = ((n-1) % BI_DIGIT_BITS)+1; digit carry = digit(digits[dig]>>n); - for(int i = dig+1; i < len; i++) - { + for(int i = dig+1; i < len; i++) { digit tmp = digits[i]; digits[i-dig-1] = digit((tmp<<(BI_DIGIT_BITS-n)) | carry); carry = digit(tmp>>n); @@ -339,15 +263,12 @@ template struct bigint shrink(); return *this; } - - bigint &lshift(int n) - { + bigint &lshift(int n) { if(!len || n<=0) return *this; int dig = n/BI_DIGIT_BITS; n %= BI_DIGIT_BITS; digit carry = 0; - loopirev(len) - { + loopirev(len) { digit tmp = digits[i]; digits[i+dig] = digit((tmp<>(BI_DIGIT_BITS-n)); @@ -357,49 +278,36 @@ template struct bigint if(dig) memset(digits, 0, dig*sizeof(digit)); return *this; } - - void zerodigits(int i, int n) - { + void zerodigits(int i, int n) { memset(&digits[i], 0, n*sizeof(digit)); } - void zerobits(int i, int n) - { + void zerobits(int i, int n) { zerodigits(i/BI_DIGIT_BITS, n/BI_DIGIT_BITS); } - - template void copydigits(int to, const bigint &y, int from, int n) - { + template void copydigits(int to, const bigint &y, int from, int n) { int avail = clamp(y.len-from, 0, n); memcpy(&digits[to], &y.digits[from], avail*sizeof(digit)); if(avail < n) memset(&digits[to+avail], 0, (n-avail)*sizeof(digit)); } - template void copybits(int to, const bigint &y, int from, int n) - { + template void copybits(int to, const bigint &y, int from, int n) { copydigits(to/BI_DIGIT_BITS, y, from/BI_DIGIT_BITS, n/BI_DIGIT_BITS); } - - void dupdigits(int to, int from, int n) - { + void dupdigits(int to, int from, int n) { memcpy(&digits[to], &digits[from], n*sizeof(digit)); } - void dupbits(int to, int from, int n) - { + void dupbits(int to, int from, int n) { dupdigits(to/BI_DIGIT_BITS, from/BI_DIGIT_BITS, n/BI_DIGIT_BITS); } - - template bool operator==(const bigint &y) const - { + template bool operator==(const bigint &y) const { if(len!=y.len) return false; loopirev(len) if(digits[i]!=y.digits[i]) return false; return true; } template bool operator!=(const bigint &y) const { return !(*this==y); } - template bool operator<(const bigint &y) const - { + template bool operator<(const bigint &y) const { if(leny.len) return false; - loopirev(len) - { + loopirev(len) { if(digits[i]y.digits[i]) return false; } @@ -418,44 +326,31 @@ typedef bigint gfint; /* NIST prime Galois fields. * Currently only supports NIST P-192, where P=2^192-2^64-1, and P-256, where P=2^256-2^224+2^192+2^96-1. */ -struct gfield : gfint -{ +struct gfield : gfint { static const gfield P; - gfield() {} gfield(digit n) : gfint(n) {} gfield(const char *s) : gfint(s) {} - template gfield(const bigint &y) : gfint(y) {} - - template gfield &operator=(const bigint &y) - { + template gfield &operator=(const bigint &y) { gfint::operator=(y); return *this; } - - template gfield &add(const bigint &x, const bigint &y) - { + template gfield &add(const bigint &x, const bigint &y) { gfint::add(x, y); if(*this >= P) gfint::sub(*this, P); return *this; } template gfield &add(const bigint &y) { return add(*this, y); } - template gfield &mul2(const bigint &x) { return add(x, x); } gfield &mul2() { return mul2(*this); } - - gfield &div2() - { + gfield &div2() { if(hasbit(0)) gfint::add(*this, P); rshift(1); return *this; } - - template gfield &sub(const bigint &x, const bigint &y) - { - if(x < y) - { + template gfield &sub(const bigint &x, const bigint &y) { + if(x < y) { gfint tmp; /* necessary if this==&y, using this instead would clobber y */ tmp.add(x, P); gfint::sub(tmp, y); @@ -464,50 +359,37 @@ struct gfield : gfint return *this; } template gfield &sub(const bigint &y) { return sub(*this, y); } - - template gfield &neg(const bigint &x) - { + template gfield &neg(const bigint &x) { gfint::sub(P, x); return *this; } gfield &neg() { return neg(*this); } - template gfield &square(const bigint &x) { return mul(x, x); } gfield &square() { return square(*this); } - - template gfield &mul(const bigint &x, const bigint &y) - { + template gfield &mul(const bigint &x, const bigint &y) { bigint result; result.mul(x, y); reduce(result); return *this; } template gfield &mul(const bigint &y) { return mul(*this, y); } - - template void reduce(const bigint &result) - { + template void reduce(const bigint &result) { #if GF_BITS==192 // B = T + S1 + S2 + S3 mod p copyshrinkdigits(result, GF_DIGITS); // T - - if(result.morebits(192)) - { + if(result.morebits(192)) { gfield s; s.copybits(0, result, 192, 64); s.dupbits(64, 0, 64); s.shrinkbits(128); add(s); // S1 - - if(result.morebits(256)) - { + if(result.morebits(256)) { s.zerobits(0, 64); s.copybits(64, result, 256, 64); s.dupbits(128, 64, 64); s.shrinkdigits(GF_DIGITS); add(s); // S2 - - if(result.morebits(320)) - { + if(result.morebits(320)) { s.copybits(0, result, 320, 64); s.dupbits(64, 0, 64); s.dupbits(128, 0, 64); @@ -520,60 +402,49 @@ struct gfield : gfint #elif GF_BITS==256 // B = T + 2*S1 + 2*S2 + S3 + S4 - D1 - D2 - D3 - D4 mod p copyshrinkdigits(result, GF_DIGITS); // T - - if(result.morebits(256)) - { + if(result.morebits(256)) { gfield s; - if(result.morebits(352)) - { + if(result.morebits(352)) { s.zerobits(0, 96); s.copybits(96, result, 352, 160); s.shrinkdigits(GF_DIGITS); add(s); add(s); // S1 - - if(result.morebits(384)) - { + if(result.morebits(384)) { //s.zerobits(0, 96); s.copybits(96, result, 384, 128); s.shrinkbits(224); add(s); add(s); // S2 } } - s.copybits(0, result, 256, 96); s.zerobits(96, 96); s.copybits(192, result, 448, 64); s.shrinkdigits(GF_DIGITS); add(s); // S3 - s.copybits(0, result, 288, 96); s.copybits(96, result, 416, 96); s.dupbits(192, 96, 32); s.copybits(224, result, 256, 32); s.shrinkdigits(GF_DIGITS); add(s); // S4 - s.copybits(0, result, 352, 96); s.zerobits(96, 96); s.copybits(192, result, 256, 32); s.copybits(224, result, 320, 32); s.shrinkdigits(GF_DIGITS); sub(s); // D1 - s.copybits(0, result, 384, 128); //s.zerobits(128, 64); s.copybits(192, result, 288, 32); s.copybits(224, result, 352, 32); s.shrinkdigits(GF_DIGITS); sub(s); // D2 - s.copybits(0, result, 416, 96); s.copybits(96, result, 256, 96); s.zerobits(192, 32); s.copybits(224, result, 384, 32); s.shrinkdigits(GF_DIGITS); sub(s); // D3 - s.copybits(0, result, 448, 64); s.zerobits(64, 32); s.copybits(96, result, 288, 96); @@ -587,38 +458,29 @@ struct gfield : gfint #error Unsupported GF #endif } - - template gfield &pow(const bigint &x, const bigint &y) - { + template gfield &pow(const bigint &x, const bigint &y) { gfield a(x); if(y.hasbit(0)) *this = a; - else - { + else { len = 1; digits[0] = 1; if(!y.len) return *this; } - for(int i = 1, j = y.numbits(); i < j; i++) - { + for(int i = 1, j = y.numbits(); i < j; i++) { a.square(); if(y.hasbit(i)) mul(a); } return *this; } template gfield &pow(const bigint &y) { return pow(*this, y); } - - bool invert(const gfield &x) - { + bool invert(const gfield &x) { if(!x.len) return false; gfint u(x), v(P), A((gfint::digit)1), C((gfint::digit)0); - while(!u.iszero()) - { + while(!u.iszero()) { int ushift = 0, ashift = 0; - while(!u.hasbit(ushift)) - { + while(!u.hasbit(ushift)) { ushift++; - if(A.hasbit(ashift)) - { + if(A.hasbit(ashift)) { if(ashift) { A.rshift(ashift); ashift = 0; } A.add(P); } @@ -627,11 +489,9 @@ struct gfield : gfint if(ushift) u.rshift(ushift); if(ashift) A.rshift(ashift); int vshift = 0, cshift = 0; - while(!v.hasbit(vshift)) - { + while(!v.hasbit(vshift)) { vshift++; - if(C.hasbit(cshift)) - { + if(C.hasbit(cshift)) { if(cshift) { C.rshift(cshift); cshift = 0; } C.add(P); } @@ -639,14 +499,12 @@ struct gfield : gfint } if(vshift) v.rshift(vshift); if(cshift) C.rshift(cshift); - if(u >= v) - { + if(u >= v) { u.sub(v); if(A < C) A.add(P); A.sub(C); } - else - { + else { v.sub(v, u); if(C < A) C.add(P); C.sub(A); @@ -658,9 +516,7 @@ struct gfield : gfint return true; } void invert() { invert(*this); } - - template static int legendre(const bigint &x) - { + template static int legendre(const bigint &x) { static const gfint Psub1div2(gfint(P).sub(bigint<1>(1)).rshift(1)); gfield L; L.pow(x, Psub1div2); @@ -669,17 +525,14 @@ struct gfield : gfint return -1; } int legendre() const { return legendre(*this); } - - bool sqrt(const gfield &x) - { + bool sqrt(const gfield &x) { if(!x.len) { len = 0; return true; } #if GF_BITS==224 #error Unsupported GF #else ASSERT((P.digits[0]%4)==3); static const gfint Padd1div4(gfint(P).add(bigint<1>(1)).rshift(2)); - switch(legendre(x)) - { + switch(legendre(x)) { case 0: len = 0; return true; case -1: return false; default: pow(x, Padd1div4); return true; @@ -689,20 +542,15 @@ struct gfield : gfint bool sqrt() { return sqrt(*this); } }; -struct ecjacobian -{ +struct ecjacobian { static const gfield B; static const ecjacobian base; static const ecjacobian origin; - gfield x, y, z; - ecjacobian() {} ecjacobian(const gfield &x, const gfield &y) : x(x), y(y), z(bigint<1>(1)) {} ecjacobian(const gfield &x, const gfield &y, const gfield &z) : x(x), y(y), z(z) {} - - void mul2() - { + void mul2() { if(z.iszero()) return; else if(y.iszero()) { *this = origin; return; } gfield a, b, c, d; @@ -717,24 +565,20 @@ struct ecjacobian a.square(b).add(a); y.sub(d, x).mul(c).sub(a); } - - void add(const ecjacobian &q) - { + void add(const ecjacobian &q) { if(q.z.iszero()) return; else if(z.iszero()) { *this = q; return; } gfield a, b, c, d, e, f; a.square(z); b.mul(q.y, a).mul(z); a.mul(q.x); - if(q.z.isone()) - { + if(q.z.isone()) { c.add(x, a); d.add(y, b); a.sub(x, a); b.sub(y, b); } - else - { + else { f.mul(y, e.square(q.z)).mul(q.z); e.mul(x); c.add(e, a); @@ -748,20 +592,15 @@ struct ecjacobian x.square(b).sub(f.mul(c, e.square(a))); y.sub(f, x).sub(x).mul(b).sub(e.mul(a).mul(d)).div2(); } - - template void mul(const ecjacobian &p, const bigint &q) - { + template void mul(const ecjacobian &p, const bigint &q) { *this = origin; - loopirev(q.numbits()) - { + loopirev(q.numbits()) { mul2(); if(q.hasbit(i)) add(p); } } template void mul(const bigint &q) { ecjacobian tmp(*this); mul(tmp, q); } - - void normalize() - { + void normalize() { if(z.iszero() || z.isone()) return; gfield tmp; z.invert(); @@ -770,25 +609,19 @@ struct ecjacobian y.mul(tmp).mul(z); z = bigint<1>(1); } - - bool calcy(bool ybit) - { + bool calcy(bool ybit) { gfield y2, tmp; y2.square(x).mul(x).sub(tmp.add(x, x).add(x)).add(B); if(!y.sqrt(y2)) { y.zero(); return false; } if(y.hasbit(0) != ybit) y.neg(); return true; } - - void print(vector &buf) - { + void print(vector &buf) { normalize(); buf.add(y.hasbit(0) ? '-' : '+'); x.printdigits(buf); } - - void parse(const char *s) - { + void parse(const char *s) { bool ybit = *s++ == '-'; x.parse(s); calcy(ybit); @@ -837,8 +670,7 @@ const ecjacobian ecjacobian::base( #error Unsupported GF #endif -void calcpubkey(gfint privkey, vector &pubstr) -{ +void calcpubkey(gfint privkey, vector &pubstr) { ecjacobian c(ecjacobian::base); c.mul(privkey); c.normalize(); @@ -846,8 +678,7 @@ void calcpubkey(gfint privkey, vector &pubstr) pubstr.add('\0'); } -bool calcpubkey(const char *privstr, vector &pubstr) -{ +bool calcpubkey(const char *privstr, vector &pubstr) { if(!privstr[0]) return false; gfint privkey; privkey.parse(privstr); @@ -855,8 +686,7 @@ bool calcpubkey(const char *privstr, vector &pubstr) return true; } -void genprivkey(const char *seed, vector &privstr, vector &pubstr) -{ +void genprivkey(const char *seed, vector &privstr, vector &pubstr) { tiger::hashval hash; tiger::hash((const uchar *)seed, (int)strlen(seed), hash); bigint<8*sizeof(hash.bytes)/BI_DIGIT_BITS> privkey; @@ -865,17 +695,14 @@ void genprivkey(const char *seed, vector &privstr, vector &pubstr) privkey.shrink(); privkey.printdigits(privstr); privstr.add('\0'); - calcpubkey(privkey, pubstr); } -bool hashstring(const char *str, char *result, int maxlen) -{ +bool hashstring(const char *str, char *result, int maxlen) { tiger::hashval hv; if(maxlen < 2*(int)sizeof(hv.bytes) + 1) return false; tiger::hash((uchar *)str, strlen(str), hv); - loopi(sizeof(hv.bytes)) - { + loopi(sizeof(hv.bytes)) { uchar c = hv.bytes[i]; *result++ = "0123456789abcdef"[c&0xF]; *result++ = "0123456789abcdef"[c>>4]; @@ -884,8 +711,7 @@ bool hashstring(const char *str, char *result, int maxlen) return true; } -void answerchallenge(const char *privstr, const char *challenge, vector &answerstr) -{ +void answerchallenge(const char *privstr, const char *challenge, vector &answerstr) { gfint privkey; privkey.parse(privstr); ecjacobian answer; @@ -896,48 +722,39 @@ void answerchallenge(const char *privstr, const char *challenge, vector &a answerstr.add('\0'); } -void *parsepubkey(const char *pubstr) -{ +void *parsepubkey(const char *pubstr) { ecjacobian *pubkey = new ecjacobian; pubkey->parse(pubstr); return pubkey; } -void freepubkey(void *pubkey) -{ +void freepubkey(void *pubkey) { delete (ecjacobian *)pubkey; } -void *genchallenge(void *pubkey, const void *seed, int seedlen, vector &challengestr) -{ +void *genchallenge(void *pubkey, const void *seed, int seedlen, vector &challengestr) { tiger::hashval hash; tiger::hash((const uchar *)seed, seedlen, hash); gfint challenge; memcpy(challenge.digits, hash.bytes, sizeof(hash.bytes)); challenge.len = 8*sizeof(hash.bytes)/BI_DIGIT_BITS; challenge.shrink(); - ecjacobian answer(*(ecjacobian *)pubkey); answer.mul(challenge); answer.normalize(); - ecjacobian secret(ecjacobian::base); secret.mul(challenge); secret.normalize(); - secret.print(challengestr); challengestr.add('\0'); - return new gfield(answer.x); } -void freechallenge(void *answer) -{ +void freechallenge(void *answer) { delete (gfint *)answer; } -bool checkchallenge(const char *answerstr, void *correct) -{ +bool checkchallenge(const char *answerstr, void *correct) { gfint answer(answerstr); return answer == *(gfint *)correct; } diff --git a/src/shared/cube2font.c b/src/shared/cube2font.c index 75ea8ff..bbd8878 100644 --- a/src/shared/cube2font.c +++ b/src/shared/cube2font.c @@ -16,8 +16,8 @@ typedef unsigned int uint; int imin(int a, int b) { return a < b ? a : b; } int imax(int a, int b) { return a > b ? a : b; } -void fatal(const char *fmt, ...) -{ +void fatal(const char *fmt, ...) { + va_list v; va_start(v, fmt); vfprintf(stderr, fmt, v); @@ -27,20 +27,20 @@ void fatal(const char *fmt, ...) exit(EXIT_FAILURE); } -uint bigswap(uint n) -{ +uint bigswap(uint n) { + const int islittleendian = 1; return *(const uchar *)&islittleendian ? (n<<24) | (n>>24) | ((n>>8)&0xFF00) | ((n<<8)&0xFF0000) : n; } -size_t writebig(FILE *f, uint n) -{ +size_t writebig(FILE *f, uint n) { + n = bigswap(n); return fwrite(&n, 1, sizeof(n), f); } -void writepngchunk(FILE *f, const char *type, uchar *data, uint len) -{ +void writepngchunk(FILE *f, const char *type, uchar *data, uint len) { + uint crc; writebig(f, len); fwrite(type, 1, 4, f); @@ -52,14 +52,14 @@ void writepngchunk(FILE *f, const char *type, uchar *data, uint len) writebig(f, crc); } -struct pngihdr -{ +struct pngihdr { + uint width, height; uchar bitdepth, colortype, compress, filter, interlace; }; -void savepng(const char *filename, uchar *data, int w, int h, int bpp, int flip) -{ +void savepng(const char *filename, uchar *data, int w, int h, int bpp, int flip) { + const uchar signature[] = { 137, 80, 78, 71, 13, 10, 26, 10 }; struct pngihdr ihdr; FILE *f; @@ -73,8 +73,8 @@ void savepng(const char *filename, uchar *data, int w, int h, int bpp, int flip) ihdr.width = bigswap(w); ihdr.height = bigswap(h); ihdr.bitdepth = 8; - switch(bpp) - { + switch(bpp) { + case 1: ihdr.colortype = 0; break; case 2: ihdr.colortype = 4; break; case 3: ihdr.colortype = 2; break; @@ -104,15 +104,15 @@ void savepng(const char *filename, uchar *data, int w, int h, int bpp, int flip) z.next_out = (Bytef *)buf; z.avail_out = sizeof(buf); - for(i = 0; i < h; i++) - { + for(i = 0; i < h; i++) { + uchar filter = 0; - for(j = 0; j < 2; j++) - { + for(j = 0; j < 2; j++) { + z.next_in = j ? (Bytef *)data + (flip ? h-i-1 : i)*w*bpp : (Bytef *)&filter; z.avail_in = j ? w*bpp : 1; - while(z.avail_in > 0) - { + while(z.avail_in > 0) { + if(deflate(&z, Z_NO_FLUSH) != Z_OK) goto cleanuperror; #define FLUSHZ do { \ int flush = sizeof(buf) - z.avail_out; \ @@ -127,8 +127,8 @@ void savepng(const char *filename, uchar *data, int w, int h, int bpp, int flip) } } - for(;;) - { + for(;;) { + int err = deflate(&z, Z_FINISH); if(err != Z_OK && err != Z_STREAM_END) goto cleanuperror; FLUSHZ; @@ -156,8 +156,8 @@ error: fatal("cube2font: failed saving PNG to %s", filename); } -enum -{ +enum { + CT_PRINT = 1<<0, CT_SPACE = 1<<1, CT_DIGIT = 1<<2, @@ -183,8 +183,8 @@ enum U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, \ U, U, U, U, u, u, u, u, u, u, u, u, u, u, u, u, \ u, u, u, u, u, u, u, u, u, u, u, u, u, u, U, u -const uchar cubectype[256] = -{ +const uchar cubectype[256] = { + CUBECTYPE(CT_SPACE, CT_PRINT, CT_PRINT|CT_DIGIT, @@ -199,8 +199,8 @@ int iscubealpha(uchar c) { return cubectype[c]&CT_ALPHA; } int iscubealnum(uchar c) { return cubectype[c]&(CT_ALPHA|CT_DIGIT); } int iscubelower(uchar c) { return cubectype[c]&CT_LOWER; } int iscubeupper(uchar c) { return cubectype[c]&CT_UPPER; } -const int cube2unichars[256] = -{ +const int cube2unichars[256] = { + 0, 192, 193, 194, 195, 196, 197, 198, 199, 9, 10, 11, 12, 13, 200, 201, 202, 203, 204, 205, 206, 207, 209, 210, 211, 212, 213, 214, 216, 217, 218, 219, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, @@ -218,13 +218,13 @@ const int cube2unichars[256] = 0x42C, 0x42D, 0x42E, 0x42F, 0x431, 0x432, 0x433, 0x434, 0x436, 0x437, 0x438, 0x439, 0x43A, 0x43B, 0x43C, 0x43D, 0x43F, 0x442, 0x444, 0x446, 0x447, 0x448, 0x449, 0x44A, 0x44B, 0x44C, 0x44D, 0x44E, 0x44F, 0x454, 0x490, 0x491 }; -int cube2uni(uchar c) -{ +int cube2uni(uchar c) { + return cube2unichars[c]; } -const char *encodeutf8(int uni) -{ +const char *encodeutf8(int uni) { + static char buf[7]; char *dst = buf; if(uni <= 0x7F) { *dst++ = uni; goto uni1; } @@ -247,41 +247,41 @@ struct fontchar { int code, uni, tex, x, y, w, h, offx, offy, offset, advance; F const char *texdir = ""; -const char *texfilename(const char *name, int texnum) -{ +const char *texfilename(const char *name, int texnum) { + static char file[256]; snprintf(file, sizeof(file), "%s%d.png", name, texnum); return file; } -const char *texname(const char *name, int texnum) -{ +const char *texname(const char *name, int texnum) { + static char file[512]; snprintf(file, sizeof(file), "%s%s", texdir, texfilename(name, texnum)); return file; } -void writetexs(const char *name, struct fontchar *chars, int numchars, int numtexs, int tw, int th) -{ +void writetexs(const char *name, struct fontchar *chars, int numchars, int numtexs, int tw, int th) { + int tex; uchar *pixels = (uchar *)malloc(tw*th*2); if(!pixels) fatal("cube2font: failed allocating textures"); - for(tex = 0; tex < numtexs; tex++) - { + for(tex = 0; tex < numtexs; tex++) { + const char *file = texfilename(name, tex); int texchars = 0, i; uchar *dst, *src; memset(pixels, 0, tw*th*2); - for(i = 0; i < numchars; i++) - { + for(i = 0; i < numchars; i++) { + struct fontchar *c = &chars[i]; int x, y; if(c->tex != tex) continue; texchars++; dst = &pixels[2*((c->y + c->offy - c->color->top)*tw + c->x + c->color->left - c->offx)]; src = (uchar *)c->color->bitmap.buffer; - for(y = 0; y < c->color->bitmap.rows; y++) - { + for(y = 0; y < c->color->bitmap.rows; y++) { + for(x = 0; x < c->color->bitmap.width; x++) dst[2*x] = src[x]; src += c->color->bitmap.pitch; @@ -289,8 +289,8 @@ void writetexs(const char *name, struct fontchar *chars, int numchars, int numte } dst = &pixels[2*((c->y + c->offy - c->alpha->top)*tw + c->x + c->alpha->left - c->offx)]; src = (uchar *)c->alpha->bitmap.buffer; - for(y = 0; y < c->alpha->bitmap.rows; y++) - { + for(y = 0; y < c->alpha->bitmap.rows; y++) { + for(x = 0; x < c->alpha->bitmap.width; x++) dst[2*x+1] = src[x]; src += c->alpha->bitmap.pitch; @@ -303,8 +303,8 @@ void writetexs(const char *name, struct fontchar *chars, int numchars, int numte free(pixels); } -void writecfg(const char *name, struct fontchar *chars, int numchars, int x1, int y1, int x2, int y2, int sw, int sh, int argc, char **argv) -{ +void writecfg(const char *name, struct fontchar *chars, int numchars, int x1, int y1, int x2, int y2, int sw, int sh, int argc, char **argv) { + FILE *f; char file[256]; int i, lastcode = 0, lasttex = 0; @@ -317,24 +317,24 @@ void writecfg(const char *name, struct fontchar *chars, int numchars, int x1, in fprintf(f, " %s", argv[i]); fprintf(f, "\n"); fprintf(f, "font \"%s\" \"%s\" %d %d\n", name, texname(name, 0), sw, sh); - for(i = 0; i < numchars; i++) - { + for(i = 0; i < numchars; i++) { + struct fontchar *c = &chars[i]; - if(!lastcode && lastcode < c->code) - { + if(!lastcode && lastcode < c->code) { + fprintf(f, "fontoffset \"%s\"\n", encodeutf8(c->uni)); lastcode = c->code; } - else if(lastcode < c->code) - { + else if(lastcode < c->code) { + if(lastcode + 1 == c->code) fprintf(f, "fontskip // %d\n", lastcode); else fprintf(f, "fontskip %d // %d .. %d\n", c->code - lastcode, lastcode, c->code-1); lastcode = c->code; } - if(lasttex != c->tex) - { + if(lasttex != c->tex) { + fprintf(f, "\nfonttex \"%s\"\n", texname(name, c->tex)); lasttex = c->tex; } @@ -347,10 +347,10 @@ void writecfg(const char *name, struct fontchar *chars, int numchars, int x1, in fclose(f); } -int groupchar(int c) -{ - switch(c) - { +int groupchar(int c) { + + switch(c) { + case 0x152: case 0x153: case 0x178: return 1; } if(c < 127 || c >= 0x2000) return 0; @@ -359,8 +359,8 @@ int groupchar(int c) return 3; } -int sortchars(const void *x, const void *y) -{ +int sortchars(const void *x, const void *y) { + const struct fontchar *xc = *(const struct fontchar **)x, *yc = *(const struct fontchar **)y; int xg = groupchar(xc->uni), yg = groupchar(yc->uni); if(xg < yg) return -1; @@ -370,16 +370,16 @@ int sortchars(const void *x, const void *y) return yc->uni - xc->uni; } -int scorechar(struct fontchar *f, int pad, int tw, int th, int rw, int rh, int ry) -{ +int scorechar(struct fontchar *f, int pad, int tw, int th, int rw, int rh, int ry) { + int score = 0; if(rw + f->w > tw) { ry += rh + pad; score = 1; } if(ry + f->h > th) score = 2; return score; } -int main(int argc, char **argv) -{ +int main(int argc, char **argv) { + FT_Library l; FT_Face f; FT_Stroker s, s2; @@ -411,8 +411,8 @@ int main(int argc, char **argv) fatal("cube2font: failed loading font %s", argv[1]); if(outborder > 0) FT_Stroker_Set(s, (FT_Fixed)(outborder * 64), FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); if(inborder > 0) FT_Stroker_Set(s2, (FT_Fixed)(inborder * 64), FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); - for(c = 0; c < 256; c++) if(iscubeprint(c)) - { + for(c = 0; c < 256; c++) if(iscubeprint(c)) { + FT_Glyph p, p2; FT_BitmapGlyph b, b2; struct fontchar *dst = &chars[numchars]; @@ -443,38 +443,38 @@ int main(int argc, char **argv) order[numchars++] = dst; } qsort(order, numchars, sizeof(order[0]), sortchars); - for(i = 0; i < numchars;) - { + for(i = 0; i < numchars;) { + struct fontchar *dst; int j, k, trial0, prevscore, dstscore, fitscore; - for(trial0 = trial, prevscore = -1; (trial -= 2) >= trial0-512;) - { + for(trial0 = trial, prevscore = -1; (trial -= 2) >= trial0-512;) { + int g, fw = rw, fh = rh, fy = ry, curscore = 0, reused = 0; - for(j = i; j < numchars; j++) - { + for(j = i; j < numchars; j++) { + dst = order[j]; if(dst->tex >= 0 || dst->tex <= trial) continue; g = groupchar(dst->uni); dstscore = scorechar(dst, pad, tw, th, fw, fh, fy); - for(k = j; k < numchars; k++) - { + for(k = j; k < numchars; k++) { + struct fontchar *fit = order[k]; if(fit->tex >= 0 || fit->tex <= trial) continue; if(fit->tex >= trial0 && groupchar(fit->uni) != g) break; fitscore = scorechar(fit, pad, tw, th, fw, fh, fy); - if(fitscore < dstscore || (fitscore == dstscore && fit->h > dst->h)) - { + if(fitscore < dstscore || (fitscore == dstscore && fit->h > dst->h)) { + dst = fit; dstscore = fitscore; } } - if(fw + dst->w > tw) - { + if(fw + dst->w > tw) { + fy += fh + pad; fw = fh = 0; } - if(fy + dst->h > th) - { + if(fy + dst->h > th) { + fy = fw = fh = 0; if(curscore > 0) break; } @@ -488,30 +488,30 @@ int main(int argc, char **argv) if(reused < prevscore || curscore <= prevscore) break; prevscore = curscore; } - for(; i < numchars; i++) - { + for(; i < numchars; i++) { + dst = order[i]; if(dst->tex >= 0) continue; dstscore = scorechar(dst, pad, tw, th, rw, rh, ry); - for(j = i; j < numchars; j++) - { + for(j = i; j < numchars; j++) { + struct fontchar *fit = order[j]; if(fit->tex < trial || fit->tex > trial+2) continue; fitscore = scorechar(fit, pad, tw, th, rw, rh, ry); - if(fitscore < dstscore || (fitscore == dstscore && fit->h > dst->h)) - { + if(fitscore < dstscore || (fitscore == dstscore && fit->h > dst->h)) { + dst = fit; dstscore = fitscore; } } if(dst->tex < trial || dst->tex > trial+2) break; - if(rw + dst->w > tw) - { + if(rw + dst->w > tw) { + ry += rh + pad; rw = rh = 0; } - if(ry + dst->h > th) - { + if(ry + dst->h > th) { + ry = rw = rh = 0; numtex++; } @@ -531,8 +531,8 @@ int main(int argc, char **argv) } if(rh > 0) numtex++; #if 0 - if(sw <= 0) - { + if(sw <= 0) { + if(FT_Load_Char(f, ' ', FT_LOAD_DEFAULT)) fatal("cube2font: failed loading space character"); sw = (f->glyph->advance.x+0x3F)>>6; @@ -542,8 +542,8 @@ int main(int argc, char **argv) if(sw <= 0) sw = sh/3; writetexs(argv[2], chars, numchars, numtex, tw, th); writecfg(argv[2], chars, numchars, x1, y1, x2, y2, sw, sh, argc, argv); - for(i = 0; i < numchars; i++) - { + for(i = 0; i < numchars; i++) { + if(chars[i].alpha != chars[i].color) FT_Done_Glyph((FT_Glyph)chars[i].alpha); FT_Done_Glyph((FT_Glyph)chars[i].color); } diff --git a/src/shared/ents.h b/src/shared/ents.h index 3ceccf4..6b1dfca 100644 --- a/src/shared/ents.h +++ b/src/shared/ents.h @@ -5,24 +5,21 @@ enum { ET_EMPTY=0, ET_LIGHT, ET_MAPMODEL, ET_PLAYERSTART, ET_PARTICLES, ET_SOUND, ET_SPOTLIGHT, ET_GAMESPECIFIC }; -struct entity // persistent map entity -{ +// persistent map entity +struct entity { vec o; // position short attr1, attr2, attr3, attr4, attr5; uchar type; // type is one of the above uchar reserved; }; -struct entitylight -{ +struct entitylight { vec color, dir; int millis; - entitylight() : color(1, 1, 1), dir(0, 0, 1), millis(-1) {} }; -enum -{ +enum { EF_NOVIS = 1<<0, EF_NOSHADOW = 1<<1, EF_NOCOLLIDE = 1<<2, @@ -34,19 +31,16 @@ enum EF_NOPICKUP = 1<<8 }; -struct extentity : entity // part of the entity that doesn't get saved to disk -{ +// part of the entity that doesn't get saved to disk +struct extentity : entity { int flags; // the only dynamic state of a map entity entitylight light; extentity *attached; - extentity() : flags(0), attached(NULL) {} - bool spawned() const { return (flags&EF_SPAWNED) != 0; } void setspawned(bool val) { if(val) flags |= EF_SPAWNED; else flags &= ~EF_SPAWNED; } void setspawned() { flags |= EF_SPAWNED; } void clearspawned() { flags &= ~EF_SPAWNED; } - bool nopickup() const { return (flags&EF_NOPICKUP) != 0; } void setnopickup(bool val) { if(val) flags |= EF_NOPICKUP; else flags &= ~EF_NOPICKUP; } void setnopickup() { flags |= EF_NOPICKUP; } @@ -65,8 +59,7 @@ enum { ENT_PLAYER = 0, ENT_AI, ENT_INANIMATE, ENT_CAMERA, ENT_BOUNCE }; enum { COLLIDE_NONE = 0, COLLIDE_ELLIPSE, COLLIDE_OBB, COLLIDE_ELLIPSE_PRECISE }; -struct physent // base entity type, can be affected by physics -{ +struct physent { // base entity type, can be affected by physics { vec o, vel, falling; // origin, velocity vec deltapos, newpos; // movement interpolation float yaw, pitch, roll; @@ -74,34 +67,26 @@ struct physent // base entity type, can be affected by physics float radius, eyeheight, aboveeye; // bounding box size float xradius, yradius, zmargin; vec floor; // the normal of floor the dynent is on - ushort timeinair; uchar inwater; bool jumping; schar move, strafe; - uchar physstate; // one of PHYS_* above uchar state, editstate; // one of CS_* above uchar type; // one of ENT_* above uchar collidetype; // one of COLLIDE_* above - bool blocked; // used by physics to signal ai - physent() : o(0, 0, 0), deltapos(0, 0, 0), newpos(0, 0, 0), yaw(0), pitch(0), roll(0), maxspeed(100), radius(4.1f), eyeheight(14), aboveeye(1), xradius(4.1f), yradius(4.1f), zmargin(0), state(CS_ALIVE), editstate(CS_ALIVE), type(ENT_PLAYER), collidetype(COLLIDE_ELLIPSE), blocked(false) - { reset(); } - - void resetinterp() - { + { reset(); } + void resetinterp() { newpos = o; deltapos = vec(0, 0, 0); } - - void reset() - { + void reset() { inwater = 0; timeinair = 0; jumping = false; @@ -110,15 +95,12 @@ struct physent // base entity type, can be affected by physics vel = falling = vec(0, 0, 0); floor = vec(0, 0, 1); } - vec feetpos(float offset = 0) const { return vec(o).add(vec(0, 0, offset - eyeheight)); } vec headpos(float offset = 0) const { return vec(o).add(vec(0, 0, offset)); } - bool maymove() const { return timeinair || physstate < PHYS_FLOOR || vel.squaredlen() > 1e-4f || deltapos.squaredlen() > 1e-4f; } }; -enum -{ +enum { ANIM_DEAD = 0, ANIM_DYING, ANIM_IDLE, ANIM_FORWARD, ANIM_BACKWARD, ANIM_LEFT, ANIM_RIGHT, ANIM_HOLD1, ANIM_HOLD2, ANIM_HOLD3, ANIM_HOLD4, ANIM_HOLD5, ANIM_HOLD6, ANIM_HOLD7, @@ -132,8 +114,7 @@ enum NUMANIMS }; -static const char * const animnames[] = -{ +static const char * const animnames[] = { "dead", "dying", "idle", "forward", "backward", "left", "right", "hold 1", "hold 2", "hold 3", "hold 4", "hold 5", "hold 6", "hold 7", @@ -166,26 +147,20 @@ static const char * const animnames[] = #define ANIM_GHOST (1<<30) #define ANIM_FLAGS (0x1FF<<22) -struct animinfo // description of a character's animation -{ +struct animinfo { // description of a character's animation { int anim, frame, range, basetime; float speed; uint varseed; - animinfo() : anim(0), frame(0), range(0), basetime(0), speed(100.0f), varseed(0) { } - bool operator==(const animinfo &o) const { return frame==o.frame && range==o.range && (anim&(ANIM_SETTIME|ANIM_DIR))==(o.anim&(ANIM_SETTIME|ANIM_DIR)) && (anim&ANIM_SETTIME || basetime==o.basetime) && speed==o.speed; } bool operator!=(const animinfo &o) const { return frame!=o.frame || range!=o.range || (anim&(ANIM_SETTIME|ANIM_DIR))!=(o.anim&(ANIM_SETTIME|ANIM_DIR)) || (!(anim&ANIM_SETTIME) && basetime!=o.basetime) || speed!=o.speed; } }; -struct animinterpinfo // used for animation blending of animated characters -{ +struct animinterpinfo { // used for animation blending of animated characters { animinfo prev, cur; int lastswitch; void *lastmodel; - animinterpinfo() : lastswitch(-1), lastmodel(NULL) {} - void reset() { lastswitch = -1; } }; @@ -194,44 +169,31 @@ struct animinterpinfo // used for animation blending of animated characters struct occludequery; struct ragdolldata; -struct dynent : physent // animated characters, or characters that can receive input -{ +struct dynent : physent { // animated characters, or characters that can receive input { bool k_left, k_right, k_up, k_down; // see input code - entitylight light; animinterpinfo animinterp[MAXANIMPARTS]; ragdolldata *ragdoll; occludequery *query; int lastrendered; uchar occluded; - - dynent() : ragdoll(NULL), query(NULL), lastrendered(0), occluded(0) - { + dynent() : ragdoll(NULL), query(NULL), lastrendered(0), occluded(0) { reset(); } - - ~dynent() - { + ~dynent() { #ifndef STANDALONE extern void cleanragdoll(dynent *d); if(ragdoll) cleanragdoll(this); #endif } - - void stopmoving() - { + void stopmoving() { k_left = k_right = k_up = k_down = jumping = false; move = strafe = 0; } - - void reset() - { + void reset() { physent::reset(); stopmoving(); loopi(MAXANIMPARTS) animinterp[i].reset(); } - vec abovehead() { return vec(o).add(vec(0, 0, aboveeye+4)); } }; - - diff --git a/src/shared/geom.cpp b/src/shared/geom.cpp index a5192e4..ad71841 100644 --- a/src/shared/geom.cpp +++ b/src/shared/geom.cpp @@ -4,15 +4,13 @@ static inline double det2x2(double a, double b, double c, double d) { return a*d - b*c; } static inline double det3x3(double a1, double a2, double a3, double b1, double b2, double b3, - double c1, double c2, double c3) -{ + double c1, double c2, double c3) { return a1 * det2x2(b2, b3, c2, c3) - b1 * det2x2(a2, a3, c2, c3) + c1 * det2x2(a2, a3, b2, b3); } -bool matrix4::invert(const matrix4 &m, double mindet) -{ +bool matrix4::invert(const matrix4 &m, double mindet) { double a1 = m.a.x, a2 = m.a.y, a3 = m.a.z, a4 = m.a.w, b1 = m.b.x, b2 = m.b.y, b3 = m.b.z, b4 = m.b.w, c1 = m.c.x, c2 = m.c.y, c3 = m.c.z, c4 = m.c.w, @@ -22,36 +20,28 @@ bool matrix4::invert(const matrix4 &m, double mindet) det3 = det3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4), det4 = -det3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4), det = a1*det1 + b1*det2 + c1*det3 + d1*det4; - if(fabs(det) < mindet) return false; - double invdet = 1/det; - a.x = det1 * invdet; a.y = det2 * invdet; a.z = det3 * invdet; a.w = det4 * invdet; - b.x = -det3x3(b1, b3, b4, c1, c3, c4, d1, d3, d4) * invdet; b.y = det3x3(a1, a3, a4, c1, c3, c4, d1, d3, d4) * invdet; b.z = -det3x3(a1, a3, a4, b1, b3, b4, d1, d3, d4) * invdet; b.w = det3x3(a1, a3, a4, b1, b3, b4, c1, c3, c4) * invdet; - c.x = det3x3(b1, b2, b4, c1, c2, c4, d1, d2, d4) * invdet; c.y = -det3x3(a1, a2, a4, c1, c2, c4, d1, d2, d4) * invdet; c.z = det3x3(a1, a2, a4, b1, b2, b4, d1, d2, d4) * invdet; c.w = -det3x3(a1, a2, a4, b1, b2, b4, c1, c2, c4) * invdet; - d.x = -det3x3(b1, b2, b3, c1, c2, c3, d1, d2, d3) * invdet; d.y = det3x3(a1, a2, a3, c1, c2, c3, d1, d2, d3) * invdet; d.z = -det3x3(a1, a2, a3, b1, b2, b3, d1, d2, d3) * invdet; d.w = det3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3) * invdet; - return true; } -bool raysphereintersect(const vec ¢er, float radius, const vec &o, const vec &ray, float &dist) -{ +bool raysphereintersect(const vec ¢er, float radius, const vec &o, const vec &ray, float &dist) { vec c(center); c.sub(o); float v = c.dot(ray), @@ -63,17 +53,14 @@ bool raysphereintersect(const vec ¢er, float radius, const vec &o, const vec return true; } -bool rayboxintersect(const vec &b, const vec &s, const vec &o, const vec &ray, float &dist, int &orient) -{ - loop(d, 3) if(ray[d]) - { +bool rayboxintersect(const vec &b, const vec &s, const vec &o, const vec &ray, float &dist, int &orient) { + loop(d, 3) if(ray[d]) { int dc = ray[d]<0 ? 1 : 0; float pdist = (b[d]+s[d]*dc - o[d]) / ray[d]; vec v(ray); v.mul(pdist).add(o); if(v[R[d]] >= b[R[d]] && v[R[d]] <= b[R[d]]+s[R[d]] - && v[C[d]] >= b[C[d]] && v[C[d]] <= b[C[d]]+s[C[d]]) - { + && v[C[d]] >= b[C[d]] && v[C[d]] <= b[C[d]]+s[C[d]]) { dist = pdist; orient = 2*d+dc; return true; @@ -82,8 +69,7 @@ bool rayboxintersect(const vec &b, const vec &s, const vec &o, const vec &ray, f return false; } -bool linecylinderintersect(const vec &from, const vec &to, const vec &start, const vec &end, float radius, float &dist) -{ +bool linecylinderintersect(const vec &from, const vec &to, const vec &start, const vec &end, float radius, float &dist) { vec d(end), m(from), n(to); d.sub(start); m.sub(start); @@ -98,16 +84,14 @@ bool linecylinderintersect(const vec &from, const vec &to, const vec &start, con a = dd*nn - nd*nd, k = m.squaredlen() - radius*radius, c = dd*k - md*md; - if(fabs(a) < 0.005f) - { + if(fabs(a) < 0.005f) { if(c > 0) return false; if(md < 0) dist = -mn / nn; else if(md > dd) dist = (nd - mn) / nn; else dist = 0; return true; } - else if(c > 0) - { + else if(c > 0) { float b = dd*mn - nd*md, discrim = b*b - a*c; if(discrim < 0) return false; @@ -115,14 +99,12 @@ bool linecylinderintersect(const vec &from, const vec &to, const vec &start, con } else dist = 0; float offset = md + dist*nd; - if(offset < 0) - { + if(offset < 0) { if(nd <= 0) return false; dist = -md / nd; if(k + dist*(2*mn + dist*nn) > 0) return false; } - else if(offset > dd) - { + else if(offset > dd) { if(nd >= 0) return false; dist = (dd - md) / nd; if(k + dd - 2*md + dist*(2*(mn-nd) + dist*nn) > 0) return false; @@ -130,8 +112,7 @@ bool linecylinderintersect(const vec &from, const vec &to, const vec &start, con return dist >= 0 && dist <= 1; } -extern const vec2 sincos360[721] = -{ +extern const vec2 sincos360[721] = { vec2(1.00000000, 0.00000000), vec2(0.99984770, 0.01745241), vec2(0.99939083, 0.03489950), vec2(0.99862953, 0.05233596), vec2(0.99756405, 0.06975647), vec2(0.99619470, 0.08715574), // 0 vec2(0.99452190, 0.10452846), vec2(0.99254615, 0.12186934), vec2(0.99026807, 0.13917310), vec2(0.98768834, 0.15643447), vec2(0.98480775, 0.17364818), vec2(0.98162718, 0.19080900), // 6 vec2(0.97814760, 0.20791169), vec2(0.97437006, 0.22495105), vec2(0.97029573, 0.24192190), vec2(0.96592583, 0.25881905), vec2(0.96126170, 0.27563736), vec2(0.95630476, 0.29237170), // 12 diff --git a/src/shared/geom.h b/src/shared/geom.h index a0ef7c8..745ff37 100644 --- a/src/shared/geom.h +++ b/src/shared/geom.h @@ -1,48 +1,41 @@ struct vec; struct vec4; -struct vec2 -{ - union - { +struct vec2 { + union { struct { float x, y; }; float v[2]; }; - vec2() {} vec2(float x, float y) : x(x), y(y) {} explicit vec2(const vec &v); explicit vec2(const vec4 &v); - - float &operator[](int i) { return v[i]; } + float &operator[](int i) { return v[i]; } float operator[](int i) const { return v[i]; } - bool operator==(const vec2 &o) const { return x == o.x && y == o.y; } bool operator!=(const vec2 &o) const { return x != o.x || y != o.y; } - bool iszero() const { return x==0 && y==0; } - float dot(const vec2 &o) const { return x*o.x + y*o.y; } + float dot(const vec2 &o) const { return x*o.x + y*o.y; } float squaredlen() const { return dot(*this); } - float magnitude() const { return sqrtf(squaredlen()); } + float magnitude() const { return sqrtf(squaredlen()); } vec2 &normalize() { mul(1/magnitude()); return *this; } vec2 &safenormalize() { float m = magnitude(); if(m) mul(1/m); return *this; } float cross(const vec2 &o) const { return x*o.y - y*o.x; } - - vec2 &mul(float f) { x *= f; y *= f; return *this; } + vec2 &mul(float f) { x *= f; y *= f; return *this; } vec2 &mul(const vec2 &o) { x *= o.x; y *= o.y; return *this; } - vec2 &square() { mul(*this); return *this; } - vec2 &div(float f) { x /= f; y /= f; return *this; } + vec2 &square() { mul(*this); return *this; } + vec2 &div(float f) { x /= f; y /= f; return *this; } vec2 &div(const vec2 &o) { x /= o.x; y /= o.y; return *this; } vec2 &recip() { x = 1/x; y = 1/y; return *this; } - vec2 &add(float f) { x += f; y += f; return *this; } + vec2 &add(float f) { x += f; y += f; return *this; } vec2 &add(const vec2 &o) { x += o.x; y += o.y; return *this; } - vec2 &sub(float f) { x -= f; y -= f; return *this; } + vec2 &sub(float f) { x -= f; y -= f; return *this; } vec2 &sub(const vec2 &o) { x -= o.x; y -= o.y; return *this; } - vec2 &neg() { x = -x; y = -y; return *this; } + vec2 &neg() { x = -x; y = -y; return *this; } vec2 &min(const vec2 &o) { x = ::min(x, o.x); y = ::min(y, o.y); return *this; } vec2 &max(const vec2 &o) { x = ::max(x, o.x); y = ::max(y, o.y); return *this; } - vec2 &min(float f) { x = ::min(x, f); y = ::min(y, f); return *this; } - vec2 &max(float f) { x = ::max(x, f); y = ::max(y, f); return *this; } + vec2 &min(float f) { x = ::min(x, f); y = ::min(y, f); return *this; } + vec2 &max(float f) { x = ::max(x, f); y = ::max(y, f); return *this; } vec2 &abs() { x = fabs(x); y = fabs(y); return *this; } vec2 &clamp(float l, float h) { x = ::clamp(x, l, h); y = ::clamp(y, l, h); return *this; } vec2 &reflect(const vec2 &n) { float k = 2*dot(n); x -= k*n.x; y -= k*n.y; return *this; } @@ -52,13 +45,11 @@ struct vec2 template vec2 &msub(const vec2 &a, const B &b) { return sub(vec2(a).mul(b)); } }; -static inline bool htcmp(const vec2 &x, const vec2 &y) -{ +static inline bool htcmp(const vec2 &x, const vec2 &y) { return x == y; } -static inline uint hthash(const vec2 &k) -{ +static inline uint hthash(const vec2 &k) { union { uint i; float f; } x, y; x.f = k.x; y.f = k.y; uint v = x.i^y.i; @@ -67,15 +58,12 @@ static inline uint hthash(const vec2 &k) struct ivec; -struct vec -{ - union - { +struct vec { + union { struct { float x, y, z; }; struct { float r, g, b; }; float v[3]; }; - vec() {} explicit vec(int a) : x(a), y(a), z(a) {} explicit vec(float a) : x(a), y(a), z(a) {} @@ -85,50 +73,45 @@ struct vec explicit vec(const vec2 &v, float z = 0) : x(v.x), y(v.y), z(z) {} explicit vec(const vec4 &v); explicit vec(const ivec &v); - vec(float yaw, float pitch) : x(-sinf(yaw)*cosf(pitch)), y(cosf(yaw)*cosf(pitch)), z(sinf(pitch)) {} - - float &operator[](int i) { return v[i]; } + float &operator[](int i) { return v[i]; } float operator[](int i) const { return v[i]; } - vec &set(int i, float f) { v[i] = f; return *this; } - bool operator==(const vec &o) const { return x == o.x && y == o.y && z == o.z; } bool operator!=(const vec &o) const { return x != o.x || y != o.y || z != o.z; } - bool iszero() const { return x==0 && y==0 && z==0; } float squaredlen() const { return x*x + y*y + z*z; } template float dot2(const T &o) const { return x*o.x + y*o.y; } float dot(const vec &o) const { return x*o.x + y*o.y + z*o.z; } float absdot(const vec &o) const { return fabs(x*o.x) + fabs(y*o.y) + fabs(z*o.z); } vec &pow(float f) { x = ::pow(x, f); y = ::pow(y, f); z = ::pow(z, f); return *this; } - vec &exp() { x = ::exp(x); y = ::exp(y); z = ::exp(z); return *this; } - vec &exp2() { x = ::exp2(x); y = ::exp2(y); z = ::exp2(z); return *this; } - vec &sqrt() { x = sqrtf(x); y = sqrtf(y); z = sqrtf(z); return *this; } - vec &mul(const vec &o) { x *= o.x; y *= o.y; z *= o.z; return *this; } + vec &exp() { x = ::exp(x); y = ::exp(y); z = ::exp(z); return *this; } + vec &exp2() { x = ::exp2(x); y = ::exp2(y); z = ::exp2(z); return *this; } + vec &sqrt() { x = sqrtf(x); y = sqrtf(y); z = sqrtf(z); return *this; } + vec &mul(const vec &o) { x *= o.x; y *= o.y; z *= o.z; return *this; } vec &mul(float f) { x *= f; y *= f; z *= f; return *this; } vec &square() { mul(*this); return *this; } - vec &div(const vec &o) { x /= o.x; y /= o.y; z /= o.z; return *this; } + vec &div(const vec &o) { x /= o.x; y /= o.y; z /= o.z; return *this; } vec &div(float f) { x /= f; y /= f; z /= f; return *this; } vec &recip() { x = 1/x; y = 1/y; z = 1/z; return *this; } - vec &add(const vec &o) { x += o.x; y += o.y; z += o.z; return *this; } + vec &add(const vec &o) { x += o.x; y += o.y; z += o.z; return *this; } vec &add(float f) { x += f; y += f; z += f; return *this; } - vec &add2(float f) { x += f; y += f; return *this; } - vec &addz(float f) { z += f; return *this; } - vec &sub(const vec &o) { x -= o.x; y -= o.y; z -= o.z; return *this; } + vec &add2(float f) { x += f; y += f; return *this; } + vec &addz(float f) { z += f; return *this; } + vec &sub(const vec &o) { x -= o.x; y -= o.y; z -= o.z; return *this; } vec &sub(float f) { x -= f; y -= f; z -= f; return *this; } - vec &sub2(float f) { x -= f; y -= f; return *this; } - vec &subz(float f) { z -= f; return *this; } - vec &neg2() { x = -x; y = -y; return *this; } - vec &neg() { x = -x; y = -y; z = -z; return *this; } - vec &min(const vec &o) { x = ::min(x, o.x); y = ::min(y, o.y); z = ::min(z, o.z); return *this; } - vec &max(const vec &o) { x = ::max(x, o.x); y = ::max(y, o.y); z = ::max(z, o.z); return *this; } + vec &sub2(float f) { x -= f; y -= f; return *this; } + vec &subz(float f) { z -= f; return *this; } + vec &neg2() { x = -x; y = -y; return *this; } + vec &neg() { x = -x; y = -y; z = -z; return *this; } + vec &min(const vec &o) { x = ::min(x, o.x); y = ::min(y, o.y); z = ::min(z, o.z); return *this; } + vec &max(const vec &o) { x = ::max(x, o.x); y = ::max(y, o.y); z = ::max(z, o.z); return *this; } vec &min(float f) { x = ::min(x, f); y = ::min(y, f); z = ::min(z, f); return *this; } vec &max(float f) { x = ::max(x, f); y = ::max(y, f); z = ::max(z, f); return *this; } vec &clamp(float f, float h) { x = ::clamp(x, f, h); y = ::clamp(y, f, h); z = ::clamp(z, f, h); return *this; } vec &abs() { x = fabs(x); y = fabs(y); z = fabs(z); return *this; } float magnitude2() const { return sqrtf(dot2(*this)); } - float magnitude() const { return sqrtf(squaredlen()); } + float magnitude() const { return sqrtf(squaredlen()); } vec &normalize() { div(magnitude()); return *this; } vec &safenormalize() { float m = magnitude(); if(m) div(m); return *this; } bool isnormalized() const { float m = squaredlen(); return (m>0.99f && m<1.01f); } @@ -145,15 +128,13 @@ struct vec vec &reflect(const vec &n) { float k = 2*dot(n); x -= k*n.x; y -= k*n.y; z -= k*n.z; return *this; } vec &project(const vec &n) { float k = dot(n); x -= k*n.x; y -= k*n.y; z -= k*n.z; return *this; } vec &projectxydir(const vec &n) { if(n.z) z = -(x*n.x/n.z + y*n.y/n.z); return *this; } - vec &projectxy(const vec &n) - { + vec &projectxy(const vec &n) { float m = squaredlen(), k = dot(n); projectxydir(n); rescale(sqrtf(::max(m - k*k, 0.0f))); return *this; } - vec &projectxy(const vec &n, float threshold) - { + vec &projectxy(const vec &n, float threshold) { float m = squaredlen(), k = ::min(dot(n), threshold); projectxydir(n); rescale(sqrtf(::max(m - k*k, 0.0f))); @@ -163,28 +144,21 @@ struct vec vec &lerp(const vec &a, const vec &b, float t) { x = a.x + (b.x-a.x)*t; y = a.y + (b.y-a.y)*t; z = a.z + (b.z-a.z)*t; return *this; } template vec &madd(const vec &a, const B &b) { return add(vec(a).mul(b)); } template vec &msub(const vec &a, const B &b) { return sub(vec(a).mul(b)); } - - vec &rescale(float k) - { + vec &rescale(float k) { float mag = magnitude(); if(mag > 1e-6f) mul(k / mag); return *this; } - vec &rotate_around_z(float c, float s) { float rx = x, ry = y; x = c*rx-s*ry; y = c*ry+s*rx; return *this; } vec &rotate_around_x(float c, float s) { float ry = y, rz = z; y = c*ry-s*rz; z = c*rz+s*ry; return *this; } vec &rotate_around_y(float c, float s) { float rx = x, rz = z; x = c*rx+s*rz; z = c*rz-s*rx; return *this; } - vec &rotate_around_z(float angle) { return rotate_around_z(cosf(angle), sinf(angle)); } vec &rotate_around_x(float angle) { return rotate_around_x(cosf(angle), sinf(angle)); } vec &rotate_around_y(float angle) { return rotate_around_y(cosf(angle), sinf(angle)); } - vec &rotate_around_z(const vec2 &sc) { return rotate_around_z(sc.x, sc.y); } vec &rotate_around_x(const vec2 &sc) { return rotate_around_x(sc.x, sc.y); } vec &rotate_around_y(const vec2 &sc) { return rotate_around_y(sc.x, sc.y); } - - vec &rotate(float c, float s, const vec &d) - { + vec &rotate(float c, float s, const vec &d) { *this = vec(x*(d.x*d.x*(1-c)+c) + y*(d.x*d.y*(1-c)-d.z*s) + z*(d.x*d.z*(1-c)+d.y*s), x*(d.y*d.x*(1-c)+d.z*s) + y*(d.y*d.y*(1-c)+c) + z*(d.y*d.z*(1-c)-d.x*s), x*(d.x*d.z*(1-c)-d.y*s) + y*(d.y*d.z*(1-c)+d.x*s) + z*(d.z*d.z*(1-c)+c)); @@ -192,49 +166,34 @@ struct vec } vec &rotate(float angle, const vec &d) { return rotate(cosf(angle), sinf(angle), d); } vec &rotate(const vec2 &sc, const vec &d) { return rotate(sc.x, sc.y, d); } - - void orthogonal(const vec &d) - { + void orthogonal(const vec &d) { *this = fabs(d.x) > fabs(d.z) ? vec(-d.y, d.x, 0) : vec(0, -d.z, d.y); } - - void orthonormalize(vec &s, vec &t) const - { + void orthonormalize(vec &s, vec &t) const { s.sub(vec(*this).mul(dot(s))); t.sub(vec(*this).mul(dot(t))) .sub(vec(s).mul(s.dot(t))); } - template - bool insidebb(const T &bbmin, const T &bbmax) const - { + bool insidebb(const T &bbmin, const T &bbmax) const { return x >= bbmin.x && x <= bbmax.x && y >= bbmin.y && y <= bbmax.y && z >= bbmin.z && z <= bbmax.z; } - template - bool insidebb(const T &o, U size) const - { + bool insidebb(const T &o, U size) const { return x >= o.x && x <= o.x + size && y >= o.y && y <= o.y + size && z >= o.z && z <= o.z + size; } - - template float dist_to_bb(const T &min, const T &max) const - { + template float dist_to_bb(const T &min, const T &max) const { float sqrdist = 0; - loopi(3) - { + loopi(3) { if (v[i] < min[i]) { float delta = v[i]-min[i]; sqrdist += delta*delta; } else if(v[i] > max[i]) { float delta = max[i]-v[i]; sqrdist += delta*delta; } } return sqrtf(sqrdist); } - - template float dist_to_bb(const T &o, S size) const - { + template float dist_to_bb(const T &o, S size) const { return dist_to_bb(o, T(o).add(size)); } - - static vec hexcolor(int color) - { + static vec hexcolor(int color) { return vec(((color>>16)&0xFF)*(1.0f/255.0f), ((color>>8)&0xFF)*(1.0f/255.0f), (color&0xFF)*(1.0f/255.0f)); } int tohexcolor() const { return (int(::clamp(r, 0.0f, 1.0f)*255)<<16)|(int(::clamp(g, 0.0f, 1.0f)*255)<<8)|int(::clamp(b, 0.0f, 1.0f)*255); } @@ -242,85 +201,71 @@ struct vec inline vec2::vec2(const vec &v) : x(v.x), y(v.y) {} -static inline bool htcmp(const vec &x, const vec &y) -{ +static inline bool htcmp(const vec &x, const vec &y) { return x == y; } -static inline uint hthash(const vec &k) -{ +static inline uint hthash(const vec &k) { union { uint i; float f; } x, y, z; x.f = k.x; y.f = k.y; z.f = k.z; uint v = x.i^y.i^z.i; return v + (v>>12); } -struct vec4 -{ - union - { +struct vec4 { + union { struct { float x, y, z, w; }; struct { float r, g, b, a; }; float v[4]; }; - vec4() {} explicit vec4(const vec &p, float w = 0) : x(p.x), y(p.y), z(p.z), w(w) {} vec4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {} explicit vec4(const float *v) : x(v[0]), y(v[1]), z(v[2]), w(v[3]) {} - - float &operator[](int i) { return v[i]; } + float &operator[](int i) { return v[i]; } float operator[](int i) const { return v[i]; } - template float dot3(const T &o) const { return x*o.x + y*o.y + z*o.z; } float dot(const vec4 &o) const { return dot3(o) + w*o.w; } - float dot(const vec &o) const { return x*o.x + y*o.y + z*o.z + w; } + float dot(const vec &o) const { return x*o.x + y*o.y + z*o.z + w; } float squaredlen() const { return dot(*this); } - float magnitude() const { return sqrtf(squaredlen()); } + float magnitude() const { return sqrtf(squaredlen()); } float magnitude3() const { return sqrtf(dot3(*this)); } vec4 &normalize() { mul(1/magnitude()); return *this; } vec4 &safenormalize() { float m = magnitude(); if(m) mul(1/m); return *this; } - - vec4 &lerp(const vec4 &b, float t) - { + vec4 &lerp(const vec4 &b, float t) { x += (b.x-x)*t; y += (b.y-y)*t; z += (b.z-z)*t; w += (b.w-w)*t; return *this; } - vec4 &lerp(const vec4 &a, const vec4 &b, float t) - { + vec4 &lerp(const vec4 &a, const vec4 &b, float t) { x = a.x+(b.x-a.x)*t; y = a.y+(b.y-a.y)*t; z = a.z+(b.z-a.z)*t; w = a.w+(b.w-a.w)*t; return *this; } - - vec4 &mul3(float f) { x *= f; y *= f; z *= f; return *this; } - vec4 &mul(float f) { mul3(f); w *= f; return *this; } + vec4 &mul3(float f) { x *= f; y *= f; z *= f; return *this; } + vec4 &mul(float f) { mul3(f); w *= f; return *this; } vec4 &mul(const vec4 &o) { x *= o.x; y *= o.y; z *= o.z; w *= o.w; return *this; } - vec4 &square() { mul(*this); return *this; } - vec4 &div3(float f) { x /= f; y /= f; z /= f; return *this; } - vec4 &div(float f) { div3(f); w /= f; return *this; } + vec4 &square() { mul(*this); return *this; } + vec4 &div3(float f) { x /= f; y /= f; z /= f; return *this; } + vec4 &div(float f) { div3(f); w /= f; return *this; } vec4 &div(const vec4 &o) { x /= o.x; y /= o.y; z /= o.z; w /= o.w; return *this; } vec4 &recip() { x = 1/x; y = 1/y; z = 1/z; w = 1/w; return *this; } vec4 &add(const vec4 &o) { x += o.x; y += o.y; z += o.z; w += o.w; return *this; } - vec4 &addw(float f) { w += f; return *this; } + vec4 &addw(float f) { w += f; return *this; } vec4 &sub(const vec4 &o) { x -= o.x; y -= o.y; z -= o.z; w -= o.w; return *this; } - vec4 &subw(float f) { w -= f; return *this; } + vec4 &subw(float f) { w -= f; return *this; } vec4 &neg3() { x = -x; y = -y; z = -z; return *this; } - vec4 &neg() { neg3(); w = -w; return *this; } + vec4 &neg() { neg3(); w = -w; return *this; } template vec4 &madd(const vec4 &a, const B &b) { return add(vec4(a).mul(b)); } template vec4 &msub(const vec4 &a, const B &b) { return sub(vec4(a).mul(b)); } - void setxyz(const vec &v) { x = v.x; y = v.y; z = v.z; } - vec4 &rotate_around_z(float c, float s) { float rx = x, ry = y; x = c*rx-s*ry; y = c*ry+s*rx; return *this; } vec4 &rotate_around_x(float c, float s) { float ry = y, rz = z; y = c*ry-s*rz; z = c*rz+s*ry; return *this; } vec4 &rotate_around_y(float c, float s) { float rx = x, rz = z; x = c*rx+s*rz; z = c*rz-s*rx; return *this; } - vec4 &rotate_around_z(float angle) { return rotate_around_z(cosf(angle), sinf(angle)); } vec4 &rotate_around_x(float angle) { return rotate_around_x(cosf(angle), sinf(angle)); } vec4 &rotate_around_y(float angle) { return rotate_around_y(cosf(angle), sinf(angle)); } @@ -332,20 +277,17 @@ struct matrix3; struct matrix4x3; struct matrix4; -struct quat : vec4 -{ +struct quat : vec4 { quat() {} quat(float x, float y, float z, float w) : vec4(x, y, z, w) {} - quat(const vec &axis, float angle) - { + quat(const vec &axis, float angle) { w = cosf(angle/2); float s = sinf(angle/2); x = s*axis.x; y = s*axis.y; z = s*axis.z; } - explicit quat(const vec &v) - { + explicit quat(const vec &v) { x = v.x; y = v.y; z = v.z; @@ -354,15 +296,11 @@ struct quat : vec4 explicit quat(const matrix3 &m) { convertmatrix(m); } explicit quat(const matrix4x3 &m) { convertmatrix(m); } explicit quat(const matrix4 &m) { convertmatrix(m); } - void restorew() { w = 1.0f-x*x-y*y-z*z; w = w<0 ? 0 : -sqrtf(w); } - quat &add(const vec4 &o) { vec4::add(o); return *this; } quat &sub(const vec4 &o) { vec4::sub(o); return *this; } quat &mul(float k) { vec4::mul(k); return *this; } - - quat &mul(const quat &p, const quat &o) - { + quat &mul(const quat &p, const quat &o) { x = p.w*o.x + p.x*o.w + p.y*o.z - p.z*o.y; y = p.w*o.y - p.x*o.z + p.y*o.w + p.z*o.x; z = p.w*o.z + p.x*o.y - p.y*o.x + p.z*o.w; @@ -370,60 +308,46 @@ struct quat : vec4 return *this; } quat &mul(const quat &o) { return mul(quat(*this), o); } - quat &invert() { neg3(); return *this; } - - void calcangleaxis(float &angle, vec &axis) - { + void calcangleaxis(float &angle, vec &axis) { float rr = dot3(*this); - if(rr>0) - { + if(rr>0) { angle = 2*acosf(w); axis = vec(x, y, z).mul(1/rr); } else { angle = 0; axis = vec(0, 0, 1); } } - - vec rotate(const vec &v) const - { + vec rotate(const vec &v) const { return vec().cross(*this, vec().cross(*this, v).add(vec(v).mul(w))).mul(2).add(v); } - - vec invertedrotate(const vec &v) const - { + vec invertedrotate(const vec &v) const { return vec().cross(*this, vec().cross(*this, v).sub(vec(v).mul(w))).mul(2).add(v); } - template - void convertmatrix(const M &m) - { + void convertmatrix(const M &m) { float trace = m.a.x + m.b.y + m.c.z; - if(trace>0) - { + if(trace>0) { float r = sqrtf(1 + trace), inv = 0.5f/r; w = 0.5f*r; x = (m.b.z - m.c.y)*inv; y = (m.c.x - m.a.z)*inv; z = (m.a.y - m.b.x)*inv; } - else if(m.a.x > m.b.y && m.a.x > m.c.z) - { + else if(m.a.x > m.b.y && m.a.x > m.c.z) { float r = sqrtf(1 + m.a.x - m.b.y - m.c.z), inv = 0.5f/r; x = 0.5f*r; y = (m.a.y + m.b.x)*inv; z = (m.c.x + m.a.z)*inv; w = (m.b.z - m.c.y)*inv; } - else if(m.b.y > m.c.z) - { + else if(m.b.y > m.c.z) { float r = sqrtf(1 + m.b.y - m.a.x - m.c.z), inv = 0.5f/r; x = (m.a.y + m.b.x)*inv; y = 0.5f*r; z = (m.b.z + m.c.y)*inv; w = (m.c.x - m.a.z)*inv; } - else - { + else { float r = sqrtf(1 + m.c.z - m.a.x - m.b.y), inv = 0.5f/r; x = (m.c.x + m.a.z)*inv; y = (m.b.z + m.c.y)*inv; @@ -433,147 +357,105 @@ struct quat : vec4 } }; -struct dualquat -{ +struct dualquat { quat real, dual; - dualquat() {} dualquat(const quat &q, const vec &p) : real(q), dual(0.5f*( p.x*q.w + p.y*q.z - p.z*q.y), 0.5f*(-p.x*q.z + p.y*q.w + p.z*q.x), 0.5f*( p.x*q.y - p.y*q.x + p.z*q.w), - -0.5f*( p.x*q.x + p.y*q.y + p.z*q.z)) - { + -0.5f*( p.x*q.x + p.y*q.y + p.z*q.z)) { } explicit dualquat(const quat &q) : real(q), dual(0, 0, 0, 0) {} explicit dualquat(const matrix4x3 &m); - dualquat &mul(float k) { real.mul(k); dual.mul(k); return *this; } dualquat &add(const dualquat &d) { real.add(d.real); dual.add(d.dual); return *this; } - - dualquat &lerp(const dualquat &to, float t) - { + dualquat &lerp(const dualquat &to, float t) { float k = real.dot(to.real) < 0 ? -t : t; real.mul(1-t).add(vec4(to.real).mul(k)); dual.mul(1-t).add(vec4(to.dual).mul(k)); return *this; } - dualquat &lerp(const dualquat &from, const dualquat &to, float t) - { + dualquat &lerp(const dualquat &from, const dualquat &to, float t) { float k = from.real.dot(to.real) < 0 ? -t : t; (real = from.real).mul(1-t).add(vec4(to.real).mul(k)); (dual = from.dual).mul(1-t).add(vec4(to.dual).mul(k)); return *this; } - - dualquat &invert() - { + dualquat &invert() { real.invert(); dual.invert(); dual.sub(quat(real).mul(2*real.dot(dual))); return *this; } - - void mul(const dualquat &p, const dualquat &o) - { + void mul(const dualquat &p, const dualquat &o) { real.mul(p.real, o.real); dual.mul(p.real, o.dual).add(quat().mul(p.dual, o.real)); } void mul(const dualquat &o) { mul(dualquat(*this), o); } - - void mulorient(const quat &q) - { + void mulorient(const quat &q) { real.mul(q, quat(real)); dual.mul(quat(q).invert(), quat(dual)); } - - void mulorient(const quat &q, const dualquat &base) - { + void mulorient(const quat &q, const dualquat &base) { quat trans; trans.mul(base.dual, quat(base.real).invert()); dual.mul(quat(q).invert(), quat(real).mul(trans).add(dual)); - real.mul(q, quat(real)); dual.add(quat().mul(real, trans.invert())).sub(quat(real).mul(2*base.real.dot(base.dual))); } - - void normalize() - { + void normalize() { float invlen = 1/real.magnitude(); real.mul(invlen); dual.mul(invlen); } - - void translate(const vec &p) - { + void translate(const vec &p) { dual.x += 0.5f*( p.x*real.w + p.y*real.z - p.z*real.y); dual.y += 0.5f*(-p.x*real.z + p.y*real.w + p.z*real.x); dual.z += 0.5f*( p.x*real.y - p.y*real.x + p.z*real.w); dual.w += -0.5f*( p.x*real.x + p.y*real.y + p.z*real.z); } - - void scale(float k) - { + void scale(float k) { dual.mul(k); } - - void fixantipodal(const dualquat &d) - { - if(real.dot(d.real) < 0) - { + void fixantipodal(const dualquat &d) { + if(real.dot(d.real) < 0) { real.neg(); dual.neg(); } } - - void accumulate(const dualquat &d, float k) - { + void accumulate(const dualquat &d, float k) { if(real.dot(d.real) < 0) k = -k; real.add(vec4(d.real).mul(k)); dual.add(vec4(d.dual).mul(k)); } - - vec transform(const vec &v) const - { + vec transform(const vec &v) const { return vec().cross(real, vec().cross(real, v).add(vec(v).mul(real.w)).add(vec(dual))).add(vec(dual).mul(real.w)).sub(vec(real).mul(dual.w)).mul(2).add(v); } - - quat transform(const quat &q) const - { + quat transform(const quat &q) const { return quat().mul(real, q); } - - vec transposedtransform(const vec &v) const - { + vec transposedtransform(const vec &v) const { return dualquat(*this).invert().transform(v); } - - vec transformnormal(const vec &v) const - { + vec transformnormal(const vec &v) const { return real.rotate(v); } - - vec transposedtransformnormal(const vec &v) const - { + vec transposedtransformnormal(const vec &v) const { return real.invertedrotate(v); } - - vec gettranslation() const - { + vec gettranslation() const { return vec().cross(real, dual).add(vec(dual).mul(real.w)).sub(vec(real).mul(dual.w)).mul(2); } }; -struct matrix3 -{ +struct matrix3 { vec a, b, c; - matrix3() {} matrix3(const vec &a, const vec &b, const vec &c) : a(a), b(b), c(c) {} explicit matrix3(float angle, const vec &axis) { rotate(angle, axis); } - explicit matrix3(const quat &q) - { + explicit matrix3(const quat &q) { float x = q.x, y = q.y, z = q.z, w = q.w, tx = 2*x, ty = 2*y, tz = 2*z, txx = tx*x, tyy = ty*y, tzz = tz*z, @@ -585,47 +467,35 @@ struct matrix3 } explicit matrix3(const matrix4x3 &m); explicit matrix3(const matrix4 &m); - - void mul(const matrix3 &m, const matrix3 &n) - { + void mul(const matrix3 &m, const matrix3 &n) { a = vec(m.a).mul(n.a.x).madd(m.b, n.a.y).madd(m.c, n.a.z); b = vec(m.a).mul(n.b.x).madd(m.b, n.b.y).madd(m.c, n.b.z); c = vec(m.a).mul(n.c.x).madd(m.b, n.c.y).madd(m.c, n.c.z); } void mul(const matrix3 &n) { mul(matrix3(*this), n); } - - void multranspose(const matrix3 &m, const matrix3 &n) - { + void multranspose(const matrix3 &m, const matrix3 &n) { a = vec(m.a).mul(n.a.x).madd(m.b, n.b.x).madd(m.c, n.c.x); b = vec(m.a).mul(n.a.y).madd(m.b, n.b.y).madd(m.c, n.c.y); c = vec(m.a).mul(n.a.z).madd(m.b, n.b.z).madd(m.c, n.c.z); } void multranspose(const matrix3 &n) { multranspose(matrix3(*this), n); } - - void transposemul(const matrix3 &m, const matrix3 &n) - { + void transposemul(const matrix3 &m, const matrix3 &n) { a = vec(m.a.dot(n.a), m.b.dot(n.a), m.c.dot(n.a)); b = vec(m.a.dot(n.b), m.b.dot(n.b), m.c.dot(n.b)); c = vec(m.a.dot(n.c), m.b.dot(n.c), m.c.dot(n.c)); } void transposemul(const matrix3 &n) { transposemul(matrix3(*this), n); } - - void transpose() - { + void transpose() { swap(a.y, b.x); swap(a.z, c.x); swap(b.z, c.y); } - template - void transpose(const M &m) - { + void transpose(const M &m) { a = vec(m.a.x, m.b.x, m.c.x); b = vec(m.a.y, m.b.y, m.c.y); c = vec(m.a.z, m.b.z, m.c.z); } - - void invert(const matrix3 &o) - { + void invert(const matrix3 &o) { vec unscale(1/o.a.squaredlen(), 1/o.b.squaredlen(), 1/o.c.squaredlen()); transpose(o); a.mul(unscale); @@ -633,53 +503,36 @@ struct matrix3 c.mul(unscale); } void invert() { invert(matrix3(*this)); } - - void normalize() - { + void normalize() { a.normalize(); b.normalize(); c.normalize(); } - - void scale(float k) - { + void scale(float k) { a.mul(k); b.mul(k); c.mul(k); } - - void rotate(float angle, const vec &axis) - { + void rotate(float angle, const vec &axis) { rotate(cosf(angle), sinf(angle), axis); } - - void rotate(float ck, float sk, const vec &axis) - { + void rotate(float ck, float sk, const vec &axis) { a = vec(axis.x*axis.x*(1-ck)+ck, axis.x*axis.y*(1-ck)+axis.z*sk, axis.x*axis.z*(1-ck)-axis.y*sk); b = vec(axis.x*axis.y*(1-ck)-axis.z*sk, axis.y*axis.y*(1-ck)+ck, axis.y*axis.z*(1-ck)+axis.x*sk); c = vec(axis.x*axis.z*(1-ck)+axis.y*sk, axis.y*axis.z*(1-ck)-axis.x*sk, axis.z*axis.z*(1-ck)+ck); } - - void setyaw(float ck, float sk) - { + void setyaw(float ck, float sk) { a = vec(ck, sk, 0); b = vec(-sk, ck, 0); c = vec(0, 0, 1); } - - void setyaw(float angle) - { + void setyaw(float angle) { setyaw(cosf(angle), sinf(angle)); } - float trace() const { return a.x + b.y + c.z; } - - bool calcangleaxis(float tr, float &angle, vec &axis, float threshold = 1e-16f) const - { - if(tr <= -1) - { - if(a.x >= b.y && a.x >= c.z) - { + bool calcangleaxis(float tr, float &angle, vec &axis, float threshold = 1e-16f) const { + if(tr <= -1) { + if(a.x >= b.y && a.x >= c.z) { float r = 1 + a.x - b.y - c.z; if(r <= threshold) return false; r = sqrtf(r); @@ -687,8 +540,7 @@ struct matrix3 axis.y = b.x/r; axis.z = c.x/r; } - else if(b.y >= c.z) - { + else if(b.y >= c.z) { float r = 1 + b.y - a.x - c.z; if(r <= threshold) return false; r = sqrtf(r); @@ -696,8 +548,7 @@ struct matrix3 axis.x = b.x/r; axis.z = c.y/r; } - else - { + else { float r = 1 + b.y - a.x - c.z; if(r <= threshold) return false; r = sqrtf(r); @@ -707,13 +558,11 @@ struct matrix3 } angle = M_PI; } - else if(tr >= 3) - { + else if(tr >= 3) { axis = vec(0, 0, 1); angle = 0; } - else - { + else { axis = vec(b.z - c.y, c.x - a.z, a.y - b.x); float r = axis.squaredlen(); if(r <= threshold) return false; @@ -722,32 +571,23 @@ struct matrix3 } return true; } - bool calcangleaxis(float &angle, vec &axis, float threshold = 1e-16f) const { return calcangleaxis(trace(), angle, axis, threshold); } - - vec transform(const vec &o) const - { + vec transform(const vec &o) const { return vec(a).mul(o.x).madd(b, o.y).madd(c, o.z); } vec transposedtransform(const vec &o) const { return vec(a.dot(o), b.dot(o), c.dot(o)); } - vec abstransform(const vec &o) const - { + vec abstransform(const vec &o) const { return vec(a).mul(o.x).abs().add(vec(b).mul(o.y).abs()).add(vec(c).mul(o.z).abs()); } - vec abstransposedtransform(const vec &o) const - { + vec abstransposedtransform(const vec &o) const { return vec(a.absdot(o), b.absdot(o), c.absdot(o)); } - - void identity() - { + void identity() { a = vec(1, 0, 0); b = vec(0, 1, 0); c = vec(0, 0, 1); } - - void rotate_around_x(float ck, float sk) - { + void rotate_around_x(float ck, float sk) { vec rb = vec(b).mul(ck).madd(c, sk), rc = vec(c).mul(ck).msub(b, sk); b = rb; @@ -755,9 +595,7 @@ struct matrix3 } void rotate_around_x(float angle) { rotate_around_x(cosf(angle), sinf(angle)); } void rotate_around_x(const vec2 &sc) { rotate_around_x(sc.x, sc.y); } - - void rotate_around_y(float ck, float sk) - { + void rotate_around_y(float ck, float sk) { vec rc = vec(c).mul(ck).madd(a, sk), ra = vec(a).mul(ck).msub(c, sk); c = rc; @@ -765,9 +603,7 @@ struct matrix3 } void rotate_around_y(float angle) { rotate_around_y(cosf(angle), sinf(angle)); } void rotate_around_y(const vec2 &sc) { rotate_around_y(sc.x, sc.y); } - - void rotate_around_z(float ck, float sk) - { + void rotate_around_z(float ck, float sk) { vec ra = vec(a).mul(ck).madd(b, sk), rb = vec(b).mul(ck).msub(a, sk); a = ra; @@ -775,24 +611,19 @@ struct matrix3 } void rotate_around_z(float angle) { rotate_around_z(cosf(angle), sinf(angle)); } void rotate_around_z(const vec2 &sc) { rotate_around_z(sc.x, sc.y); } - vec transform(const vec2 &o) { return vec(a).mul(o.x).madd(b, o.y); } vec transposedtransform(const vec2 &o) const { return vec(a.dot2(o), b.dot2(o), c.dot2(o)); } - vec rowx() const { return vec(a.x, b.x, c.x); } vec rowy() const { return vec(a.y, b.y, c.y); } vec rowz() const { return vec(a.z, b.z, c.z); } }; -struct matrix4x3 -{ +struct matrix4x3 { vec a, b, c, d; - matrix4x3() {} matrix4x3(const vec &a, const vec &b, const vec &c, const vec &d) : a(a), b(b), c(c), d(d) {} matrix4x3(const matrix3 &rot, const vec &trans) : a(rot.a), b(rot.b), c(rot.c), d(trans) {} - matrix4x3(const dualquat &dq) - { + matrix4x3(const dualquat &dq) { vec4 r = vec4(dq.real).mul(1/dq.real.squaredlen()), rr = vec4(r).mul(dq.real); r.mul(2); float xy = r.x*dq.real.y, xz = r.x*dq.real.z, yz = r.y*dq.real.z, @@ -803,138 +634,104 @@ struct matrix4x3 d = vec(-(dq.dual.w*r.x - dq.dual.x*r.w + dq.dual.y*r.z - dq.dual.z*r.y), -(dq.dual.w*r.y - dq.dual.x*r.z - dq.dual.y*r.w + dq.dual.z*r.x), -(dq.dual.w*r.z + dq.dual.x*r.y - dq.dual.y*r.x - dq.dual.z*r.w)); - } explicit matrix4x3(const matrix4 &m); - - void mul(float k) - { + void mul(float k) { a.mul(k); b.mul(k); c.mul(k); d.mul(k); } - void setscale(float x, float y, float z) { a.x = x; b.y = y; c.z = z; } void setscale(const vec &v) { setscale(v.x, v.y, v.z); } void setscale(float n) { setscale(n, n, n); } - - void scale(float x, float y, float z) - { + void scale(float x, float y, float z) { a.mul(x); b.mul(y); c.mul(z); } void scale(const vec &v) { scale(v.x, v.y, v.z); } void scale(float n) { scale(n, n, n); } - void settranslation(const vec &p) { d = p; } void settranslation(float x, float y, float z) { d = vec(x, y, z); } - void translate(const vec &p) { d.madd(a, p.x).madd(b, p.y).madd(c, p.z); } void translate(float x, float y, float z) { translate(vec(x, y, z)); } void translate(const vec &p, float scale) { translate(vec(p).mul(scale)); } - void posttranslate(const vec &p) { d.add(p); } void posttranslate(float x, float y, float z) { posttranslate(vec(x, y, z)); } void posttranslate(const vec &p, float scale) { d.madd(p, scale); } - - void accumulate(const matrix4x3 &m, float k) - { + void accumulate(const matrix4x3 &m, float k) { a.madd(m.a, k); b.madd(m.b, k); c.madd(m.c, k); d.madd(m.d, k); } - - void normalize() - { + void normalize() { a.normalize(); b.normalize(); c.normalize(); } - - void lerp(const matrix4x3 &to, float t) - { + void lerp(const matrix4x3 &to, float t) { a.lerp(to.a, t); b.lerp(to.b, t); c.lerp(to.c, t); d.lerp(to.d, t); } - void lerp(const matrix4x3 &from, const matrix4x3 &to, float t) - { + void lerp(const matrix4x3 &from, const matrix4x3 &to, float t) { a.lerp(from.a, to.a, t); b.lerp(from.b, to.b, t); c.lerp(from.c, to.c, t); d.lerp(from.d, to.d, t); } - - void identity() - { + void identity() { a = vec(1, 0, 0); b = vec(0, 1, 0); c = vec(0, 0, 1); d = vec(0, 0, 0); } - - void mul(const matrix4x3 &m, const matrix4x3 &n) - { + void mul(const matrix4x3 &m, const matrix4x3 &n) { a = vec(m.a).mul(n.a.x).madd(m.b, n.a.y).madd(m.c, n.a.z); b = vec(m.a).mul(n.b.x).madd(m.b, n.b.y).madd(m.c, n.b.z); c = vec(m.a).mul(n.c.x).madd(m.b, n.c.y).madd(m.c, n.c.z); d = vec(m.d).madd(m.a, n.d.x).madd(m.b, n.d.y).madd(m.c, n.d.z); } void mul(const matrix4x3 &n) { mul(matrix4x3(*this), n); } - - void mul(const matrix3 &m, const matrix4x3 &n) - { + void mul(const matrix3 &m, const matrix4x3 &n) { a = vec(m.a).mul(n.a.x).madd(m.b, n.a.y).madd(m.c, n.a.z); b = vec(m.a).mul(n.b.x).madd(m.b, n.b.y).madd(m.c, n.b.z); c = vec(m.a).mul(n.c.x).madd(m.b, n.c.y).madd(m.c, n.c.z); d = vec(m.a).mul(n.d.x).madd(m.b, n.d.y).madd(m.c, n.d.z); } - - void mul(const matrix3 &rot, const vec &trans, const matrix4x3 &n) - { + void mul(const matrix3 &rot, const vec &trans, const matrix4x3 &n) { mul(rot, n); d.add(trans); } - - void transpose() - { + void transpose() { d = vec(a.dot(d), b.dot(d), c.dot(d)).neg(); swap(a.y, b.x); swap(a.z, c.x); swap(b.z, c.y); } - - void transpose(const matrix4x3 &o) - { + void transpose(const matrix4x3 &o) { a = vec(o.a.x, o.b.x, o.c.x); b = vec(o.a.y, o.b.y, o.c.y); c = vec(o.a.z, o.b.z, o.c.z); d = vec(o.a.dot(o.d), o.b.dot(o.d), o.c.dot(o.d)).neg(); } - - void transposemul(const matrix4x3 &m, const matrix4x3 &n) - { + void transposemul(const matrix4x3 &m, const matrix4x3 &n) { vec t(m.a.dot(m.d), m.b.dot(m.d), m.c.dot(m.d)); a = vec(m.a.dot(n.a), m.b.dot(n.a), m.c.dot(n.a)); b = vec(m.a.dot(n.b), m.b.dot(n.b), m.c.dot(n.b)); c = vec(m.a.dot(n.c), m.b.dot(n.c), m.c.dot(n.c)); d = vec(m.a.dot(n.d), m.b.dot(n.d), m.c.dot(n.d)).sub(t); } - - void multranspose(const matrix4x3 &m, const matrix4x3 &n) - { + void multranspose(const matrix4x3 &m, const matrix4x3 &n) { vec t(n.a.dot(n.d), n.b.dot(n.d), n.c.dot(n.d)); a = vec(m.a).mul(n.a.x).madd(m.b, n.b.x).madd(m.c, n.c.x); b = vec(m.a).mul(n.a.y).madd(m.b, n.b.y).madd(m.c, n.c.y); c = vec(m.a).mul(n.a.z).madd(m.b, n.b.z).madd(m.c, n.c.z); d = vec(m.d).msub(m.a, t.x).msub(m.b, t.y).msub(m.c, t.z); } - - void invert(const matrix4x3 &o) - { + void invert(const matrix4x3 &o) { vec unscale(1/o.a.squaredlen(), 1/o.b.squaredlen(), 1/o.c.squaredlen()); transpose(o); a.mul(unscale); @@ -943,21 +740,15 @@ struct matrix4x3 d.mul(unscale); } void invert() { invert(matrix4x3(*this)); } - - void rotate(float angle, const vec &d) - { + void rotate(float angle, const vec &d) { rotate(cosf(angle), sinf(angle), d); } - - void rotate(float ck, float sk, const vec &axis) - { + void rotate(float ck, float sk, const vec &axis) { matrix3 m; m.rotate(ck, sk, axis); *this = matrix4x3(m, vec(0, 0, 0)); } - - void rotate_around_x(float ck, float sk) - { + void rotate_around_x(float ck, float sk) { vec rb = vec(b).mul(ck).madd(c, sk), rc = vec(c).mul(ck).msub(b, sk); b = rb; @@ -965,9 +756,7 @@ struct matrix4x3 } void rotate_around_x(float angle) { rotate_around_x(cosf(angle), sinf(angle)); } void rotate_around_x(const vec2 &sc) { rotate_around_x(sc.x, sc.y); } - - void rotate_around_y(float ck, float sk) - { + void rotate_around_y(float ck, float sk) { vec rc = vec(c).mul(ck).madd(a, sk), ra = vec(a).mul(ck).msub(c, sk); c = rc; @@ -975,9 +764,7 @@ struct matrix4x3 } void rotate_around_y(float angle) { rotate_around_y(cosf(angle), sinf(angle)); } void rotate_around_y(const vec2 &sc) { rotate_around_y(sc.x, sc.y); } - - void rotate_around_z(float ck, float sk) - { + void rotate_around_z(float ck, float sk) { vec ra = vec(a).mul(ck).madd(b, sk), rb = vec(b).mul(ck).msub(a, sk); a = ra; @@ -985,20 +772,17 @@ struct matrix4x3 } void rotate_around_z(float angle) { rotate_around_z(cosf(angle), sinf(angle)); } void rotate_around_z(const vec2 &sc) { rotate_around_z(sc.x, sc.y); } - vec transform(const vec &o) const { return vec(d).madd(a, o.x).madd(b, o.y).madd(c, o.z); } vec transposedtransform(const vec &o) const { vec p = vec(o).sub(d); return vec(a.dot(p), b.dot(p), c.dot(p)); } vec transformnormal(const vec &o) const { return vec(a).mul(o.x).madd(b, o.y).madd(c, o.z); } vec transposedtransformnormal(const vec &o) const { return vec(a.dot(o), b.dot(o), c.dot(o)); } vec transform(const vec2 &o) const { return vec(d).madd(a, o.x).madd(b, o.y); } - vec4 rowx() const { return vec4(a.x, b.x, c.x, d.x); } vec4 rowy() const { return vec4(a.y, b.y, c.y, d.y); } vec4 rowz() const { return vec4(a.z, b.z, c.z, d.z); } }; -inline dualquat::dualquat(const matrix4x3 &m) : real(m) -{ +inline dualquat::dualquat(const matrix4x3 &m) : real(m) { dual.x = 0.5f*( m.d.x*real.w + m.d.y*real.z - m.d.z*real.y); dual.y = 0.5f*(-m.d.x*real.z + m.d.y*real.w + m.d.z*real.x); dual.z = 0.5f*( m.d.x*real.y - m.d.y*real.x + m.d.z*real.w); @@ -1007,34 +791,26 @@ inline dualquat::dualquat(const matrix4x3 &m) : real(m) inline matrix3::matrix3(const matrix4x3 &m) : a(m.a), b(m.b), c(m.c) {} -struct plane : vec -{ +struct plane : vec { float offset; - float dist(const vec &p) const { return dot(p)+offset; } float dist(const vec4 &p) const { return p.dot3(*this) + p.w*offset; } bool operator==(const plane &p) const { return x==p.x && y==p.y && z==p.z && offset==p.offset; } bool operator!=(const plane &p) const { return x!=p.x || y!=p.y || z!=p.z || offset!=p.offset; } - plane() {} plane(const vec &c, float off) : vec(c), offset(off) {} plane(const vec4 &p) : vec(p), offset(p.w) {} - plane(int d, float off) - { + plane(int d, float off) { x = y = z = 0.0f; v[d] = 1.0f; offset = -off; } plane(float a, float b, float c, float d) : vec(a, b, c), offset(d) {} - - void toplane(const vec &n, const vec &p) - { + void toplane(const vec &n, const vec &p) { x = n.x; y = n.y; z = n.z; offset = -dot(p); } - - bool toplane(const vec &a, const vec &b, const vec &c) - { + bool toplane(const vec &a, const vec &b, const vec &c) { cross(vec(b).sub(a), vec(c).sub(a)); float mag = magnitude(); if(!mag) return false; @@ -1042,65 +818,48 @@ struct plane : vec offset = -dot(a); return true; } - - bool rayintersect(const vec &o, const vec &ray, float &dist) - { + bool rayintersect(const vec &o, const vec &ray, float &dist) { float cosalpha = dot(ray); if(cosalpha==0) return false; float deltac = offset+dot(o); dist -= deltac/cosalpha; return true; } - - plane &reflectz(float rz) - { + plane &reflectz(float rz) { offset += 2*rz*z; z = -z; return *this; } - - plane &invert() - { + plane &invert() { neg(); offset = -offset; return *this; } - - plane &scale(float k) - { + plane &scale(float k) { mul(k); return *this; } - - plane &translate(const vec &p) - { + plane &translate(const vec &p) { offset += dot(p); return *this; } - - plane &normalize() - { + plane &normalize() { float mag = magnitude(); div(mag); offset /= mag; return *this; } - float zintersect(const vec &p) const { return -(x*p.x+y*p.y+offset)/z; } float zdelta(const vec &p) const { return -(x*p.x+y*p.y)/z; } float zdist(const vec &p) const { return p.z-zintersect(p); } }; -struct triangle -{ +struct triangle { vec a, b, c; - triangle(const vec &a, const vec &b, const vec &c) : a(a), b(b), c(c) {} triangle() {} - triangle &add(const vec &o) { a.add(o); b.add(o); c.add(o); return *this; } triangle &sub(const vec &o) { a.sub(o); b.sub(o); c.sub(o); return *this; } - bool operator==(const triangle &t) const { return a == t.a && b == t.b && c == t.c; } }; @@ -1131,20 +890,16 @@ struct ivec2; struct usvec; struct svec; -struct ivec -{ - union - { +struct ivec { + union { struct { int x, y, z; }; struct { int r, g, b; }; int v[3]; }; - ivec() {} explicit ivec(const vec &v) : x(int(v.x)), y(int(v.y)), z(int(v.z)) {} ivec(int a, int b, int c) : x(a), y(b), z(c) {} - ivec(int d, int row, int col, int depth) - { + ivec(int d, int row, int col, int depth) { v[R[d]] = row; v[C[d]] = col; v[D[d]] = depth; @@ -1154,10 +909,8 @@ struct ivec explicit ivec(const ivec2 &v, int z = 0); explicit ivec(const usvec &v); explicit ivec(const svec &v); - - int &operator[](int i) { return v[i]; } + int &operator[](int i) { return v[i]; } int operator[](int i) const { return v[i]; } - //int idx(int i) { return v[i]; } bool operator==(const ivec &v) const { return x==v.x && y==v.y && z==v.z; } bool operator!=(const ivec &v) const { return x!=v.x || y!=v.y || z!=v.z; } @@ -1183,42 +936,33 @@ struct ivec ivec &cross(const ivec &a, const ivec &b) { x = a.y*b.z-a.z*b.y; y = a.z*b.x-a.x*b.z; z = a.x*b.y-a.y*b.x; return *this; } int dot(const ivec &o) const { return x*o.x + y*o.y + z*o.z; } float dist(const plane &p) const { return x*p.x + y*p.y + z*p.z + p.offset; } - static inline ivec floor(const vec &o) { return ivec(int(::floor(o.x)), int(::floor(o.y)), int(::floor(o.z))); } static inline ivec ceil(const vec &o) { return ivec(int(::ceil(o.x)), int(::ceil(o.y)), int(::ceil(o.z))); } }; inline vec::vec(const ivec &v) : x(v.x), y(v.y), z(v.z) {} -static inline bool htcmp(const ivec &x, const ivec &y) -{ +static inline bool htcmp(const ivec &x, const ivec &y) { return x == y; } -static inline uint hthash(const ivec &k) -{ +static inline uint hthash(const ivec &k) { return k.x^k.y^k.z; } -struct ivec2 -{ - union - { +struct ivec2 { + union { struct { int x, y; }; int v[2]; }; - ivec2() {} ivec2(int x, int y) : x(x), y(y) {} explicit ivec2(const vec2 &v) : x(int(v.x)), y(int(v.y)) {} explicit ivec2(const ivec &v) : x(v.x), y(v.y) {} - - int &operator[](int i) { return v[i]; } + int &operator[](int i) { return v[i]; } int operator[](int i) const { return v[i]; } - bool operator==(const ivec2 &o) const { return x == o.x && y == o.y; } bool operator!=(const ivec2 &o) const { return x != o.x || y != o.y; } - bool iszero() const { return x==0 && y==0; } ivec2 &shl(int n) { x<<= n; y<<= n; return *this; } ivec2 &shr(int n) { x>>= n; y>>= n; return *this; } @@ -1243,74 +987,57 @@ struct ivec2 inline ivec::ivec(const ivec2 &v, int z) : x(v.x), y(v.y), z(z) {} -static inline bool htcmp(const ivec2 &x, const ivec2 &y) -{ +static inline bool htcmp(const ivec2 &x, const ivec2 &y) { return x == y; } -static inline uint hthash(const ivec2 &k) -{ +static inline uint hthash(const ivec2 &k) { return k.x^k.y; } -struct ivec4 -{ - union - { +struct ivec4 { + union { struct { int x, y, z, w; }; struct { int r, g, b, a; }; int v[4]; }; - ivec4() {} explicit ivec4(const ivec &p, int w = 0) : x(p.x), y(p.y), z(p.z), w(w) {} ivec4(int x, int y, int z, int w) : x(x), y(y), z(z), w(w) {} explicit ivec4(const vec4 &v) : x(int(v.x)), y(int(v.y)), z(int(v.z)), w(int(v.w)) {} - bool operator==(const ivec4 &o) const { return x == o.x && y == o.y && z == o.z && w == o.w; } bool operator!=(const ivec4 &o) const { return x != o.x || y != o.y || z != o.z || w != o.w; } }; inline ivec::ivec(const ivec4 &v) : x(v.x), y(v.y), z(v.z) {} -static inline bool htcmp(const ivec4 &x, const ivec4 &y) -{ +static inline bool htcmp(const ivec4 &x, const ivec4 &y) { return x == y; } -static inline uint hthash(const ivec4 &k) -{ +static inline uint hthash(const ivec4 &k) { return k.x^k.y^k.z^k.w; } struct bvec4; -struct bvec -{ - union - { +struct bvec { + union { struct { uchar x, y, z; }; struct { uchar r, g, b; }; uchar v[3]; }; - bvec() {} bvec(uchar x, uchar y, uchar z) : x(x), y(y), z(z) {} explicit bvec(const vec &v) : x(uchar((v.x+1)*(255.0f/2.0f))), y(uchar((v.y+1)*(255.0f/2.0f))), z(uchar((v.z+1)*(255.0f/2.0f))) {} explicit bvec(const bvec4 &v); - - uchar &operator[](int i) { return v[i]; } + uchar &operator[](int i) { return v[i]; } uchar operator[](int i) const { return v[i]; } - bool operator==(const bvec &v) const { return x==v.x && y==v.y && z==v.z; } bool operator!=(const bvec &v) const { return x!=v.x || y!=v.y || z!=v.z; } - bool iszero() const { return x==0 && y==0 && z==0; } - vec tonormal() const { return vec(x*(2.0f/255.0f)-1.0f, y*(2.0f/255.0f)-1.0f, z*(2.0f/255.0f)-1.0f); } - - bvec &normalize() - { + bvec &normalize() { vec n(x-127.5f, y-127.5f, z-127.5f); float mag = 127.5f/n.magnitude(); x = uchar(n.x*mag+127.5f); @@ -1318,193 +1045,144 @@ struct bvec z = uchar(n.z*mag+127.5f); return *this; } - void lerp(const bvec &a, const bvec &b, float t) { x = uchar(a.x + (b.x-a.x)*t); y = uchar(a.y + (b.y-a.y)*t); z = uchar(a.z + (b.z-a.z)*t); } - - void lerp(const bvec &a, const bvec &b, int ka, int kb, int d) - { + void lerp(const bvec &a, const bvec &b, int ka, int kb, int d) { x = uchar((a.x*ka + b.x*kb)/d); y = uchar((a.y*ka + b.y*kb)/d); z = uchar((a.z*ka + b.z*kb)/d); } - void flip() { x ^= 0x80; y ^= 0x80; z ^= 0x80; } - void scale(int k, int d) { x = uchar((x*k)/d); y = uchar((y*k)/d); z = uchar((z*k)/d); } - bvec &shl(int n) { x<<= n; y<<= n; z<<= n; return *this; } bvec &shr(int n) { x>>= n; y>>= n; z>>= n; return *this; } - static bvec fromcolor(const vec &v) { return bvec(uchar(v.x*255.0f), uchar(v.y*255.0f), uchar(v.z*255.0f)); } vec tocolor() const { return vec(x*(1.0f/255.0f), y*(1.0f/255.0f), z*(1.0f/255.0f)); } - static bvec from565(ushort c) { return bvec((((c>>11)&0x1F)*527 + 15) >> 6, (((c>>5)&0x3F)*259 + 35) >> 6, ((c&0x1F)*527 + 15) >> 6); } - - static bvec hexcolor(int color) - { + static bvec hexcolor(int color) { return bvec((color>>16)&0xFF, (color>>8)&0xFF, color&0xFF); } int tohexcolor() const { return (int(r)<<16)|(int(g)<<8)|int(b); } }; -struct bvec4 -{ - union - { +struct bvec4 { + union { struct { uchar x, y, z, w; }; struct { uchar r, g, b, a; }; uchar v[4]; uint mask; }; - bvec4() {} bvec4(uchar x, uchar y, uchar z, uchar w = 0) : x(x), y(y), z(z), w(w) {} bvec4(const bvec &v, uchar w = 0) : x(v.x), y(v.y), z(v.z), w(w) {} - - uchar &operator[](int i) { return v[i]; } + uchar &operator[](int i) { return v[i]; } uchar operator[](int i) const { return v[i]; } - bool operator==(const bvec4 &v) const { return mask==v.mask; } bool operator!=(const bvec4 &v) const { return mask!=v.mask; } - bool iszero() const { return mask==0; } - vec tonormal() const { return vec(x*(2.0f/255.0f)-1.0f, y*(2.0f/255.0f)-1.0f, z*(2.0f/255.0f)-1.0f); } - - void lerp(const bvec4 &a, const bvec4 &b, float t) - { + void lerp(const bvec4 &a, const bvec4 &b, float t) { x = uchar(a.x + (b.x-a.x)*t); y = uchar(a.y + (b.y-a.y)*t); z = uchar(a.z + (b.z-a.z)*t); w = a.w; } - - void lerp(const bvec4 &a, const bvec4 &b, int ka, int kb, int d) - { + void lerp(const bvec4 &a, const bvec4 &b, int ka, int kb, int d) { x = uchar((a.x*ka + b.x*kb)/d); y = uchar((a.y*ka + b.y*kb)/d); z = uchar((a.z*ka + b.z*kb)/d); w = a.w; } - void flip() { mask ^= 0x80808080; } }; inline bvec::bvec(const bvec4 &v) : x(v.x), y(v.y), z(v.z) {} -struct usvec -{ - union - { +struct usvec { + union { struct { ushort x, y, z; }; ushort v[3]; }; - ushort &operator[](int i) { return v[i]; } ushort operator[](int i) const { return v[i]; } }; inline ivec::ivec(const usvec &v) : x(v.x), y(v.y), z(v.z) {} -struct svec -{ - union - { +struct svec { + union { struct { short x, y, z; }; short v[3]; }; - svec() {} svec(short x, short y, short z) : x(x), y(y), z(z) {} explicit svec(const ivec &v) : x(v.x), y(v.y), z(v.z) {} - short &operator[](int i) { return v[i]; } short operator[](int i) const { return v[i]; } }; inline ivec::ivec(const svec &v) : x(v.x), y(v.y), z(v.z) {} -struct svec2 -{ - union - { +struct svec2 { + union { struct { short x, y; }; short v[2]; }; - svec2() {} svec2(short x, short y) : x(x), y(y) {} - short &operator[](int i) { return v[i]; } short operator[](int i) const { return v[i]; } - bool operator==(const svec2 &o) const { return x == o.x && y == o.y; } bool operator!=(const svec2 &o) const { return x != o.x || y != o.y; } - bool iszero() const { return x==0 && y==0; } }; -struct dvec4 -{ +struct dvec4 { double x, y, z, w; - dvec4() {} dvec4(double x, double y, double z, double w) : x(x), y(y), z(z), w(w) {} dvec4(const vec4 &v) : x(v.x), y(v.y), z(v.z), w(v.w) {} - template dvec4 &madd(const dvec4 &a, const B &b) { return add(dvec4(a).mul(b)); } - dvec4 &mul(double f) { x *= f; y *= f; z *= f; w *= f; return *this; } + dvec4 &mul(double f) { x *= f; y *= f; z *= f; w *= f; return *this; } dvec4 &mul(const dvec4 &o) { x *= o.x; y *= o.y; z *= o.z; w *= o.w; return *this; } - dvec4 &add(double f) { x += f; y += f; z += f; w += f; return *this; } + dvec4 &add(double f) { x += f; y += f; z += f; w += f; return *this; } dvec4 &add(const dvec4 &o) { x += o.x; y += o.y; z += o.z; w += o.w; return *this; } - operator vec4() const { return vec4(x, y, z, w); } }; -struct matrix4 -{ +struct matrix4 { vec4 a, b, c, d; - matrix4() {} matrix4(const float *m) : a(m), b(m+4), c(m+8), d(m+12) {} matrix4(const vec &a, const vec &b, const vec &c = vec(0, 0, 1)) - : a(a.x, b.x, c.x, 0), b(a.y, b.y, c.y, 0), c(a.z, b.z, c.z, 0), d(0, 0, 0, 1) - {} + : a(a.x, b.x, c.x, 0), b(a.y, b.y, c.y, 0), c(a.z, b.z, c.z, 0), d(0, 0, 0, 1) { + } matrix4(const vec4 &a, const vec4 &b, const vec4 &c, const vec4 &d = vec4(0, 0, 0, 1)) - : a(a), b(b), c(c), d(d) - {} + : a(a), b(b), c(c), d(d) { + } matrix4(const matrix4x3 &m) - : a(m.a, 0), b(m.b, 0), c(m.c, 0), d(m.d, 1) - {} + : a(m.a, 0), b(m.b, 0), c(m.c, 0), d(m.d, 1) { + } matrix4(const matrix3 &rot, const vec &trans) - : a(rot.a, 0), b(rot.b, 0), c(rot.c, 0), d(trans, 1) - {} - - void mul(const matrix4 &x, const matrix3 &y) - { + : a(rot.a, 0), b(rot.b, 0), c(rot.c, 0), d(trans, 1) { + } + void mul(const matrix4 &x, const matrix3 &y) { a = vec4(x.a).mul(y.a.x).madd(x.b, y.a.y).madd(x.c, y.a.z); b = vec4(x.a).mul(y.b.x).madd(x.b, y.b.y).madd(x.c, y.b.z); c = vec4(x.a).mul(y.c.x).madd(x.b, y.c.y).madd(x.c, y.c.z); d = x.d; } void mul(const matrix3 &y) { mul(matrix4(*this), y); } - - template void mult(const matrix4 &x, const matrix4 &y) - { + template void mult(const matrix4 &x, const matrix4 &y) { a = T(x.a).mul(y.a.x).madd(x.b, y.a.y).madd(x.c, y.a.z).madd(x.d, y.a.w); b = T(x.a).mul(y.b.x).madd(x.b, y.b.y).madd(x.c, y.b.z).madd(x.d, y.b.w); c = T(x.a).mul(y.c.x).madd(x.b, y.c.y).madd(x.c, y.c.z).madd(x.d, y.c.w); d = T(x.a).mul(y.d.x).madd(x.b, y.d.y).madd(x.c, y.d.z).madd(x.d, y.d.w); } - void mul(const matrix4 &x, const matrix4 &y) { mult(x, y); } void mul(const matrix4 &y) { mult(matrix4(*this), y); } - void muld(const matrix4 &x, const matrix4 &y) { mult(x, y); } void muld(const matrix4 &y) { mult(matrix4(*this), y); } - - void rotate_around_x(float ck, float sk) - { + void rotate_around_x(float ck, float sk) { vec4 rb = vec4(b).mul(ck).madd(c, sk), rc = vec4(c).mul(ck).msub(b, sk); b = rb; @@ -1512,9 +1190,7 @@ struct matrix4 } void rotate_around_x(float angle) { rotate_around_x(cosf(angle), sinf(angle)); } void rotate_around_x(const vec2 &sc) { rotate_around_x(sc.x, sc.y); } - - void rotate_around_y(float ck, float sk) - { + void rotate_around_y(float ck, float sk) { vec4 rc = vec4(c).mul(ck).madd(a, sk), ra = vec4(a).mul(ck).msub(c, sk); c = rc; @@ -1522,9 +1198,7 @@ struct matrix4 } void rotate_around_y(float angle) { rotate_around_y(cosf(angle), sinf(angle)); } void rotate_around_y(const vec2 &sc) { rotate_around_y(sc.x, sc.y); } - - void rotate_around_z(float ck, float sk) - { + void rotate_around_z(float ck, float sk) { vec4 ra = vec4(a).mul(ck).madd(b, sk), rb = vec4(b).mul(ck).msub(a, sk); a = ra; @@ -1532,68 +1206,51 @@ struct matrix4 } void rotate_around_z(float angle) { rotate_around_z(cosf(angle), sinf(angle)); } void rotate_around_z(const vec2 &sc) { rotate_around_z(sc.x, sc.y); } - - void rotate(float ck, float sk, const vec &axis) - { + void rotate(float ck, float sk, const vec &axis) { matrix3 m; m.rotate(ck, sk, axis); mul(m); } void rotate(float angle, const vec &dir) { rotate(cosf(angle), sinf(angle), dir); } void rotate(const vec2 &sc, const vec &dir) { rotate(sc.x, sc.y, dir); } - - void identity() - { + void identity() { a = vec4(1, 0, 0, 0); b = vec4(0, 1, 0, 0); c = vec4(0, 0, 1, 0); d = vec4(0, 0, 0, 1); } - void settranslation(const vec &v) { d.setxyz(v); } void settranslation(float x, float y, float z) { d.x = x; d.y = y; d.z = z; } - void translate(const vec &p) { d.madd(a, p.x).madd(b, p.y).madd(c, p.z); } void translate(float x, float y, float z) { translate(vec(x, y, z)); } void translate(const vec &p, float scale) { translate(vec(p).mul(scale)); } - void setscale(float x, float y, float z) { a.x = x; b.y = y; c.z = z; } void setscale(const vec &v) { setscale(v.x, v.y, v.z); } void setscale(float n) { setscale(n, n, n); } - - void scale(float x, float y, float z) - { + void scale(float x, float y, float z) { a.mul(x); b.mul(y); c.mul(z); } void scale(const vec &v) { scale(v.x, v.y, v.z); } void scale(float n) { scale(n, n, n); } - - void scalexy(float x, float y) - { + void scalexy(float x, float y) { a.x *= x; a.y *= y; b.x *= x; b.y *= y; c.x *= x; c.y *= y; d.x *= x; d.y *= y; } - - void scalez(float k) - { + void scalez(float k) { a.z *= k; b.z *= k; c.z *= k; d.z *= k; } - - void reflectz(float z) - { + void reflectz(float z) { d.add(vec4(c).mul(2*z)); c.neg(); } - - void projective(float zscale = 0.5f, float zoffset = 0.5f) - { + void projective(float zscale = 0.5f, float zoffset = 0.5f) { a.x = 0.5f*(a.x + a.w); a.y = 0.5f*(a.y + a.w); b.x = 0.5f*(b.x + b.w); @@ -1607,9 +1264,7 @@ struct matrix4 c.z = zscale*c.z + zoffset*c.w; d.z = zscale*d.z + zoffset*d.w; } - - void jitter(float x, float y) - { + void jitter(float x, float y) { a.x += x * a.w; a.y += y * a.w; b.x += x * b.w; @@ -1619,48 +1274,36 @@ struct matrix4 d.x += x * d.w; d.y += y * d.w; } - - void transpose() - { + void transpose() { swap(a.y, b.x); swap(a.z, c.x); swap(a.w, d.x); swap(b.z, c.y); swap(b.w, d.y); swap(c.w, d.z); } - - void transpose(const matrix4 &m) - { + void transpose(const matrix4 &m) { a = vec4(m.a.x, m.b.x, m.c.x, m.d.x); b = vec4(m.a.y, m.b.y, m.c.y, m.d.y); c = vec4(m.a.z, m.b.z, m.c.z, m.d.z); d = vec4(m.a.w, m.b.w, m.c.w, m.d.w); } - - void frustum(float left, float right, float bottom, float top, float znear, float zfar) - { + void frustum(float left, float right, float bottom, float top, float znear, float zfar) { float width = right - left, height = top - bottom, zrange = znear - zfar; a = vec4(2*znear/width, 0, 0, 0); b = vec4(0, 2*znear/height, 0, 0); c = vec4((right + left)/width, (top + bottom)/height, (zfar + znear)/zrange, -1); d = vec4(0, 0, 2*znear*zfar/zrange, 0); } - - void perspective(float fovy, float aspect, float znear, float zfar) - { + void perspective(float fovy, float aspect, float znear, float zfar) { float ydist = znear * tan(fovy/2*RAD), xdist = ydist * aspect; frustum(-xdist, xdist, -ydist, ydist, znear, zfar); } - - void ortho(float left, float right, float bottom, float top, float znear, float zfar) - { + void ortho(float left, float right, float bottom, float top, float znear, float zfar) { float width = right - left, height = top - bottom, zrange = znear - zfar; a = vec4(2/width, 0, 0, 0); b = vec4(0, 2/height, 0, 0); c = vec4(0, 0, 2/zrange, 0); d = vec4(-(right+left)/width, -(top+bottom)/height, (zfar+znear)/zrange, 1); } - - void clip(const plane &p, const matrix4 &m) - { + void clip(const plane &p, const matrix4 &m) { float x = ((p.x<0 ? -1 : (p.x>0 ? 1 : 0)) + m.c.x) / m.a.x, y = ((p.y<0 ? -1 : (p.y>0 ? 1 : 0)) + m.c.y) / m.b.y, w = (1 + m.c.z) / m.d.z, @@ -1670,134 +1313,96 @@ struct matrix4 c = vec4(m.c.x, m.c.y, p.z*scale + 1.0f, m.c.w); d = vec4(m.d.x, m.d.y, p.offset*scale, m.d.w); } - - void transform(const vec &in, vec &out) const - { + void transform(const vec &in, vec &out) const { out = vec(a).mul(in.x).add(vec(b).mul(in.y)).add(vec(c).mul(in.z)).add(vec(d)); } - - void transform(const vec4 &in, vec &out) const - { + void transform(const vec4 &in, vec &out) const { out = vec(a).mul(in.x).add(vec(b).mul(in.y)).add(vec(c).mul(in.z)).add(vec(d).mul(in.w)); } - - void transform(const vec &in, vec4 &out) const - { + void transform(const vec &in, vec4 &out) const { out = vec4(a).mul(in.x).madd(b, in.y).madd(c, in.z).add(d); } - - void transform(const vec4 &in, vec4 &out) const - { + void transform(const vec4 &in, vec4 &out) const { out = vec4(a).mul(in.x).madd(b, in.y).madd(c, in.z).madd(d, in.w); } - - template T transform(const U &in) const - { + template T transform(const U &in) const { T v; transform(in, v); return v; } - - template vec perspectivetransform(const T &in) const - { + template vec perspectivetransform(const T &in) const { vec4 v; transform(in, v); return vec(v).div(v.w); } - - void transformnormal(const vec &in, vec &out) const - { + void transformnormal(const vec &in, vec &out) const { out = vec(a).mul(in.x).add(vec(b).mul(in.y)).add(vec(c).mul(in.z)); } - - void transformnormal(const vec &in, vec4 &out) const - { + void transformnormal(const vec &in, vec4 &out) const { out = vec4(a).mul(in.x).madd(b, in.y).madd(c, in.z); } - - template T transformnormal(const U &in) const - { + template T transformnormal(const U &in) const { T v; transformnormal(in, v); return v; } - - void transposedtransform(const vec &in, vec &out) const - { + void transposedtransform(const vec &in, vec &out) const { vec p = vec(in).sub(vec(d)); out.x = a.dot3(p); out.y = b.dot3(p); out.z = c.dot3(p); } - - void transposedtransformnormal(const vec &in, vec &out) const - { + void transposedtransformnormal(const vec &in, vec &out) const { out.x = a.dot3(in); out.y = b.dot3(in); out.z = c.dot3(in); } - - void transposedtransform(const plane &in, plane &out) const - { + void transposedtransform(const plane &in, plane &out) const { out.x = in.dist(a); out.y = in.dist(b); out.z = in.dist(c); out.offset = in.dist(d); } - - float getscale() const - { + float getscale() const { return sqrtf(a.x*a.y + b.x*b.x + c.x*c.x); } - - vec gettranslation() const - { + vec gettranslation() const { return vec(d); } - vec4 rowx() const { return vec4(a.x, b.x, c.x, d.x); } vec4 rowy() const { return vec4(a.y, b.y, c.y, d.y); } vec4 rowz() const { return vec4(a.z, b.z, c.z, d.z); } vec4 roww() const { return vec4(a.w, b.w, c.w, d.w); } - bool invert(const matrix4 &m, double mindet = 1.0e-12); }; inline matrix3::matrix3(const matrix4 &m) - : a(m.a), b(m.b), c(m.c) -{} + : a(m.a), b(m.b), c(m.c) { +} inline matrix4x3::matrix4x3(const matrix4 &m) - : a(m.a), b(m.b), c(m.c), d(m.d) -{} + : a(m.a), b(m.b), c(m.c), d(m.d) { +} -struct matrix2 -{ +struct matrix2 { vec2 a, b; - matrix2() {} matrix2(const vec2 &a, const vec2 &b) : a(a), b(b) {} explicit matrix2(const matrix4 &m) : a(m.a), b(m.b) {} explicit matrix2(const matrix3 &m) : a(m.a), b(m.b) {} }; -struct squat -{ +struct squat { short x, y, z, w; - squat() {} squat(const vec4 &q) { convert(q); } - - void convert(const vec4 &q) - { + void convert(const vec4 &q) { x = short(q.x*32767.5f-0.5f); y = short(q.y*32767.5f-0.5f); z = short(q.z*32767.5f-0.5f); w = short(q.w*32767.5f-0.5f); } - - void lerp(const vec4 &a, const vec4 &b, float t) - { + void lerp(const vec4 &a, const vec4 &b, float t) { vec4 q; q.lerp(a, b, t); convert(q); @@ -1809,8 +1414,7 @@ extern bool rayboxintersect(const vec &b, const vec &s, const vec &o, const vec extern bool linecylinderintersect(const vec &from, const vec &to, const vec &start, const vec &end, float radius, float &dist); extern const vec2 sincos360[]; -static inline int mod360(int angle) -{ +static inline int mod360(int angle) { if(angle < 0) angle = 360 + (angle <= -360 ? angle%360 : angle); else if(angle >= 360) angle %= 360; return angle; diff --git a/src/shared/glemu.cpp b/src/shared/glemu.cpp index 58e071d..c728b9f 100644 --- a/src/shared/glemu.cpp +++ b/src/shared/glemu.cpp @@ -3,25 +3,18 @@ extern int glversion; extern int intel_mapbufferrange_bug; -namespace gle -{ - struct attribinfo - { +namespace gle { + struct attribinfo { int type, size, formatsize, offset; GLenum format; - attribinfo() : type(0), size(0), formatsize(0), offset(0), format(GL_FALSE) {} - - bool operator==(const attribinfo &a) const - { + bool operator==(const attribinfo &a) const { return type == a.type && size == a.size && format == a.format && offset == a.offset; } - bool operator!=(const attribinfo &a) const - { + bool operator!=(const attribinfo &a) const { return type != a.type || size != a.size || format != a.format || offset != a.offset; } }; - extern const char * const attribnames[MAXATTRIBS] = { "vvertex", "vcolor", "vtexcoord0", "vtexcoord1", "vnormal", "vtangent", "vboneweight", "vboneindex" }; ucharbuf attribbuf; static uchar *attribdata; @@ -33,33 +26,23 @@ namespace gle static bool changedattribs = false; static vector multidrawstart; static vector multidrawcount; - #define MAXQUADS (0x10000/4) static GLuint quadindexes = 0; static bool quadsenabled = false; - #define MAXVBOSIZE (4*1024*1024) static GLuint vbo = 0; static int vbooffset = MAXVBOSIZE; - static GLuint defaultvao = 0; - - void enablequads() - { + void enablequads() { quadsenabled = true; - if(glversion < 300) return; - - if(quadindexes) - { + if(quadindexes) { glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER, quadindexes); return; } - glGenBuffers_(1, &quadindexes); ushort *data = new ushort[MAXQUADS*6], *dst = data; - for(int idx = 0; idx < MAXQUADS*4; idx += 4, dst += 6) - { + for(int idx = 0; idx < MAXQUADS*4; idx += 4, dst += 6) { dst[0] = idx; dst[1] = idx + 1; dst[2] = idx + 2; @@ -71,36 +54,25 @@ namespace gle glBufferData_(GL_ELEMENT_ARRAY_BUFFER, MAXQUADS*6*sizeof(ushort), data, GL_STATIC_DRAW); delete[] data; } - - void disablequads() - { + void disablequads() { quadsenabled = false; - if(glversion < 300) return; - glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER, 0); } - - void drawquads(int offset, int count) - { + void drawquads(int offset, int count) { if(count <= 0) return; - if(glversion < 300) - { + if(glversion < 300) { glDrawArrays(GL_QUADS, offset*4, count*4); return; } - if(offset + count > MAXQUADS) - { + if(offset + count > MAXQUADS) { if(offset >= MAXQUADS) return; count = MAXQUADS - offset; } glDrawRangeElements_(GL_TRIANGLES, offset*4, (offset + count)*4-1, count*6, GL_UNSIGNED_SHORT, (ushort *)0 + offset*6); } - - void defattrib(int type, int size, int format) - { - if(type == ATTRIB_VERTEX) - { + void defattrib(int type, int size, int format) { + if(type == ATTRIB_VERTEX) { numattribs = attribmask = 0; vertexsize = 0; } @@ -110,8 +82,7 @@ namespace gle a.type = type; a.size = size; a.format = format; - switch(format) - { + switch(format) { case 'B': case GL_UNSIGNED_BYTE: a.formatsize = 1; a.format = GL_UNSIGNED_BYTE; break; case 'b': case GL_BYTE: a.formatsize = 1; a.format = GL_BYTE; break; case 'S': case GL_UNSIGNED_SHORT: a.formatsize = 2; a.format = GL_UNSIGNED_SHORT; break; @@ -126,14 +97,10 @@ namespace gle a.offset = vertexsize; vertexsize += a.formatsize; } - - void defattribs(const char *fmt) - { - for(;; fmt += 3) - { + void defattribs(const char *fmt) { + for(;; fmt += 3) { GLenum format; - switch(fmt[0]) - { + switch(fmt[0]) { case 'v': format = ATTRIB_VERTEX; break; case 'c': format = ATTRIB_COLOR; break; case 't': format = ATTRIB_TEXCOORD0; break; @@ -147,11 +114,8 @@ namespace gle defattrib(format, fmt[1]-'0', fmt[2]); } } - - static inline void setattrib(const attribinfo &a, uchar *buf) - { - switch(a.type) - { + static inline void setattrib(const attribinfo &a, uchar *buf) { + switch(a.type) { case ATTRIB_VERTEX: case ATTRIB_TEXCOORD0: case ATTRIB_TEXCOORD1: @@ -165,36 +129,27 @@ namespace gle glVertexAttribPointer_(a.type, a.size, a.format, GL_TRUE, vertexsize, buf); break; } - if(!(enabled&(1<= 300 && !intel_mapbufferrange_bug) - { + if(glversion >= 300 && !intel_mapbufferrange_bug) { int len = numverts * vertexsize; - if(vbooffset + len >= MAXVBOSIZE) - { + if(vbooffset + len >= MAXVBOSIZE) { len = min(len, MAXVBOSIZE); if(!vbo) glGenBuffers_(1, &vbo); glBindBuffer_(GL_ARRAY_BUFFER, vbo); @@ -232,37 +181,27 @@ namespace gle if(buf) attribbuf.reset((uchar *)buf, len); } } - - void multidraw() - { + void multidraw() { int start = multidrawstart.length() ? multidrawstart.last() + multidrawcount.last() : 0, count = attribbuf.length()/vertexsize - start; - if(count > 0) - { + if(count > 0) { multidrawstart.add(start); multidrawcount.add(count); } } - - int end() - { + int end() { uchar *buf = attribbuf.getbuf(); - if(attribbuf.empty()) - { - if(buf != attribdata) - { + if(attribbuf.empty()) { + if(buf != attribdata) { glUnmapBuffer_(GL_ARRAY_BUFFER); attribbuf.reset(attribdata, MAXVBOSIZE); } return 0; } int start = 0; - if(glversion >= 300) - { - if(buf == attribdata) - { - if(vbooffset + attribbuf.length() >= MAXVBOSIZE) - { + if(glversion >= 300) { + if(buf == attribdata) { + if(vbooffset + attribbuf.length() >= MAXVBOSIZE) { if(!vbo) glGenBuffers_(1, &vbo); glBindBuffer_(GL_ARRAY_BUFFER, vbo); glBufferData_(GL_ARRAY_BUFFER, MAXVBOSIZE, NULL, GL_STREAM_DRAW); @@ -271,8 +210,7 @@ namespace gle else if(!lastvertexsize) glBindBuffer_(GL_ARRAY_BUFFER, vbo); void *dst = intel_mapbufferrange_bug ? NULL : glMapBufferRange_(GL_ARRAY_BUFFER, vbooffset, attribbuf.length(), GL_MAP_WRITE_BIT|GL_MAP_INVALIDATE_RANGE_BIT|GL_MAP_UNSYNCHRONIZED_BIT); - if(dst) - { + if(dst) { memcpy(dst, attribbuf.getbuf(), attribbuf.length()); glUnmapBuffer_(GL_ARRAY_BUFFER); } @@ -280,8 +218,7 @@ namespace gle } else glUnmapBuffer_(GL_ARRAY_BUFFER); buf = (uchar *)0 + vbooffset; - if(vertexsize == lastvertexsize && buf >= lastbuf) - { + if(vertexsize == lastvertexsize && buf >= lastbuf) { start = int(buf - lastbuf)/vertexsize; if(primtype == GL_QUADS && (start%4 || start + attribbuf.length()/vertexsize >= 4*MAXQUADS)) start = 0; @@ -291,11 +228,9 @@ namespace gle } setattribs(buf); int numvertexes = attribbuf.length()/vertexsize; - if(primtype == GL_QUADS) - { + if(primtype == GL_QUADS) { if(!quadsenabled) enablequads(); - for(int quads = numvertexes/4;;) - { + for(int quads = numvertexes/4;;) { int count = min(quads, MAXQUADS); drawquads(start/4, count); quads -= count; @@ -304,10 +239,8 @@ namespace gle start = 0; } } - else - { - if(multidrawstart.length()) - { + else { + if(multidrawstart.length()) { multidraw(); if(start) loopv(multidrawstart) multidrawstart[i] += start; glMultiDrawArrays_(primtype, multidrawstart.getbuf(), multidrawcount.getbuf(), multidrawstart.length()); @@ -319,36 +252,26 @@ namespace gle attribbuf.reset(attribdata, MAXVBOSIZE); return numvertexes; } - - void forcedisable() - { + void forcedisable() { for(int i = 0; enabled; i++) if(enabled&(1<= 300) glBindBuffer_(GL_ARRAY_BUFFER, 0); } - - void setup() - { - if(glversion >= 300) - { + void setup() { + if(glversion >= 300) { if(!defaultvao) glGenVertexArrays_(1, &defaultvao); glBindVertexArray_(defaultvao); } attribdata = new uchar[MAXVBOSIZE]; attribbuf.reset(attribdata, MAXVBOSIZE); } - - void cleanup() - { + void cleanup() { disable(); - if(quadindexes) { glDeleteBuffers_(1, &quadindexes); quadindexes = 0; } - if(vbo) { glDeleteBuffers_(1, &vbo); vbo = 0; } vbooffset = MAXVBOSIZE; - if(defaultvao) { glDeleteVertexArrays_(1, &defaultvao); defaultvao = 0; } } } diff --git a/src/shared/glemu.h b/src/shared/glemu.h index e4f4d26..be4ea9f 100644 --- a/src/shared/glemu.h +++ b/src/shared/glemu.h @@ -1,7 +1,5 @@ -namespace gle -{ - enum - { +namespace gle { + enum { ATTRIB_VERTEX = 0, ATTRIB_COLOR = 1, ATTRIB_TEXCOORD0 = 2, @@ -12,22 +10,17 @@ namespace gle ATTRIB_BONEINDEX = 7, MAXATTRIBS = 8 }; - extern const char * const attribnames[MAXATTRIBS]; extern ucharbuf attribbuf; - extern int enabled; extern void forcedisable(); static inline void disable() { if(enabled) forcedisable(); } - extern void begin(GLenum mode); extern void begin(GLenum mode, int numverts); extern void defattribs(const char *fmt); extern void defattrib(int type, int size, int format); - #define GLE_DEFATTRIB(name, type, defaultsize, defaultformat) \ static inline void def##name(int size = defaultsize, int format = defaultformat) { defattrib(type, size, format); } - GLE_DEFATTRIB(vertex, ATTRIB_VERTEX, 3, GL_FLOAT) GLE_DEFATTRIB(color, ATTRIB_COLOR, 3, GL_FLOAT) GLE_DEFATTRIB(texcoord0, ATTRIB_TEXCOORD0, 2, GL_FLOAT) @@ -36,7 +29,6 @@ namespace gle GLE_DEFATTRIB(tangent, ATTRIB_TANGENT, 4, GL_FLOAT) GLE_DEFATTRIB(boneweight, ATTRIB_BONEWEIGHT, 4, GL_UNSIGNED_BYTE) GLE_DEFATTRIB(boneindex, ATTRIB_BONEINDEX, 4, GL_UNSIGNED_BYTE) - #define GLE_INITATTRIB(name, index, suffix, type) \ static inline void name##suffix(type x) { glVertexAttrib1##suffix##_(index, x); } \ static inline void name##suffix(type x, type y) { glVertexAttrib2##suffix##_(index, x, y); } \ @@ -50,7 +42,6 @@ namespace gle static inline void name(const vec4 &v) { glVertexAttrib4fv_(index, v.v); } #define GLE_INITATTRIBN(name, index, suffix, type, defaultw) \ static inline void name##suffix(type x, type y, type z, type w = defaultw) { glVertexAttrib4N##suffix##_(index, x, y, z, w); } - GLE_INITATTRIBF(vertex, ATTRIB_VERTEX) GLE_INITATTRIBF(color, ATTRIB_COLOR) static inline void color(const bvec4 &v) { glVertexAttrib4Nubv_(ATTRIB_COLOR, v.v); } @@ -63,7 +54,6 @@ namespace gle static inline void tangent(float x, float y, float z, float w = 1.0f) { glVertexAttrib4f_(ATTRIB_TANGENT, x, y, z, w); } static inline void tangent(const vec &v, float w = 1.0f) { glVertexAttrib4f_(ATTRIB_TANGENT, v.x, v.y, v.z, w); } static inline void tangent(const vec4 &v) { glVertexAttrib4fv_(ATTRIB_TANGENT, v.v); } - #define GLE_ATTRIBPOINTER(name, index, defaultnormalized, defaultsize, defaulttype, prepare) \ static inline void enable##name() { prepare; glEnableVertexAttribArray_(index); } \ static inline void disable##name() { glDisableVertexAttribArray_(index); } \ @@ -71,7 +61,6 @@ namespace gle prepare; \ glVertexAttribPointer_(index, size, type, normalized, stride, data); \ } - static inline void enableattrib(int index) { disable(); glEnableVertexAttribArray_(index); } static inline void disableattrib(int index) { glDisableVertexAttribArray_(index); } GLE_ATTRIBPOINTER(vertex, ATTRIB_VERTEX, GL_FALSE, 3, GL_FLOAT, disable()) @@ -82,50 +71,37 @@ namespace gle GLE_ATTRIBPOINTER(tangent, ATTRIB_TANGENT, GL_TRUE, 4, GL_FLOAT, ) GLE_ATTRIBPOINTER(boneweight, ATTRIB_BONEWEIGHT, GL_TRUE, 4, GL_UNSIGNED_BYTE, ) GLE_ATTRIBPOINTER(boneindex, ATTRIB_BONEINDEX, GL_FALSE, 4, GL_UNSIGNED_BYTE, ) - static inline void bindebo(GLuint ebo) { disable(); glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER, ebo); } static inline void clearebo() { glBindBuffer_(GL_ELEMENT_ARRAY_BUFFER, 0); } static inline void bindvbo(GLuint vbo) { disable(); glBindBuffer_(GL_ARRAY_BUFFER, vbo); } static inline void clearvbo() { glBindBuffer_(GL_ARRAY_BUFFER, 0); } - template - static inline void attrib(T x) - { - if(attribbuf.check(sizeof(T))) - { + static inline void attrib(T x) { + if(attribbuf.check(sizeof(T))) { T *buf = (T *)attribbuf.pad(sizeof(T)); buf[0] = x; } } - template - static inline void attrib(T x, T y) - { - if(attribbuf.check(2*sizeof(T))) - { + static inline void attrib(T x, T y) { + if(attribbuf.check(2*sizeof(T))) { T *buf = (T *)attribbuf.pad(2*sizeof(T)); buf[0] = x; buf[1] = y; } } - template - static inline void attrib(T x, T y, T z) - { - if(attribbuf.check(3*sizeof(T))) - { + static inline void attrib(T x, T y, T z) { + if(attribbuf.check(3*sizeof(T))) { T *buf = (T *)attribbuf.pad(3*sizeof(T)); buf[0] = x; buf[1] = y; buf[2] = z; } } - template - static inline void attrib(T x, T y, T z, T w) - { - if(attribbuf.check(4*sizeof(T))) - { + static inline void attrib(T x, T y, T z, T w) { + if(attribbuf.check(4*sizeof(T))) { T *buf = (T *)attribbuf.pad(4*sizeof(T)); buf[0] = x; buf[1] = y; @@ -133,19 +109,15 @@ namespace gle buf[3] = w; } } - template - static inline void attribv(const T *v) - { + static inline void attribv(const T *v) { attribbuf.put((const uchar *)v, N*sizeof(T)); } - #define GLE_ATTRIB(suffix, type) \ static inline void attrib##suffix(type x) { attrib(x); } \ static inline void attrib##suffix(type x, type y) { attrib(x, y); } \ static inline void attrib##suffix(type x, type y, type z) { attrib(x, y, z); } \ static inline void attrib##suffix(type x, type y, type z, type w) { attrib(x, y, z, w); } - GLE_ATTRIB(f, float) GLE_ATTRIB(d, double) GLE_ATTRIB(b, char) @@ -154,7 +126,6 @@ namespace gle GLE_ATTRIB(us, ushort) GLE_ATTRIB(i, int) GLE_ATTRIB(ui, uint) - static inline void attrib(const vec &v) { attribf(v.x, v.y, v.z); } static inline void attrib(const vec &v, float w) { attribf(v.x, v.y, v.z, w); } static inline void attrib(const vec2 &v) { attribf(v.x, v.y); } @@ -166,14 +137,11 @@ namespace gle static inline void attrib(const bvec &b) { attribub(b.x, b.y, b.z); } static inline void attrib(const bvec &b, uchar w) { attribub(b.x, b.y, b.z, w); } static inline void attrib(const bvec4 &b) { attribub(b.x, b.y, b.z, b.w); } - extern void multidraw(); extern int end(); - extern void enablequads(); extern void disablequads(); extern void drawquads(int offset, int count); - extern void setup(); extern void cleanup(); } diff --git a/src/shared/iengine.h b/src/shared/iengine.h index 74a6634..f4e822d 100644 --- a/src/shared/iengine.h +++ b/src/shared/iengine.h @@ -7,25 +7,20 @@ extern int totalmillis; // total elapsed time extern uint totalsecs; extern int gamespeed, paused; -enum -{ +enum { MATF_INDEX_SHIFT = 0, MATF_CLIP_SHIFT = 5, MATF_FLAG_SHIFT = 8, - MATF_INDEX = 3 << MATF_INDEX_SHIFT, MATF_CLIP = 7 << MATF_CLIP_SHIFT, MATF_FLAGS = 0xFF << MATF_FLAG_SHIFT }; -enum // cube empty-space materials -{ +enum { // cube empty-space materials { MAT_AIR = 0, // the default, fill the empty space with air - MAT_NOCLIP = 1 << MATF_CLIP_SHIFT, // collisions always treat cube as empty MAT_CLIP = 2 << MATF_CLIP_SHIFT, // collisions always treat cube as solid MAT_GAMECLIP = 3 << MATF_CLIP_SHIFT, // game specific clip material - MAT_DEATH = 1 << MATF_FLAG_SHIFT, // force player suicide MAT_ALPHA = 4 << MATF_FLAG_SHIFT // alpha blended }; @@ -50,8 +45,7 @@ extern bool settexture(const char *name, int clamp = 0); enum { EDIT_FACE = 0, EDIT_TEX, EDIT_MAT, EDIT_FLIP, EDIT_COPY, EDIT_PASTE, EDIT_ROTATE, EDIT_REPLACE, EDIT_DELCUBE, EDIT_REMIP, EDIT_VSLOT, EDIT_UNDO, EDIT_REDO }; -struct selinfo -{ +struct selinfo { int corner; int cx, cxs, cy, cys; ivec o, s; @@ -60,8 +54,7 @@ struct selinfo int size() const { return s.x*s.y*s.z; } int us(int d) const { return s[d]*grid; } bool operator==(const selinfo &sel) const { return o==sel.o && s==sel.s && grid==sel.grid && orient==sel.orient; } - bool validate() - { + bool validate() { extern int worldsize; if(grid <= 0 || grid >= worldsize) return false; if(o.x >= worldsize || o.y >= worldsize || o.z >= worldsize) return false; @@ -176,15 +169,13 @@ static inline void loopiter(ident *id, identstack &stack, const char *s) { tagva // console -enum -{ +enum { CON_INFO = 1<<0, CON_WARN = 1<<1, CON_ERROR = 1<<2, CON_DEBUG = 1<<3, CON_INIT = 1<<4, CON_ECHO = 1<<5, - CON_FLAGS = 0xFFFF, CON_TAG_SHIFT = 16, CON_TAG_MASK = (0x7FFF << CON_TAG_SHIFT) @@ -210,14 +201,12 @@ extern int cleargui(int n = 0); // octa extern int lookupmaterial(const vec &o); -static inline bool insideworld(const vec &o) -{ +static inline bool insideworld(const vec &o) { extern int worldsize; return o.x>=0 && o.x=0 && o.y=0 && o.z &args); - extern void gamedisconnect(bool cleanup); extern void parsepacketclient(int chan, packetbuf &p); extern void connectattempt(const char *name, const char *password, const ENetAddress &address); @@ -36,7 +33,6 @@ namespace game extern bool ispaused(); extern int scaletime(int t); extern bool allowmouselook(); - extern const char *gameident(); extern const char *savedconfig(); extern const char *restoreconfig(); @@ -44,7 +40,6 @@ namespace game extern const char *autoexec(); extern const char *savedservers(); extern void loadconfigs(); - extern void updateworld(); extern void initclient(); extern void physicstrigger(physent *d, bool local, int floorlevel, int material = 0); @@ -92,8 +87,7 @@ namespace game extern bool serverinfoentry(g3d_gui *g, int i, const char *name, int port, const char *desc, const char *map, int ping, const vector &attr, int np); } -namespace server -{ +namespace server { extern void *newclientinfo(); extern void deleteclientinfo(void *ci); extern void serverinit(); @@ -115,7 +109,7 @@ namespace server extern int serverport(int infoport = -1); extern const char *defaultmaster(); extern int masterport(); - extern void processmasterinput(const char *cmd, int cmdlen, const char *args); + extern void processmasterinput(const char *cmd, int cmdlen); extern void masterconnected(); extern void masterdisconnected(); extern bool ispaused(); diff --git a/src/shared/stream.cpp b/src/shared/stream.cpp index 8f218ad..1878801 100644 --- a/src/shared/stream.cpp +++ b/src/shared/stream.cpp @@ -2,24 +2,21 @@ ///////////////////////////// console //////////////////////// -void conoutf(const char *fmt, ...) -{ +void conoutf(const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(CON_INFO, fmt, args); va_end(args); } -void conoutf(int type, const char *fmt, ...) -{ +void conoutf(int type, const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(type, fmt, args); va_end(args); } -void conoutf(int type, int tag, const char *fmt, ...) -{ +void conoutf(int type, int tag, const char *fmt, ...) { va_list args; va_start(args, fmt); conoutfv(type | ((tag << CON_TAG_SHIFT) & CON_TAG_MASK), fmt, args); @@ -46,8 +43,7 @@ void conoutf(int type, int tag, const char *fmt, ...) U, U, U, U, u, u, u, u, u, u, u, u, u, u, u, u, \ u, u, u, u, u, u, u, u, u, u, u, u, u, u, U, u -extern const uchar cubectype[256] = -{ +extern const uchar cubectype[256] = { CUBECTYPE(CT_SPACE, CT_PRINT, CT_PRINT|CT_DIGIT, @@ -56,8 +52,7 @@ extern const uchar cubectype[256] = CT_PRINT|CT_UNICODE|CT_ALPHA|CT_LOWER, CT_PRINT|CT_UNICODE|CT_ALPHA|CT_UPPER) }; -extern const int cube2unichars[256] = -{ +extern const int cube2unichars[256] = { 0, 192, 193, 194, 195, 196, 197, 198, 199, 9, 10, 11, 12, 13, 200, 201, 202, 203, 204, 205, 206, 207, 209, 210, 211, 212, 213, 214, 216, 217, 218, 219, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, @@ -75,12 +70,10 @@ extern const int cube2unichars[256] = 0x42C, 0x42D, 0x42E, 0x42F, 0x431, 0x432, 0x433, 0x434, 0x436, 0x437, 0x438, 0x439, 0x43A, 0x43B, 0x43C, 0x43D, 0x43F, 0x442, 0x444, 0x446, 0x447, 0x448, 0x449, 0x44A, 0x44B, 0x44C, 0x44D, 0x44E, 0x44F, 0x454, 0x490, 0x491 }; -extern const int uni2cubeoffsets[8] = -{ +extern const int uni2cubeoffsets[8] = { 0, 256, 658, 658, 512, 658, 658, 658 }; -extern const uchar uni2cubechars[878] = -{ +extern const uchar uni2cubechars[878] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 12, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, @@ -110,8 +103,7 @@ extern const uchar uni2cubechars[878] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; -extern const uchar cubelowerchars[256] = -{ +extern const uchar cubelowerchars[256] = { 0, 130, 131, 132, 133, 134, 135, 136, 137, 9, 10, 11, 12, 13, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, @@ -129,8 +121,7 @@ extern const uchar cubelowerchars[256] = 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; -extern const uchar cubeupperchars[256] = -{ +extern const uchar cubeupperchars[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, @@ -149,12 +140,10 @@ extern const uchar cubeupperchars[256] = 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; -size_t decodeutf8(uchar *dstbuf, size_t dstlen, const uchar *srcbuf, size_t srclen, size_t *carry) -{ +size_t decodeutf8(uchar *dstbuf, size_t dstlen, const uchar *srcbuf, size_t srclen, size_t *carry) { uchar *dst = dstbuf, *dstend = &dstbuf[dstlen]; const uchar *src = srcbuf, *srcend = &srcbuf[srclen]; - if(dstbuf == srcbuf) - { + if(dstbuf == srcbuf) { int len = min(dstlen, srclen); for(const uchar *end4 = &srcbuf[len&~3]; src < end4; src += 4) if(*(const int *)src & 0x80808080) goto decode; for(const uchar *end = &srcbuf[len]; src < end; src++) if(*src & 0x80) goto decode; @@ -164,21 +153,15 @@ size_t decodeutf8(uchar *dstbuf, size_t dstlen, const uchar *srcbuf, size_t srcl decode: dst += src - srcbuf; - while(src < srcend && dst < dstend) - { + while(src < srcend && dst < dstend) { int c = *src++; if(c < 0x80) *dst++ = c; - else if(c >= 0xC0) - { + else if(c >= 0xC0) { int uni; - if(c >= 0xE0) - { - if(c >= 0xF0) - { - if(c >= 0xF8) - { - if(c >= 0xFC) - { + if(c >= 0xE0) { + if(c >= 0xF0) { + if(c >= 0xF8) { + if(c >= 0xFC) { if(c >= 0xFE) continue; uni = c&1; if(srcend - src < 5) break; c = *src; if((c&0xC0) != 0x80) continue; src++; uni = (uni<<6) | (c&0x3F); @@ -203,21 +186,16 @@ decode: return dst - dstbuf; } -size_t encodeutf8(uchar *dstbuf, size_t dstlen, const uchar *srcbuf, size_t srclen, size_t *carry) -{ +size_t encodeutf8(uchar *dstbuf, size_t dstlen, const uchar *srcbuf, size_t srclen, size_t *carry) { uchar *dst = dstbuf, *dstend = &dstbuf[dstlen]; const uchar *src = srcbuf, *srcend = &srcbuf[srclen]; - if(src < srcend && dst < dstend) do - { + if(src < srcend && dst < dstend) do { int uni = cube2uni(*src); - if(uni <= 0x7F) - { + if(uni <= 0x7F) { if(dst >= dstend) goto done; const uchar *end = min(srcend, &src[dstend-dst]); - do - { - if(uni == '\f') - { + do { + if(uni == '\f') { if(++src >= srcend) goto done; goto uni1; } @@ -255,31 +233,26 @@ done: #include string homedir = ""; -struct packagedir -{ +struct packagedir { char *dir, *filter; size_t dirlen, filterlen; }; vector packagedirs; -char *makerelpath(const char *dir, const char *file, const char *prefix, const char *cmd) -{ +char *makerelpath(const char *dir, const char *file, const char *prefix, const char *cmd) { static string tmp; if(prefix) copystring(tmp, prefix); else tmp[0] = '\0'; - if(file[0]=='<') - { + if(file[0]=='<') { const char *end = strrchr(file, '>'); - if(end) - { + if(end) { size_t len = strlen(tmp); copystring(&tmp[len], file, min(sizeof(tmp)-len, size_t(end+2-file))); file = end+1; } } if(cmd) concatstring(tmp, cmd); - if(dir) - { + if(dir) { defformatstring(pname, "%s/%s", dir, file); concatstring(tmp, pname); } @@ -288,43 +261,35 @@ char *makerelpath(const char *dir, const char *file, const char *prefix, const c } -char *path(char *s) -{ - for(char *curpart = s;;) - { +char *path(char *s) { + for(char *curpart = s;;) { char *endpart = strchr(curpart, '&'); if(endpart) *endpart = '\0'; - if(curpart[0]=='<') - { + if(curpart[0]=='<') { char *file = strrchr(curpart, '>'); if(!file) return s; curpart = file+1; } for(char *t = curpart; (t = strpbrk(t, "/\\")); *t++ = PATHDIV); - for(char *prevdir = NULL, *curdir = curpart;;) - { + for(char *prevdir = NULL, *curdir = curpart;;) { prevdir = curdir[0]==PATHDIV ? curdir+1 : curdir; curdir = strchr(prevdir, PATHDIV); if(!curdir) break; - if(prevdir+1==curdir && prevdir[0]=='.') - { + if(prevdir+1==curdir && prevdir[0]=='.') { memmove(prevdir, curdir+1, strlen(curdir+1)+1); curdir = prevdir; } - else if(curdir[1]=='.' && curdir[2]=='.' && curdir[3]==PATHDIV) - { + else if(curdir[1]=='.' && curdir[2]=='.' && curdir[3]==PATHDIV) { if(prevdir+2==curdir && prevdir[0]=='.' && prevdir[1]=='.') continue; memmove(prevdir, curdir+4, strlen(curdir+4)+1); - if(prevdir-2 >= curpart && prevdir[-1]==PATHDIV) - { + if(prevdir-2 >= curpart && prevdir[-1]==PATHDIV) { prevdir -= 2; while(prevdir-1 >= curpart && prevdir[-1] != PATHDIV) --prevdir; } curdir = prevdir; } } - if(endpart) - { + if(endpart) { *endpart = '&'; curpart = endpart+1; } @@ -333,16 +298,14 @@ char *path(char *s) return s; } -char *path(const char *s, bool copy) -{ +char *path(const char *s, bool copy) { static string tmp; copystring(tmp, s); path(tmp); return tmp; } -const char *parentdir(const char *directory) -{ +const char *parentdir(const char *directory) { const char *p = directory + strlen(directory); while(p > directory && *p != '/' && *p != '\\') p--; static string parent; @@ -351,43 +314,36 @@ const char *parentdir(const char *directory) return parent; } -bool fileexists(const char *path, const char *mode) -{ +bool fileexists(const char *path, const char *mode) { bool exists = true; if(mode[0]=='w' || mode[0]=='a') path = parentdir(path); if(access(path[0] ? path : ".", mode[0]=='w' || mode[0]=='a' ? W_OK : (mode[0]=='d' ? X_OK : R_OK)) == -1) exists = false; return exists; } -bool createdir(const char *path) -{ +bool createdir(const char *path) { size_t len = strlen(path); - if(path[len-1]==PATHDIV) - { + if(path[len-1]==PATHDIV) { static string strip; path = copystring(strip, path, len); } return mkdir(path, 0777)==0; } -size_t fixpackagedir(char *dir) -{ +size_t fixpackagedir(char *dir) { path(dir); size_t len = strlen(dir); - if(len > 0 && dir[len-1] != PATHDIV) - { + if(len > 0 && dir[len-1] != PATHDIV) { dir[len] = PATHDIV; dir[len+1] = '\0'; } return len; } -bool subhomedir(char *dst, int len, const char *src) -{ +bool subhomedir(char *dst, int len, const char *src) { const char *sub = strstr(src, "$HOME"); if(!sub) sub = strchr(src, '~'); - if(sub && sub-src < len) - { + if(sub && sub-src < len) { const char *home = getenv("HOME"); if(!home || !home[0]) return false; dst[sub-src] = '\0'; @@ -397,8 +353,7 @@ bool subhomedir(char *dst, int len, const char *src) return true; } -const char *sethomedir(const char *dir) -{ +const char *sethomedir(const char *dir) { string pdir; copystring(pdir, dir); if(!subhomedir(pdir, sizeof(pdir), dir) || !fixpackagedir(pdir)) return NULL; @@ -406,14 +361,12 @@ const char *sethomedir(const char *dir) return homedir; } -const char *addpackagedir(const char *dir) -{ +const char *addpackagedir(const char *dir) { string pdir; copystring(pdir, dir); if(!subhomedir(pdir, sizeof(pdir), dir) || !fixpackagedir(pdir)) return NULL; char *filter = pdir; - for(;;) - { + for(;;) { static int len = strlen("packages"); filter = strstr(filter, "packages"); if(!filter) break; @@ -428,20 +381,16 @@ const char *addpackagedir(const char *dir) return pf.dir; } -const char *findfile(const char *filename, const char *mode) -{ +const char *findfile(const char *filename, const char *mode) { static string s; - if(homedir[0]) - { + if(homedir[0]) { formatstring(s, "%s%s", homedir, filename); if(fileexists(s, mode)) return s; - if(mode[0]=='w' || mode[0]=='a') - { + if(mode[0]=='w' || mode[0]=='a') { string dirs; copystring(dirs, s); char *dir = strchr(dirs[0]==PATHDIV ? dirs+1 : dirs, PATHDIV); - while(dir) - { + while(dir) { *dir = '\0'; if(!fileexists(dirs, "d") && !createdir(dirs)) return s; *dir = PATHDIV; @@ -451,8 +400,7 @@ const char *findfile(const char *filename, const char *mode) } } if(mode[0]=='w' || mode[0]=='a') return filename; - loopv(packagedirs) - { + loopv(packagedirs) { packagedir &pf = packagedirs[i]; if(pf.filter && strncmp(filename, pf.filter, pf.filterlen)) continue; formatstring(s, "%s%s", pf.dir, filename); @@ -462,22 +410,17 @@ const char *findfile(const char *filename, const char *mode) return filename; } -bool listdir(const char *dirname, bool rel, const char *ext, vector &files) -{ +bool listdir(const char *dirname, bool rel, const char *ext, vector &files) { size_t extsize = ext ? strlen(ext)+1 : 0; defformatstring(pathname, rel ? "./%s" : "%s", dirname); DIR *d = opendir(pathname); - if(d) - { + if(d) { struct dirent *de; - while((de = readdir(d)) != NULL) - { + while((de = readdir(d)) != NULL) { if(!ext) files.add(newstring(de->d_name)); - else - { + else { size_t namelen = strlen(de->d_name); - if(namelen > extsize) - { + if(namelen > extsize) { namelen -= extsize; if(de->d_name[namelen] == '.' && strncmp(de->d_name+namelen+1, ext, extsize-1)==0) files.add(newstring(de->d_name, namelen)); @@ -490,8 +433,7 @@ bool listdir(const char *dirname, bool rel, const char *ext, vector &fil else return false; } -int listfiles(const char *dir, const char *ext, vector &files) -{ +int listfiles(const char *dir, const char *ext, vector &files) { string dirname; copystring(dirname, dir); path(dirname); @@ -500,13 +442,11 @@ int listfiles(const char *dir, const char *ext, vector &files) int dirs = 0; if(listdir(dirname, true, ext, files)) dirs++; string s; - if(homedir[0]) - { + if(homedir[0]) { formatstring(s, "%s%s", homedir, dirname); if(listdir(s, false, ext, files)) dirs++; } - loopv(packagedirs) - { + loopv(packagedirs) { packagedir &pf = packagedirs[i]; if(pf.filter && strncmp(dirname, pf.filter, dirlen == pf.filterlen-1 ? dirlen : pf.filterlen)) continue; @@ -520,32 +460,27 @@ int listfiles(const char *dir, const char *ext, vector &files) } #ifndef STANDALONE -static Sint64 rwopsseek(SDL_RWops *rw, Sint64 pos, int whence) -{ +static Sint64 rwopsseek(SDL_RWops *rw, Sint64 pos, int whence) { stream *f = (stream *)rw->hidden.unknown.data1; if((!pos && whence==SEEK_CUR) || f->seek(pos, whence)) return (int)f->tell(); return -1; } -static size_t rwopsread(SDL_RWops *rw, void *buf, size_t size, size_t nmemb) -{ +static size_t rwopsread(SDL_RWops *rw, void *buf, size_t size, size_t nmemb) { stream *f = (stream *)rw->hidden.unknown.data1; return f->read(buf, size*nmemb)/size; } -static size_t rwopswrite(SDL_RWops *rw, const void *buf, size_t size, size_t nmemb) -{ +static size_t rwopswrite(SDL_RWops *rw, const void *buf, size_t size, size_t nmemb) { stream *f = (stream *)rw->hidden.unknown.data1; return f->write(buf, size*nmemb)/size; } -static int rwopsclose(SDL_RWops *rw) -{ +static int rwopsclose(SDL_RWops *rw) { return 0; } -SDL_RWops *stream::rwops() -{ +SDL_RWops *stream::rwops() { SDL_RWops *rw = SDL_AllocRW(); if(!rw) return NULL; rw->hidden.unknown.data1 = this; @@ -557,18 +492,15 @@ SDL_RWops *stream::rwops() } #endif -stream::offset stream::size() -{ +stream::offset stream::size() { offset pos = tell(), endpos; if(pos < 0 || !seek(0, SEEK_END)) return -1; endpos = tell(); return pos == endpos || seek(pos, SEEK_SET) ? endpos : -1; } -bool stream::getline(char *str, size_t len) -{ - loopi(len-1) - { +bool stream::getline(char *str, size_t len) { + loopi(len-1) { if(read(&str[i], 1) != 1) { str[i] = '\0'; return i > 0; } else if(str[i] == '\n') { str[i+1] = '\0'; return true; } } @@ -576,8 +508,7 @@ bool stream::getline(char *str, size_t len) return true; } -size_t stream::printf(const char *fmt, ...) -{ +size_t stream::printf(const char *fmt, ...) { char buf[512]; char *str = buf; va_list args; @@ -585,8 +516,7 @@ size_t stream::printf(const char *fmt, ...) int len = vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); if(len <= 0) return 0; - if(len >= (int)sizeof(buf)) - { + if(len >= (int)sizeof(buf)) { str = new char[len+1]; va_start(args, fmt); vsnprintf(str, len+1, fmt, args); @@ -597,43 +527,31 @@ size_t stream::printf(const char *fmt, ...) return n; } -struct filestream : stream -{ +struct filestream : stream { FILE *file; - filestream() : file(NULL) {} ~filestream() { close(); } - - bool open(const char *name, const char *mode) - { + bool open(const char *name, const char *mode) { if(file) return false; file = fopen(name, mode); return file!=NULL; } - - bool opentemp(const char *name, const char *mode) - { + bool opentemp(const char *name, const char *mode) { if(file) return false; file = tmpfile(); return file!=NULL; } - - void close() - { + void close() { if(file) { fclose(file); file = NULL; } } - bool end() { return feof(file)!=0; } - offset tell() - { + offset tell() { offset off = ftello(file); return off + 1 >= 0 ? off : -1; } - bool seek(offset pos, int whence = SEEK_SET) - { + bool seek(offset pos, int whence = SEEK_SET) { return fseeko(file, pos, whence) >= 0; } - size_t read(void *buf, size_t len) { return fread(buf, 1, len, file); } size_t write(const void *buf, size_t len) { return fwrite(buf, 1, len, file); } bool flush() { return !fflush(file); } @@ -641,9 +559,7 @@ struct filestream : stream bool putchar(int c) { return fputc(c, file)!=EOF; } bool getline(char *str, size_t len) { return fgets(str, len, file)!=NULL; } bool putstring(const char *str) { return fputs(str, file)!=EOF; } - - size_t printf(const char *fmt, ...) - { + size_t printf(const char *fmt, ...) { va_list v; va_start(v, fmt); int result = vfprintf(file, fmt, v); @@ -652,18 +568,14 @@ struct filestream : stream } }; -struct gzstream : stream -{ - enum - { +struct gzstream : stream { + enum { MAGIC1 = 0x1F, MAGIC2 = 0x8B, BUFSIZE = 16384, OS_UNIX = 0x03 }; - - enum - { + enum { F_ASCII = 0x01, F_CRC = 0x02, F_EXTRA = 0x04, @@ -671,54 +583,40 @@ struct gzstream : stream F_COMMENT = 0x10, F_RESERVED = 0xE0 }; - stream *file; z_stream zfile; uchar *buf; bool reading, writing, autoclose; uint crc; size_t headersize; - - gzstream() : file(NULL), buf(NULL), reading(false), writing(false), autoclose(false), crc(0), headersize(0) - { + gzstream() : file(NULL), buf(NULL), reading(false), writing(false), autoclose(false), crc(0), headersize(0) { zfile.zalloc = NULL; zfile.zfree = NULL; zfile.opaque = NULL; zfile.next_in = zfile.next_out = NULL; zfile.avail_in = zfile.avail_out = 0; } - - ~gzstream() - { + ~gzstream() { close(); } - - void writeheader() - { + void writeheader() { uchar header[] = { MAGIC1, MAGIC2, Z_DEFLATED, 0, 0, 0, 0, 0, 0, OS_UNIX }; file->write(header, sizeof(header)); } - - void readbuf(size_t size = BUFSIZE) - { + void readbuf(size_t size = BUFSIZE) { if(!zfile.avail_in) zfile.next_in = (Bytef *)buf; size = min(size, size_t(&buf[BUFSIZE] - &zfile.next_in[zfile.avail_in])); size_t n = file->read(zfile.next_in + zfile.avail_in, size); if(n > 0) zfile.avail_in += n; } - - uchar readbyte(size_t size = BUFSIZE) - { + uchar readbyte(size_t size = BUFSIZE) { if(!zfile.avail_in) readbuf(size); if(!zfile.avail_in) return 0; zfile.avail_in--; return *(uchar *)zfile.next_in++; } - - void skipbytes(size_t n) - { - while(n > 0 && zfile.avail_in > 0) - { + void skipbytes(size_t n) { + while(n > 0 && zfile.avail_in > 0) { size_t skipped = min(n, size_t(zfile.avail_in)); zfile.avail_in -= skipped; zfile.next_in += skipped; @@ -727,16 +625,13 @@ struct gzstream : stream if(n <= 0) return; file->seek(n, SEEK_CUR); } - - bool checkheader() - { + bool checkheader() { readbuf(10); if(readbyte() != MAGIC1 || readbyte() != MAGIC2 || readbyte() != Z_DEFLATED) return false; uchar flags = readbyte(); if(flags & F_RESERVED) return false; skipbytes(6); - if(flags & F_EXTRA) - { + if(flags & F_EXTRA) { size_t len = readbyte(512); len |= size_t(readbyte(512))<<8; skipbytes(len); @@ -747,77 +642,56 @@ struct gzstream : stream headersize = size_t(file->tell() - zfile.avail_in); return zfile.avail_in > 0 || !file->end(); } - - bool open(stream *f, const char *mode, bool needclose, int level) - { + bool open(stream *f, const char *mode, bool needclose, int level) { if(file) return false; - for(; *mode; mode++) - { + for(; *mode; mode++) { if(*mode=='r') { reading = true; break; } else if(*mode=='w') { writing = true; break; } } - if(reading) - { + if(reading) { if(inflateInit2(&zfile, -MAX_WBITS) != Z_OK) reading = false; } else if(writing && deflateInit2(&zfile, level, Z_DEFLATED, -MAX_WBITS, min(MAX_MEM_LEVEL, 8), Z_DEFAULT_STRATEGY) != Z_OK) writing = false; if(!reading && !writing) return false; - file = f; crc = crc32(0, NULL, 0); buf = new uchar[BUFSIZE]; - - if(reading) - { + if(reading) { if(!checkheader()) { stopreading(); return false; } } else if(writing) writeheader(); - autoclose = needclose; return true; } - uint getcrc() { return crc; } - - void finishreading() - { + void finishreading() { if(!reading) return; } - - void stopreading() - { + void stopreading() { if(!reading) return; inflateEnd(&zfile); reading = false; } - - void finishwriting() - { + void finishwriting() { if(!writing) return; - for(;;) - { + for(;;) { int err = zfile.avail_out > 0 ? deflate(&zfile, Z_FINISH) : Z_OK; if(err != Z_OK && err != Z_STREAM_END) break; flushbuf(); if(err == Z_STREAM_END) break; } - uchar trailer[8] = - { + uchar trailer[8] = { uchar(crc&0xFF), uchar((crc>>8)&0xFF), uchar((crc>>16)&0xFF), uchar((crc>>24)&0xFF), uchar(zfile.total_in&0xFF), uchar((zfile.total_in>>8)&0xFF), uchar((zfile.total_in>>16)&0xFF), uchar((zfile.total_in>>24)&0xFF) }; file->write(trailer, sizeof(trailer)); } - - void stopwriting() - { + void stopwriting() { if(!writing) return; deflateEnd(&zfile); writing = false; } - - void close() - { + void close() { if(reading) finishreading(); stopreading(); if(writing) finishwriting(); @@ -825,72 +699,53 @@ struct gzstream : stream DELETEA(buf); if(autoclose) DELETEP(file); } - bool end() { return !reading && !writing; } offset tell() { return reading ? zfile.total_out : (writing ? zfile.total_in : offset(-1)); } offset rawtell() { return file ? file->tell() : offset(-1); } - - offset size() - { + offset size() { if(!file) return -1; offset pos = tell(); if(!file->seek(-4, SEEK_END)) return -1; uint isize = file->getlil(); return file->seek(pos, SEEK_SET) ? isize : offset(-1); } - offset rawsize() { return file ? file->size() : offset(-1); } - - bool seek(offset pos, int whence) - { + bool seek(offset pos, int whence) { if(writing || !reading) return false; - - if(whence == SEEK_END) - { + if(whence == SEEK_END) { uchar skip[512]; while(read(skip, sizeof(skip)) == sizeof(skip)); return !pos; } else if(whence == SEEK_CUR) pos += zfile.total_out; - if(pos >= (offset)zfile.total_out) pos -= zfile.total_out; else if(pos < 0 || !file->seek(headersize, SEEK_SET)) return false; - else - { - if(zfile.next_in && zfile.total_in <= uint(zfile.next_in - buf)) - { + else { + if(zfile.next_in && zfile.total_in <= uint(zfile.next_in - buf)) { zfile.avail_in += zfile.total_in; zfile.next_in -= zfile.total_in; } - else - { + else { zfile.avail_in = 0; zfile.next_in = NULL; } inflateReset(&zfile); crc = crc32(0, NULL, 0); } - uchar skip[512]; - while(pos > 0) - { + while(pos > 0) { size_t skipped = (size_t)min(pos, (offset)sizeof(skip)); if(read(skip, skipped) != skipped) { stopreading(); return false; } pos -= skipped; } - return true; } - - size_t read(void *buf, size_t len) - { + size_t read(void *buf, size_t len) { if(!reading || !buf || !len) return 0; zfile.next_out = (Bytef *)buf; zfile.avail_out = len; - while(zfile.avail_out > 0) - { - if(!zfile.avail_in) - { + while(zfile.avail_out > 0) { + if(!zfile.avail_in) { readbuf(BUFSIZE); if(!zfile.avail_in) { stopreading(); break; } } @@ -901,12 +756,9 @@ struct gzstream : stream crc = crc32(crc, (Bytef *)buf, len - zfile.avail_out); return len - zfile.avail_out; } - - bool flushbuf(bool full = false) - { + bool flushbuf(bool full = false) { if(full) deflate(&zfile, Z_SYNC_FLUSH); - if(zfile.next_out && zfile.avail_out < BUFSIZE) - { + if(zfile.next_out && zfile.avail_out < BUFSIZE) { if(file->write(buf, BUFSIZE - zfile.avail_out) != BUFSIZE - zfile.avail_out || (full && !file->flush())) return false; } @@ -914,16 +766,12 @@ struct gzstream : stream zfile.avail_out = BUFSIZE; return true; } - bool flush() { return flushbuf(true); } - - size_t write(const void *buf, size_t len) - { + size_t write(const void *buf, size_t len) { if(!writing || !buf || !len) return 0; zfile.next_in = (Bytef *)buf; zfile.avail_in = len; - while(zfile.avail_in > 0) - { + while(zfile.avail_in > 0) { if(!zfile.avail_out && !flushbuf()) { stopwriting(); break; } int err = deflate(&zfile, Z_NO_FLUSH); if(err != Z_OK) { stopwriting(); break; } @@ -933,10 +781,8 @@ struct gzstream : stream } }; -struct utf8stream : stream -{ - enum - { +struct utf8stream : stream { + enum { BUFSIZE = 4096 }; stream *file; @@ -944,18 +790,12 @@ struct utf8stream : stream size_t bufread, bufcarry, buflen; bool reading, writing, autoclose; uchar buf[BUFSIZE]; - - utf8stream() : file(NULL), pos(0), bufread(0), bufcarry(0), buflen(0), reading(false), writing(false), autoclose(false) - { + utf8stream() : file(NULL), pos(0), bufread(0), bufcarry(0), buflen(0), reading(false), writing(false), autoclose(false) { } - - ~utf8stream() - { + ~utf8stream() { close(); } - - bool readbuf(size_t size = BUFSIZE) - { + bool readbuf(size_t size = BUFSIZE) { if(bufread >= bufcarry) { if(bufcarry > 0 && bufcarry < buflen) memmove(buf, &buf[bufcarry], buflen - bufcarry); buflen -= bufcarry; bufread = bufcarry = 0; } size_t n = file->read(&buf[buflen], min(size, BUFSIZE - buflen)); if(n <= 0) return false; @@ -965,98 +805,69 @@ struct utf8stream : stream if(carry > bufcarry && carry < buflen) { memmove(&buf[bufcarry], &buf[carry], buflen - carry); buflen -= carry - bufcarry; } return true; } - - bool checkheader() - { + bool checkheader() { size_t n = file->read(buf, 3); if(n == 3 && buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF) return true; buflen = n; return false; } - - bool open(stream *f, const char *mode, bool needclose) - { + bool open(stream *f, const char *mode, bool needclose) { if(file) return false; - for(; *mode; mode++) - { + for(; *mode; mode++) { if(*mode=='r') { reading = true; break; } else if(*mode=='w') { writing = true; break; } } if(!reading && !writing) return false; - file = f; - if(reading) checkheader(); - autoclose = needclose; return true; } - - void finishreading() - { + void finishreading() { if(!reading) return; } - - void stopreading() - { + void stopreading() { if(!reading) return; reading = false; } - - void stopwriting() - { + void stopwriting() { if(!writing) return; writing = false; } - - void close() - { + void close() { stopreading(); stopwriting(); if(autoclose) DELETEP(file); } - bool end() { return !reading && !writing; } offset tell() { return reading || writing ? pos : offset(-1); } - - bool seek(offset off, int whence) - { + bool seek(offset off, int whence) { if(writing || !reading) return false; - - if(whence == SEEK_END) - { + if(whence == SEEK_END) { uchar skip[512]; while(read(skip, sizeof(skip)) == sizeof(skip)); return !off; } else if(whence == SEEK_CUR) off += pos; - if(off >= pos) off -= pos; else if(off < 0 || !file->seek(0, SEEK_SET)) return false; - else - { + else { bufread = bufcarry = buflen = 0; pos = 0; checkheader(); } - uchar skip[512]; - while(off > 0) - { + while(off > 0) { size_t skipped = (size_t)min(off, (offset)sizeof(skip)); if(read(skip, skipped) != skipped) { stopreading(); return false; } off -= skipped; } - return true; } - - size_t read(void *dst, size_t len) - { + size_t read(void *dst, size_t len) { if(!reading || !dst || !len) return 0; size_t next = 0; - while(next < len) - { + while(next < len) { if(bufread >= bufcarry) { if(readbuf(BUFSIZE)) continue; stopreading(); break; } size_t n = min(len - next, bufcarry - bufread); memcpy(&((uchar *)dst)[next], &buf[bufread], n); @@ -1066,14 +877,11 @@ struct utf8stream : stream pos += next; return next; } - - bool getline(char *dst, size_t len) - { + bool getline(char *dst, size_t len) { if(!reading || !dst || !len) return false; --len; size_t next = 0; - while(next < len) - { + while(next < len) { if(bufread >= bufcarry) { if(readbuf(BUFSIZE)) continue; stopreading(); if(!next) return false; break; } size_t n = min(len - next, bufcarry - bufread); uchar *endline = (uchar *)memchr(&buf[bufread], '\n', n); @@ -1086,14 +894,11 @@ struct utf8stream : stream pos += next; return true; } - - size_t write(const void *src, size_t len) - { + size_t write(const void *src, size_t len) { if(!writing || !src || !len) return 0; uchar dst[512]; size_t next = 0; - while(next < len) - { + while(next < len) { size_t carry = 0, n = encodeutf8(dst, sizeof(dst), &((uchar *)src)[next], len - next, &carry); if(n > 0 && file->write(dst, n) != n) { stopwriting(); break; } next += carry; @@ -1101,12 +906,10 @@ struct utf8stream : stream pos += next; return next; } - bool flush() { return file->flush(); } }; -stream *openrawfile(const char *filename, const char *mode) -{ +stream *openrawfile(const char *filename, const char *mode) { const char *found = findfile(filename, mode); if(!found) return NULL; filestream *file = new filestream; @@ -1114,8 +917,7 @@ stream *openrawfile(const char *filename, const char *mode) return file; } -stream *openfile(const char *filename, const char *mode) -{ +stream *openfile(const char *filename, const char *mode) { #ifndef STANDALONE stream *s = openzipfile(filename, mode); if(s) return s; @@ -1123,16 +925,14 @@ stream *openfile(const char *filename, const char *mode) return openrawfile(filename, mode); } -stream *opentempfile(const char *name, const char *mode) -{ +stream *opentempfile(const char *name, const char *mode) { const char *found = findfile(name, mode); filestream *file = new filestream; if(!file->opentemp(found ? found : name, mode)) { delete file; return NULL; } return file; } -stream *opengzfile(const char *filename, const char *mode, stream *file, int level) -{ +stream *opengzfile(const char *filename, const char *mode, stream *file, int level) { stream *source = file ? file : openfile(filename, mode); if(!source) return NULL; gzstream *gz = new gzstream; @@ -1140,8 +940,7 @@ stream *opengzfile(const char *filename, const char *mode, stream *file, int lev return gz; } -stream *openutf8file(const char *filename, const char *mode, stream *file) -{ +stream *openutf8file(const char *filename, const char *mode, stream *file) { stream *source = file ? file : openfile(filename, mode); if(!source) return NULL; utf8stream *utf8 = new utf8stream; @@ -1149,8 +948,7 @@ stream *openutf8file(const char *filename, const char *mode, stream *file) return utf8; } -char *loadfile(const char *fn, size_t *size, bool utf8) -{ +char *loadfile(const char *fn, size_t *size, bool utf8) { stream *f = openfile(fn, "rb"); if(!f) return NULL; stream::offset fsize = f->size(); @@ -1159,8 +957,7 @@ char *loadfile(const char *fn, size_t *size, bool utf8) char *buf = new (false) char[len+1]; if(!buf) { delete f; return NULL; } size_t offset = 0; - if(utf8 && len >= 3) - { + if(utf8 && len >= 3) { if(f->read(buf, 3) != 3) { delete f; delete[] buf; return NULL; } if(((uchar *)buf)[0] == 0xEF && ((uchar *)buf)[1] == 0xBB && ((uchar *)buf)[2] == 0xBF) len -= 3; else offset += 3; diff --git a/src/shared/tools.cpp b/src/shared/tools.cpp index 1b49a8c..7eae44a 100644 --- a/src/shared/tools.cpp +++ b/src/shared/tools.cpp @@ -2,15 +2,13 @@ #include "cube.h" -void *operator new(size_t size) -{ +void *operator new(size_t size) { void *p = malloc(size); if(!p) abort(); return p; } -void *operator new[](size_t size) -{ +void *operator new[](size_t size) { void *p = malloc(size); if(!p) abort(); return p; @@ -22,15 +20,13 @@ void operator delete[](void *p) { if(p) free(p); } void operator delete(void *p, size_t n) { (void) n; if(p) free(p); } void operator delete[](void *p, size_t n) { (void) n; if(p) free(p); } -void *operator new(size_t size, bool err) -{ +void *operator new(size_t size, bool err) { void *p = malloc(size); if(!p && err) abort(); return p; } -void *operator new[](size_t size, bool err) -{ +void *operator new[](size_t size, bool err) { void *p = malloc(size); if(!p && err) abort(); return p; @@ -45,19 +41,16 @@ void *operator new[](size_t size, bool err) static uint state[N]; static int next = N; -void seedMT(uint seed) -{ +void seedMT(uint seed) { state[0] = seed; for(uint i = 1; i < N; i++) state[i] = seed = 1812433253U * (seed ^ (seed >> 30)) + i; next = 0; } -uint randomMT() -{ +uint randomMT() { int cur = next; - if(++next >= N) - { + if(++next >= N) { if(next > N) { seedMT(5489U + time(NULL)); cur = next++; } else next = 0; } @@ -75,8 +68,7 @@ uint randomMT() // all network traffic is in 32bit ints, which are then compressed using the following simple scheme (assumes that most values are small). template -static inline void putint_(T &p, int n) -{ +static inline void putint_(T &p, int n) { if(n<128 && n>-127) p.put(n); else if(n<0x8000 && n>=-0x8000) { p.put(0x80); p.put(n); p.put(n>>8); } else { p.put(0x81); p.put(n); p.put(n>>8); p.put(n>>16); p.put(n>>24); } @@ -85,8 +77,7 @@ void putint(ucharbuf &p, int n) { putint_(p, n); } void putint(packetbuf &p, int n) { putint_(p, n); } void putint(vector &p, int n) { putint_(p, n); } -int getint(ucharbuf &p) -{ +int getint(ucharbuf &p) { int c = (schar)p.get(); if(c==-128) { int n = p.get(); n |= ((schar)p.get())<<8; return n; } else if(c==-127) { int n = p.get(); n |= p.get()<<8; n |= p.get()<<16; return n|(p.get()<<24); } @@ -95,23 +86,19 @@ int getint(ucharbuf &p) // much smaller encoding for unsigned integers up to 28 bits, but can handle signed template -static inline void putuint_(T &p, int n) -{ - if(n < 0 || n >= (1<<21)) - { +static inline void putuint_(T &p, int n) { + if(n < 0 || n >= (1<<21)) { p.put(0x80 | (n & 0x7F)); p.put(0x80 | ((n >> 7) & 0x7F)); p.put(0x80 | ((n >> 14) & 0x7F)); p.put(n >> 21); } else if(n < (1<<7)) p.put(n); - else if(n < (1<<14)) - { + else if(n < (1<<14)) { p.put(0x80 | (n & 0x7F)); p.put(n >> 7); } - else - { + else { p.put(0x80 | (n & 0x7F)); p.put(0x80 | ((n >> 7) & 0x7F)); p.put(n >> 14); @@ -121,11 +108,9 @@ void putuint(ucharbuf &p, int n) { putuint_(p, n); } void putuint(packetbuf &p, int n) { putuint_(p, n); } void putuint(vector &p, int n) { putuint_(p, n); } -int getuint(ucharbuf &p) -{ +int getuint(ucharbuf &p) { int n = p.get(); - if(n & 0x80) - { + if(n & 0x80) { n += (p.get() << 7) - 0x80; if(n & (1<<14)) n += (p.get() << 14) - (1<<14); if(n & (1<<21)) n += (p.get() << 21) - (1<<21); @@ -135,8 +120,7 @@ int getuint(ucharbuf &p) } template -static inline void putfloat_(T &p, float f) -{ +static inline void putfloat_(T &p, float f) { lilswap(&f, 1); p.put((uchar *)&f, sizeof(float)); } @@ -144,16 +128,14 @@ void putfloat(ucharbuf &p, float f) { putfloat_(p, f); } void putfloat(packetbuf &p, float f) { putfloat_(p, f); } void putfloat(vector &p, float f) { putfloat_(p, f); } -float getfloat(ucharbuf &p) -{ +float getfloat(ucharbuf &p) { float f; p.get((uchar *)&f, sizeof(float)); return lilswap(f); } template -static inline void sendstring_(const char *t, T &p) -{ +static inline void sendstring_(const char *t, T &p) { while(*t) putint(p, *t++); putint(p, 0); } @@ -161,11 +143,9 @@ void sendstring(const char *t, ucharbuf &p) { sendstring_(t, p); } void sendstring(const char *t, packetbuf &p) { sendstring_(t, p); } void sendstring(const char *t, vector &p) { sendstring_(t, p); } -void getstring(char *text, ucharbuf &p, size_t len) -{ +void getstring(char *text, ucharbuf &p, size_t len) { char *t = text; - do - { + do { if(t>=&text[len]) { text[len-1] = 0; return; } if(!p.remaining()) { *t = 0; return; } *t = getint(p); @@ -173,17 +153,13 @@ void getstring(char *text, ucharbuf &p, size_t len) while(*t++); } -void filtertext(char *dst, const char *src, bool whitespace, bool forcespace, size_t len) -{ - for(int c = uchar(*src); c; c = uchar(*++src)) - { - if(c == '\f') - { +void filtertext(char *dst, const char *src, bool whitespace, bool forcespace, size_t len) { + for(int c = uchar(*src); c; c = uchar(*++src)) { + if(c == '\f') { if(!*++src) break; continue; } - if(!iscubeprint(c)) - { + if(!iscubeprint(c)) { if(!iscubespace(c) || !whitespace) continue; if(forcespace) c = ' '; } @@ -193,24 +169,20 @@ void filtertext(char *dst, const char *src, bool whitespace, bool forcespace, si *dst = '\0'; } -void ipmask::parse(const char *name) -{ +void ipmask::parse(const char *name) { union { uchar b[sizeof(enet_uint32)]; enet_uint32 i; } ipconv, maskconv; ipconv.i = 0; maskconv.i = 0; - loopi(4) - { + loopi(4) { char *end = NULL; int n = strtol(name, &end, 10); if(!end) break; if(end > name) { ipconv.b[i] = n; maskconv.b[i] = 0xFF; } name = end; - while(int c = *name) - { + while(int c = *name) { ++name; if(c == '.') break; - if(c == '/') - { + if(c == '/') { int range = clamp(int(strtol(name, NULL, 10)), 0, 32); mask = range ? ENET_HOST_TO_NET_32(0xFFffFFff << (32 - range)) : maskconv.i; ip = ipconv.i & mask; @@ -222,15 +194,13 @@ void ipmask::parse(const char *name) mask = maskconv.i; } -int ipmask::print(char *buf) const -{ +int ipmask::print(char *buf) const { char *start = buf; union { uchar b[sizeof(enet_uint32)]; enet_uint32 i; } ipconv, maskconv; ipconv.i = ip; maskconv.i = mask; int lastdigit = -1; - loopi(4) if(maskconv.b[i]) - { + loopi(4) if(maskconv.b[i]) { if(lastdigit >= 0) *buf++ = '.'; loopj(i - lastdigit - 1) { *buf++ = '*'; *buf++ = '.'; } buf += sprintf(buf, "%d", ipconv.b[i]); diff --git a/src/shared/tools.h b/src/shared/tools.h index 0550668..709f056 100644 --- a/src/shared/tools.h +++ b/src/shared/tools.h @@ -31,8 +31,7 @@ inline void operator delete[](void *, void *) {} #undef swap #endif template -static inline void swap(T &a, T &b) -{ +static inline void swap(T &a, T &b) { T t = a; a = b; b = t; @@ -44,18 +43,15 @@ static inline void swap(T &a, T &b) #undef min #endif template -static inline T max(T a, T b) -{ +static inline T max(T a, T b) { return a > b ? a : b; } template -static inline T min(T a, T b) -{ +static inline T min(T a, T b) { return a < b ? a : b; } template -static inline T clamp(T a, U b, U c) -{ +static inline T clamp(T a, U b, U c) { return max(T(b), min(a, T(c))); } @@ -99,8 +95,7 @@ typedef char string[MAXSTRLEN]; inline void vformatstring(char *d, const char *fmt, va_list v, int len) { _vsnprintf(d, len, fmt, v); d[len-1] = 0; } template inline void vformatstring(char (&d)[N], const char *fmt, va_list v) { vformatstring(d, fmt, v, N); } -inline char *copystring(char *d, const char *s, size_t len) -{ +inline char *copystring(char *d, const char *s, size_t len) { size_t slen = min(strlen(s), len-1); memcpy(d, s, slen); d[slen] = 0; @@ -111,8 +106,7 @@ template inline char *copystring(char (&d)[N], const char *s) { return inline char *concatstring(char *d, const char *s, size_t len) { size_t used = strlen(d); return used < len ? copystring(d+used, s, len-used) : d; } template inline char *concatstring(char (&d)[N], const char *s) { return concatstring(d, s, N); } -inline char *prependstring(char *d, const char *s, size_t len) -{ +inline char *prependstring(char *d, const char *s, size_t len) { size_t slen = min(strlen(s), len); memmove(&d[slen], d, min(len - slen, strlen(d) + 1)); memcpy(d, s, slen); @@ -122,8 +116,7 @@ inline char *prependstring(char *d, const char *s, size_t len) template inline char *prependstring(char (&d)[N], const char *s) { return prependstring(d, s, N); } inline void nformatstring(char *d, int len, const char *fmt, ...) PRINTFARGS(3, 4); -inline void nformatstring(char *d, int len, const char *fmt, ...) -{ +inline void nformatstring(char *d, int len, const char *fmt, ...) { va_list v; va_start(v, fmt); vformatstring(d, fmt, v, len); @@ -131,8 +124,7 @@ inline void nformatstring(char *d, int len, const char *fmt, ...) } template inline void formatstring(char (&d)[N], const char *fmt, ...) PRINTFARGS(2, 3); -template inline void formatstring(char (&d)[N], const char *fmt, ...) -{ +template inline void formatstring(char (&d)[N], const char *fmt, ...) { va_list v; va_start(v, fmt); vformatstring(d, fmt, v, int(N)); @@ -140,8 +132,7 @@ template inline void formatstring(char (&d)[N], const char *fmt, ...) } template inline void concformatstring(char (&d)[N], const char *fmt, ...) PRINTFARGS(2, 3); -template inline void concformatstring(char (&d)[N], const char *fmt, ...) -{ +template inline void concformatstring(char (&d)[N], const char *fmt, ...) { va_list v; va_start(v, fmt); int len = strlen(d); @@ -152,14 +143,13 @@ template inline void concformatstring(char (&d)[N], const char *fmt, . #define defformatstring(d,...) string d; formatstring(d, __VA_ARGS__) #define defvformatstring(d,last,fmt) string d; { va_list ap; va_start(ap, last); vformatstring(d, fmt, ap); va_end(ap); } -template inline bool matchstring(const char *s, size_t len, const char (&d)[N]) -{ +template inline bool matchstring(const char *s, size_t len, const char (&d)[N]) { return len == N-1 && !memcmp(s, d, N-1); } inline char *newstring(size_t l) { return new char[l+1]; } inline char *newstring(const char *s, size_t l) { return copystring(newstring(l), s, l+1); } -inline char *newstring(const char *s) { size_t l = strlen(s); char *d = newstring(l); memcpy(d, s, l+1); return d; } +inline char *newstring(const char *s) { size_t l = strlen(s); char *d = newstring(l); memcpy(d, s, l+1); return d; } #define loopv(v) for(int i = 0; i<(v).length(); i++) #define loopvj(v) for(int j = 0; j<(v).length(); j++) @@ -171,99 +161,72 @@ template inline void memclear(T &p) { memset((void *)&p, 0, sizeof(T)); template inline void memclear(T (&p)[N]) { memset((void *)p, 0, N * sizeof(T)); } template -struct databuf -{ - enum - { +struct databuf { + enum { OVERREAD = 1<<0, OVERWROTE = 1<<1 }; - T *buf; int len, maxlen; uchar flags; - databuf() : buf(NULL), len(0), maxlen(0), flags(0) {} - template databuf(T *buf, U maxlen) : buf(buf), len(0), maxlen((int)maxlen), flags(0) {} - - void reset() - { + void reset() { len = 0; flags = 0; } - - void reset(T *buf_, int maxlen_) - { + void reset(T *buf_, int maxlen_) { reset(); buf = buf_; maxlen = maxlen_; } - - const T &get() - { + const T &get() { static T overreadval = 0; if(len= n; } - - void forceoverread() - { + void forceoverread() { len = maxlen; flags |= OVERREAD; } @@ -272,60 +235,42 @@ struct databuf typedef databuf charbuf; typedef databuf ucharbuf; -struct packetbuf : ucharbuf -{ +struct packetbuf : ucharbuf { ENetPacket *packet; int growth; - packetbuf(ENetPacket *packet) : ucharbuf(packet->data, packet->dataLength), packet(packet), growth(0) {} - packetbuf(int growth, int pflags = 0) : growth(growth) - { + packetbuf(int growth, int pflags = 0) : growth(growth) { packet = enet_packet_create(NULL, growth, pflags); buf = (uchar *)packet->data; maxlen = packet->dataLength; } ~packetbuf() { cleanup(); } - void reliable() { packet->flags |= ENET_PACKET_FLAG_RELIABLE; } - - void resize(int n) - { + void resize(int n) { enet_packet_resize(packet, n); buf = (uchar *)packet->data; maxlen = packet->dataLength; } - - void checkspace(int n) - { + void checkspace(int n) { if(len + n > maxlen && packet && growth > 0) resize(max(len + n, maxlen + growth)); } - - ucharbuf subbuf(int sz) - { + ucharbuf subbuf(int sz) { checkspace(sz); return ucharbuf::subbuf(sz); } - - void put(const uchar &val) - { + void put(const uchar &val) { checkspace(1); ucharbuf::put(val); } - - void put(const uchar *vals, int numvals) - { + void put(const uchar *vals, int numvals) { checkspace(numvals); ucharbuf::put(vals, numvals); } - - ENetPacket *finalize() - { + ENetPacket *finalize() { resize(len); return packet; } - - void cleanup() - { + void cleanup() { if(growth > 0 && packet && !packet->referenceCount) { enet_packet_destroy(packet); packet = NULL; buf = NULL; len = maxlen = 0; } } }; @@ -333,27 +278,22 @@ struct packetbuf : ucharbuf template static inline float heapscore(const T &n) { return n; } -struct sortless -{ +struct sortless { template bool operator()(const T &x, const T &y) const { return x < y; } bool operator()(char *x, char *y) const { return strcmp(x, y) < 0; } bool operator()(const char *x, const char *y) const { return strcmp(x, y) < 0; } }; -struct sortnameless -{ +struct sortnameless { template bool operator()(const T &x, const T &y) const { return sortless()(x.name, y.name); } template bool operator()(T *x, T *y) const { return sortless()(x->name, y->name); } template bool operator()(const T *x, const T *y) const { return sortless()(x->name, y->name); } }; template -static inline void insertionsort(T *start, T *end, F fun) -{ - for(T *i = start+1; i < end; i++) - { - if(fun(*i, i[-1])) - { +static inline void insertionsort(T *start, T *end, F fun) { + for(T *i = start+1; i < end; i++) { + if(fun(*i, i[-1])) { T tmp = *i; *i = i[-1]; T *j = i-1; @@ -366,25 +306,20 @@ static inline void insertionsort(T *start, T *end, F fun) } template -static inline void insertionsort(T *buf, int n, F fun) -{ +static inline void insertionsort(T *buf, int n, F fun) { insertionsort(buf, buf+n, fun); } template -static inline void insertionsort(T *buf, int n) -{ +static inline void insertionsort(T *buf, int n) { insertionsort(buf, buf+n, sortless()); } template -static inline void quicksort(T *start, T *end, F fun) -{ - while(end-start > 10) - { +static inline void quicksort(T *start, T *end, F fun) { + while(end-start > 10) { T *mid = &start[(end-start)/2], *i = start+1, *j = end-2, pivot; - if(fun(*start, *mid)) /* start < mid */ - { + if(fun(*start, *mid)) /* start < mid */ { if(fun(end[-1], *start)) { pivot = *start; *start = end[-1]; end[-1] = *mid; } /* end < start < mid */ else if(fun(end[-1], *mid)) { pivot = end[-1]; end[-1] = *mid; } /* start <= end < mid */ else { pivot = *mid; } /* start < mid <= end */ @@ -393,8 +328,7 @@ static inline void quicksort(T *start, T *end, F fun) else if(fun(*mid, end[-1])) { pivot = end[-1]; end[-1] = *start; *start = *mid; } /* mid < end <= start */ else { pivot = *mid; swap(*start, end[-1]); } /* end <= mid <= start */ *mid = end[-2]; - do - { + do { while(fun(*i, pivot)) if(++i >= j) goto partitioned; while(fun(pivot, *--j)) if(i >= j) goto partitioned; swap(*i, *j); @@ -403,61 +337,50 @@ static inline void quicksort(T *start, T *end, F fun) partitioned: end[-2] = *i; *i = pivot; - - if(i-start < end-(i+1)) - { + if(i-start < end-(i+1)) { quicksort(start, i, fun); start = i+1; } - else - { + else { quicksort(i+1, end, fun); end = i; } } - insertionsort(start, end, fun); } template -static inline void quicksort(T *buf, int n, F fun) -{ +static inline void quicksort(T *buf, int n, F fun) { quicksort(buf, buf+n, fun); } template -static inline void quicksort(T *buf, int n) -{ +static inline void quicksort(T *buf, int n) { quicksort(buf, buf+n, sortless()); } -template struct isclass -{ +template struct isclass { template static char test(void (C::*)(void)); template static int test(...); enum { yes = sizeof(test(0)) == 1 ? 1 : 0, no = yes^1 }; }; -static inline uint hthash(const char *key) -{ +static inline uint hthash(const char *key) { uint h = 5381; for(int i = 0, k; (k = key[i]); i++) h = ((h<<5)+h)^k; // bernstein k=33 xor return h; } -static inline bool htcmp(const char *x, const char *y) -{ +static inline bool htcmp(const char *x, const char *y) { return !strcmp(x, y); } -struct stringslice -{ +struct stringslice { const char *str; int len; stringslice() {} stringslice(const char *str, int len) : str(str), len(len) {} stringslice(const char *str, const char *end) : str(str), len(int(end-str)) {} - const char *end() const { return &str[len]; } }; @@ -467,8 +390,7 @@ inline const char *stringptr(const stringslice &s) { return s.str; } inline int stringlen(const char *s) { return int(strlen(s)); } inline int stringlen(const stringslice &s) { return s.len; } -inline char *copystring(char *d, const stringslice &s, size_t len) -{ +inline char *copystring(char *d, const stringslice &s, size_t len) { size_t slen = min(size_t(s.len), len-1); memcpy(d, s.str, slen); d[slen] = 0; @@ -476,8 +398,7 @@ inline char *copystring(char *d, const stringslice &s, size_t len) } template inline char *copystring(char (&d)[N], const stringslice &s) { return copystring(d, s, N); } -static inline uint memhash(const void *ptr, int len) -{ +static inline uint memhash(const void *ptr, int len) { const uchar *data = (const uchar *)ptr; uint h = 5381; loopi(len) h = ((h<<5)+h)^data[i]; @@ -486,269 +407,193 @@ static inline uint memhash(const void *ptr, int len) static inline uint hthash(const stringslice &s) { return memhash(s.str, s.len); } -static inline bool htcmp(const stringslice &x, const char *y) -{ +static inline bool htcmp(const stringslice &x, const char *y) { return x.len == (int)strlen(y) && !memcmp(x.str, y, x.len); } -static inline uint hthash(int key) -{ +static inline uint hthash(int key) { return key; } -static inline bool htcmp(int x, int y) -{ +static inline bool htcmp(int x, int y) { return x==y; } #ifndef STANDALONE -static inline uint hthash(GLuint key) -{ +static inline uint hthash(GLuint key) { return key; } -static inline bool htcmp(GLuint x, GLuint y) -{ +static inline bool htcmp(GLuint x, GLuint y) { return x==y; } #endif -template struct vector -{ +template struct vector { static const int MINSIZE = 8; - T *buf; int alen, ulen; - - vector() : buf(NULL), alen(0), ulen(0) - { + vector() : buf(NULL), alen(0), ulen(0) { } - - vector(const vector &v) : buf(NULL), alen(0), ulen(0) - { + vector(const vector &v) : buf(NULL), alen(0), ulen(0) { *this = v; } - ~vector() { shrink(0); if(buf) delete[] (uchar *)buf; } - - vector &operator=(const vector &v) - { + vector &operator=(const vector &v) { shrink(0); if(v.length() > alen) growbuf(v.length()); loopv(v) add(v[i]); return *this; } - - T &add(const T &x) - { + T &add(const T &x) { if(ulen==alen) growbuf(ulen+1); new (&buf[ulen]) T(x); return buf[ulen++]; } - - T &add() - { + T &add() { if(ulen==alen) growbuf(ulen+1); new (&buf[ulen]) T; return buf[ulen++]; } - - T &dup() - { + T &dup() { if(ulen==alen) growbuf(ulen+1); new (&buf[ulen]) T(buf[ulen-1]); return buf[ulen++]; } - - void move(vector &v) - { - if(!ulen) - { + void move(vector &v) { + if(!ulen) { swap(buf, v.buf); swap(ulen, v.ulen); swap(alen, v.alen); } - else - { + else { growbuf(ulen+v.ulen); if(v.ulen) memcpy(&buf[ulen], (void *)v.buf, v.ulen*sizeof(T)); ulen += v.ulen; v.ulen = 0; } } - bool inrange(size_t i) const { return i=0 && i=0 && i= 0 && i::no) ulen = i; else while(ulen>i) drop(); } void setsize(int i) { ASSERT(i<=ulen); ulen = i; } - void deletecontents() { while(!empty()) delete pop(); } void deletearrays() { while(!empty()) delete[] pop(); } - T *getbuf() { return buf; } const T *getbuf() const { return buf; } bool inbuf(const T *e) const { return e >= buf && e < &buf[ulen]; } - template - void sort(F fun, int i = 0, int n = -1) - { + void sort(F fun, int i = 0, int n = -1) { quicksort(&buf[i], n < 0 ? ulen-i : n, fun); } - void sort() { sort(sortless()); } void sortname() { sort(sortnameless()); } - - void growbuf(int sz) - { + void growbuf(int sz) { int olen = alen; if(alen <= 0) alen = max(MINSIZE, sz); else while(alen < sz) alen += alen/2; if(alen <= olen) return; uchar *newbuf = new uchar[alen*sizeof(T)]; - if(olen > 0) - { + if(olen > 0) { if(ulen > 0) memcpy(newbuf, (void *)buf, ulen*sizeof(T)); delete[] (uchar *)buf; } buf = (T *)newbuf; } - - databuf reserve(int sz) - { + databuf reserve(int sz) { if(alen-ulen < sz) growbuf(ulen+sz); return databuf(&buf[ulen], sz); } - - void advance(int sz) - { + void advance(int sz) { ulen += sz; } - - void addbuf(const databuf &p) - { + void addbuf(const databuf &p) { advance(p.length()); } - - T *pad(int n) - { + T *pad(int n) { T *buf = reserve(n).buf; advance(n); return buf; } - void put(const T &v) { add(v); } - - void put(const T *v, int n) - { + void put(const T *v, int n) { databuf buf = reserve(n); buf.put(v, n); addbuf(buf); } - - void remove(int i, int n) - { + void remove(int i, int n) { for(int p = i+n; p0) buf[i] = buf[ulen]; return e; } - template - int find(const U &o) - { + int find(const U &o) { loopi(ulen) if(buf[i]==o) return i; return -1; } - - void addunique(const T &o) - { + void addunique(const T &o) { if(find(o) < 0) add(o); } - - void removeobj(const T &o) - { - loopi(ulen) if(buf[i] == o) - { + void removeobj(const T &o) { + loopi(ulen) if(buf[i] == o) { int dst = i; for(int j = i+1; j < ulen; j++) if(!(buf[j] == o)) buf[dst++] = buf[j]; setsize(dst); break; } } - - void replacewithlast(const T &o) - { + void replacewithlast(const T &o) { if(!ulen) return; - loopi(ulen-1) if(buf[i]==o) - { + loopi(ulen-1) if(buf[i]==o) { buf[i] = buf[ulen-1]; break; } ulen--; } - - T &insert(int i, const T &e) - { + T &insert(int i, const T &e) { add(T()); for(int p = ulen-1; p>i; p--) buf[p] = buf[p-1]; buf[i] = e; return buf[i]; } - - T *insert(int i, const T *e, int n) - { + T *insert(int i, const T *e, int n) { if(alen-ulen < n) growbuf(ulen+n); loopj(n) add(T()); for(int p = ulen-1; p>=i+n; p--) buf[p] = buf[p-n]; loopj(n) buf[i+j] = e[j]; return &buf[i]; } - - void reverse() - { + void reverse() { loopi(ulen/2) swap(buf[i], buf[ulen-1-i]); } - static int heapparent(int i) { return (i - 1) >> 1; } static int heapchild(int i) { return (i << 1) + 1; } - - void buildheap() - { + void buildheap() { for(int i = ulen/2; i >= 0; i--) downheap(i); } - - int upheap(int i) - { + int upheap(int i) { float score = heapscore(buf[i]); - while(i > 0) - { + while(i > 0) { int pi = heapparent(i); if(score >= heapscore(buf[pi])) break; swap(buf[i], buf[pi]); @@ -756,23 +601,17 @@ template struct vector } return i; } - - T &addheap(const T &x) - { + T &addheap(const T &x) { add(x); return buf[upheap(ulen-1)]; } - - int downheap(int i) - { + int downheap(int i) { float score = heapscore(buf[i]); - for(;;) - { + for(;;) { int ci = heapchild(i); if(ci >= ulen) break; float cscore = heapscore(buf[ci]); - if(score > cscore) - { + if(score > cscore) { if(ci+1 < ulen && heapscore(buf[ci+1]) < cscore) { swap(buf[ci+1], buf[i]); i = ci+1; } else { swap(buf[ci], buf[i]); i = ci; } } @@ -781,62 +620,45 @@ template struct vector } return i; } - - T removeheap() - { + T removeheap() { T e = removeunordered(0); if(ulen) downheap(0); return e; } - template - int htfind(const K &key) - { + int htfind(const K &key) { loopi(ulen) if(htcmp(key, buf[i])) return i; return -1; } }; -template struct hashbase -{ +template struct hashbase { typedef E elemtype; typedef K keytype; typedef T datatype; - enum { CHUNKSIZE = 64 }; - struct chain { E elem; chain *next; }; struct chainchunk { chain chains[CHUNKSIZE]; chainchunk *next; }; - int size; int numelems; chain **chains; - chainchunk *chunks; chain *unused; - enum { DEFAULTSIZE = 1<<10 }; - hashbase(int size = DEFAULTSIZE) - : size(size) - { + : size(size) { numelems = 0; chunks = NULL; unused = NULL; chains = new chain *[size]; memset(chains, 0, size*sizeof(chain *)); } - - ~hashbase() - { + ~hashbase() { DELETEA(chains); deletechunks(); } - - chain *insert(uint h) - { - if(!unused) - { + chain *insert(uint h) { + if(!unused) { chainchunk *chunk = new chainchunk; chunk->next = chunks; chunks = chunk; @@ -851,61 +673,44 @@ template struct hashbase numelems++; return c; } - template - T &insert(uint h, const U &key) - { + T &insert(uint h, const U &key) { chain *c = insert(h); H::setkey(c->elem, key); return H::getdata(c->elem); } - #define HTFIND(success, fail) \ uint h = hthash(key)&(this->size-1); \ - for(chain *c = this->chains[h]; c; c = c->next) \ - { \ + for(chain *c = this->chains[h]; c; c = c->next) { \ + \ if(htcmp(key, H::getkey(c->elem))) return success H::getdata(c->elem); \ } \ return (fail); - template - T *access(const U &key) - { + T *access(const U &key) { HTFIND(&, NULL); } - template - T &access(const U &key, const V &elem) - { + T &access(const U &key, const V &elem) { HTFIND( , insert(h, key) = elem); } - template - T &operator[](const U &key) - { + T &operator[](const U &key) { HTFIND( , insert(h, key)); } - template - T &find(const U &key, T ¬found) - { + T &find(const U &key, T ¬found) { HTFIND( , notfound); } - template - const T &find(const U &key, const T ¬found) - { + const T &find(const U &key, const T ¬found) { HTFIND( , notfound); } - template - bool remove(const U &key) - { + bool remove(const U &key) { uint h = hthash(key)&(size-1); - for(chain **p = &chains[h], *c = chains[h]; c; p = &c->next, c = c->next) - { - if(htcmp(key, H::getkey(c->elem))) - { + for(chain **p = &chains[h], *c = chains[h]; c; p = &c->next, c = c->next) { + if(htcmp(key, H::getkey(c->elem))) { *p = c->next; c->elem.~E(); new (&c->elem) E; @@ -917,78 +722,58 @@ template struct hashbase } return false; } - - void deletechunks() - { - for(chainchunk *nextchunk; chunks; chunks = nextchunk) - { + void deletechunks() { + for(chainchunk *nextchunk; chunks; chunks = nextchunk) { nextchunk = chunks->next; delete chunks; } } - - void clear() - { + void clear() { if(!numelems) return; memset(chains, 0, size*sizeof(chain *)); numelems = 0; unused = NULL; deletechunks(); } - static inline chain *enumnext(void *i) { return ((chain *)i)->next; } static inline K &enumkey(void *i) { return H::getkey(((chain *)i)->elem); } static inline T &enumdata(void *i) { return H::getdata(((chain *)i)->elem); } }; -template struct hashset : hashbase, T, T, T> -{ +template struct hashset : hashbase, T, T, T> { typedef hashbase, T, T, T> basetype; - hashset(int size = basetype::DEFAULTSIZE) : basetype(size) {} - static inline const T &getkey(const T &elem) { return elem; } static inline T &getdata(T &elem) { return elem; } - template static inline void setkey(T &elem, const K &key) {} - + template static inline void setkey(T &, const K &) {} template - T &add(const V &elem) - { + T &add(const V &elem) { return basetype::access(elem, elem); } }; -template struct hashnameset : hashbase, T, const char *, T> -{ +template struct hashnameset : hashbase, T, const char *, T> { typedef hashbase, T, const char *, T> basetype; - hashnameset(int size = basetype::DEFAULTSIZE) : basetype(size) {} - template static inline const char *getkey(const U &elem) { return elem.name; } template static inline const char *getkey(U *elem) { return elem->name; } static inline T &getdata(T &elem) { return elem; } template static inline void setkey(T &elem, const K &key) {} - template - T &add(const V &elem) - { + T &add(const V &elem) { return basetype::access(getkey(elem), elem); } }; -template struct hashtableentry -{ +template struct hashtableentry { K key; T data; }; -template struct hashtable : hashbase, hashtableentry, K, T> -{ +template struct hashtable : hashbase, hashtableentry, K, T> { typedef hashbase, hashtableentry, K, T> basetype; typedef typename basetype::elemtype elemtype; - hashtable(int size = basetype::DEFAULTSIZE) : basetype(size) {} - static inline K &getkey(elemtype &elem) { return elem.key; } static inline T &getdata(elemtype &elem) { return elem.data; } template static inline void setkey(elemtype &elem, const U &key) { elem.key = key; } @@ -997,69 +782,51 @@ template struct hashtable : hashbase, hashtabl #define enumeratekt(ht,k,e,t,f,b) loopi((ht).size) for(void *ec = (ht).chains[i]; ec;) { k &e = (ht).enumkey(ec); t &f = (ht).enumdata(ec); ec = (ht).enumnext(ec); b; } #define enumerate(ht,t,e,b) loopi((ht).size) for(void *ec = (ht).chains[i]; ec;) { t &e = (ht).enumdata(ec); ec = (ht).enumnext(ec); b; } -struct unionfind -{ - struct ufval - { +struct unionfind { + struct ufval { int rank, next; - ufval() : rank(0), next(-1) {} }; - vector ufvals; - - int find(int k) - { + int find(int k) { if(k>=ufvals.length()) return k; while(ufvals[k].next>=0) k = ufvals[k].next; return k; } - - int compressfind(int k) - { + int compressfind(int k) { if(ufvals[k].next<0) return k; return ufvals[k].next = compressfind(ufvals[k].next); } - - void unite (int x, int y) - { + void unite (int x, int y) { while(ufvals.length() <= max(x, y)) ufvals.add(); x = compressfind(x); y = compressfind(y); if(x==y) return; ufval &xval = ufvals[x], &yval = ufvals[y]; if(xval.rank < yval.rank) xval.next = y; - else - { + else { yval.next = x; if(xval.rank==yval.rank) yval.rank++; } } }; -template struct queue -{ +template struct queue { int head, tail, len; T data[SIZE]; - queue() { clear(); } - void clear() { head = tail = len = 0; } - int capacity() const { return SIZE; } int length() const { return len; } bool empty() const { return !len; } bool full() const { return len == SIZE; } - bool inrange(size_t i) const { return i=0 && i 0 ? tail-1 : SIZE-1]; } T &added(int offset) { return data[tail-offset > 0 ? tail-offset-1 : tail-offset-1 + SIZE]; } T &adding() { return data[tail]; } T &adding(int offset) { return data[tail+offset >= SIZE ? tail+offset - SIZE : tail+offset]; } - T &add() - { + T &add() { T &t = data[tail]; tail++; if(tail >= SIZE) tail -= SIZE; @@ -1067,52 +834,39 @@ template struct queue return t; } T &add(const T &e) { return add() = e; } - - databuf reserve(int sz) - { + databuf reserve(int sz) { if(!len) head = tail = 0; return databuf(&data[tail], min(sz, SIZE-tail)); } - - void advance(int sz) - { + void advance(int sz) { if(len + sz > SIZE) sz = SIZE - len; tail += sz; if(tail >= SIZE) tail -= SIZE; len += sz; } - - void addbuf(const databuf &p) - { + void addbuf(const databuf &p) { advance(p.length()); } - - T &pop() - { + T &pop() { tail--; if(tail < 0) tail += SIZE; len--; return data[tail]; } - T &removing() { return data[head]; } T &removing(int offset) { return data[head+offset >= SIZE ? head+offset - SIZE : head+offset]; } - T &remove() - { + T &remove() { T &t = data[head]; head++; if(head >= SIZE) head -= SIZE; len--; return t; } - - T remove(int offset) - { + T remove(int offset) { T val = removing(offset); if(head+offset >= SIZE) for(int i = head+offset - SIZE + 1; i < tail; i++) data[i-1] = data[i]; else if(head < tail) for(int i = head+offset + 1; i < tail; i++) data[i-1] = data[i]; - else - { + else { for(int i = head+offset + 1; i < SIZE; i++) data[i-1] = data[i]; data[SIZE-1] = data[0]; for(int i = 1; i < tail; i++) data[i-1] = data[i]; @@ -1122,13 +876,11 @@ template struct queue len--; return val; } - T &operator[](int offset) { return removing(offset); } const T &operator[](int offset) const { return removing(offset); } }; -template struct reversequeue : queue -{ +template struct reversequeue : queue { T &operator[](int offset) { return queue::added(offset); } const T &operator[](int offset) const { return queue::added(offset); } }; @@ -1153,7 +905,8 @@ template<> inline llong endianswap(llong n) { return endianswap64(n); } template<> inline double endianswap(double n) { union { double t; uint i; } conv; conv.t = n; conv.i = endianswap64(conv.i); return conv.t; } template inline void endianswap(T *buf, size_t len) { for(T *end = &buf[len]; buf < end; buf++) *buf = endianswap(*buf); } template inline T endiansame(T n) { return n; } -template inline void endiansame(T *buf, size_t len) {} +//~template inline void endiansame(T *buf, size_t len) {} +template inline void endiansame(T *, size_t) {} #ifdef SDL_BYTEORDER #if SDL_BYTEORDER == SDL_LIL_ENDIAN #define lilswap endiansame @@ -1177,20 +930,18 @@ template inline T bigswap(T n) { return *(const uchar *)&islittleendian template inline void bigswap(T *buf, size_t len) { if(*(const uchar *)&islittleendian) endianswap(buf, len); } #endif -struct stream -{ +struct stream { typedef off_t offset; - virtual ~stream() {} virtual void close() = 0; virtual bool end() = 0; virtual offset tell() { return -1; } virtual offset rawtell() { return tell(); } - virtual bool seek(offset pos, int whence = SEEK_SET) { return false; } + virtual bool seek(offset pos, int whence = SEEK_SET) { (void) pos; (void) whence; return false; } virtual offset size(); virtual offset rawsize() { return size(); } - virtual size_t read(void *buf, size_t len) { return 0; } - virtual size_t write(const void *buf, size_t len) { return 0; } + virtual size_t read(void *buf, size_t len) { (void) buf; (void) len; return 0; } + virtual size_t write(const void *buf, size_t len) { (void) buf; (void) len; return 0; } virtual bool flush() { return true; } virtual int getchar() { uchar c; return read(&c, 1) == 1 ? c : -1; } virtual bool putchar(int n) { uchar c = n; return write(&c, 1) == 1; } @@ -1199,12 +950,10 @@ struct stream virtual bool putline(const char *str) { return putstring(str) && putchar('\n'); } virtual size_t printf(const char *fmt, ...) PRINTFARGS(2, 3); virtual uint getcrc() { return 0; } - template size_t put(const T *v, size_t n) { return write(v, n*sizeof(T))/sizeof(T); } template bool put(T n) { return write(&n, sizeof(n)) == sizeof(n); } template bool putlil(T n) { return put(lilswap(n)); } template bool putbig(T n) { return put(bigswap(n)); } - template size_t get(T *v, size_t n) { return read(v, n*sizeof(T))/sizeof(T); } template T get() { T n; return read(&n, sizeof(n)) == sizeof(n) ? n : 0; } template T getlil() { return lilswap(get()); } @@ -1216,12 +965,9 @@ struct stream }; template -struct streambuf -{ +struct streambuf { stream *s; - streambuf(stream *s) : s(s) {} - T get() { return s->get(); } size_t get(T *vals, size_t numvals) { return s->get(vals, numvals); } void put(const T &val) { s->put(&val, 1); } @@ -1229,8 +975,7 @@ struct streambuf size_t length() { return s->size(); } }; -enum -{ +enum { CT_PRINT = 1<<0, CT_SPACE = 1<<1, CT_DIGIT = 1<<2, @@ -1247,24 +992,20 @@ static inline int iscubealnum(uchar c) { return cubectype[c]&(CT_ALPHA|CT_DIGIT) static inline int iscubelower(uchar c) { return cubectype[c]&CT_LOWER; } static inline int iscubeupper(uchar c) { return cubectype[c]&CT_UPPER; } static inline int iscubepunct(uchar c) { return cubectype[c] == CT_PRINT; } -static inline int cube2uni(uchar c) -{ +static inline int cube2uni(uchar c) { extern const int cube2unichars[256]; return cube2unichars[c]; } -static inline uchar uni2cube(int c) -{ +static inline uchar uni2cube(int c) { extern const int uni2cubeoffsets[8]; extern const uchar uni2cubechars[]; return uint(c) <= 0x7FF ? uni2cubechars[uni2cubeoffsets[c>>8] + (c&0xFF)] : 0; } -static inline uchar cubelower(uchar c) -{ +static inline uchar cubelower(uchar c) { extern const uchar cubelowerchars[256]; return cubelowerchars[c]; } -static inline uchar cubeupper(uchar c) -{ +static inline uchar cubeupper(uchar c) { extern const uchar cubeupperchars[256]; return cubeupperchars[c]; } @@ -1317,10 +1058,8 @@ template static inline void getstring(char (&t)[N], ucharbuf &p) { get extern void filtertext(char *dst, const char *src, bool whitespace, bool forcespace, size_t len); template static inline void filtertext(char (&dst)[N], const char *src, bool whitespace = true, bool forcespace = false) { filtertext(dst, src, whitespace, forcespace, N-1); } -struct ipmask -{ +struct ipmask { enet_uint32 ip, mask; - void parse(const char *name); int print(char *buf) const; bool check(enet_uint32 host) const { return (host & mask) == ip; } diff --git a/src/shared/zip.cpp b/src/shared/zip.cpp index 83b2952..c60ea16 100644 --- a/src/shared/zip.cpp +++ b/src/shared/zip.cpp @@ -1,7 +1,6 @@ #include "cube.h" -enum -{ +enum { ZIP_LOCAL_FILE_SIGNATURE = 0x04034B50, ZIP_LOCAL_FILE_SIZE = 30, ZIP_FILE_SIGNATURE = 0x02014B50, @@ -10,16 +9,14 @@ enum ZIP_DIRECTORY_SIZE = 22 }; -struct ziplocalfileheader -{ +struct ziplocalfileheader { uint signature; ushort version, flags, compression, modtime, moddate; uint crc32, compressedsize, uncompressedsize; ushort namelength, extralength; }; -struct zipfileheader -{ +struct zipfileheader { uint signature; ushort version, needversion, flags, compression, modtime, moddate; uint crc32, compressedsize, uncompressedsize; @@ -27,62 +24,48 @@ struct zipfileheader uint externalattribs, offset; }; -struct zipdirectoryheader -{ +struct zipdirectoryheader { uint signature; ushort disknumber, directorydisk, diskentries, entries; uint size, offset; ushort commentlength; }; -struct zipfile -{ +struct zipfile { char *name; uint header, offset, size, compressedsize; - - zipfile() : name(NULL), header(0), offset(~0U), size(0), compressedsize(0) - { + zipfile() : name(NULL), header(0), offset(~0U), size(0), compressedsize(0) { } - ~zipfile() - { + ~zipfile() { DELETEA(name); } }; struct zipstream; -struct ziparchive -{ +struct ziparchive { char *name; FILE *data; hashnameset files; int openfiles; zipstream *owner; - - ziparchive() : name(NULL), data(NULL), files(512), openfiles(0), owner(NULL) - { + ziparchive() : name(NULL), data(NULL), files(512), openfiles(0), owner(NULL) { } - ~ziparchive() - { + ~ziparchive() { DELETEA(name); if(data) { fclose(data); data = NULL; } } }; -static bool findzipdirectory(FILE *f, zipdirectoryheader &hdr) -{ +static bool findzipdirectory(FILE *f, zipdirectoryheader &hdr) { if(fseek(f, 0, SEEK_END) < 0) return false; - long offset = ftell(f); if(offset < 0) return false; - uchar buf[1024], *src = NULL; long end = max(offset - 0xFFFFL - ZIP_DIRECTORY_SIZE, 0L); size_t len = 0; const uint signature = lilswap(ZIP_DIRECTORY_SIGNATURE); - - while(offset > end) - { + while(offset > end) { size_t carry = min(len, size_t(ZIP_DIRECTORY_SIZE-1)), next = min(sizeof(buf) - carry, size_t(offset - end)); offset -= next; memmove(&buf[next], buf, carry); @@ -92,9 +75,7 @@ static bool findzipdirectory(FILE *f, zipdirectoryheader &hdr) for(; search >= buf; search--) if(*(uint *)search == signature) break; if(search >= buf) { src = search; break; } } - if(!src || &buf[len] - src < ZIP_DIRECTORY_SIZE) return false; - hdr.signature = lilswap(*(uint *)src); src += 4; hdr.disknumber = lilswap(*(ushort *)src); src += 2; hdr.directorydisk = lilswap(*(ushort *)src); src += 2; @@ -103,20 +84,15 @@ static bool findzipdirectory(FILE *f, zipdirectoryheader &hdr) hdr.size = lilswap(*(uint *)src); src += 4; hdr.offset = lilswap(*(uint *)src); src += 4; hdr.commentlength = lilswap(*(ushort *)src); src += 2; - if(hdr.signature != ZIP_DIRECTORY_SIGNATURE || hdr.disknumber != hdr.directorydisk || hdr.diskentries != hdr.entries) return false; - return true; } -static bool readzipdirectory(const char *archname, FILE *f, int entries, int offset, uint size, vector &files) -{ +static bool readzipdirectory(const char *archname, FILE *f, int entries, int offset, uint size, vector &files) { uchar *buf = new (false) uchar[size], *src = buf; if(!buf || fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, size, f) != size) { delete[] buf; return false; } - loopi(entries) - { + loopi(entries) { if(src + ZIP_FILE_SIZE > &buf[size]) break; - zipfileheader hdr; hdr.signature = lilswap(*(uint *)src); src += 4; hdr.version = lilswap(*(ushort *)src); src += 2; @@ -136,35 +112,29 @@ static bool readzipdirectory(const char *archname, FILE *f, int entries, int off hdr.externalattribs = lilswap(*(uint *)src); src += 4; hdr.offset = lilswap(*(uint *)src); src += 4; if(hdr.signature != ZIP_FILE_SIGNATURE) break; - if(!hdr.namelength || !hdr.uncompressedsize || (hdr.compression && (hdr.compression != Z_DEFLATED || !hdr.compressedsize))) - { + if(!hdr.namelength || !hdr.uncompressedsize || (hdr.compression && (hdr.compression != Z_DEFLATED || !hdr.compressedsize))) { src += hdr.namelength + hdr.extralength + hdr.commentlength; continue; } if(src + hdr.namelength > &buf[size]) break; - string pname; int namelen = min((int)hdr.namelength, (int)sizeof(pname)-1); memcpy(pname, src, namelen); pname[namelen] = '\0'; path(pname); char *name = newstring(pname); - zipfile &f = files.add(); f.name = name; f.header = hdr.offset; f.size = hdr.uncompressedsize; f.compressedsize = hdr.compression ? hdr.compressedsize : 0; - src += hdr.namelength + hdr.extralength + hdr.commentlength; } delete[] buf; - return files.length() > 0; } -static bool readlocalfileheader(FILE *f, ziplocalfileheader &h, uint offset) -{ +static bool readlocalfileheader(FILE *f, ziplocalfileheader &h, uint offset) { uchar buf[ZIP_LOCAL_FILE_SIZE]; if(fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, ZIP_LOCAL_FILE_SIZE, f) != ZIP_LOCAL_FILE_SIZE) return false; @@ -187,48 +157,38 @@ static bool readlocalfileheader(FILE *f, ziplocalfileheader &h, uint offset) static vector archives; -ziparchive *findzip(const char *name) -{ +ziparchive *findzip(const char *name) { loopv(archives) if(!strcmp(name, archives[i]->name)) return archives[i]; return NULL; } -static bool checkprefix(vector &files, const char *prefix, int prefixlen) -{ - loopv(files) - { +static bool checkprefix(vector &files, const char *prefix, int prefixlen) { + loopv(files) { if(!strncmp(files[i].name, prefix, prefixlen)) return false; } return true; } -static void mountzip(ziparchive &arch, vector &files, const char *mountdir, const char *stripdir) -{ +static void mountzip(ziparchive &arch, vector &files, const char *mountdir, const char *stripdir) { string packagesdir = "packages/"; path(packagesdir); size_t striplen = stripdir ? strlen(stripdir) : 0; - if(!mountdir && !stripdir) loopv(files) - { + if(!mountdir && !stripdir) loopv(files) { zipfile &f = files[i]; const char *foundpackages = strstr(f.name, packagesdir); - if(foundpackages) - { - if(foundpackages > f.name) - { + if(foundpackages) { + if(foundpackages > f.name) { stripdir = f.name; striplen = foundpackages - f.name; } break; } const char *foundogz = strstr(f.name, ".ogz"); - if(foundogz) - { + if(foundogz) { const char *ogzdir = foundogz; while(--ogzdir >= f.name && *ogzdir != PATHDIV); - if(ogzdir < f.name || checkprefix(files, f.name, ogzdir + 1 - f.name)) - { - if(ogzdir >= f.name) - { + if(ogzdir < f.name || checkprefix(files, f.name, ogzdir + 1 - f.name)) { + if(ogzdir >= f.name) { stripdir = f.name; striplen = ogzdir + 1 - f.name; } @@ -238,13 +198,11 @@ static void mountzip(ziparchive &arch, vector &files, const char *mount } } string mdir = "", fname; - if(mountdir) - { + if(mountdir) { copystring(mdir, mountdir); if(fixpackagedir(mdir) <= 1) mdir[0] = '\0'; } - loopv(files) - { + loopv(files) { zipfile &f = files[i]; formatstring(fname, "%s%s", mdir, striplen && !strncmp(f.name, stripdir, striplen) ? &f.name[striplen] : f.name); if(arch.files.access(fname)) continue; @@ -255,61 +213,50 @@ static void mountzip(ziparchive &arch, vector &files, const char *mount } } -bool addzip(const char *name, const char *mount = NULL, const char *strip = NULL) -{ +bool addzip(const char *name, const char *mount = NULL, const char *strip = NULL) { string pname; copystring(pname, name); path(pname); size_t plen = strlen(pname); if(plen < 4 || !strchr(&pname[plen-4], '.')) concatstring(pname, ".zip"); - ziparchive *exists = findzip(pname); - if(exists) - { + if(exists) { conoutf(CON_ERROR, "already added zip %s", pname); return true; } - FILE *f = fopen(findfile(pname, "rb"), "rb"); - if(!f) - { + if(!f) { conoutf(CON_ERROR, "could not open file %s", pname); return false; } zipdirectoryheader h; vector files; - if(!findzipdirectory(f, h) || !readzipdirectory(pname, f, h.entries, h.offset, h.size, files)) - { + if(!findzipdirectory(f, h) || !readzipdirectory(pname, f, h.entries, h.offset, h.size, files)) { conoutf(CON_ERROR, "could not read directory in zip %s", pname); fclose(f); return false; } - ziparchive *arch = new ziparchive; arch->name = newstring(pname); arch->data = f; mountzip(*arch, files, mount, strip); archives.add(arch); - conoutf("added zip %s", pname); return true; } -bool removezip(const char *name) -{ +bool removezip(const char *name) { string pname; copystring(pname, name); path(pname); int plen = (int)strlen(pname); if(plen < 4 || !strchr(&pname[plen-4], '.')) concatstring(pname, ".zip"); ziparchive *exists = findzip(pname); - if(!exists) - { + if(!exists) { conoutf(CON_ERROR, "zip %s is not loaded", pname); return false; } - if(exists->openfiles) - { + if(exists->openfiles) { conoutf(CON_ERROR, "zip %s has open files", pname); return false; } @@ -319,40 +266,30 @@ bool removezip(const char *name) return true; } -struct zipstream : stream -{ - enum - { +struct zipstream : stream { + enum { BUFSIZE = 16384 }; - ziparchive *arch; zipfile *info; z_stream zfile; uchar *buf; uint reading; bool ended; - - zipstream() : arch(NULL), info(NULL), buf(NULL), reading(~0U), ended(false) - { + zipstream() : arch(NULL), info(NULL), buf(NULL), reading(~0U), ended(false) { zfile.zalloc = NULL; zfile.zfree = NULL; zfile.opaque = NULL; zfile.next_in = zfile.next_out = NULL; zfile.avail_in = zfile.avail_out = 0; } - - ~zipstream() - { + ~zipstream() { close(); } - - void readbuf(uint size = BUFSIZE) - { + void readbuf(uint size = BUFSIZE) { if(!zfile.avail_in) zfile.next_in = (Bytef *)buf; size = min(size, uint(&buf[BUFSIZE] - &zfile.next_in[zfile.avail_in])); - if(arch->owner != this) - { + if(arch->owner != this) { arch->owner = NULL; if(fseek(arch->data, reading, SEEK_SET) >= 0) arch->owner = this; else return; @@ -362,19 +299,14 @@ struct zipstream : stream zfile.avail_in += n; reading += n; } - - bool open(ziparchive *a, zipfile *f) - { - if(f->offset == ~0U) - { + bool open(ziparchive *a, zipfile *f) { + if(f->offset == ~0U) { ziplocalfileheader h; a->owner = NULL; if(!readlocalfileheader(a->data, h, f->header)) return false; f->offset = f->header + ZIP_LOCAL_FILE_SIZE + h.namelength + h.extralength; } - if(f->compressedsize && inflateInit2(&zfile, -MAX_WBITS) != Z_OK) return false; - a->openfiles++; arch = a; info = f; @@ -383,32 +315,23 @@ struct zipstream : stream if(f->compressedsize) buf = new uchar[BUFSIZE]; return true; } - - void stopreading() - { + void stopreading() { if(reading == ~0U) return; if(info->compressedsize) inflateEnd(&zfile); reading = ~0U; } - - void close() - { + void close() { stopreading(); DELETEA(buf); if(arch) { arch->owner = NULL; arch->openfiles--; arch = NULL; } } - offset size() { return info->size; } bool end() { return reading == ~0U || ended; } offset tell() { return reading != ~0U ? (info->compressedsize ? zfile.total_out : reading - info->offset) : offset(-1); } - - bool seek(offset pos, int whence) - { + bool seek(offset pos, int whence) { if(reading == ~0U) return false; - if(!info->compressedsize) - { - switch(whence) - { + if(!info->compressedsize) { + switch(whence) { case SEEK_END: pos += info->offset + info->size; break; case SEEK_CUR: pos += reading; break; case SEEK_SET: pos += info->offset; break; @@ -422,17 +345,13 @@ struct zipstream : stream ended = false; return true; } - - switch(whence) - { + switch(whence) { case SEEK_END: pos += info->size; break; case SEEK_CUR: pos += zfile.total_out; break; case SEEK_SET: break; default: return false; } - - if(pos >= (offset)info->size) - { + if(pos >= (offset)info->size) { reading = info->offset + info->compressedsize; zfile.next_in += zfile.avail_in; zfile.avail_in = 0; @@ -442,18 +361,14 @@ struct zipstream : stream ended = false; return true; } - if(pos < 0) return false; if(pos >= (offset)zfile.total_out) pos -= zfile.total_out; - else - { - if(zfile.next_in && zfile.total_in <= uint(zfile.next_in - buf)) - { + else { + if(zfile.next_in && zfile.total_in <= uint(zfile.next_in - buf)) { zfile.avail_in += zfile.total_in; zfile.next_in -= zfile.total_in; } - else - { + else { arch->owner = NULL; zfile.avail_in = 0; zfile.next_in = NULL; @@ -461,45 +376,34 @@ struct zipstream : stream } inflateReset(&zfile); } - uchar skip[512]; - while(pos > 0) - { + while(pos > 0) { size_t skipped = (size_t)min(pos, (offset)sizeof(skip)); if(read(skip, skipped) != skipped) return false; pos -= skipped; } - ended = false; return true; } - - size_t read(void *buf, size_t len) - { + size_t read(void *buf, size_t len) { if(reading == ~0U || !buf || !len) return 0; - if(!info->compressedsize) - { - if(arch->owner != this) - { + if(!info->compressedsize) { + if(arch->owner != this) { arch->owner = NULL; if(fseek(arch->data, reading, SEEK_SET) < 0) { stopreading(); return 0; } arch->owner = this; } - size_t n = fread(buf, 1, min(len, size_t(info->size + info->offset - reading)), arch->data); reading += n; if(n < len) ended = true; return n; } - zfile.next_out = (Bytef *)buf; zfile.avail_out = len; - while(zfile.avail_out > 0) - { + while(zfile.avail_out > 0) { if(!zfile.avail_in) readbuf(BUFSIZE); int err = inflate(&zfile, Z_NO_FLUSH); - if(err != Z_OK) - { + if(err != Z_OK) { if(err == Z_STREAM_END) ended = true; else stopreading(); break; @@ -509,11 +413,9 @@ struct zipstream : stream } }; -stream *openzipfile(const char *name, const char *mode) -{ +stream *openzipfile(const char *name, const char *mode) { for(; *mode; mode++) if(*mode=='w' || *mode=='a') return NULL; - loopvrev(archives) - { + loopvrev(archives) { ziparchive *arch = archives[i]; zipfile *f = arch->files.access(name); if(!f) continue; @@ -524,36 +426,29 @@ stream *openzipfile(const char *name, const char *mode) return NULL; } -bool findzipfile(const char *name) -{ - loopvrev(archives) - { +bool findzipfile(const char *name) { + loopvrev(archives) { ziparchive *arch = archives[i]; if(arch->files.access(name)) return true; } return false; } -int listzipfiles(const char *dir, const char *ext, vector &files) -{ +int listzipfiles(const char *dir, const char *ext, vector &files) { size_t extsize = ext ? strlen(ext)+1 : 0, dirsize = strlen(dir); int dirs = 0; - loopvrev(archives) - { + loopvrev(archives) { ziparchive *arch = archives[i]; int oldsize = files.length(); - enumerate(arch->files, zipfile, f, - { + enumerate(arch->files, zipfile, f, { if(strncmp(f.name, dir, dirsize)) continue; const char *name = f.name + dirsize; if(name[0] == PATHDIV) name++; if(strchr(name, PATHDIV)) continue; if(!ext) files.add(newstring(name)); - else - { + else { size_t namelen = strlen(name); - if(namelen > extsize) - { + if(namelen > extsize) { namelen -= extsize; if(name[namelen] == '.' && strncmp(name+namelen+1, ext, extsize-1)==0) files.add(newstring(name, namelen)); -- cgit v1.2.3