Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

Champion Island: the island streams its scenery, water and live objects

Mason Chend49b1e1f17e2
diff --git a/games/championisland/src/ent.c b/games/championisland/src/ent.c
index c5c1cbe6..94ac1924 100644
--- a/games/championisland/src/ent.c
+++ b/games/championisland/src/ent.c
@@ -708,6 +708,14 @@ void sys_ground_height(void) {
}
}
+/* Oq: a translatable text shows the message with its id */
+void ent_translate(NodeId e) {
+ if (!e || nodes[e].T == NONE16 || !comp_has(nodes[e].T, C_translatable)) return;
+ uint16_t id = comp_str(nodes[e].T, C_translatable, F_id);
+ NodeId t = node_child(e, "text");
+ if (id != NONE16 && t) node_set_text(t, msg(str(id)));
+}
+
/* addFx / removeFx: spawn an effect where an entity appears or goes */
static void spawn_fx(NodeId e, int comp) {
uint16_t s = comp_sym(nodes[e].T, comp, F_mc);
diff --git a/games/championisland/src/ent.h b/games/championisland/src/ent.h
index 9954d659..9f19fbdd 100644
--- a/games/championisland/src/ent.h
+++ b/games/championisland/src/ent.h
@@ -121,5 +121,6 @@ void ent_on_trigger(TriggerFn fn);
/* per-scene hooks for spawned entities (addFx / removeFx) */
void sys_add_fx(NodeId e); /* Xp */
+void ent_translate(NodeId e); /* Oq: translatable texts */
void sys_remove_fx(NodeId e); /* Yp */
#endif
diff --git a/games/championisland/src/gfx.c b/games/championisland/src/gfx.c
index bbc4eb84..6815ab07 100644
--- a/games/championisland/src/gfx.c
+++ b/games/championisland/src/gfx.c
@@ -181,6 +181,9 @@ static int bg_see; /* palette index that shows the water (-1: n
static const uint8_t *water; /* the water: a tile of palette indices, repeating from world (0, 0) */
static int water_w, water_h;
static const uint8_t *bglut; /* RGB444 -> palette index, to blend into the layer */
+/* the see-through entries of the layer's palette: a pixel partly over the
+ * water keeps the nearest one, and is blended over the water when drawn */
+static uint8_t seethru[32], nseethru;
void bg_setup(uint8_t *mem, int w, int h, uint8_t sheet, BgPaint paint) {
bgmem = mem;
@@ -194,8 +197,11 @@ void bg_setup(uint8_t *mem, int w, int h, uint8_t sheet, BgPaint paint) {
bglut = NULL;
bg_gen++;
const uint8_t *al = palalpha(sheet);
- for (int i = 0; i < 256; i++)
- if (!al[i]) { bg_see = i; break; }
+ nseethru = 0;
+ for (int i = 0; i < 256; i++) {
+ if (!al[i] && bg_see < 0) bg_see = i;
+ if (al[i] && al[i] != 255 && nseethru < (int)sizeof seethru) seethru[nseethru++] = (uint8_t)i;
+ }
}
void bg_off(void) { bgmem = NULL; bg_gen++; }
@@ -261,6 +267,22 @@ void bg_fill(int x, int y, int w, int h, uint8_t index) {
}
/* one pixel of a sprite (palette of `sheet`) onto the layer, with alpha 0..255 */
+
+static uint8_t nearest_seethru(uint16_t col, unsigned a) {
+ const uint16_t *pal = pal565(bgsheet);
+ const uint8_t *al = palalpha(bgsheet);
+ int best = -1;
+ unsigned bd = 0;
+ for (int i = 0; i < nseethru; i++) {
+ uint16_t p = pal[seethru[i]];
+ int dr = (int)(p >> 11) - (int)(col >> 11), dg = (int)(p >> 5 & 63) - (int)(col >> 5 & 63), db = (int)(p & 31) - (int)(col & 31);
+ int da = (int)al[seethru[i]] - (int)a;
+ unsigned dd = (unsigned)(4 * dr * dr + dg * dg + 4 * db * db) + (unsigned)(da * da) / 16;
+ if (best < 0 || dd < bd) { best = seethru[i]; bd = dd; }
+ }
+ return (uint8_t)(best < 0 ? bg_see : best);
+}
+
static inline void bg_put(uint8_t *d, uint8_t c, const uint16_t *spal, const uint8_t *sal, uint8_t sheet, unsigned alpha) {
unsigned a = sal[c] * alpha; /* 0..65025 */
if (!a) return;
@@ -269,8 +291,18 @@ static inline void bg_put(uint8_t *d, uint8_t c, const uint16_t *spal, const uin
uint16_t fg = spal[c];
uint16_t col = fg;
if (a < 255 * 255 - 255) {
- uint16_t bgc = (bg_see >= 0 && *d == bg_see && water) ? fg : pal565(bgsheet)[*d];
- col = blend(fg, bgc, (a + 1024) >> 11);
+ const uint8_t *al = palalpha(bgsheet);
+ if (water && al[*d] != 255) {
+ /* over the water (or over something see-through): stays see-through */
+ unsigned a8 = (a + 127) / 255;
+ if (al[*d]) {
+ a8 = a8 + al[*d] * (255 - a8) / 255;
+ col = blend(fg, pal565(bgsheet)[*d], (unsigned)((a + 1024) >> 11) * 255 / (a8 ? a8 : 1) > 32 ? 32 : (unsigned)(((a + 1024) >> 11) * 255 / (a8 ? a8 : 1)));
+ }
+ *d = a8 >= 250 ? bglut[(col >> 12 & 15) << 8 | (col >> 7 & 15) << 4 | (col >> 1 & 15)] : nearest_seethru(col, a8);
+ return;
+ }
+ col = blend(fg, pal565(bgsheet)[*d], (a + 1024) >> 11);
}
*d = bglut[(col >> 12 & 15) << 8 | (col >> 7 & 15) << 4 | (col >> 1 & 15)];
}
@@ -331,10 +363,12 @@ void bg_draw(uint16_t sp, int x, int y, uint8_t flags, uint8_t alpha) {
int w = rd16(r), h = rd16(r + 2);
for (int v = 0; v < h; v++) {
const uint8_t *p = r + rd16(r + 4 + 2 * v);
- int n = *p++, u = 0;
+ int n = rd16(p), u = 0;
+ p += 2;
for (int k = 0; k < n; k++) {
u += *p++;
- int len = *p++;
+ int code = *p++, len = code & 0x80 ? (code & 0x7F) + 1 : code;
+ bool fill = code & 0x80;
for (int i = 0; i < len; i++, u++) {
/* source (u, v) -> offset (i, j) in the drawn rectangle */
int di = tr ? v : u, dj = tr ? u : v;
@@ -342,9 +376,9 @@ void bg_draw(uint16_t sp, int x, int y, uint8_t flags, uint8_t alpha) {
if (fy) dj = dh - 1 - dj;
int wx = x + di, wy = y + dj;
if (wx < clip_x0 || wx >= clip_x1 || wy < clip_y0 || wy >= clip_y1) continue;
- bg_put(bg_at(wx, wy), p[i], spal, sal, s.sheet, alpha);
+ bg_put(bg_at(wx, wy), fill ? p[0] : p[i], spal, sal, s.sheet, alpha);
}
- p += len;
+ p += fill ? 1 : len;
}
}
(void)w;
@@ -403,10 +437,11 @@ static void band_bg(int by, int rows) {
const uint8_t *wrow = water + ty * water_w;
int tx = bg_cx % water_w;
if (tx < 0) tx += water_w;
- uint8_t see = (uint8_t)bg_see;
+ const uint8_t *al = palalpha(bgsheet);
for (int x = 0; x < VIEW_W; x++) {
uint8_t c = row[lx];
- d[x] = pal[c == see ? wrow[tx] : c];
+ unsigned a = al[c];
+ d[x] = a == 255 ? pal[c] : !a ? pal[wrow[tx]] : blend(pal[c], pal[wrow[tx]], (a + 4) >> 3);
if (++lx == bgw) lx = 0;
if (++tx == water_w) tx = 0;
}
@@ -421,42 +456,55 @@ static void band_bg(int by, int rows) {
static void draw_rle_row(const uint8_t *p, int x, int w, bool flipx, uint16_t *d, const uint16_t *pal,
const uint8_t *al, unsigned galpha) {
- int n = *p++, cx = 0;
+ int n = rd16(p), cx = 0;
+ p += 2;
for (int k = 0; k < n; k++) {
cx += *p++;
- int len = *p++;
+ int code = *p++;
+ bool fill = code & 0x80;
+ int len = fill ? (code & 0x7F) + 1 : code;
const uint8_t *src = p;
- p += len;
+ p += fill ? 1 : len;
int start = cx;
cx += len;
int i0 = 0, i1 = len;
uint16_t *dd;
+ int step;
if (!flipx) {
- int sx = x + start; /* screen x of src[0] */
+ int sx = x + start; /* screen x of the run's first pixel */
if (sx >= VIEW_W) break;
if (sx < 0) i0 = -sx;
if (sx + len > VIEW_W) i1 = VIEW_W - sx;
dd = d + sx;
- if (galpha == 32) {
- for (int i = i0; i < i1; i++) {
- unsigned c = src[i], a = al[c];
- dd[i] = a == 255 ? pal[c] : blend(pal[c], dd[i], (a + 4) >> 3);
- }
- } else {
- for (int i = i0; i < i1; i++) {
- unsigned c = src[i];
- dd[i] = blend(pal[c], dd[i], (al[c] * galpha + 128) >> 8);
- }
- }
+ step = 1;
} else {
- int base = x + w - 1 - start; /* screen x of src[0]; src[i] lands at base - i */
+ int base = x + w - 1 - start; /* screen x of the run's first pixel; the run goes left */
if (base < 0) break;
if (base >= VIEW_W) i0 = base - VIEW_W + 1;
if (base - (len - 1) < 0) i1 = base + 1;
dd = d + base;
+ step = -1;
+ }
+ if (i0 >= i1) continue;
+ if (fill) {
+ unsigned c = src[0], a = al[c];
+ if (!a) continue;
+ uint16_t col = pal[c];
+ if (a == 255 && galpha == 32) {
+ for (int i = i0; i < i1; i++) dd[i * step] = col;
+ } else {
+ unsigned aa = (a * galpha + 128) >> 8;
+ for (int i = i0; i < i1; i++) dd[i * step] = blend(col, dd[i * step], aa);
+ }
+ } else if (galpha == 32) {
for (int i = i0; i < i1; i++) {
unsigned c = src[i], a = al[c];
- dd[-i] = (a == 255 && galpha == 32) ? pal[c] : blend(pal[c], dd[-i], (a * galpha + 128) >> 8);
+ dd[i * step] = a == 255 ? pal[c] : blend(pal[c], dd[i * step], (a + 4) >> 3);
+ }
+ } else {
+ for (int i = i0; i < i1; i++) {
+ unsigned c = src[i];
+ dd[i * step] = blend(pal[c], dd[i * step], (al[c] * galpha + 128) >> 8);
}
}
}
@@ -473,15 +521,18 @@ static uint8_t line_mask[(SPRITE_W_MAX + 7) / 8];
static void line_decode(const uint8_t *r, int v, int w) {
memset(line_mask, 0, (size_t)(w + 7) / 8);
const uint8_t *p = r + rd16(r + 4 + 2 * v);
- int n = *p++, cx = 0;
+ int n = rd16(p), cx = 0;
+ p += 2;
for (int k = 0; k < n; k++) {
cx += *p++;
- int len = *p++;
+ int code = *p++;
+ bool fill = code & 0x80;
+ int len = fill ? (code & 0x7F) + 1 : code;
for (int i = 0; i < len && cx + i < w; i++) {
- stream_buf[cx + i] = p[i];
+ stream_buf[cx + i] = fill ? p[0] : p[i];
line_mask[(cx + i) >> 3] |= (uint8_t)(1 << ((cx + i) & 7));
}
- p += len;
+ p += fill ? 1 : len;
cx += len;
}
line_spr = r;
diff --git a/games/championisland/src/node.c b/games/championisland/src/node.c
index 3813fb3e..4161e7bc 100644
--- a/games/championisland/src/node.c
+++ b/games/championisland/src/node.c
@@ -612,21 +612,116 @@ static bool shape_bounds(const uint8_t *sh, float *x, float *y, float *w, float
return true;
}
-bool node_bounds(NodeId n, float *x, float *y, float *w, float *h) {
- const Node *p = &nodes[n];
- if (p->kind == NK_SHAPE && p->ref != NONE16) return shape_bounds(payload(p->ref), x, y, w, h);
- if (p->kind == NK_BITMAP) {
- Sprite s;
- sprite_info(p->ref, &s);
- *x = 0; *y = 0; *w = s.w; *h = s.h;
- return true;
+/* CreateJS getBounds: a bitmap's rectangle, a shape's extent, and for a
+ * clip the union of its visible children's bounds at its current frame */
+typedef struct { float lx, ly, hx, hy; bool any; } Acc;
+
+static void acc_rect(Acc *a, Mat m, float x, float y, float w, float h) {
+ float xs[4] = {x, x + w, x, x + w}, ys[4] = {y, y, y + h, y + h};
+ for (int i = 0; i < 4; i++) {
+ float X = m.a * xs[i] + m.c * ys[i] + m.tx, Y = m.b * xs[i] + m.d * ys[i] + m.ty;
+ if (!a->any) { a->lx = a->hx = X; a->ly = a->hy = Y; a->any = true; continue; }
+ a->lx = X < a->lx ? X : a->lx; a->hx = X > a->hx ? X : a->hx;
+ a->ly = Y < a->ly ? Y : a->ly; a->hy = Y > a->hy ? Y : a->hy;
+ }
+}
+
+static Mat key_mat(const Key *k) {
+ float a = 1, b = 0, c = 0, d = 1;
+ if (k->mat) { const float *mm = mat(k->mat); a = mm[0]; b = mm[1]; c = mm[2]; d = mm[3]; }
+ float rx = k->rx4 * 0.25f, ry = k->ry4 * 0.25f;
+ return (Mat){a, b, c, d, k->x - (rx * a + ry * c), k->y - (rx * b + ry * d)};
+}
+
+static void sym_acc(uint16_t sym, unsigned frame, Mat m, Acc *a, int depth) {
+ if (sym >= SYM_COUNT || depth > 12) return;
+ SymInfo si;
+ sym_info(sym, &si);
+ float x, y, w, h;
+ if (si.type == SYM_BITMAP) {
+ Sprite sp;
+ sprite_info((uint16_t)si.v, &sp);
+ acc_rect(a, m, 0, 0, sp.w, sp.h);
+ } else if (si.type == SYM_SHAPE) {
+ if (shape_bounds(payload((uint16_t)si.v), &x, &y, &w, &h)) acc_rect(a, m, x, y, w, h);
+ } else if (si.type == SYM_CLIP) {
+ Clip c;
+ if (!clip_get(sym, &c)) return;
+ if (c.nframes && frame >= c.nframes) frame %= c.nframes;
+ const uint8_t *q = c.slots;
+ for (unsigned s = 0; s < c.nslots; s++) {
+ Key k;
+ uint16_t idx;
+ q = slot_key(q, frame, &k, &idx);
+ if (idx == NONE16 || (k.flags & (K_ABSENT | K_HIDDEN))) continue;
+ Mat km = mat_mul(m, key_mat(&k));
+ if (k.kind == CK_SHAPE) { if (shape_bounds(payload(k.ref), &x, &y, &w, &h)) acc_rect(a, km, x, y, w, h); }
+ else if (k.kind == CK_SYM) {
+ unsigned f = k.mode == MODE_SYNCHED ? k.sp + frame - k.start : k.mode == MODE_SINGLE ? k.sp : 0;
+ sym_acc(k.ref, f, km, a, depth + 1);
+ }
+ }
+ }
+}
+
+static void node_acc(NodeId id, Mat m, Acc *a, int depth) {
+ const Node *n = &nodes[id];
+ float x, y, w, h;
+ if (depth > 12) return;
+ if (n->kind == NK_BITMAP) {
+ Sprite sp;
+ sprite_info(n->ref, &sp);
+ acc_rect(a, m, 0, 0, sp.w, sp.h);
+ return;
+ }
+ if (n->kind == NK_SHAPE) {
+ if (n->ref != NONE16 && shape_bounds(payload(n->ref), &x, &y, &w, &h)) acc_rect(a, m, x, y, w, h);
+ return;
}
+ if (n->kind == NK_TEXT) return;
Clip c;
- if (p->kind == NK_CLIP && clip_get(p->sym, &c) && (c.nb[2] || c.nb[3])) {
- *x = c.nb[0]; *y = c.nb[1]; *w = c.nb[2]; *h = c.nb[3];
- return true;
+ NodeId ch = n->first;
+ if (n->kind == NK_CLIP && !(n->flags & NF_SORTED) && clip_get(n->sym, &c)) {
+ const uint8_t *q = c.slots;
+ for (unsigned s = 0; s < c.nslots; s++) {
+ while (ch && nodes[ch].slot != NONE16 && nodes[ch].slot < s) ch = nodes[ch].next;
+ Key k;
+ uint16_t idx;
+ q = slot_key(q, n->frame, &k, &idx);
+ if (ch && nodes[ch].slot == s) {
+ if (node_visible(ch)) node_acc(ch, mat_mul(m, node_local(ch)), a, depth + 1);
+ continue;
+ }
+ if (idx == NONE16 || (k.flags & (K_ABSENT | K_HIDDEN)) || needs_node(&k)) continue;
+ Mat km = mat_mul(m, key_mat(&k));
+ if (k.kind == CK_SHAPE) { if (shape_bounds(payload(k.ref), &x, &y, &w, &h)) acc_rect(a, km, x, y, w, h); }
+ else if (k.kind == CK_SYM) {
+ unsigned f = k.mode == MODE_SYNCHED ? k.sp + n->frame - k.start : k.mode == MODE_SINGLE ? k.sp : 0;
+ sym_acc(k.ref, f, km, a, depth + 1);
+ }
+ }
+ for (NodeId x2 = n->first; x2; x2 = nodes[x2].next)
+ if (nodes[x2].slot == NONE16 && node_visible(x2)) node_acc(x2, mat_mul(m, node_local(x2)), a, depth + 1);
+ return;
}
- return false;
+ for (NodeId x2 = n->first; x2; x2 = nodes[x2].next)
+ if (node_visible(x2)) node_acc(x2, mat_mul(m, node_local(x2)), a, depth + 1);
+}
+
+bool node_bounds(NodeId n, float *x, float *y, float *w, float *h) {
+ Acc a = {0, 0, 0, 0, false};
+ node_acc(n, MAT_ID, &a, 0);
+ if (!a.any) {
+ /* nothing to show: Animate's nominal bounds, if any */
+ Clip c;
+ if (nodes[n].kind == NK_CLIP && clip_get(nodes[n].sym, &c) && (c.nb[2] || c.nb[3])) {
+ *x = c.nb[0]; *y = c.nb[1]; *w = c.nb[2]; *h = c.nb[3];
+ return true;
+ }
+ return false;
+ }
+ *x = a.lx; *y = a.ly; *w = a.hx - a.lx; *h = a.hy - a.ly;
+ return true;
}
bool node_bounds_in(NodeId n, NodeId space, float *x, float *y, float *w, float *h) {
diff --git a/games/championisland/src/sport_pingpong.c b/games/championisland/src/sport_pingpong.c
index f3956776..414ea2e3 100644
--- a/games/championisland/src/sport_pingpong.c
+++ b/games/championisland/src/sport_pingpong.c
@@ -19,6 +19,9 @@
* the filtered ball, in the map's draw order, without nodes. */
#include <math.h>
#include <stdio.h>
+#ifdef HOST
+#include <stdlib.h>
+#endif
#include "../src/ent.h"
#include "../src/font.h"
#include "../src/phys.h"
@@ -34,7 +37,7 @@ enum { PART_SMOKE, PART_FLAME }; /* mna, UV */
typedef struct {
NodeId n, sprite, shadow;
- int16_t body;
+ int8_t body; /* the physics has seen it (Gp) */
uint8_t state; /* 0 normal, 1 smoking, 2 flaming, 3 power shot */
uint8_t dl; /* DL: the player's hits */
uint8_t side;
@@ -65,7 +68,7 @@ typedef struct {
NodeId walls[WALL_MAX];
int16_t wall_body[WALL_MAX];
int nwalls;
- int16_t table_body, player_body;
+ int16_t player_body;
Rect table_box, court_box, ptarget_box, etarget_box, ebounds_box;
float table_top; /* its z + height */
float pvx, pvy, pvz; /* the player's velocity component */
@@ -87,7 +90,7 @@ typedef struct {
bool over, reported; /* Zo, Xd */
int end_t, rating;
float score;
- int last_meter, last_pprog, last_eprog;
+ int last_meter, last_pprog, last_eprog, meter_f;
Part parts[PART_MAX];
int nparts;
Banner banner;
@@ -356,7 +359,6 @@ static Ball *ball_of(NodeId n) {
static void ball_remove(int i) {
Ball *b = &S->balls[i];
- if (b->body >= 0) phys_remove(b->body);
ent_remove(b->n);
memmove(&S->balls[i], &S->balls[i + 1], (size_t)(S->nballs - i - 1) * sizeof(Ball));
S->nballs--;
@@ -495,8 +497,12 @@ static bool power_shot(void) {
return true;
}
+/* (the engine also ticks the sprites a clip is not showing, and their scripts
+ * dispatch: only the pose on stage counts, as in createjs) */
+static bool showing(NodeId n, const char *label) { return !strcmp(node_label(n), label); }
+
static void on_super_swing(NodeId t, uint16_t ev, void *ctx) {
- if (!S || !S->super_on) return;
+ if (!S || !S->super_on || !showing(t, "super")) return;
SOUND(power_swing);
for (int i = 0; i < S->nballs; i++) {
Ball *b = &S->balls[i];
@@ -514,7 +520,7 @@ static void on_super_swing(NodeId t, uint16_t ev, void *ctx) {
}
static void on_super_end(NodeId t, uint16_t ev, void *ctx) {
- if (!S || !S->super_on) return;
+ if (!S || !S->super_on || !showing(t, "super")) return;
S->super_on = false;
S->pstate = 0;
S->pmove = true;
@@ -527,7 +533,7 @@ static void on_super_end(NodeId t, uint16_t ev, void *ctx) {
/* st: a paddle's swing ends */
static void on_swing_finished(NodeId t, uint16_t ev, void *ctx) {
- if (!S) return;
+ if (!S || !showing(t, "swing")) return;
ent_label(t, "walk", false);
if (t == S->player) { S->pstate = 0; S->pmove = true; }
else S->estate = 0;
@@ -661,7 +667,11 @@ static void scoring(void) {
if (S->t_score) node_set_text(S->t_score, S->s_score);
meter(S->pprog, (float)S->wp / S->dJ, &S->last_pprog);
meter(S->eprog, (float)S->eu / S->dJ, &S->last_eprog);
- meter(S->meter, S->my, &S->last_meter);
+ /* the power meter's progress bar is masked (frames 1-30): the clip stays on
+ * its empty frame and draw_over draws the bar as far as the mask shows it */
+ int mf = (int)floorf(S->my * 31);
+ S->meter_f = mf < 0 ? 0 : mf > 31 ? 31 : mf;
+ meter(S->meter, S->meter_f == 31 ? 1.0f : 0.0f, &S->last_meter);
if (S->plabel) node_set_text(S->plabel, msg("TUT_PINGPONG_DESKTOP_ACTION"));
}
@@ -807,7 +817,7 @@ static void start(void) {
const char *v = game.variant;
const char *label = !strcmp(v, "hard") || !strcmp(v, "ultra") || !strcmp(v, "tutorial") ? v : "game";
S->tutorial = !strcmp(v, "tutorial");
- S->table_body = S->player_body = -1;
+ S->player_body = -1;
S->last_meter = S->last_pprog = S->last_eprog = -1;
S->pmove = true;
S->ty = 10000;
@@ -896,12 +906,72 @@ static void countdown(void) { /* Wo */
if (S->cd > 0) S->cd--;
}
+
+#if defined(HOST) || defined(PP_AUTO)
+/* tests: PPAUTO=1 (or a build with -DPP_AUTO) plays the player: it goes to
+ * the ball coming its way and uses the power shot when two balls are in play */
+static void autopilot(void) {
+#ifdef PP_AUTO
+ const bool on = true;
+#else
+ static int on = -1;
+ if (on < 0) on = getenv("PPAUTO") != NULL;
+#endif
+ if (!on || !S->pmove) return;
+ Rect r;
+ if (!box_of(S->player, &r)) return;
+ float best = 1e9f, gx = 0, gy = 0;
+ bool any = false;
+ for (int i = 0; i < S->nballs; i++) {
+ Ball *b = &S->balls[i];
+ float x, y;
+ pos_of(b->n, &x, &y);
+ if (!b->live || b->side == SIDE_PLAYER || x > S->table_box.x + S->table_box.w) continue;
+ if (x < best) { best = x; gx = x; gy = y - b->z; any = true; }
+ }
+ in.jx = in.jy = 0;
+ if (any) {
+ float dx = gx - (r.x + r.w / 2), dy = gy - (r.y + r.h / 2), d = sqrtf(dx * dx + dy * dy);
+ if (d > 2) { in.jx = dx / d; in.jy = dy / d; }
+ }
+ in.held[A_ACTION] = S->my >= 1 && S->nballs >= 2;
+}
+#else
+static void autopilot(void) {}
+#endif
+
static void movement(void) { /* Rp */
if (!S->pmove) return;
S->pvx = in.jx * S->pspeed;
S->pvy = in.jy * S->pspeed;
}
+
+#ifdef HOST
+static void debug_log(void) {
+ static int on = -1;
+ if (on < 0) on = getenv("PPDBG") != NULL;
+ if (!on) return;
+ float px, py, ex, ey;
+ pos_of(S->player, &px, &py);
+ pos_of(S->enemy, &ex, &ey);
+ printf("T %u p %.2f %.2f e %.2f %.2f wp %d eu %d my %.3f", game.ticks, px, py, ex, ey, S->wp, S->eu, S->my);
+ if (getenv("PPDBG")[0] == '2') {
+ printf(" pl %s f%d st%d:", node_label(S->player), nodes[S->player].frame, S->pstate);
+ for (NodeId c = nodes[S->player].first; c; c = nodes[c].next) printf(" %u/%d%s", nodes[c].sym, nodes[c].frame, (nodes[c].flags & NF_ONSTAGE) ? "+" : "");
+ }
+ for (int i = 0; i < S->nballs; i++) {
+ Ball *b = &S->balls[i];
+ float x, y;
+ pos_of(b->n, &x, &y);
+ printf(" [%.2f %.2f z %.2f kt %.2f v %.3f %.3f %.3f dl %d st %d]", x, y, b->z, b->kt, b->vx, b->vy, b->vz, b->dl, b->state);
+ }
+ printf("\n");
+}
+#else
+static void debug_log(void) {}
+#endif
+
static void tick(void) {
if (!S || !S->map) { sys_back_pauses(); return; }
nodes[S->map].flags |= NF_VISIBLE;
@@ -918,6 +988,7 @@ static void tick(void) {
end_of_game(); /* qt, pt */
remove_dead(); /* ot */
if (on && !S->over) spawn_balls(); /* jt */
+ autopilot();
movement(); /* Rp */
if (on && !S->over && !power_shot()) { /* et */
paddle_swing(SIDE_PLAYER);
@@ -925,6 +996,7 @@ static void tick(void) {
}
physics(); /* yr */
if (on) ground_heights(); /* Ar */
+ debug_log();
if (!S->over || S->tutorial) scoring(); /* lt */
if (on) { shadows(); zsprites(); } /* tt, dq */
sort_map(); /* Qp */
@@ -1002,9 +1074,23 @@ static void draw_under(void) {
mp->flags &= (uint8_t)~NF_VISIBLE;
}
+/* l4a's frames 1 to 30: PowerShotBarProgressArt (a yellow bar with round
+ * ends, at (1, 1)) under a mask whose right edge is at 3 + 10 (frame - 1) */
+static void draw_meter(void) {
+ int f = S->meter_f;
+ if (!S->meter || f < 1 || f > 30 || !node_visible_chain(S->meter)) return;
+ Mat m = mat_mul((Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, 0}, node_global(S->meter));
+ int w = 2 + 10 * (f - 1), x = (int)floorf(m.tx + 1 + .5f), y = (int)floorf(m.ty + 1 + .5f);
+ uint16_t c = rgb565(253, 202, 64);
+ gfx_rect(x, y + 1, w, 4, c, 255);
+ gfx_rect(x + 1, y, w - 1, 1, c, 255);
+ gfx_rect(x + 1, y + 5, w - 1, 1, c, 255);
+}
+
static void draw_over(void) {
if (!S) return;
if (S->map) nodes[S->map].flags |= NF_VISIBLE;
+ if (S->map) draw_meter();
banner_draw();
}
diff --git a/games/championisland/src/sport_rugby.c b/games/championisland/src/sport_rugby.c
index 90ff6ab5..828e2df9 100644
--- a/games/championisland/src/sport_rugby.c
+++ b/games/championisland/src/sport_rugby.c
@@ -24,6 +24,9 @@
#include <stdio.h>
#include "ent.h"
#include "phys.h"
+#ifdef RG_DEBUG
+#include <stdlib.h>
+#endif
#define ACT_MAX 32
#define OB_MAX 176
@@ -625,6 +628,15 @@ static void start(void) {
S->view = (Rect){x0, y0, 960 / g.a, 540 / g.d};
}
}
+#ifdef RG_DEBUG
+ if (getenv("RG_X")) /* tests: the team starts further on */
+ for (int i = 0; i < S->nact; i++)
+ if (S->act[i].kind == A_CHAR) { S->act[i].x += atof(getenv("RG_X")); if (getenv("RG_Y")) S->act[i].y += atof(getenv("RG_Y")); }
+#endif
+#ifdef RG_START_X /* performance tests on the calculator: the team starts further on */
+ for (int i = 0; i < S->nact; i++)
+ if (S->act[i].kind == A_CHAR) S->act[i].x += RG_START_X;
+#endif
for (int i = 0; i < S->nact; i++) {
Actor *a = &S->act[i];
Rect v = rect_pad(S->view, 240, 216, 240, 432);
@@ -1036,7 +1048,7 @@ static void physics(void) {
bd->vx = 30 * a->vx;
bd->vy = 30 * a->vy;
bd->vz = 0;
- if (nmv < ACT_MAX) mv[nmv++] = rect_pad(r, 24, 24, 24, 24);
+ if (nmv < ACT_MAX) mv[nmv++] = rect_pad(r, 16, 16, 16, 16);
}
/* rocks: bodies only where something moves near them */
for (int i = 0; i < S->nob; i++) {
@@ -1355,6 +1367,7 @@ static void tick(void) {
the_end(zone); /* Et */
#ifdef RG_DEBUG
if (S->pl >= 0) { Actor *a = &S->act[S->pl]; float x, y; act_pos(a, &x, &y);
+ { int nb = 0; for (int i = 0; i < BODY_MAX; i++) nb += bodies[i].used; static int mx; if (nb > mx) { mx = nb; fprintf(stderr, "bodies max %d, state %d\n", mx, (int)sizeof(State)); } }
fprintf(stderr, "t%u pl %d pos %.2f %.2f v %.2f %.2f body %d go %d label %s nodes %u\n", game.ticks, S->pl, x, y, a->vx, a->vy, a->body, go, a->n ? node_label(a->n) : "-", node_count()); }
#endif
}
@@ -1451,6 +1464,8 @@ static void draw_under(void) {
}
static void end(void) {
+ if (S)
+ for (int i = 0; i < S->nproto; i++) node_free(S->proto[i]); /* not in the scene's tree */
phys_reset();
S = NULL;
}
diff --git a/games/championisland/src/sport_skate.c b/games/championisland/src/sport_skate.c
index 2d2278a3..4cc10af3 100644
--- a/games/championisland/src/sport_skate.c
+++ b/games/championisland/src/sport_skate.c
@@ -1,9 +1,1702 @@
-#include "../src/ent.h"
-#include "../src/spr.h"
+/* Skateboarding: the doodle's scene eu (library 8AB206B0C8EC450BA137F5272C53C5F0).
+ *
+ * Lucky skates around a park for 90 seconds: the arrows push the board
+ * (it turns less the faster it goes), OK jumps (twice in the air, holding it
+ * floats), arrows and OK in the air are tricks, landing on a rail grinds it.
+ * Tricks chain into a combo that is banked 8 ticks after a clean landing:
+ * (sum of the tricks' points) x (number of tricks), plus one point per tick
+ * of grinding. Landing while a trick is still playing is a fall and loses
+ * the combo. Speed boosts push the board along their arrows, and one of the
+ * hidden champions shows at a time: touching it is "Hide and Seek" (5000).
+ * Variants park1, park2, park3 (and tutorial) are the four maps of the root
+ * clip ycb.
+ *
+ * Systems, in the doodle's order: Ep (pause), Uo (rules), Wo (countdown), Hr
+ * (triggers: speed boosts bu, champions), Yt (champions), yr (physics), Ar
+ * (ground height), Ot (the skater), Zt (HUD), Cq/Dq (camera), dq/tt (sprite
+ * heights), Qp (draw order), Os (animated tiles), $t (timer and the end).
+ *
+ * The parks have up to 639 children (and 1601 ground tiles): far more than
+ * the node pool. So the map is read from the data: its children are indexed
+ * by 64 px bands at start, and each frame the ones in view are drawn in the
+ * doodle's draw order through one prototype node per symbol, placed at each
+ * child's keyframe. Only the skater and the champions near the view are
+ * real nodes. The physics (the doodle's cannon world, where only the skater
+ * moves) is a small box/ramp solver against the collidable children near
+ * the skater. */
+#include <math.h>
#include <stdio.h>
+#include <stdlib.h>
+#include "../src/ent.h"
+#include "../src/font.h"
+
+#define SYM_MAX 64
+#define PROTO_RESERVE 72 /* nodes kept free for menus, prompt icons, champions */
+#define BANDS_MAX 120
+#define ENT_CAP 2300
+#define VIS_MAX 160
+#define CH_MAX 24
+#define KK_MAX 40
+#define ACT_KEEP 6
+#define ICON_MAX 8
+#define COL_MAX 40
+#define TIME_START 2700 /* CN */
+#define END_DELAY 80 /* Yo */
+#define PI_F 3.14159265f
+
+/* ---------------------------------------------------------------- the data's timeline keys (as node.c reads them) */
+typedef struct {
+ uint16_t start;
+ uint8_t flags, kind;
+ uint16_t ref;
+ float x, y;
+ int16_t rx4, ry4;
+ uint16_t mat, name, sp;
+ uint8_t alpha, mode, loop;
+} Key;
+
+static const uint8_t *varint(const uint8_t *p, unsigned *v) {
+ unsigned r = 0, s = 0;
+ for (int i = 0; i < 5; i++) {
+ uint8_t b = *p++;
+ r |= (unsigned)(b & 0x7F) << s;
+ if (!(b & 0x80)) break;
+ s += 7;
+ }
+ *v = r;
+ return p;
+}
+
+static const uint8_t *key_read(const uint8_t *p, Key *k) {
+ unsigned start;
+ p = varint(p, &start);
+ k->start = (uint16_t)start;
+ k->flags = *p++;
+ if (k->flags & K_ABSENT) return p;
+ if (k->flags & K_KIND) { k->kind = *p++; k->ref = rd16(p); p += 2; }
+ else { k->kind = CK_SYM; k->ref = rd16(p); p += 2; }
+ k->x = rds16(p) * 0.25f;
+ k->y = rds16(p + 2) * 0.25f;
+ p += 4;
+ k->mat = 0;
+ if (k->flags & K_MAT) { k->mat = rd16(p); p += 2; }
+ k->rx4 = k->ry4 = 0;
+ if (k->flags & K_REG) { k->rx4 = rds16(p); k->ry4 = rds16(p + 2); p += 4; }
+ k->alpha = 255;
+ if (k->flags & K_ALPHA) k->alpha = *p++;
+ k->mode = MODE_INDEPENDENT; k->sp = 0; k->loop = 1;
+ if (k->flags & K_CLIP) { k->mode = p[0]; k->sp = rd16(p + 1); k->loop = p[3]; p += 4; }
+ k->name = NONE16;
+ if (k->flags & K_NAME) { k->name = rd16(p); p += 2; }
+ return p;
+}
+
+/* the key a slot shows at `frame` (false if none); *next: the following slot */
+static bool slot_at(const uint8_t *p, unsigned frame, Key *out, const uint8_t **next) {
+ unsigned n;
+ p = varint(p, &n);
+ bool has = false;
+ for (unsigned i = 0; i < n; i++) {
+ Key k;
+ p = key_read(p, &k);
+ if (k.start <= frame) { *out = k; has = true; }
+ }
+ if (next) *next = p;
+ return has && !(out->flags & K_ABSENT);
+}
+
+static Mat key_mat(const Key *k) {
+ float a = 1, b = 0, c = 0, d = 1;
+ if (k->mat) { const float *m = mat(k->mat); a = m[0]; b = m[1]; c = m[2]; d = m[3]; }
+ float rx = k->rx4 * 0.25f, ry = k->ry4 * 0.25f;
+ return (Mat){a, b, c, d, k->x - (rx * a + ry * c), k->y - (rx * b + ry * d)};
+}
+
+static void mat_apply(Mat m, float x, float y, float *ox, float *oy) {
+ *ox = m.a * x + m.c * y + m.tx;
+ *oy = m.b * x + m.d * y + m.ty;
+}
+
+static bool mat_inv_apply(Mat m, float x, float y, float *ox, float *oy) {
+ float det = m.a * m.d - m.b * m.c;
+ if (fabsf(det) < 1e-9f) return false;
+ float dx = x - m.tx, dy = y - m.ty;
+ *ox = (m.d * dx - m.c * dy) / det;
+ *oy = (-m.b * dx + m.a * dy) / det;
+ return true;
+}
+
+/* the axis-aligned box of rect r placed by m */
+static Rect mat_rect(Mat m, Rect r) {
+ float xs[4] = {r.x, r.x + r.w, r.x, r.x + r.w}, ys[4] = {r.y, r.y, r.y + r.h, r.y + r.h};
+ float lx = 1e9f, ly = 1e9f, hx = -1e9f, hy = -1e9f;
+ for (int i = 0; i < 4; i++) {
+ float X, Y;
+ mat_apply(m, xs[i], ys[i], &X, &Y);
+ lx = X < lx ? X : lx; hx = X > hx ? X : hx; ly = Y < ly ? Y : ly; hy = Y > hy ? Y : hy;
+ }
+ return (Rect){lx, ly, hx - lx, hy - ly};
+}
+
+/* ---------------------------------------------------------------- vectors and directions, as kitsune has them */
+static float vlen(float x, float y) { return sqrtf(x * x + y * y); }
+/* hh: the angle of a vector in degrees [0, 360), NaN for a zero vector */
+static float hh(float x, float y) {
+ if (x == 0 && y == 0) return NAN;
+ return fmodf(atan2f(y, x) + 2 * PI_F, 2 * PI_F) * 180 / PI_F;
+}
+static bool bh(float lo, float v, float hi) { return (v >= lo && v <= hi) || (v <= lo && v >= hi); }
+/* lh / mh: the 8-way direction (0 e, 1 se ... 7 ne) of an angle / a vector, -1 for none */
+static int lh(float a) {
+ if (isnan(a)) return -1;
+ a = fmodf(a, 360);
+ if (bh(0, a, 22.5f) || bh(337.5f, a, 360)) return DIR_E;
+ for (int d = 1; d < 8; d++)
+ if (bh(d * 45 - 22.5f, a, d * 45 + 22.5f)) return d;
+ return -1;
+}
+static int mh(float x, float y) { return lh(hh(x, y)); }
+static int rg(int d) { return d < 0 ? -1 : (d + 4) & 7; }
+/* ih: from angle a to angle b, in (-180, 180] (NaN counts as 0) */
+static float ih(float a, float b) {
+ if (isnan(a)) a = 0;
+ if (isnan(b)) b = 0;
+ float d = b - a;
+ if (d > 180) d -= 360;
+ else if (d < -180) d += 360;
+ return d;
+}
+/* lg: v scaled to length l (zero if either is) */
+static void lg(float x, float y, float l, float *ox, float *oy) {
+ float c = vlen(x, y);
+ if (c == 0 || l == 0) { *ox = *oy = 0; return; }
+ *ox = x * l / c;
+ *oy = y * l / c;
+}
+
+/* ---------------------------------------------------------------- tricks (Kt, Wj, Xj) */
+enum { AC_N, AC_S, AC_E, AC_W, AC_ACTION, AC_AIR, AC_LAND, AC_GSTART, AC_GEND };
+typedef struct {
+ const char *text, *frame;
+ uint16_t hf;
+ uint8_t n, dur, name; /* number of actions, duration, trick name (texts are kept per name) */
+ uint8_t acts[4];
+} Trick;
+enum { TR_NOSE, TR_FAKIE = 13, TR_HIDE = 14, TR_COUNT };
+static const Trick tricks[TR_COUNT] = {
+ {"Nose Grab", "nose_grab", 100, 1, 10, 0, {AC_ACTION}},
+ {"Kick Flip", "kick_flip_e", 200, 2, 15, 1, {AC_E, AC_ACTION}},
+ {"Kick Flip", "kick_flip_w", 200, 2, 15, 1, {AC_W, AC_ACTION}},
+ {"Barrel Roll", "barrel_roll_e", 300, 3, 24, 2, {AC_W, AC_N, AC_ACTION}},
+ {"Barrel Roll", "barrel_roll_w", 300, 3, 24, 2, {AC_E, AC_N, AC_ACTION}},
+ {"BS 180", NULL, 300, 3, 1, 3, {AC_E, AC_N, AC_W}},
+ {"BS 180", NULL, 300, 3, 1, 3, {AC_W, AC_N, AC_E}},
+ {"FS 180", NULL, 300, 3, 1, 4, {AC_E, AC_S, AC_W}},
+ {"FS 180", NULL, 300, 3, 1, 4, {AC_W, AC_S, AC_E}},
+ {"Headstand", "super_trick", 500, 4, 35, 5, {AC_S, AC_W, AC_N, AC_ACTION}},
+ {"Headstand", "super_trick", 500, 4, 35, 5, {AC_S, AC_E, AC_N, AC_ACTION}},
+ {"Helicopter", "helicopter", 500, 4, 35, 6, {AC_E, AC_W, AC_E, AC_ACTION}},
+ {"Helicopter", "helicopter", 500, 4, 35, 6, {AC_W, AC_E, AC_W, AC_ACTION}},
+ {"FAKIE", NULL, 100, 0, 0, 7, {0}},
+ {"Hide and Seek", NULL, 5000, 0, 0, 8, {0}},
+};
+#define NAME_COUNT 9
+static const char *const icon_labels[5] = {"n", "s", "e", "w", "action"};
+static const char *const player_labels[6] = {"stop", "slow", "fast", "jump", "grind", "fall"};
+
+/* ---------------------------------------------------------------- state */
+enum {
+ SF_COLL = 1, SF_ZOBJ = 2, SF_ZB = 4, SF_DORD = 8, SF_RAIL = 16, SF_CHAMP = 32, SF_BOOST = 64, SF_PLAYER = 128,
+ SF_GROUND = 256, SF_BG = 512, SF_NODRAW = 1024, SF_TILEANIM = 2048, SF_BOUNDS = 4096, SF_MARKERS = 8192,
+ SF_KEYB = 16384 /* draw order from the bounds (zObject, boundable, zBoundable) */
+};
+typedef struct {
+ uint16_t sym, T, fl, stamp;
+ NodeId proto;
+ uint8_t shape, fc; /* body shape (0 box, 1 left ramp, 2 right ramp); tile frameCount */
+ int8_t bdir; /* speed boost direction */
+ uint8_t bspeed;
+ float z, h, dord; /* zObject z, zBoundable height (for the draw order), drawOrderOverride */
+ int16_t tz0, tz1; /* trigger zMin, zMax */
+ int16_t vis[4]; /* visual box (nominal bounds) x0 y0 x1 y1 */
+ int16_t b[4]; /* bounds child rect x0 y0 x1 y1, 1/8 px */
+ int16_t r[6]; /* rail markers: x y (1/8 px), z; twice */
+} Sym;
+#define Q8(v) ((int16_t)lrintf((v) * 8))
+#define F8(v) ((v) * 0.125f)
+
+typedef struct { float y0, maxh; uint16_t nb, s0; uint16_t bh; } Index;
+typedef struct { float key; uint16_t off; uint16_t what; } Vis; /* what: 0 static, 1 player, 2 + champion */
+typedef struct { uint16_t off; NodeId n; uint8_t alpha, active, out; uint16_t out_t; } Champ;
+typedef struct { uint8_t type; int8_t dir; float vx, vy; } Action;
+typedef struct {
+ NodeId n;
+ float x0, x1, a0, a1;
+ uint8_t tx, ta; /* tween ticks done (5 = over) */
+ bool used, listed, fading;
+} Icon;
+
+typedef struct {
+ /* the map */
+ const uint8_t *mslots, *bslots; /* timeline slots of the map and of its ground entity */
+ uint16_t map_sym, bg_sym, player_off;
+ Mat bgm; /* the ground entity in map space */
+ Index mi, bi;
+ uint16_t nent, nstarts;
+ uint16_t starts[BANDS_MAX];
+ uint16_t ent[ENT_CAP];
+ uint16_t nsym, stamp;
+ Sym sym[SYM_MAX];
+ uint8_t nkk;
+ int16_t kk[KK_MAX][2]; /* park 1: origins of the 288 px ground tiles (Kk) */
+ uint16_t kk_sprite;
+ uint8_t nch;
+ Champ ch[CH_MAX];
+ int8_t champ; /* Yt's champion, -1 none yet */
+ uint16_t inside[4]; /* speed boosts the skater is in (Hr's ex) */
+ uint8_t ninside;
+ uint16_t nvis;
+ Vis vis[VIS_MAX];
+ /* nodes */
+ NodeId map, player, hud, prompt, score, score_sh, time, time_sh, tname, tscore, spark_l, spark_r;
+ float mrx, mry; /* the map's registration point */
+ float qx, qy; /* Cq's goal for the map */
+ Mat mapm; /* map to screen, this frame */
+ /* the skater */
+ float px, py, z, vx, vy, vz, kt; /* position (map), z; velocity (px per tick); KT */
+ float bcx, bcy, bhx, bhy; /* bounds centre from the position, half sizes */
+ int8_t dir, isc_dir;
+ uint16_t isc; /* ticks the joystick has kept its direction (Kh.Sc) */
+ float gravity;
+ /* skatePlayer (ak) */
+ int32_t cn, hf, iy;
+ bool tb, flat, a7, grinding, markers_hidden, go, over, done, tut_done, time_red, trick_red;
+ int16_t bb, ca, sk, kbt, oc;
+ float rail[6];
+ uint16_t rail_off;
+ uint8_t nact;
+ uint16_t act_total;
+ Action act[ACT_KEEP];
+ uint16_t ck_n;
+ uint32_t ck_sum;
+ const char *ck_frame;
+ uint8_t nnames, name_order[NAME_COUNT];
+ uint16_t name_cnt[NAME_COUNT];
+ /* HUD */
+ Icon icon[ICON_MAX];
+ uint8_t nlist, list[ICON_MAX];
+ float tr_a0, tr_a1; /* trick texts' alpha tween */
+ uint8_t tr_t;
+ uint8_t tr_alpha;
+ int16_t end_t;
+ Countdown cd;
+ uint32_t ticks;
+ char score_buf[12], time_buf[12], tscore_buf[24], tname_buf[120];
+} State;
+
+static State *S;
+_Static_assert(sizeof(State) <= SCENE_STATE_MAX, "skate state too big");
+
+/* ---------------------------------------------------------------- symbols */
+static void clip_frame0(uint16_t sym, Clip *c) { if (!clip_get(sym, c)) memset(c, 0, sizeof *c); }
+
+static Sym *sym_get(uint16_t ref) {
+ for (int i = 0; i < S->nsym; i++)
+ if (S->sym[i].sym == ref) return &S->sym[i];
+ if (S->nsym >= SYM_MAX) return NULL;
+ SymInfo si;
+ if (ref >= SYM_COUNT) return NULL;
+ sym_info(ref, &si);
+ Sym *s = &S->sym[S->nsym++];
+ memset(s, 0, sizeof *s);
+ s->sym = ref;
+ s->T = NONE16;
+ s->bdir = -1;
+ if (si.type != SYM_CLIP) {
+ s->fl = SF_NODRAW;
+ return s;
+ }
+ Clip c;
+ clip_frame0(ref, &c);
+ uint16_t T = s->T = c.T;
+ if (comp_has(T, C_zObject)) { s->fl |= SF_ZOBJ; s->z = comp_float(T, C_zObject, F_z, 0); }
+ if (comp_has(T, C_zBoundable)) { s->fl |= SF_ZB; s->h = comp_float(T, C_zBoundable, F_height, 100); }
+ if (comp_has(T, C_drawOrderOverride)) { s->fl |= SF_DORD; s->dord = comp_float(T, C_drawOrderOverride, F_drawOrder, 0); }
+ if (comp_has(T, C_skateRail)) s->fl |= SF_RAIL;
+ if (comp_has(T, C_skateChamp)) s->fl |= SF_CHAMP;
+ if (comp_has(T, C_skatePlayer)) s->fl |= SF_PLAYER;
+ if (comp_has(T, C_speedBoost)) {
+ s->fl |= SF_BOOST;
+ uint16_t d = comp_str(T, C_speedBoost, F_direction);
+ s->bdir = (int8_t)(d != NONE16 ? dir_parse(str(d)) : DIR_W);
+ s->bspeed = (uint8_t)comp_float(T, C_speedBoost, F_speed, 0);
+ }
+ if (comp_has(T, C_trigger)) {
+ s->tz0 = (int16_t)clampf(comp_float(T, C_trigger, F_zMin, -30000), -30000, 30000);
+ s->tz1 = (int16_t)clampf(comp_float(T, C_trigger, F_zMax, 30000), -30000, 30000);
+ }
+ if (comp_has(T, C_tileBackground)) {
+ int fc = comp_int(T, C_tileBackground, F_frameCount, 0);
+ if (s->fl & SF_DORD && s->dord <= -1e5f) s->fl |= ref == S_skate_Kk ? SF_GROUND : SF_BG;
+ else if (fc > 0) { s->fl |= SF_TILEANIM; s->fc = (uint8_t)fc; }
+ }
+ if ((s->fl & SF_ZOBJ) && (s->fl & SF_ZB)) {
+ uint16_t sh = comp_str(T, C_zBoundable, F_shape);
+ if (sh != NONE16 && !strcmp(str(sh), "leftRamp")) s->shape = 1;
+ if (sh != NONE16 && !strcmp(str(sh), "rightRamp")) s->shape = 2;
+ }
+ /* the children of the first frame: the bounds child (Oj), rail markers (Mt), what is drawn */
+ bool draws = false;
+ int nmark = 0;
+ const uint8_t *p = c.slots;
+ for (unsigned i = 0; i < c.nslots; i++) {
+ Key k;
+ const uint8_t *nx;
+ bool on = slot_at(p, 0, &k, &nx);
+ p = nx;
+ if (!on) continue;
+ if (!(k.flags & K_HIDDEN) && k.alpha) draws = true;
+ if (k.kind != CK_SYM || k.ref >= SYM_COUNT) continue;
+ Clip cc;
+ SymInfo ci;
+ sym_info(k.ref, &ci);
+ if (ci.type != SYM_CLIP) continue;
+ clip_frame0(k.ref, &cc);
+ Mat m = key_mat(&k);
+ if (!(s->fl & SF_BOUNDS) && comp_has(cc.T, C_bounds) && (cc.nb[2] || cc.nb[3])) {
+ Rect r = mat_rect(m, (Rect){cc.nb[0], cc.nb[1], cc.nb[2], cc.nb[3]});
+ s->b[0] = Q8(r.x); s->b[1] = Q8(r.y); s->b[2] = Q8(r.x + r.w); s->b[3] = Q8(r.y + r.h);
+ s->fl |= SF_BOUNDS;
+ }
+ if (comp_has(cc.T, C_skateRailMarker) && nmark < 2) {
+ s->r[nmark * 3] = Q8(m.tx);
+ s->r[nmark * 3 + 1] = Q8(m.ty);
+ s->r[nmark * 3 + 2] = (int16_t)comp_float(cc.T, C_skateRailMarker, F_z, 0);
+ nmark++;
+ s->fl |= SF_MARKERS;
+ }
+ }
+ if (nmark < 2) s->fl &= (uint16_t)~(SF_MARKERS | SF_RAIL);
+ if (!draws && c.nframes <= 1) s->fl |= SF_NODRAW;
+ if (comp_has(T, C_collidable) && comp_has(T, C_boundable) && (s->fl & SF_BOUNDS)) s->fl |= SF_COLL;
+ if ((s->fl & SF_ZOBJ) && (s->fl & SF_ZB) && (s->fl & SF_BOUNDS) && comp_has(T, C_boundable)) s->fl |= SF_KEYB;
+ /* what it may draw: nominal bounds, up by its height (dq) and some room for effects */
+ float x0 = c.nb[0], y0 = c.nb[1], x1 = c.nb[0] + c.nb[2], y1 = c.nb[1] + c.nb[3];
+ if (!c.nb[2] && !c.nb[3]) { x0 = -64; y0 = -128; x1 = 64; y1 = 32; }
+ if (s->fl & SF_ZOBJ) y0 -= s->z;
+ if (s->fl & SF_CHAMP) y0 -= 200;
+ s->vis[0] = (int16_t)floorf(x0); s->vis[1] = (int16_t)floorf(y0); s->vis[2] = (int16_t)ceilf(x1); s->vis[3] = (int16_t)ceilf(y1);
+ return s;
+}
+
+/* a map (or ground) child: its key, symbol and placement */
+typedef struct { Key k; Sym *s; Mat m; Rect box; } Item;
+
+/* grow: room around the nominal bounds (map children), 0 for ground tiles */
+static bool item_at(const uint8_t *slots, uint16_t off, Mat parent, Item *it, float grow) {
+ if (!slot_at(slots + off, 0, &it->k, NULL) || it->k.kind != CK_SYM) return false;
+ it->s = sym_get(it->k.ref);
+ if (!it->s) return false;
+ it->m = mat_mul(parent, key_mat(&it->k));
+ const int16_t *v = it->s->vis;
+ it->box = mat_rect(it->m, (Rect){v[0] - grow, v[1] - grow, v[2] - v[0] + 2 * grow, v[3] - v[1] + 2 * grow});
+ return true;
+}
+
+static Rect item_bounds(const Item *it) {
+ const int16_t *b = it->s->b;
+ return mat_rect(it->m, (Rect){F8(b[0]), F8(b[1]), F8(b[2] - b[0]), F8(b[3] - b[1])});
+}
+
+/* the cannon body: zObject and zBoundable give its bottom and height, else 0 and 100 */
+static float body_z0(const Sym *s) { return (s->fl & SF_ZOBJ) && (s->fl & SF_ZB) ? s->z : 0; }
+static float body_h(const Sym *s) { return (s->fl & SF_ZOBJ) && (s->fl & SF_ZB) ? fminf(s->h, 20000) : 100; }
+
+/* ---------------------------------------------------------------- band index
+ * Each child is listed once, in the band of its top edge, in timeline order;
+ * a query looks up to the index's tallest child above. Children taller than
+ * TALL are in one more list that every query reads. */
+#define TALL 160
+static void index_build(Index *ix, const uint8_t *slots, unsigned nslots, Mat parent, uint16_t bh, bool ground) {
+ float lo = 1e9f, hi = -1e9f, maxh = 0;
+ for (int pass = 0; pass < 3; pass++) {
+ const uint8_t *p = slots;
+ for (unsigned i = 0; i < nslots; i++) {
+ uint16_t off = (uint16_t)(p - slots);
+ Key k;
+ const uint8_t *nx;
+ slot_at(p, 0, &k, &nx);
+ p = nx;
+ Item it;
+ if (!item_at(slots, off, parent, &it, ground ? 0 : 8)) continue;
+ uint16_t fl = it.s->fl;
+ if (!ground && (fl & (SF_GROUND | SF_BG | SF_PLAYER))) continue;
+ if ((fl & SF_NODRAW) && !(fl & (SF_COLL | SF_RAIL | SF_BOOST))) continue;
+ Rect r = it.box;
+ if (fl & SF_COLL) {
+ Rect c = item_bounds(&it);
+ float x0 = fminf(r.x, c.x), y0 = fminf(r.y, c.y);
+ r = (Rect){x0, y0, fmaxf(r.x + r.w, c.x + c.w) - x0, fmaxf(r.y + r.h, c.y + c.h) - y0};
+ }
+ if (fl & SF_RAIL) {
+ float ax, ay, bx, by;
+ mat_apply(it.m, F8(it.s->r[0]), F8(it.s->r[1]), &ax, &ay);
+ mat_apply(it.m, F8(it.s->r[3]), F8(it.s->r[4]), &bx, &by);
+ float x0 = fminf(r.x, fminf(ax, bx)), y0 = fminf(r.y, fminf(ay, by));
+ r = (Rect){x0, y0, fmaxf(r.x + r.w, fmaxf(ax, bx)) - x0, fmaxf(r.y + r.h, fmaxf(ay, by)) - y0};
+ }
+ bool tall = r.h > TALL;
+ if (pass == 0) {
+ lo = fminf(lo, r.y);
+ hi = fmaxf(hi, r.y);
+ if (!tall) maxh = fmaxf(maxh, r.h);
+ continue;
+ }
+ int b = tall ? ix->nb : clampi((int)floorf((r.y - ix->y0) / bh), 0, ix->nb - 1);
+ if (pass == 1) S->starts[ix->s0 + b + 1]++;
+ else if (S->starts[ix->s0 + b] < ENT_CAP) S->ent[S->starts[ix->s0 + b]++] = off;
+ }
+ if (pass == 0) {
+ if (lo > hi) { lo = 0; hi = 1; }
+ ix->y0 = floorf(lo);
+ ix->bh = bh;
+ ix->maxh = maxh;
+ int nb = (int)((hi - ix->y0) / bh) + 1;
+ ix->nb = (uint16_t)clampi(nb, 1, BANDS_MAX - 2 - S->nstarts);
+ ix->s0 = S->nstarts;
+ S->nstarts = (uint16_t)(S->nstarts + ix->nb + 2);
+ S->starts[ix->s0] = S->nent;
+ for (int b = 1; b <= ix->nb + 1; b++) S->starts[ix->s0 + b] = 0;
+ } else if (pass == 1) {
+ for (int b = 1; b <= ix->nb + 1; b++) {
+ uint32_t v = (uint32_t)S->starts[ix->s0 + b] + S->starts[ix->s0 + b - 1];
+#ifdef HOST
+ if (v > ENT_CAP) fprintf(stderr, "skate: index needs %u entries\n", v);
+#endif
+ S->starts[ix->s0 + b] = (uint16_t)(v > ENT_CAP ? ENT_CAP : v);
+ }
+ }
+ }
+ /* pass 2 left each list's start at the next one's: shift back */
+ for (int b = ix->nb + 1; b >= 1; b--) S->starts[ix->s0 + b] = S->starts[ix->s0 + b - 1];
+ S->starts[ix->s0] = S->nent;
+ S->nent = S->starts[ix->s0 + ix->nb + 1];
+}
+
+/* the children that may reach rows [y0, y1), each once, in timeline order */
+typedef void (*ItemFn)(uint16_t off, void *ctx);
+static void index_query(const Index *ix, float y0, float y1, ItemFn fn, void *ctx) {
+ if (!ix->nb) return;
+ int b0 = (int)floorf((y0 - ix->maxh - ix->y0) / ix->bh), b1 = (int)floorf((y1 - ix->y0) / ix->bh);
+ uint16_t pos[18], end[18];
+ int k = 0;
+ if (b1 >= 0 && b0 < ix->nb) {
+ b0 = clampi(b0, 0, ix->nb - 1);
+ b1 = clampi(b1, 0, ix->nb - 1);
+ if (b1 - b0 > 16) b1 = b0 + 16;
+ for (int b = b0; b <= b1; b++, k++) {
+ pos[k] = S->starts[ix->s0 + b];
+ end[k] = S->starts[ix->s0 + b + 1];
+ }
+ }
+ pos[k] = S->starts[ix->s0 + ix->nb]; /* the tall ones */
+ end[k] = S->starts[ix->s0 + ix->nb + 1];
+ k++;
+ for (;;) {
+ int best = -1;
+ for (int i = 0; i < k; i++)
+ if (pos[i] < end[i] && (best < 0 || S->ent[pos[i]] < S->ent[pos[best]])) best = i;
+ if (best < 0) break;
+ fn(S->ent[pos[best]++], ctx);
+ }
+}
+
+/* ---------------------------------------------------------------- prototypes: one node per symbol, placed per child */
+/* frame-0 scripts that stop: CreateJS runs them before the first tick */
+static void first_stops(NodeId n, int depth) {
+ if (depth > 12) return;
+ if (nodes[n].kind == NK_CLIP) {
+ Clip c;
+ if (clip_get(nodes[n].sym, &c))
+ for (int i = 0; i < c.nacts; i++)
+ if (rd16(c.acts + 5 * i) == nodes[n].frame && c.acts[5 * i + 2] == ACT_STOP) node_stop(n);
+ }
+ for (NodeId c = nodes[n].first; c; c = nodes[c].next) first_stops(c, depth + 1);
+}
+
+/* where a clip created at the scene's start would be after t ticks */
+static void advance(NodeId n, uint32_t t, int depth) {
+ if (depth > 12) return;
+ Node *p = &nodes[n];
+ if (p->kind == NK_CLIP && node_mode(p) == MODE_INDEPENDENT && (p->flags & NF_PLAYING) && (p->flags & NF_TICK)) {
+ Clip c;
+ if (clip_get(p->sym, &c) && c.nframes > 1) {
+ int stop = -1;
+ for (int i = 0; i < c.nacts; i++)
+ if (c.acts[5 * i + 2] == ACT_STOP && (stop < 0 || rd16(c.acts + 5 * i) < stop)) stop = rd16(c.acts + 5 * i);
+ uint32_t f = p->frame + t;
+ if (stop >= 0 && f >= (uint32_t)stop) { f = (uint32_t)stop; node_stop(n); }
+ else if (!node_loops(p) && f >= c.nframes) f = c.nframes - 1u;
+ else f %= c.nframes;
+ p->frame = (uint16_t)f;
+ node_update_one(n);
+ }
+ }
+ for (NodeId c = nodes[n].first; c; c = nodes[c].next) advance(c, t, depth + 1);
+}
+
+/* dq: zSprite children sit at (0, -z) of the zObject within three parents; tt: shadows at -KT */
+static void set_local(NodeId n, float x, float y) {
+ Mat l = node_local(n);
+ nodes[n].x = x + nodes[n].rx4 * 0.25f * l.a;
+ nodes[n].y = y + nodes[n].ry4 * 0.25f * l.d;
+}
+
+static void zsprites(NodeId n, NodeId root, float root_z, int depth) {
+ if (depth > 10) return;
+ for (NodeId c = nodes[n].first; c; c = nodes[c].next) {
+ uint16_t T = nodes[c].T;
+ if (T != NONE16 && comp_has(T, C_zSprite)) {
+ NodeId a = n;
+ for (int up = 0; up < 3 && a; up++, a = nodes[a].parent) {
+ if (a == root) { set_local(c, 0, -root_z); break; }
+ if (nodes[a].T != NONE16 && comp_has(nodes[a].T, C_zObject)) { set_local(c, 0, -comp_float(nodes[a].T, C_zObject, F_z, 0)); break; }
+ }
+ }
+ zsprites(c, root, root_z, depth + 1);
+ }
+}
+
+static void hide_markers(NodeId n) {
+ for (NodeId c = nodes[n].first; c; c = nodes[c].next)
+ if (nodes[c].T != NONE16 && comp_has(nodes[c].T, C_skateRailMarker)) nodes[c].alpha = 0;
+}
+
+static void proto_setup(Sym *s) {
+ NodeId p = s->proto;
+ if (s->fl & SF_TILEANIM)
+ for (NodeId c = nodes[p].first; c; c = nodes[c].next) nodes[c].flags &= (uint8_t)~NF_TICK; /* Ps caches them */
+ else {
+ first_stops(p, 0);
+ advance(p, S->ticks, 0);
+ }
+ if (S->go) zsprites(p, p, s->z, 0);
+ if (S->markers_hidden && (s->fl & SF_MARKERS)) hide_markers(p);
+}
+
+static NodeId proto(Sym *s) {
+ s->stamp = S->stamp;
+ if (s->proto) return s->proto;
+ /* room: forget the prototypes not drawn lately */
+ while (node_count() + PROTO_RESERVE >= NODE_MAX) {
+ Sym *old = NULL;
+ for (int i = 0; i < S->nsym; i++) {
+ Sym *o = &S->sym[i];
+ if (o->proto && o->stamp != S->stamp && (!old || (uint16_t)(S->stamp - o->stamp) > (uint16_t)(S->stamp - old->stamp))) old = o;
+ }
+ if (!old) return 0;
+ node_free(old->proto);
+ old->proto = 0;
+ }
+ NodeId n = node_new_sym(s->sym);
+ if (!n) return 0;
+ node_add(S->map, n);
+ s->proto = n;
+ proto_setup(s);
+ return n;
+}
+
+static void place(NodeId p, const Key *k) {
+ Node *n = &nodes[p];
+ n->x = k->x;
+ n->y = k->y;
+ n->rx4 = k->rx4;
+ n->ry4 = k->ry4;
+ n->mat = k->mat;
+ n->alpha = k->alpha;
+ if (k->flags & K_HIDDEN) n->flags &= (uint8_t)~NF_VISIBLE; else n->flags |= NF_VISIBLE;
+}
+
+/* Os: tiles with frameCount show frame floor(tick / duration) % count */
+static void tile_frames(Sym *s) {
+ int f = (int)(S->ticks % (s->fc ? s->fc : 1));
+ for (NodeId c = nodes[s->proto].first; c; c = nodes[c].next)
+ if (nodes[c].kind == NK_CLIP && nodes[c].frame != f) {
+ nodes[c].frame = (uint16_t)(f % node_frames(c));
+ node_update_one(c);
+ }
+}
+
+static void draw_item(const Item *it, Mat parent) {
+ NodeId p = proto(it->s);
+ if (!p) return;
+ if (it->s->fl & SF_TILEANIM) tile_frames(it->s);
+ place(p, &it->k);
+ node_draw(p, parent);
+}
+
+/* ---------------------------------------------------------------- the HUD (ck): texts, trick prompt icons, tweens */
+static float cubic_out(float t) { t -= 1; return t * t * t + 1; }
+
+static void icon_x(Icon *ic, float x) {
+ ic->x0 = nodes[ic->n].x;
+ ic->x1 = x;
+ ic->tx = 0;
+}
+static void icon_fade(Icon *ic) {
+ ic->a0 = nodes[ic->n].alpha / 255.0f;
+ ic->a1 = 0;
+ ic->ta = 0;
+ ic->fading = true;
+}
+
+static void icon_free(int i) {
+ if (S->icon[i].used && S->icon[i].n) node_free(S->icon[i].n);
+ memset(&S->icon[i], 0, sizeof S->icon[i]);
+}
+
+static int icon_new(void) {
+ for (int i = 0; i < ICON_MAX; i++)
+ if (!S->icon[i].used) return i;
+ /* the one fading longest */
+ int best = -1;
+ for (int i = 0; i < ICON_MAX; i++)
+ if (!S->icon[i].listed && (best < 0 || S->icon[i].ta > S->icon[best].ta)) best = i;
+ if (best >= 0) icon_free(best);
+ return best;
+}
+
+static float lerp(float a, float b, float t) { return a + (b - a) * t; }
+
+/* Ut: the prompt's icons fade out */
+static void ut(void) {
+ for (int i = 0; i < S->nlist; i++) {
+ Icon *ic = &S->icon[S->list[i]];
+ icon_fade(ic);
+ ic->listed = false;
+ }
+ S->nlist = 0;
+}
+
+/* Vt: the trick texts show again, the sparkles play */
+static void vt(void) {
+ if (S->spark_l) { node_goto(S->spark_l, NULL, 1, true); node_update_one(S->spark_l); }
+ if (S->spark_r) { node_goto(S->spark_r, NULL, 1, true); node_update_one(S->spark_r); }
+ S->trick_red = false;
+ S->tr_t = 255;
+ S->tr_alpha = 255;
+}
+
+static void trick_texts_fade(void) {
+ S->tr_a0 = S->tr_alpha / 255.0f;
+ S->tr_a1 = 0;
+ S->tr_t = 0;
+}
+
+static int32_t combo_score(void) { return S->iy + (int32_t)(S->ck_sum * S->ck_n); } /* IY + Lt(CK) */
+
+static void combo_clear(void) {
+ S->ck_n = 0;
+ S->ck_sum = 0;
+ S->nnames = 0;
+ memset(S->name_cnt, 0, sizeof S->name_cnt);
+}
+
+/* Wt: the combo is banked */
+static void wt(void) {
+ int32_t g = combo_score();
+ S->hf += g;
+ S->iy = 0;
+ snprintf(S->score_buf, sizeof S->score_buf, "%d", (int)S->hf);
+ trick_texts_fade();
+ /* (the score also swells to 1.2 for a moment: the pixel font has no size between 1 and 2) */
+ combo_clear();
+}
+
+/* Pt: an action, and its icon on the prompt for directions and OK */
+static void pt(uint8_t type) {
+ if (S->nact == ACT_KEEP) memmove(S->act, S->act + 1, sizeof S->act[0] * (ACT_KEEP - 1)), S->nact--;
+ S->act[S->nact++] = (Action){type, S->dir, S->vx, S->vy};
+ if (S->act_total < 60000) S->act_total++;
+ if (type > AC_ACTION || !S->prompt) return;
+ int i = icon_new();
+ if (i < 0) return;
+ NodeId n = node_new_sym(S_skate_Lqa);
+ if (!n) return;
+ node_add(S->prompt, n);
+ node_goto(n, icon_labels[type], 0, false);
+ node_update_one(n);
+ Icon *ic = &S->icon[i];
+ *ic = (Icon){n, 0, 0, 1, 1, 5, 5, true, true, false};
+ if (S->nlist < ICON_MAX) S->list[S->nlist++] = (uint8_t)i;
+ int g = S->nlist;
+ bool k = g > 4;
+ for (int a = 0; a < g; a++) {
+ Icon *c = &S->icon[S->list[a]];
+ float h = k ? lerp(-60, 60, (a - 1) / 3.0f) : g > 1 ? lerp(-20.0f * (g - 1), 20.0f * (g - 1), a / (float)(g - 1)) : 0;
+ if (c == ic) { nodes[n].x = h; c->x0 = c->x1 = h; }
+ else {
+ c->ta = 5; /* removeTweens */
+ c->fading = false;
+ icon_x(c, h);
+ if (k && a == 0) { icon_fade(c); c->listed = false; }
+ }
+ }
+ if (k) {
+ memmove(S->list, S->list + 1, (size_t)(S->nlist - 1));
+ S->nlist--;
+ }
+}
+
+/* Xt: a trick joins the combo */
+static void xt(int t, int nacts) {
+ const Trick *tr = &tricks[t];
+ S->ck_n++;
+ S->ck_sum += tr->hf;
+ S->ck_frame = tr->frame;
+ if (t == TR_NOSE) S->ck_frame = S->dir == DIR_E || S->dir == DIR_N ? "nose_grab_e" : "nose_grab_w";
+ if (!S->name_cnt[tr->name] && S->nnames < NAME_COUNT) S->name_order[S->nnames++] = tr->name;
+ S->name_cnt[tr->name]++;
+ if (tr->dur > 0) S->kbt = tr->dur;
+ S->nact = 0;
+ S->act_total = 0;
+ /* uh(name + "_COMPLETE", true): never read back by the doodle, not kept here */
+ vt();
+ (void)nacts;
+ if (S->nlist) {
+ int m = S->nlist, g = tr->n, c = m - g;
+ for (int a = 0; a < m; a++) {
+ Icon *ic = &S->icon[S->list[a]];
+ float x = g > 1 ? lerp(-20.0f * (g - 1), 20.0f * (g - 1), (a - c) / (float)(g - 1)) : 0;
+ ic->ta = 5;
+ ic->fading = false;
+ icon_x(ic, x);
+ if (a < c) { icon_fade(ic); ic->listed = false; }
+ /* else: the doodle tints the trick's icons green (ColorFilter), which the renderer cannot */
+ }
+ if (c > 0) {
+ memmove(S->list, S->list + c, (size_t)(m - c));
+ S->nlist = (uint8_t)(m - c);
+ }
+ }
+}
+
+static void tweens(void) {
+ for (int i = 0; i < ICON_MAX; i++) {
+ Icon *ic = &S->icon[i];
+ if (!ic->used) continue;
+ if (ic->tx < 5) {
+ ic->tx++;
+ nodes[ic->n].x = lerp(ic->x0, ic->x1, cubic_out(ic->tx / 5.0f));
+ }
+ if (ic->fading && ic->ta < 5) {
+ ic->ta++;
+ nodes[ic->n].alpha = (uint8_t)(255 * lerp(ic->a0, ic->a1, ic->ta / 5.0f) + .5f);
+ }
+ if (!ic->listed && ic->fading && ic->ta >= 5 && ic->tx >= 5) icon_free(i);
+ }
+ if (S->tr_t < 30) {
+ S->tr_t++;
+ S->tr_alpha = (uint8_t)(255 * lerp(S->tr_a0, S->tr_a1, S->tr_t / 30.0f) + .5f);
+ }
+ if (S->tname) nodes[S->tname].alpha = S->tr_alpha;
+ if (S->tscore) nodes[S->tscore].alpha = S->tr_alpha;
+}
+
+static void time_text(char *b, size_t n, int32_t cn) {
+ snprintf(b, n, "%d:%02d.%02d", (int)(cn / 1800 % 60), (int)(cn / 30 % 60), (int)(cn % 30 * 100 / 30));
+}
+
+/* Zt */
+static void hud_update(void) {
+ time_text(S->time_buf, sizeof S->time_buf, S->cn);
+ snprintf(S->score_buf, sizeof S->score_buf, "%d", (int)S->hf);
+ int32_t m = combo_score();
+ if (m) {
+ int k = S->ck_n;
+ if (k > 1) snprintf(S->tscore_buf, sizeof S->tscore_buf, "x%d! %d", k, (int)m);
+ else snprintf(S->tscore_buf, sizeof S->tscore_buf, "%d", (int)m);
+ size_t len = 0;
+ S->tname_buf[0] = 0;
+ for (int i = 0; i < S->nnames; i++) {
+ int nm = S->name_order[i];
+ const char *text = "";
+ for (int t = 0; t < TR_COUNT; t++) if (tricks[t].name == nm) { text = tricks[t].text; break; }
+ len += (size_t)snprintf(S->tname_buf + len, len < sizeof S->tname_buf ? sizeof S->tname_buf - len : 0, "%s%s", i ? " + " : "", text);
+ if (S->name_cnt[nm] > 1 && len < sizeof S->tname_buf)
+ len += (size_t)snprintf(S->tname_buf + len, sizeof S->tname_buf - len, " x %d", S->name_cnt[nm]);
+ if (len >= sizeof S->tname_buf) break;
+ }
+ /* the sparkles either side of the trick's score */
+ if (S->tscore && S->spark_l && S->spark_r) {
+ int w, h;
+ font_scale(1);
+ font_measure(S->tscore_buf, 0, 0, &w, &h);
+ float cx = nodes[S->tscore].x, x0 = cx - w * 1.5f;
+ nodes[S->spark_l].x = x0 - 45;
+ nodes[S->spark_r].x = x0 + w * 3 + 30;
+ }
+ }
+ S->time_red = S->cn < 450 && (S->cn / 15) % 2 == 0;
+}
+
+/* ---------------------------------------------------------------- the skater's world: boxes and ramps near it (yr, Ar) */
+typedef struct { float x0, y0, x1, y1, z0, z1; uint8_t shape; } Col;
+typedef struct { Col c[COL_MAX]; int n; float x0, y0, x1, y1; } ColSet;
+
+static void col_add(uint16_t off, void *ctx) {
+ ColSet *cs = ctx;
+ Item it;
+ if (cs->n >= COL_MAX || !item_at(S->mslots, off, MAT_ID, &it, 0) || !(it.s->fl & SF_COLL)) return;
+ Rect b = item_bounds(&it);
+ if (b.x > cs->x1 || b.y > cs->y1 || b.x + b.w < cs->x0 || b.y + b.h < cs->y0) return;
+ float z0 = body_z0(it.s);
+ cs->c[cs->n++] = (Col){b.x, b.y, b.x + b.w, b.y + b.h, z0, z0 + body_h(it.s), it.s->shape};
+}
+
+/* the top of a collider at x (a ramp's slope) */
+static float col_top(const Col *c, float x) {
+ if (!c->shape) return c->z1;
+ float t = (x - c->x0) / (c->x1 - c->x0);
+ t = clampf(t, 0, 1);
+ if (c->shape == 2) t = 1 - t;
+ return c->z0 + (c->z1 - c->z0) * t;
+}
+
+typedef struct { float x, y, z, vx, vy, vz, hx, hy, hz; } Body;
+
+/* pushes the body out of c; 0: no contact, 1: a side, 2: a surface it stands on */
+static int collide(Body *b, const Col *c) {
+ float ox = fminf(b->x + b->hx, c->x1) - fmaxf(b->x - b->hx, c->x0);
+ float oy = fminf(b->y + b->hy, c->y1) - fmaxf(b->y - b->hy, c->y0);
+ float bot = b->z - b->hz, top = b->z + b->hz;
+ if (ox <= 0 || oy <= 0 || top <= c->z0 || bot >= c->z1) return 0;
+ float sy = b->y < (c->y0 + c->y1) / 2 ? -1.0f : 1.0f;
+ if (!c->shape) {
+ float oz = fminf(top, c->z1) - fmaxf(bot, c->z0);
+ if (oz <= ox && oz <= oy) {
+ if (b->z > (c->z0 + c->z1) / 2) { b->z += c->z1 - bot; if (b->vz < 0) b->vz = 0; return 2; }
+ b->z -= top - c->z0;
+ if (b->vz > 0) b->vz = 0;
+ return 1;
+ }
+ if (ox <= oy) {
+ if (b->x < (c->x0 + c->x1) / 2) { b->x -= b->x + b->hx - c->x0; if (b->vx > 0) b->vx = 0; }
+ else { b->x += c->x1 - (b->x - b->hx); if (b->vx < 0) b->vx = 0; }
+ return 1;
+ }
+ if (sy < 0) { b->y -= b->y + b->hy - c->y0; if (b->vy > 0) b->vy = 0; }
+ else { b->y += c->y1 - (b->y - b->hy); if (b->vy < 0) b->vy = 0; }
+ return 1;
+ }
+ /* a ramp (cannon's convex leftRamp / rightRamp): the slope, the wall at its high end, its sides */
+ bool left = c->shape == 1;
+ float span = c->x1 - c->x0, hgt = c->z1 - c->z0, s = span > 0 ? hgt / span : 0;
+ float up = left ? fminf(b->x + b->hx, c->x1) : fmaxf(b->x - b->hx, c->x0);
+ float over = col_top(c, up) - bot;
+ if (over <= 0) return 0;
+ float l = sqrtf(1 + s * s), pn = over / l;
+ bool behind = left ? b->x > c->x1 : b->x < c->x0;
+ float wall = left ? c->x1 - (b->x - b->hx) : b->x + b->hx - c->x0;
+ if (behind && wall < pn && wall <= oy) {
+ if (left) { b->x += wall; if (b->vx < 0) b->vx = 0; }
+ else { b->x -= wall; if (b->vx > 0) b->vx = 0; }
+ return 1;
+ }
+ if (oy < pn) {
+ if (sy < 0) { b->y -= oy; if (b->vy > 0) b->vy = 0; }
+ else { b->y += oy; if (b->vy < 0) b->vy = 0; }
+ return 1;
+ }
+ b->z += over;
+ float nx = (left ? -s : s) / l, nz = 1 / l;
+ float vn = b->vx * nx + b->vz * nz;
+ if (vn < 0) { b->vx -= vn * nx; b->vz -= vn * nz; }
+ return 2;
+}
+
+/* yr: one frame of the cannon world (4 substeps), then Ar (the ground under the skater) */
+static void physics(void) {
+ ColSet cs;
+ cs.n = 0;
+ cs.x0 = S->px + S->bcx - S->bhx - 40;
+ cs.x1 = S->px + S->bcx + S->bhx + 40;
+ cs.y0 = S->py + S->bcy - S->bhy - 40;
+ cs.y1 = S->py + S->bcy + S->bhy + 40;
+ index_query(&S->mi, cs.y0 - 8, cs.y1 + 8, col_add, &cs);
+ Body b = {S->px + S->bcx, S->py + S->bcy, S->z + 10, S->vx * 30, S->vy * 30, S->vz * 30, S->bhx, S->bhy, 10};
+ float h = 1.0f / (FPS * 4), damp = powf(1 - .4f, h);
+ bool flat = false;
+ for (int st = 0; st < 4; st++) {
+ b.vz += S->gravity * h;
+ b.vx *= damp;
+ b.vy *= damp;
+ b.vz *= damp;
+ b.x += b.vx * h;
+ b.y += b.vy * h;
+ b.z += b.vz * h;
+ flat = false;
+ for (int it = 0; it < 4; it++) {
+ bool any = false;
+ if (b.z - b.hz < 0) { /* the ground plane */
+ b.z = b.hz;
+ if (b.vz < 0) b.vz = 0;
+ flat = any = true;
+ }
+ for (int i = 0; i < cs.n; i++) {
+ int r = collide(&b, &cs.c[i]);
+ if (r) any = true;
+ if (r == 2) flat = true;
+ }
+ if (!any) break;
+ }
+ }
+ S->vx = b.vx / 30;
+ S->vy = b.vy / 30;
+ S->vz = b.vz / 30;
+ S->px = b.x - S->bcx;
+ S->py = b.y - S->bcy;
+ S->z = b.z - b.hz;
+ S->flat = flat;
+ if (!S->go) return;
+ /* Ar: rays down from 9 above at the corners of its bounds */
+ float g = 0;
+ for (int k = 0; k < 4; k++) {
+ float x = b.x + (k & 1 ? b.hx : -b.hx), y = b.y + (k & 2 ? b.hy : -b.hy), hit = 0;
+ for (int i = 0; i < cs.n; i++) {
+ const Col *c = &cs.c[i];
+ if (x < c->x0 || x > c->x1 || y < c->y0 || y > c->y1) continue;
+ float t = col_top(c, x);
+ if (t <= S->z + 9 && t > hit) hit = t;
+ }
+ float v = fminf(hit, S->z);
+ if (v > g) g = v;
+ }
+ S->kt = g;
+}
+
+/* ---------------------------------------------------------------- the skater (Ot and its helpers St, Rt, Qt, Tt) */
+/* Nt: the point of line (a, b) nearest to p, within the segment unless `line` */
+static void nt(const float *a, const float *b, const float *p, bool line, float *o) {
+ float c[3] = {b[0] - a[0], b[1] - a[1], b[2] - a[2]};
+ float len = sqrtf(c[0] * c[0] + c[1] * c[1] + c[2] * c[2]);
+ if (len < 1e-6f) { memcpy(o, a, sizeof(float) * 3); return; }
+ for (int i = 0; i < 3; i++) c[i] /= len;
+ float d = (p[0] - a[0]) * c[0] + (p[1] - a[1]) * c[1] + (p[2] - a[2]) * c[2];
+ if (!line) d = clampf(d, 0, len);
+ for (int i = 0; i < 3; i++) o[i] = a[i] + c[i] * d;
+}
+static float dist3(const float *a, const float *b) {
+ float x = a[0] - b[0], y = a[1] - b[1], z = a[2] - b[2];
+ return sqrtf(x * x + y * y + z * z);
+}
+
+/* St: on the rail's line, 2 above it, at 5 px a tick along it */
+static void st(void) {
+ float p[3] = {S->px, S->py, S->z}, m[3];
+ const float *k0 = S->rail, *k1 = S->rail + 3;
+ float c[3] = {k1[0] - k0[0], k1[1] - k0[1], k1[2] - k0[2]};
+ nt(k0, k1, p, true, m);
+ S->px = m[0];
+ S->py = m[1];
+ S->z = m[2] + 2;
+ S->kt = S->z;
+ float len = sqrtf(c[0] * c[0] + c[1] * c[1] + c[2] * c[2]);
+ if (len < 1e-6f) return;
+ float u[3] = {c[0] / len * 5, c[1] / len * 5, c[2] / len * 5};
+ if (fabsf(ih(hh(c[0], c[1]), hh(S->vx, S->vy))) > 90) for (int i = 0; i < 3; i++) u[i] = -u[i];
+ S->vx = u[0];
+ S->vy = u[1];
+ S->vz = u[2];
+}
+
+static void qt(void) {
+ SOUND(grind_stop);
+ if (S->grinding) {
+ S->grinding = false;
+ pt(AC_GEND);
+ }
+}
+
+static void rt(const float *m, uint16_t off) {
+ SOUND(grind_loop);
+ ut();
+ S->grinding = true;
+ memcpy(S->rail, m, sizeof S->rail);
+ S->rail_off = off;
+ S->bb = S->ca = 0;
+ S->iy++;
+ pt(AC_GSTART);
+ vt();
+ st();
+}
+
+/* Tt: the trick timer, the landing timer (then the combo is banked), and tricks */
+static void tricks_check(void) {
+ if (S->kbt > 0 && --S->kbt == 0) ut();
+ if (S->tb && S->oc > 0 && --S->oc == 0) { wt(); ut(); }
+ if (!S->act_total || !S->nact) return;
+ const Action *m = &S->act[S->nact - 1];
+ if (m->type == AC_LAND && m->dir == rg(mh(m->vx, m->vy)) && vlen(m->vx, m->vy) > 1) xt(TR_FAKIE, 1);
+ if (S->a7) { S->a7 = false; xt(TR_HIDE, 0); }
+ int best = -1;
+ for (int t = 0; t < TR_FAKIE; t++) {
+ int c = tricks[t].n;
+ if (S->nact < c || (best >= 0 && tricks[best].hf >= tricks[t].hf)) continue;
+ bool same = true;
+ for (int i = 0; i < c; i++)
+ if (S->act[S->nact - c + i].type != tricks[t].acts[i]) same = false;
+ if (same) best = t;
+ }
+ if (best >= 0) xt(best, tricks[best].n);
+}
+
+/* rails (Mt: their two markers, in the map) near the skater */
+typedef struct { float p[3]; float v[2]; } RailCtx;
+static void rail_markers(const Item *it, float *m) {
+ mat_apply(it->m, F8(it->s->r[0]), F8(it->s->r[1]), &m[0], &m[1]);
+ m[2] = it->s->r[2];
+ mat_apply(it->m, F8(it->s->r[3]), F8(it->s->r[4]), &m[3], &m[4]);
+ m[5] = it->s->r[5];
+}
+
+static void rail_check(uint16_t off, void *ctx) {
+ RailCtx *rc = ctx;
+ Item it;
+ if (!item_at(S->mslots, off, MAT_ID, &it, 0) || !(it.s->fl & SF_RAIL)) return;
+ float c[6], h[3];
+ rail_markers(&it, c);
+ const float *b = rc->p;
+ float a[2] = {c[3] - c[0], c[4] - c[1]};
+ nt(c, c + 3, b, false, h);
+ float n = dist3(b, h);
+ float av = hh(a[0], a[1]), bv = hh(-a[0], -a[1]), g = hh(S->vx, S->vy);
+ if (S->grinding) {
+ float jx = in.jx, jy = in.jy, j = hh(jx, jy);
+ if (S->rail_off == off) return;
+ if (dist3(c, b) < 5) {
+ if (fabsf(ih(av, g)) < 30) rt(c, off);
+ else if (vlen(jx, jy) > 0 && fabsf(ih(av, j)) < 30 && fabsf(ih(av, g)) < 120) { S->vx = a[0]; S->vy = a[1]; rt(c, off); }
+ } else if (dist3(c + 3, b) < 5) {
+ if (fabsf(ih(bv, g)) < 30) rt(c, off);
+ else if (vlen(jx, jy) > 0 && fabsf(ih(bv, j)) < 30 && fabsf(ih(bv, g)) < 120) { S->vx = -a[0]; S->vy = -a[1]; rt(c, off); }
+ }
+ } else if (!S->tb && S->vz <= 0 && vlen(S->vx, S->vy) > 0 && n < 14 && S->z - 3 <= h[2] &&
+ (fabsf(ih(av, g)) < 60 || fabsf(ih(bv, g)) < 60))
+ rt(c, off);
+}
+
+static void markers_hide_all(void) {
+ S->markers_hidden = true;
+ for (int i = 0; i < S->nsym; i++)
+ if (S->sym[i].proto && (S->sym[i].fl & SF_MARKERS)) hide_markers(S->sym[i].proto);
+}
+
+/* Kj: gotoAndStop(label); false (and paused) when it is already there */
+static bool kj(NodeId n, const char *label) {
+ if (!strcmp(node_label(n), label)) { node_stop(n); return false; }
+ if (!node_goto(n, label, 0, false)) return false;
+ node_update_one(n);
+ return true;
+}
+
+static void skater(void) {
+ NodeId P = S->player;
+ float jx = in.jx, jy = in.jy, jl = vlen(jx, jy);
+ if (!S->grinding) {
+ bool was = S->tb;
+ S->tb = S->flat;
+ if (S->tb) S->bb = S->ca = 0;
+ if (!was && S->tb) {
+ S->nact = 0;
+ S->act_total = 0;
+ if (S->kbt > 0) { /* landed during a trick: a fall */
+ SOUND(fall);
+ S->sk = 30;
+ S->grinding = false;
+ combo_clear();
+ S->trick_red = true;
+ trick_texts_fade();
+ } else {
+ pt(AC_LAND);
+ S->oc = 8;
+ }
+ } else if (was && !S->tb) {
+ qt();
+ pt(AC_AIR);
+ }
+ }
+ if (!(S->sk > 0 || S->kbt > 0)) {
+ if (!S->markers_hidden) markers_hide_all();
+ RailCtx rc = {{S->px, S->py, S->z}, {S->vx, S->vy}};
+ index_query(&S->mi, S->py - 48, S->py + 48, rail_check, &rc);
+ if (S->grinding) {
+ float h[3];
+ nt(S->rail, S->rail + 3, rc.p, false, h);
+ float d = dist3(rc.p, h);
+ S->iy++;
+ st();
+ if (d > 14) qt();
+ }
+ }
+ if (!S->grinding) {
+ if (S->sk > 0) {
+ S->sk--;
+ S->vx *= .8f;
+ S->vy *= .8f;
+ } else if (!(S->kbt > 0)) {
+ if (S->isc == 1 && !S->tb) {
+ int d = mh(jx, jy);
+ if (d == DIR_N) pt(AC_N);
+ else if (d == DIR_S) pt(AC_S);
+ else if (d == DIR_E) pt(AC_E);
+ else if (d == DIR_W) pt(AC_W);
+ }
+ float b = vlen(S->vx, S->vy), c = hh(S->vx, S->vy);
+ float gx = jx * 5, gy = jy * 5, k = vlen(gx, gy);
+ if (jl > 0) {
+ gx -= S->vx;
+ gy -= S->vy;
+ float ma = ih(c, hh(jx, jy));
+ k = fmaxf(0, k - b);
+ if (S->tb) {
+ float c2 = fminf(.75f, k), k2 = (25 - fminf(3 + b, 25)) / 25, a = 30 * k2;
+ a = c + clampf(ma, -a, a);
+ float lx, ly;
+ lg(gx, gy, c2, &lx, &ly);
+ float g2x = S->vx + lx, g2y = S->vy + ly;
+ float m2 = k2 * clampf((180 - fabsf(ma)) / 80, 0, 1);
+ if (isnan(a)) { S->vx = g2x; S->vy = g2y; }
+ else {
+ float bx, by;
+ lg(cosf(a * PI_F / 180), sinf(a * PI_F / 180), b + fmaxf(c2, 0), &bx, &by);
+ S->vx = g2x + (bx - g2x) * m2;
+ S->vy = g2y + (by - g2y) * m2;
+ }
+ } else {
+ float b3 = fminf(.35f, k);
+ if (b3 > 0) {
+ float lx, ly;
+ lg(gx, gy, b3, &lx, &ly);
+ S->vx += lx;
+ S->vy += ly;
+ }
+ }
+ }
+ }
+ }
+ /* gravity for the next step: lighter while a jump is held */
+ S->gravity = -300;
+ if (S->bb > 0) { S->bb++; if (in.held[A_ACTION]) S->gravity = -210; }
+ if (S->ca > 0) S->ca++;
+ if (in.pressed[A_ACTION] && !(S->kbt > 0) && !(S->sk > 0)) {
+ pt(AC_ACTION);
+ if (S->tb) pt(AC_AIR);
+ if (!(S->bb != 0 && S->ca != 0)) {
+ S->vz = 6;
+ S->z += 1;
+ if (S->ca && jl > 0) { S->vx = jx * 4; S->vy = jy * 4; }
+ if (S->grinding) qt();
+ if (S->bb == 0) { S->bb = 1; SOUND(jump); }
+ else if (!S->ca) { S->ca = 1; SOUND(jump2); }
+ }
+ }
+ tricks_check();
+ /* which way it faces */
+ int b = mh(jx, jy);
+ if (b < 0) b = S->dir;
+ if (S->tb && vlen(S->vx, S->vy) > 1) {
+ int g = mh(S->vx, S->vy);
+ S->dir = (int8_t)(g >= 0 && g != rg(b) && g != b ? g : b);
+ } else if (jl > 0 && b >= 0) S->dir = (int8_t)b;
+ /* its pose */
+ if (S->sk > 0) kj(P, player_labels[5]);
+ else if (S->kbt > 0) { if (S->ck_frame) kj(P, S->ck_frame); }
+ else if (S->grinding) kj(P, player_labels[4]);
+ else if (S->bb > 0 || S->ca > 0) {
+ if (S->bb == 1 || S->ca == 1)
+ for (NodeId c = nodes[P].first; c; c = nodes[c].next)
+ if (node_visible(c) && nodes[c].T != NONE16 && comp_has(nodes[c].T, C_sprite))
+ for (NodeId g = nodes[c].first; g; g = nodes[g].next)
+ if (nodes[g].kind == NK_CLIP) node_goto(g, NULL, 0, true);
+ kj(P, player_labels[3]);
+ } else {
+ float v = vlen(S->vx, S->vy);
+ kj(P, player_labels[jl == 0 && v < .3f ? 0 : v < 2 ? 1 : 2]);
+ }
+ for (NodeId c = nodes[P].first; c; c = nodes[c].next)
+ if (node_visible(c) && nodes[c].T != NONE16 && comp_has(nodes[c].T, C_sprite)) ent_dir_label(c, S->dir);
+}
+
+/* dq and tt for the skater: its sprites at -z, its shadow on the ground (-KT) */
+static void heights(void) {
+ NodeId P = S->player;
+ for (NodeId c = nodes[P].first; c; c = nodes[c].next) {
+ uint16_t T = nodes[c].T;
+ if (T == NONE16 || !node_visible(c)) continue;
+ if (comp_has(T, C_zSprite)) set_local(c, 0, -S->z);
+ else if (comp_has(T, C_shadow) && comp_has(T, C_sprite)) set_local(c, 0, -S->kt);
+ }
+}
+
+static void player_place(void) {
+ nodes[S->player].x = S->px + nodes[S->player].rx4 * .25f;
+ nodes[S->player].y = S->py + nodes[S->player].ry4 * .25f;
+}
+
+/* ---------------------------------------------------------------- triggers (Hr): speed boosts (bu) and the champion */
+/* is the skater (its position and z) in one of e's trigger areas? m: e in the map */
+static bool in_trigger(NodeId e, Mat m, int z0, int z1) {
+ if (!bh(z0 - .1f, S->z, z1 + .1f)) return false;
+ for (NodeId a = nodes[e].first; a; a = nodes[a].next) {
+ if (nodes[a].T == NONE16 || !comp_has(nodes[a].T, C_triggerArea) || !(nodes[a].flags & NF_ONSTAGE)) continue;
+ float u, v;
+ if (mat_inv_apply(mat_mul(m, node_local(a)), S->px, S->py, &u, &v) && node_hit(a, u, v)) return true;
+ }
+ return false;
+}
+
+typedef struct { uint16_t hit[4]; int n; } HitSet;
+static void boost_check(uint16_t off, void *ctx) {
+ HitSet *hs = ctx;
+ Item it;
+ if (hs->n >= 4 || !item_at(S->mslots, off, MAT_ID, &it, 0) || !(it.s->fl & SF_BOOST)) return;
+ if (!rect_contains(it.box, S->px, S->py)) return;
+ NodeId p = proto(it.s);
+ if (!p) return;
+ place(p, &it.k);
+ if (in_trigger(p, it.m, it.s->tz0, it.s->tz1)) hs->hit[hs->n++] = off;
+}
+
+static void boost_fire(uint16_t off) {
+ Item it;
+ if (!item_at(S->mslots, off, MAT_ID, &it, 0)) return;
+ if (S->dir == it.s->bdir && vlen(S->vx, S->vy) > 2) {
+ float a = it.s->bdir * 45 * PI_F / 180;
+ S->vx += cosf(a) * it.s->bspeed / 3;
+ S->vy += sinf(a) * it.s->bspeed / 3;
+ SOUND(boost);
+ }
+}
+
+static void triggers(void) {
+ HitSet hs = {{0}, 0};
+ index_query(&S->mi, S->py - 64, S->py + 64, boost_check, &hs);
+ for (int i = 0; i < S->ninside; i++) {
+ bool still = false;
+ for (int j = 0; j < hs.n; j++) if (hs.hit[j] == S->inside[i]) still = true;
+ if (!still) { S->inside[i] = S->inside[--S->ninside]; i--; }
+ }
+ for (int j = 0; j < hs.n; j++) {
+ bool was = false;
+ for (int i = 0; i < S->ninside; i++) if (S->inside[i] == hs.hit[j]) was = true;
+ if (was || S->ninside >= 4) continue;
+ S->inside[S->ninside++] = hs.hit[j];
+ boost_fire(hs.hit[j]);
+ }
+}
+
+/* ---------------------------------------------------------------- champions (Yt): one hides somewhere at a time */
+static void champ_node_state(int i) {
+ Champ *c = &S->ch[i];
+ NodeId n = c->n;
+ if (!n) return;
+ nodes[n].alpha = c->alpha ? 255 : 0;
+}
+
+/* nodes for the champions near the view */
+static void champs_sync(Rect view) {
+ Rect near = rect_pad(view, 64, 64, 64, 64);
+ for (int i = 0; i < S->nch; i++) {
+ Champ *c = &S->ch[i];
+ Item it;
+ if (!item_at(S->mslots, c->off, MAT_ID, &it, 0)) continue;
+ bool want = rect_intersects(it.box, near);
+ if (want && !c->n && node_count() + 40 < NODE_MAX) {
+ NodeId n = node_new_sym(it.s->sym);
+ if (!n) continue;
+ node_add(S->map, n);
+ place(n, &it.k);
+ first_stops(n, 0);
+ if (c->out) {
+ node_goto(n, "out", 0, false);
+ node_update_one(n);
+ for (NodeId ch = nodes[n].first; ch; ch = nodes[ch].next) advance(ch, S->ticks - c->out_t, 1);
+ } else advance(n, S->ticks, 0);
+ if (S->go) zsprites(n, n, it.s->z, 0);
+ c->n = n;
+ champ_node_state(i);
+ } else if (!want && c->n) {
+ node_free(c->n);
+ c->n = 0;
+ }
+ }
+}
+
+static int champ_pick(bool inactive_only) {
+ int cand[CH_MAX], n = 0;
+ for (int i = 0; i < S->nch; i++)
+ if (!inactive_only || !S->ch[i].active) cand[n++] = i;
+ if (!n) return -1;
+ int k = (int)(frand() * n);
+ return cand[k < n ? k : n - 1];
+}
+
+static void champion(void) {
+ if (S->champ >= 0) {
+ Champ *c = &S->ch[S->champ];
+ Item it;
+ if (!c->n || !item_at(S->mslots, c->off, MAT_ID, &it, 0) || !in_trigger(c->n, it.m, it.s->tz0, it.s->tz1)) return;
+ S->a7 = true;
+ int pick = champ_pick(true);
+ c->active = 0;
+ c->out = 1;
+ c->out_t = (uint16_t)S->ticks;
+ node_goto(c->n, "out", 0, false);
+ node_update_one(c->n);
+ S->champ = -1;
+ if (pick >= 0) {
+ S->ch[pick].alpha = 1;
+ S->ch[pick].active = 1;
+ S->champ = (int8_t)pick;
+ champ_node_state(pick);
+ }
+ } else if (S->nch) {
+ S->champ = (int8_t)champ_pick(false);
+ for (int i = 0; i < S->nch; i++) {
+ S->ch[i].alpha = S->ch[i].active = i == S->champ;
+ champ_node_state(i);
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- camera (Cq, Dq): the map follows the skater */
+static void camera(void) {
+ NodeId map = S->map;
+ Mat l = node_local(map);
+ float cx, cy;
+ if (!mat_inv_apply(l, 480, 270, &cx, &cy)) return;
+ float ox = S->px - cx, oy = S->py - cy;
+ float gx = l.a * ox + l.c * oy, gy = l.b * ox + l.d * oy - .6f * S->z * 3;
+ if (fabsf(gx) < .1f) gx = 0;
+ if (fabsf(gy) < .1f) gy = 0;
+ S->qx = nodes[map].x - gx;
+ S->qy = nodes[map].y - gy + S->z / 2; /* minus the target's offset (0, -z / 2) */
+ uint16_t T = nodes[map].T;
+ float ease = comp_float(T, C_camera, F_ease, .6f), speed = comp_float(T, C_camera, F_speed, 60);
+ float dx = S->qx - nodes[map].x, dy = S->qy - nodes[map].y, d = vlen(dx, dy);
+ if (d > 0) {
+ float step = fminf(ease * d, speed) / d;
+ nodes[map].x += dx * step;
+ nodes[map].y += dy * step;
+ }
+}
+
+static Mat map_screen(void) {
+ Mat m = mat_mul((Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, 0}, node_local(S->map));
+ m.tx = floorf(m.tx + .5f);
+ m.ty = floorf(m.ty + .5f);
+ return m;
+}
+
+static Rect view_rect(Mat m) {
+ float x0, y0, x1, y1;
+ mat_inv_apply(m, 0, 0, &x0, &y0);
+ mat_inv_apply(m, VIEW_W, VIEW_H, &x1, &y1);
+ return (Rect){fminf(x0, x1), fminf(y0, y1), fabsf(x1 - x0), fabsf(y1 - y0)};
+}
+
+/* ---------------------------------------------------------------- the end ($t, Yo) */
+static void timer(void) {
+ if (S->over && --S->end_t <= 0 && !S->done) {
+ S->done = true;
+ menus_game_over((float)S->hf);
+ return;
+ }
+ if (S->cn > 0) S->cn--;
+ if (!S->over && S->cn == 0) {
+ time_text(S->time_buf, sizeof S->time_buf, 0);
+ toast(msg("TIMES_UP"));
+ SOUND(whistle);
+ S->over = true;
+ S->end_t = END_DELAY;
+ }
+}
+
+static void on_go(void) {
+ for (int i = 0; i < S->nsym; i++)
+ if (S->sym[i].proto) zsprites(S->sym[i].proto, S->sym[i].proto, S->sym[i].z, 0);
+ for (int i = 0; i < S->nch; i++)
+ if (S->ch[i].n) {
+ Item it;
+ if (item_at(S->mslots, S->ch[i].off, MAT_ID, &it, 0)) zsprites(S->ch[i].n, S->ch[i].n, it.s->z, 0);
+ }
+}
+
+static void tick(void) {
+ S->ticks++;
+ int d = mh(in.jx, in.jy);
+ if (d != S->isc_dir) S->isc = 0;
+ if (S->isc < 60000) S->isc++;
+ S->isc_dir = (int8_t)d;
+ sys_back_pauses();
+ if (!S->tut_done) { S->tut_done = true; sys_tutorial_once(); }
+ bool was = S->go;
+ S->go = sys_countdown(&S->cd);
+ if (S->go && !was) on_go();
+ champs_sync(view_rect(map_screen()));
+ triggers();
+ if (!S->over) champion();
+ physics();
+ if (S->go) skater();
+ player_place();
+ if (!S->over) hud_update();
+ tweens();
+ camera();
+ if (S->go) heights();
+ if (S->go) timer();
+ /* texts in another colour than their own are drawn by draw_over */
+ if (S->time) nodes[S->time].flags = (uint8_t)(S->time_red ? nodes[S->time].flags & ~NF_VISIBLE : nodes[S->time].flags | NF_VISIBLE);
+ if (S->tname) nodes[S->tname].flags = (uint8_t)(S->trick_red ? nodes[S->tname].flags & ~NF_VISIBLE : nodes[S->tname].flags | NF_VISIBLE);
+ if (S->tscore) nodes[S->tscore].flags = (uint8_t)(S->trick_red ? nodes[S->tscore].flags & ~NF_VISIBLE : nodes[S->tscore].flags | NF_VISIBLE);
+}
+
+/* ---------------------------------------------------------------- drawing: the ground, then the children in view by Qp */
+typedef struct { Rect view; Mat parent; } DrawCtx;
+
+static void ground_item(uint16_t off, void *ctx) {
+ DrawCtx *dc = ctx;
+ Item it;
+ if (!item_at(S->bslots, off, S->bgm, &it, 0) || (it.s->fl & SF_NODRAW) || !rect_intersects(it.box, dc->view)) return;
+ draw_item(&it, dc->parent);
+}
+
+static float item_key(const Item *it) {
+ const Sym *s = it->s;
+ if (s->fl & SF_DORD) return s->dord;
+ if (s->fl & SF_KEYB) {
+ Rect b = item_bounds(it);
+ return b.y + s->h + s->z;
+ }
+ return it->m.ty;
+}
+
+static void vis_add(float key, uint16_t off, uint16_t what) {
+ if (S->nvis >= VIS_MAX) return;
+ int i = S->nvis++;
+ while (i > 0 && (S->vis[i - 1].key > key || (S->vis[i - 1].key == key && S->vis[i - 1].off > off))) {
+ S->vis[i] = S->vis[i - 1];
+ i--;
+ }
+ S->vis[i] = (Vis){key, off, what};
+}
+
+static void object_item(uint16_t off, void *ctx) {
+ DrawCtx *dc = ctx;
+ Item it;
+ if (!item_at(S->mslots, off, MAT_ID, &it, 8) || !rect_intersects(it.box, dc->view)) return;
+ if (it.s->fl & SF_CHAMP) {
+ for (int i = 0; i < S->nch; i++)
+ if (S->ch[i].off == off) vis_add(it.m.ty, off, (uint16_t)(2 + i));
+ return;
+ }
+ if (it.s->fl & SF_NODRAW) return;
+ vis_add(item_key(&it), off, 0);
+}
+
+static void draw_under(void) {
+ S->stamp++;
+ Mat m = map_screen();
+ S->mapm = m;
+ Rect view = view_rect(m);
+ DrawCtx dc = {view, m};
+ /* the ground: park 1's big tiles are a 48 px tile repeated (drawn so, they fit the cache) */
+ if (S->nkk) {
+ for (int i = 0; i < S->nkk; i++) {
+ float ox = S->kk[i][0], oy = S->kk[i][1];
+ if (ox > view.x + view.w || oy > view.y + view.h || ox + 288 < view.x || oy + 288 < view.y) continue;
+ for (int ty = 0; ty < 6; ty++)
+ for (int tx = 0; tx < 6; tx++) {
+ float x = ox + 48 * tx, y = oy + 48 * ty;
+ if (x > view.x + view.w || y > view.y + view.h || x + 48 < view.x || y + 48 < view.y) continue;
+ gfx_sprite(S->kk_sprite, (Mat){1, 0, 0, 1, m.tx + x, m.ty + y}, 255);
+ }
+ }
+ }
+ if (S->bslots) {
+ DrawCtx g = {view, mat_mul(m, S->bgm)};
+ index_query(&S->bi, view.y, view.y + view.h, ground_item, &g);
+ }
+ /* everything else, in draw order */
+ S->nvis = 0;
+ index_query(&S->mi, view.y - 8, view.y + view.h + 8, object_item, &dc);
+ if (S->player) {
+ vis_add(S->py + S->bcy - S->bhy + 20 + S->kt, S->player_off, 1);
+ }
+ for (int i = 0; i < S->nvis; i++) {
+ const Vis *v = &S->vis[i];
+ if (v->what == 1) node_draw(S->player, m);
+ else if (v->what >= 2) {
+ int c = v->what - 2;
+ if (c < S->nch && S->ch[c].n) node_draw(S->ch[c].n, m);
+ } else {
+ Item it;
+ if (item_at(S->mslots, v->off, MAT_ID, &it, 0)) draw_item(&it, m);
+ }
+ }
+}
+
+/* a HUD text in a colour of the code's (the time's red, a fall's red) */
+static void text_in(NodeId n, uint16_t color) {
+ if (!n || nodes[n].kind != NK_TEXT || nodes[n].ref == NONE16 || !nodes[n].alpha) return;
+ Mat m = mat_mul((Mat){1.0f / 3, 0, 0, 1.0f / 3, 0, 0}, node_global(n));
+ const uint8_t *t = payload(nodes[n].ref);
+ float scale = sqrtf(m.a * m.a + m.b * m.b), px = t[2] * scale;
+ int k = px >= 26 ? 3 : px >= 16 ? 2 : 1;
+ int lw = (int)(rds16(t + 8) * 0.25f * scale), lh = (int)(rds16(t + 10) * 0.25f * scale);
+ if (lh > 0 && lh < FONT_LINE * k) lh = FONT_LINE * k;
+ m.ty += t[7] == 1 ? -5 * k : t[7] >= 2 ? -9 * k : 0;
+ gfx_text_k(node_text(n), m, color, t[6], (int16_t)lw, (int16_t)lh, nodes[n].alpha, k);
+}
+
+static void draw_over(void) {
+ if (S->time_red) text_in(S->time, rgb565(0xff, 0x30, 0x30));
+ if (S->trick_red) {
+ text_in(S->tscore, rgb565(0xff, 0x11, 0x11));
+ text_in(S->tname, rgb565(0xff, 0x11, 0x11));
+ }
+}
+
+/* ---------------------------------------------------------------- start */
+static NodeId hud_text(const char *name, const char *s) {
+ NodeId n = node_child(S->hud, name);
+ if (n && s) node_set_text(n, s);
+ return n;
+}
+
static void start(void) {
- const uint8_t *al = palalpha(SHEET_SKATE); const uint16_t *pal = pal565(SHEET_SKATE);
- for (int i = 0; i < 24; i++) printf("%d: %04x a%u\n", i, pal[i], al[i]);
+ S = scene_state(sizeof(State));
+ node_draw_hook_id = 0;
+ gfx_clear_color(0);
+ S->champ = -1;
+ S->isc_dir = -1;
+ S->cn = TIME_START;
+ S->tb = true;
+ S->dir = DIR_S;
+ S->gravity = -300; /* au: the cannon world of this scene */
+ S->tr_alpha = 0;
+ S->tr_t = 255;
+ sys_countdown_start(&S->cd);
+ /* the root clip ycb: one frame per park, each with its map and the HUD */
+ Clip rc;
+ clip_frame0(S_skate_ycb, &rc);
+ int frame = game.variant[0] ? clip_label(&rc, game.variant) : 0;
+ if (frame < 0) frame = 0;
+ Key mk = {0}, hk = {0};
+ bool has_map = false, has_hud = false;
+ const uint8_t *p = rc.slots;
+ for (unsigned s = 0; s < rc.nslots; s++) {
+ Key k;
+ const uint8_t *nx;
+ bool on = slot_at(p, (unsigned)frame, &k, &nx);
+ p = nx;
+ if (!on || k.kind != CK_SYM) continue;
+ if (k.ref == S_skate_lma) { hk = k; has_hud = true; }
+ else {
+ Clip c;
+ clip_frame0(k.ref, &c);
+ if (comp_has(c.T, C_map)) { mk = k; has_map = true; }
+ }
+ }
+ if (!has_map) return;
+ S->map_sym = mk.ref;
+ S->map = node_new_sym_lazy(mk.ref);
+ if (!S->map) return;
+ node_add(game.root, S->map);
+ place(S->map, &mk);
+ nodes[S->map].flags &= (uint8_t)~NF_VISIBLE; /* drawn by draw_under */
+ Clip mc;
+ clip_frame0(mk.ref, &mc);
+ S->mslots = mc.slots;
+ /* the map's children: the skater, the ground, champions; then the index */
+ p = mc.slots;
+ for (unsigned s = 0; s < mc.nslots; s++) {
+ uint16_t off = (uint16_t)(p - mc.slots);
+ Key k;
+ const uint8_t *nx;
+ bool on = slot_at(p, 0, &k, &nx);
+ p = nx;
+ if (!on || k.kind != CK_SYM) continue;
+ Sym *sy = sym_get(k.ref);
+ if (!sy) continue;
+ Mat km = key_mat(&k);
+ if ((sy->fl & SF_PLAYER) && !S->player) {
+ S->player_off = off;
+ S->player = node_new_sym(k.ref);
+ if (!S->player) continue;
+ node_add(S->map, S->player);
+ place(S->player, &k);
+ first_stops(S->player, 0);
+ S->px = km.tx;
+ S->py = km.ty;
+ S->z = sy->z;
+ S->bcx = F8(sy->b[0] + sy->b[2]) / 2;
+ S->bcy = F8(sy->b[1] + sy->b[3]) / 2;
+ S->bhx = F8(sy->b[2] - sy->b[0]) / 2;
+ S->bhy = F8(sy->b[3] - sy->b[1]) / 2;
+ } else if (sy->fl & SF_GROUND) {
+ /* Kk: its one bitmap, 288 px of the 48 px tile eGa */
+ Clip kc;
+ clip_frame0(k.ref, &kc);
+ Key bk;
+ if (S->nkk < KK_MAX && kc.nslots && slot_at(kc.slots, 0, &bk, NULL)) {
+ S->kk[S->nkk][0] = (int16_t)floorf(km.tx + bk.x + .5f);
+ S->kk[S->nkk][1] = (int16_t)floorf(km.ty + bk.y + .5f);
+ S->nkk++;
+ }
+ } else if ((sy->fl & SF_BG) && !S->bslots) {
+ Clip bc;
+ clip_frame0(k.ref, &bc);
+ S->bg_sym = k.ref;
+ S->bslots = bc.slots;
+ S->bgm = km;
+ index_build(&S->bi, bc.slots, bc.nslots, km, 48, true);
+ } else if ((sy->fl & SF_CHAMP) && S->nch < CH_MAX) {
+ S->ch[S->nch++] = (Champ){off, 0, 0, 0, 0, 0};
+ }
+ }
+ if (S->nkk) {
+ SymInfo si;
+ sym_info(S_skate_eGa, &si);
+ S->kk_sprite = (uint16_t)si.v;
+ }
+ index_build(&S->mi, mc.slots, mc.nslots, MAT_ID, 64, false);
+#ifdef HOST
+ if (getenv("SKATE_DEBUG"))
+ fprintf(stderr, "skate: %u slots, %u syms, %u entries, bands %u+%u, nodes %u\n", mc.nslots, S->nsym, S->nent, S->mi.nb, S->bi.nb, node_count());
+#endif
+ if (S->player) ent_register_tree(S->player);
+ /* the HUD */
+ if (has_hud) {
+ S->hud = node_new_sym(S_skate_lma);
+ if (S->hud) {
+ node_add(game.root, S->hud);
+ place(S->hud, &hk);
+ first_stops(S->hud, 0);
+ S->score = hud_text("score", S->score_buf);
+ S->score_sh = hud_text("scoreShadow", S->score_buf);
+ S->time = hud_text("time", S->time_buf);
+ S->time_sh = hud_text("timeShadow", S->time_buf);
+ S->tname = hud_text("trickName", S->tname_buf);
+ S->tscore = hud_text("trickScore", S->tscore_buf);
+ S->spark_l = node_child(S->hud, "sparkleLeft");
+ S->spark_r = node_child(S->hud, "sparkleRight");
+ S->prompt = node_child(S->hud, "prompt");
+ snprintf(S->score_buf, sizeof S->score_buf, "0");
+ time_text(S->time_buf, sizeof S->time_buf, S->cn);
+ }
+ }
+ /* the camera starts where the map is placed and eases to the skater (no Eq here) */
}
-static void tick(void) {}
-const SceneDef scene_skate = {"skate", start, tick, NULL, NULL, NULL, NULL};
+
+const SceneDef scene_skate = {"skate", start, tick, NULL, draw_under, draw_over, NULL};
diff --git a/games/championisland/src/spr.c b/games/championisland/src/spr.c
index 28082473..ec3e4709 100644
--- a/games/championisland/src/spr.c
+++ b/games/championisland/src/spr.c
@@ -155,16 +155,21 @@ static uint8_t *alloc(uint32_t n, bool force) {
}
/* Encodes rows of palette indices as runs of visible pixels:
- * u16 w, u16 h, u16 row offsets[h], then per row: nruns, (skip, len, px...)... */
+ * u16 w, u16 h, u16 row offsets[h] (from the start), then per row: u16 nruns,
+ * and per run: skip (transparent pixels before it), then either a fill
+ * (0x80 | (length - 1), one colour: 1 to 128 pixels of one colour) or
+ * literal pixels (length 0..127, then the colours). pack.py's rle_size()
+ * computes the same sizes. */
typedef struct { uint8_t *base, *p, *end; uint16_t row; bool ok; } Rle;
-
static void rle_row(Rle *r, const uint8_t *px, int w, const uint8_t *alpha) {
if (!r->ok) return;
uint32_t off = (uint32_t)(r->p - r->base);
r->base[4 + 2 * r->row] = (uint8_t)off;
r->base[5 + 2 * r->row] = (uint8_t)(off >> 8);
r->row++;
- uint8_t *count = r->p++;
+ if (r->p + 2 > r->end) { r->ok = false; return; }
+ uint8_t *count = r->p;
+ r->p += 2;
int n = 0, x = 0;
while (x < w) {
int skip = 0;
@@ -174,22 +179,34 @@ static void rle_row(Rle *r, const uint8_t *px, int w, const uint8_t *alpha) {
if (r->p + 2 > r->end) { r->ok = false; return; }
*r->p++ = 255; *r->p++ = 0; skip -= 255; n++;
}
- int len = 0;
- while (x + len < w && alpha[px[x + len]] && len < 255) len++;
- if (r->p + 2 + len > r->end) { r->ok = false; return; }
- *r->p++ = (uint8_t)skip;
- *r->p++ = (uint8_t)len;
- memcpy(r->p, px + x, (size_t)len);
- r->p += len;
- x += len;
+ int run = 1;
+ while (x + run < w && run < 128 && px[x + run] == px[x]) run++;
+ if (run >= 3) {
+ if (r->p + 3 > r->end) { r->ok = false; return; }
+ *r->p++ = (uint8_t)skip;
+ *r->p++ = (uint8_t)(0x80 | (run - 1));
+ *r->p++ = px[x];
+ x += run;
+ } else {
+ int len = 0;
+ while (x + len < w && len < 127 && alpha[px[x + len]] &&
+ !(x + len + 2 < w && px[x + len] == px[x + len + 1] && px[x + len] == px[x + len + 2]))
+ len++;
+ if (!len) len = 1;
+ if (r->p + 2 + len > r->end) { r->ok = false; return; }
+ *r->p++ = (uint8_t)skip;
+ *r->p++ = (uint8_t)len;
+ memcpy(r->p, px + x, (size_t)len);
+ r->p += len;
+ x += len;
+ }
n++;
}
- *count = (uint8_t)n;
+ count[0] = (uint8_t)n;
+ count[1] = (uint8_t)(n >> 8);
}
-
/* Worst-case size of a sprite's runs. */
-static uint32_t rle_bound(int w, int h) { return 4 + 2u * h + (uint32_t)h * (1 + (uint32_t)w + 2 * ((uint32_t)w / 2 + 2)); }
-
+static uint32_t rle_bound(int w, int h) { return 4 + 2u * h + (uint32_t)h * (2 + 3 * ((uint32_t)w / 2 + 2) + (uint32_t)w); }
static uint8_t rowbuf[SPRITE_W_MAX];
/* Adds sprite sp from the decoder, whose next bytes are its pixels. */
diff --git a/games/championisland/src/world.c b/games/championisland/src/world.c
index f8c46114..bca85519 100644
--- a/games/championisland/src/world.c
+++ b/games/championisland/src/world.c
@@ -11,7 +11,9 @@
* The systems are the doodle's overworld scene ($s) and interior scene (Ir). */
#include <math.h>
#include <stdio.h>
+#ifdef HOST
#include <stdlib.h>
+#endif
#include "ent.h"
#include "phys.h"
#include "spr.h"
@@ -230,8 +232,14 @@ static void draw_map(NodeId map, Mat m, uint8_t alpha) {
/* ---------------------------------------------------------------- live children */
static void on_trigger(NodeId t, NodeId other, bool entered);
+static void translate_tree(NodeId n) {
+ ent_translate(n);
+ for (NodeId c = nodes[n].first; c; c = nodes[c].next) translate_tree(c);
+}
+
static void streamed_in(NodeId c) {
ent_register_tree(c);
+ translate_tree(c);
uint16_t T = nodes[c].T;
if (T == NONE16) return;
/* sr: places are markers for the designers */
@@ -366,13 +374,16 @@ static void water_make(int look) {
int h = rd16(r + 2);
for (int v = 0; v < h && v < WATER; v++) {
const uint8_t *p = r + rd16(r + 4 + 2 * v);
- int n = *p++, u = 0;
+ int n = rd16(p), u = 0;
+ p += 2;
for (int j = 0; j < n; j++) {
u += *p++;
- int len = *p++;
- for (int i = 0; i < len; i++, u++)
- if (u < WATER && al[p[i]] >= 128) W->water[v * WATER + u] = p[i];
- p += len;
+ int code = *p++, len = code & 0x80 ? (code & 0x7F) + 1 : code;
+ for (int i = 0; i < len; i++, u++) {
+ uint8_t c = code & 0x80 ? p[0] : p[i];
+ if (u < WATER && al[c] >= 128) W->water[v * WATER + u] = c;
+ }
+ p += code & 0x80 ? 1 : len;
}
}
}
@@ -417,6 +428,11 @@ static void sys_overworld_player(void) {
}
}
+static const uint8_t COND_F[10] = {F_condition1, F_condition2, F_condition3, F_condition4, F_condition5,
+ F_condition6, F_condition7, F_condition8, F_condition9, F_condition10};
+static const uint8_t FRAME_F[5] = {F_frame1, F_frame2, F_frame3, F_frame4, F_frame5};
+static const uint8_t NODE_F[10] = {F_node1, F_node2, F_node3, F_node4, F_node5, F_node6, F_node7, F_node8, F_node9, F_node10};
+
/* Er: storageSprite shows the frame of its first true condition (a quarter of them per tick) */
static void sys_storage_sprites(void) {
for (int i = 0; i < ent_count(); i++) {
@@ -424,10 +440,10 @@ static void sys_storage_sprites(void) {
if (!n || !comp_has(nodes[n].T, C_storageSprite)) continue;
if (W->tick && n % 4 != W->tick % 4) continue;
uint16_t T = nodes[n].T;
- for (int k = 0; k < 10; k++) {
- uint16_t fr = comp_str(T, C_storageSprite, F_frame1 + 2 * k);
+ for (int k = 0; k < 5; k++) {
+ uint16_t fr = comp_str(T, C_storageSprite, FRAME_F[k]);
if (fr == NONE16 || !str(fr)[0]) continue;
- uint16_t cond = comp_str(T, C_storageSprite, F_condition1 + 2 * k);
+ uint16_t cond = comp_str(T, C_storageSprite, COND_F[k]);
if (cond == NONE16 || !str(cond)[0] || cond_eval(cond)) {
ent_label(n, str(fr), false);
break;
@@ -451,12 +467,30 @@ static bool triggered(NodeId n) {
return e && e->ntrig > 0;
}
+/* a whole string as a decimal number (newlib's strtof would pull in abort) */
+static bool parse_num(const char *s, float *out) {
+ bool neg = *s == '-';
+ if (neg || *s == '+') s++;
+ if (!*s) return false;
+ float v = 0, scale = 1;
+ bool dot = false, digits = false;
+ for (; *s; s++) {
+ if (*s == '.' && !dot) { dot = true; continue; }
+ if (*s < '0' || *s > '9') return false;
+ digits = true;
+ if (dot) { scale /= 10; v += (float)(*s - '0') * scale; }
+ else v = v * 10 + (float)(*s - '0');
+ }
+ if (!digits) return false;
+ *out = neg ? -v : v;
+ return true;
+}
+
/* a storage value as kitsune's kk() reads it: number, true, false, null, else text */
static void store_parsed(const char *key, const char *v) {
if (key[0] == '$') key++;
- char *end;
- float f = strtof(v, &end);
- if (v[0] && !*end) store_set_num(key, f);
+ float f;
+ if (parse_num(v, &f)) store_set_num(key, f);
else if (!strcmp(v, "true") || !strcmp(v, "True")) store_set_bool(key, true);
else if (!strcmp(v, "false") || !strcmp(v, "False")) store_set_bool(key, false);
else if (!strcmp(v, "null")) store_set(key, (Value){SV_NULL, false, 0, NONE16});
@@ -524,9 +558,9 @@ static void sys_npcs(void) {
uint16_t name = comp_str(T, C_npc, F_name), node = NONE16;
if (comp_has(T, C_storageNpc))
for (int k = 0; k < 10 && node == NONE16; k++) {
- uint16_t nd = comp_str(T, C_storageNpc, k == 0 ? F_node1 : F_node2 + 2 * (k - 1));
+ uint16_t nd = comp_str(T, C_storageNpc, NODE_F[k]);
if (nd == NONE16 || !str(nd)[0]) continue;
- uint16_t cond = comp_str(T, C_storageNpc, k == 0 ? F_condition1 : F_condition2 + 2 * (k - 1));
+ uint16_t cond = comp_str(T, C_storageNpc, COND_F[k]);
if (cond == NONE16 || !str(cond)[0] || cond_eval(cond)) node = nd;
}
if (node == NONE16) node = comp_str(T, C_npc, F_node);
@@ -576,6 +610,16 @@ static void sys_save_place(void) {
}
/* ---------------------------------------------------------------- the scene */
+static bool player_slot(unsigned slot, const SlotInfo *si, void *ctx) {
+ Clip c;
+ if (!clip_get(si->sym, &c) || c.T == NONE16 || !comp_has(c.T, C_overworldPlayer)) return true;
+ float *p = ctx;
+ p[0] = si->x;
+ p[1] = si->y;
+ (void)slot;
+ return false;
+}
+
static NodeId child_of_sym(NodeId n, uint16_t sym) {
for (NodeId c = nodes[n].first; c; c = nodes[c].next)
if (nodes[c].sym == sym) return c;
@@ -612,7 +656,9 @@ static void start_overworld(void) {
for (int i = 0; i < wd.nregions; i++)
if (rd16(wd.regions + 10 * i) == S_overworld_bT) W->region_rain = i;
/* the player (the map's child "Player") is always there */
- node_stream(W->map, -1e5f, -1e5f, 1e5f, 1e5f);
+ float ppos[2] = {0, 0};
+ clip_each_slot(S_overworld_jqa, 0, player_slot, ppos);
+ node_stream(W->map, ppos[0] - 1, ppos[1] - 1, ppos[0] + 1, ppos[1] + 1);
for (NodeId c = nodes[W->map].first; c; c = nodes[c].next)
if (nodes[c].T != NONE16 && comp_has(nodes[c].T, C_overworldPlayer)) W->player = c;
if (W->player) nodes[W->player].flags2 |= NF2_KEEP;
@@ -654,21 +700,31 @@ static void tick_overworld(void) {
sys_npcs();
sys_rain();
stream_children(false);
+#ifdef HOST
+ if (getenv("CI_DEBUG") && W->player && W->tick % 10 == 0) {
+ float px, py;
+ ent_pos(W->player, &px, &py);
+ Ent *e = ent_get(W->player);
+ Rect r;
+ bool hb = ent_bounds(W->player, &r);
+ fprintf(stderr, "t%u in %.1f,%.1f p %.1f,%.1f v %.2f,%.2f body %d bounds %d (%.0f %.0f %.0f %.0f) solids %d label %s\n", W->tick, in.jx, in.jy,
+ px, py, e ? e->vx : 0, e ? e->vy : 0, e ? e->body : -9, hb, r.x, r.y, r.w, r.h, W->nsolid, node_label(W->player));
+ }
+#endif
W->tick++;
}
static void draw_under_overworld(void) {
if (!W || !W->map) return;
- float vx, vy;
- view_origin(&vx, &vy);
- bg_camera((int)floorf(vx + .5f), (int)floorf(vy + .5f));
/* the sea's look changes every 16 frames */
int look = (int)(game.ticks / 16) % 2;
if (look != W->water_look) {
water_make(look);
bg_water(W->water, WATER, WATER);
- bg_redraw_water();
}
+ float vx, vy;
+ view_origin(&vx, &vy);
+ bg_camera((int)floorf(vx + .5f), (int)floorf(vy + .5f));
}
const SceneDef scene_overworld = {"overworld", start_overworld, tick_overworld, end_overworld, draw_under_overworld, NULL, NULL};
diff --git a/games/championisland/tools/pack.py b/games/championisland/tools/pack.py
index 0e16fd78..fa443120 100644
--- a/games/championisland/tools/pack.py
+++ b/games/championisland/tools/pack.py
@@ -203,6 +203,117 @@ for (lib, k) in SYMS:
SPR[SPR_ID[key]]['libs'].add(lib)
sym_sprite[(lib, k)] = SPR_ID[key]
+# ------------------------------------------------------------------ shapes & texts
+def parse_color(style):
+ if not style or style in ('null', 'undefined'):
+ return None
+ style = style.strip()
+ m = re.match(r'#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$', style)
+ if m:
+ v = int(m.group(1), 16)
+ a = int(m.group(2), 16) if m.group(2) else 255
+ return (v >> 16, v >> 8 & 255, v & 255, a)
+ m = re.match(r'#([0-9a-fA-F]{3})$', style)
+ if m:
+ r, g, b = (int(ch * 2, 16) for ch in m.group(1))
+ return (r, g, b, 255)
+ m = re.match(r'rgba?\(([^)]*)\)', style)
+ if m:
+ p = [float(v) for v in m.group(1).split(',')]
+ return (int(p[0]), int(p[1]), int(p[2]), int(round((p[3] if len(p) > 3 else 1) * 255)))
+ return None
+
+
+def flatten_path(ins):
+ """Graphics instructions -> [(fill rgba or None, [polygon, ...])]. CreateJS
+ lists a path's commands first, then its fill (or stroke)."""
+ shapes, polys, poly = [], [], []
+ cx = cy = 0.0
+
+ def close():
+ nonlocal poly
+ if len(poly) >= 2:
+ polys.append(poly)
+ poly = []
+
+ def emit(fill):
+ nonlocal polys
+ close()
+ if polys:
+ shapes.append((fill, polys))
+ polys = []
+
+ for kind, d in ins:
+ if kind == 'P':
+ emit(None)
+ elif kind == 'F':
+ emit(parse_color(d.get('style')))
+ elif kind in ('S', 'SS'):
+ close()
+ elif kind == 'M':
+ close()
+ cx, cy = d['x'], d['y']
+ poly = [(cx, cy)]
+ elif kind == 'L':
+ cx, cy = d['x'], d['y']
+ poly.append((cx, cy))
+ elif kind == 'Q':
+ x0, y0 = cx, cy
+ for i in range(1, 9):
+ t = i / 8
+ poly.append(((1 - t) ** 2 * x0 + 2 * (1 - t) * t * d['cpx'] + t * t * d['x'],
+ (1 - t) ** 2 * y0 + 2 * (1 - t) * t * d['cpy'] + t * t * d['y']))
+ cx, cy = d['x'], d['y']
+ elif kind == 'B':
+ x0, y0 = cx, cy
+ for i in range(1, 11):
+ t = i / 10
+ mt = 1 - t
+ poly.append((mt ** 3 * x0 + 3 * mt * mt * t * d['cp1x'] + 3 * mt * t * t * d['cp2x'] + t ** 3 * d['x'],
+ mt ** 3 * y0 + 3 * mt * mt * t * d['cp1y'] + 3 * mt * t * t * d['cp2y'] + t ** 3 * d['y']))
+ cx, cy = d['x'], d['y']
+ elif kind == 'Z':
+ close()
+ elif kind in ('R', 'RR'):
+ close()
+ x, y, w, h = d['x'], d['y'], d['w'], d['h']
+ polys.append([(x, y), (x + w, y), (x + w, y + h), (x, y + h)])
+ elif kind == 'C':
+ close()
+ polys.append([(d['x'] + d['radius'] * math.cos(i * math.pi / 8), d['y'] + d['radius'] * math.sin(i * math.pi / 8)) for i in range(16)])
+ elif kind == 'E':
+ close()
+ x, y, w, h = d['x'], d['y'], d['w'], d['h']
+ polys.append([(x + w / 2 + w / 2 * math.cos(i * math.pi / 8), y + h / 2 + h / 2 * math.sin(i * math.pi / 8)) for i in range(16)])
+ emit(None)
+ return shapes
+
+
+def enc_shape(ins):
+ out = bytearray()
+ shapes = flatten_path(ins)
+ out.append(len(shapes))
+ for fill, polys in shapes:
+ r, g, b, a = fill if fill else (0, 0, 0, 0)
+ out += struct.pack('<BBBBB', r, g, b, a, len(polys))
+ for p in polys:
+ out += struct.pack('<H', len(p))
+ for (x, y) in p:
+ out += struct.pack('<hh', int(round(x * 4)), int(round(y * 4)))
+ return bytes(out)
+
+
+def enc_text(c):
+ font = c.get('font') or ''
+ m = re.search(r'(\d+(?:\.\d+)?)px', font)
+ size = int(round(float(m.group(1)))) if m else 10
+ col = parse_color(c.get('color')) or (255, 255, 255, 255)
+ align = {'left': 0, 'start': 0, 'center': 1, 'right': 2, 'end': 2}.get(c.get('align') or 'left', 0)
+ base = {'top': 0, 'hanging': 0, 'middle': 1, 'alphabetic': 2, 'ideographic': 2, 'bottom': 3}.get(c.get('base') or 'top', 0)
+ return struct.pack('<HBBBBBBhh', sid(c.get('text') or ''), size, col[0], col[1], col[2], align, base,
+ int(round((c.get('lw') or 0) * 4)), int(round((c.get('lh') or 0) * 4)))
+
+
# ------------------------------------------------------------------ worlds
# The island map (the overworld's "jqa") is huge: 24 regions holding some 9000
# display objects. On the calculator its scenery (ground, trees, houses,
@@ -271,13 +382,40 @@ def flatten_draws(lib, k, M, alpha, frame, out, depth=0):
flatten_draws(lib, c['sym'], mat_mul(M, matrix(tr)), a, f, out, depth + 1)
-def sym_bounds(lib, k):
+def sym_bounds(lib, k, depth=0):
+ """CreateJS getBounds at frame 0: a bitmap's size, else the union of the visible children's bounds."""
s = LIB[lib]['syms'].get(k, {})
- if s.get('t') == 'b' and (lib, k) in sym_sprite:
- _, _, _, w, h = SPR[sym_sprite[(lib, k)]]['key']
- return (0, 0, w, h)
- nb = s.get('nb')
- return tuple(nb) if nb else None
+ if s.get('t') == 'b':
+ if (lib, k) in sym_sprite:
+ _, _, _, w, h = SPR[sym_sprite[(lib, k)]]['key']
+ return (0, 0, w, h)
+ return None
+ if s.get('t') == 's':
+ pts = [p for _, polys in flatten_path(s.get('g') or []) for poly in polys for p in poly]
+ if not pts:
+ return None
+ xs, ys = [p[0] for p in pts], [p[1] for p in pts]
+ return (min(xs), min(ys), max(xs) - min(xs), max(ys) - min(ys))
+ if s.get('t') != 'm' or depth > 12 or not s.get('frames'):
+ return None
+ box = None
+ for c in s['frames'][0]:
+ tr = c.get('tr', {})
+ if tr.get('v', 1) == 0:
+ continue
+ if c['t'] == 's':
+ pts = [p for _, polys in flatten_path(c.get('g') or []) for poly in polys for p in poly]
+ r = (min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts) - min(p[0] for p in pts),
+ max(p[1] for p in pts) - min(p[1] for p in pts)) if pts else None
+ elif c.get('sym'):
+ r = sym_bounds(lib, c['sym'], depth + 1)
+ else:
+ r = None
+ if not r:
+ continue
+ b = aabb(matrix(tr), r)
+ box = b if box is None else (min(box[0], b[0]), min(box[1], b[1]), max(box[2], b[2]), max(box[3], b[3]))
+ return (box[0], box[1], box[2] - box[0], box[3] - box[1]) if box else None
def aabb(M, r):
@@ -553,117 +691,6 @@ def enc_T(T):
return bytes(out)
-# ------------------------------------------------------------------ shapes & texts
-def parse_color(style):
- if not style or style in ('null', 'undefined'):
- return None
- style = style.strip()
- m = re.match(r'#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$', style)
- if m:
- v = int(m.group(1), 16)
- a = int(m.group(2), 16) if m.group(2) else 255
- return (v >> 16, v >> 8 & 255, v & 255, a)
- m = re.match(r'#([0-9a-fA-F]{3})$', style)
- if m:
- r, g, b = (int(ch * 2, 16) for ch in m.group(1))
- return (r, g, b, 255)
- m = re.match(r'rgba?\(([^)]*)\)', style)
- if m:
- p = [float(v) for v in m.group(1).split(',')]
- return (int(p[0]), int(p[1]), int(p[2]), int(round((p[3] if len(p) > 3 else 1) * 255)))
- return None
-
-
-def flatten_path(ins):
- """Graphics instructions -> [(fill rgba or None, [polygon, ...])]. CreateJS
- lists a path's commands first, then its fill (or stroke)."""
- shapes, polys, poly = [], [], []
- cx = cy = 0.0
-
- def close():
- nonlocal poly
- if len(poly) >= 2:
- polys.append(poly)
- poly = []
-
- def emit(fill):
- nonlocal polys
- close()
- if polys:
- shapes.append((fill, polys))
- polys = []
-
- for kind, d in ins:
- if kind == 'P':
- emit(None)
- elif kind == 'F':
- emit(parse_color(d.get('style')))
- elif kind in ('S', 'SS'):
- close()
- elif kind == 'M':
- close()
- cx, cy = d['x'], d['y']
- poly = [(cx, cy)]
- elif kind == 'L':
- cx, cy = d['x'], d['y']
- poly.append((cx, cy))
- elif kind == 'Q':
- x0, y0 = cx, cy
- for i in range(1, 9):
- t = i / 8
- poly.append(((1 - t) ** 2 * x0 + 2 * (1 - t) * t * d['cpx'] + t * t * d['x'],
- (1 - t) ** 2 * y0 + 2 * (1 - t) * t * d['cpy'] + t * t * d['y']))
- cx, cy = d['x'], d['y']
- elif kind == 'B':
- x0, y0 = cx, cy
- for i in range(1, 11):
- t = i / 10
- mt = 1 - t
- poly.append((mt ** 3 * x0 + 3 * mt * mt * t * d['cp1x'] + 3 * mt * t * t * d['cp2x'] + t ** 3 * d['x'],
- mt ** 3 * y0 + 3 * mt * mt * t * d['cp1y'] + 3 * mt * t * t * d['cp2y'] + t ** 3 * d['y']))
- cx, cy = d['x'], d['y']
- elif kind == 'Z':
- close()
- elif kind in ('R', 'RR'):
- close()
- x, y, w, h = d['x'], d['y'], d['w'], d['h']
- polys.append([(x, y), (x + w, y), (x + w, y + h), (x, y + h)])
- elif kind == 'C':
- close()
- polys.append([(d['x'] + d['radius'] * math.cos(i * math.pi / 8), d['y'] + d['radius'] * math.sin(i * math.pi / 8)) for i in range(16)])
- elif kind == 'E':
- close()
- x, y, w, h = d['x'], d['y'], d['w'], d['h']
- polys.append([(x + w / 2 + w / 2 * math.cos(i * math.pi / 8), y + h / 2 + h / 2 * math.sin(i * math.pi / 8)) for i in range(16)])
- emit(None)
- return shapes
-
-
-def enc_shape(ins):
- out = bytearray()
- shapes = flatten_path(ins)
- out.append(len(shapes))
- for fill, polys in shapes:
- r, g, b, a = fill if fill else (0, 0, 0, 0)
- out += struct.pack('<BBBBB', r, g, b, a, len(polys))
- for p in polys:
- out += struct.pack('<H', len(p))
- for (x, y) in p:
- out += struct.pack('<hh', int(round(x * 4)), int(round(y * 4)))
- return bytes(out)
-
-
-def enc_text(c):
- font = c.get('font') or ''
- m = re.search(r'(\d+(?:\.\d+)?)px', font)
- size = int(round(float(m.group(1)))) if m else 10
- col = parse_color(c.get('color')) or (255, 255, 255, 255)
- align = {'left': 0, 'start': 0, 'center': 1, 'right': 2, 'end': 2}.get(c.get('align') or 'left', 0)
- base = {'top': 0, 'hanging': 0, 'middle': 1, 'alphabetic': 2, 'ideographic': 2, 'bottom': 3}.get(c.get('base') or 'top', 0)
- return struct.pack('<HBBBBBBhh', sid(c.get('text') or ''), size, col[0], col[1], col[2], align, base,
- int(round((c.get('lw') or 0) * 4)), int(round((c.get('lh') or 0) * 4)))
-
-
# ------------------------------------------------------------------ clips
SYM_BITMAP, SYM_CLIP, SYM_SHAPE, SYM_CONT, SYM_NONE = 1, 2, 3, 4, 0
MODES = {'independent': 0, 'single': 1, 'synched': 2}
@@ -1055,24 +1082,36 @@ for sp in sorted(banded):
band_off[sp] = blob.add(struct.pack('<H', len(recs)) + b''.join(struct.pack('<II', o, n) for o, n in recs))
def rle_size(sp):
- """Bytes of the cache's run-length form (spr.c: rle_row)."""
+ """Bytes of the cache's run-length form (spr.c: rle_row), exactly."""
sh, x, y, w, h = SPR[sp]['key']
- op = sheet_alpha[sh][sprite_pixels(sp)] > 0
+ px = sprite_pixels(sp)
+ al = sheet_alpha[sh]
n = 4 + 2 * h
- for row in op:
- n += 1
+ for row in px:
+ row = row.tolist()
+ op = [al[c] > 0 for c in row]
+ n += 2
xx = 0
while xx < w:
skip = 0
- while xx < w and not row[xx]:
+ while xx < w and not op[xx]:
xx += 1
skip += 1
if xx >= w:
break
- n += 2 * (skip // 255)
+ n += 2 * ((skip - 1) // 255) if skip > 255 else 0
+ run = 1
+ while xx + run < w and run < 128 and row[xx + run] == row[xx]:
+ run += 1
+ if run >= 3:
+ n += 3
+ xx += run
+ continue
ln = 0
- while xx + ln < w and row[xx + ln] and ln < 255:
+ while xx + ln < w and ln < 127 and op[xx + ln] and not (
+ xx + ln + 2 < w and row[xx + ln] == row[xx + ln + 1] and row[xx + ln] == row[xx + ln + 2]):
ln += 1
+ ln = max(ln, 1)
n += 2 + ln
xx += ln
return n
@@ -1157,15 +1196,18 @@ for w in WORLD:
dw, dh = (shh, sw) if fl & 4 else (sw, shh)
draws.append(struct.pack('<HhhBB', sp, x, y, fl, int(round(min(1, a) * 255))))
bx0, by0, bx1, by1 = min(bx0, x), min(by0, y), max(bx1, x + dw), max(by1, y + dh)
- if not draws:
- bx0 = by0 = bx1 = by1 = 0
coll = st['coll']
+ if coll: # invisible walls are found by their solid box
+ cx0, cy0, cx1, cy1 = (int(math.floor(coll[0])), int(math.floor(coll[1])), int(math.ceil(coll[2])), int(math.ceil(coll[3])))
+ bx0, by0, bx1, by1 = min(bx0, cx0), min(by0, cy0), max(bx1, cx1), max(by1, cy1)
+ if bx0 > bx1:
+ bx0 = by0 = bx1 = by1 = 0
rec = struct.pack('<fhhhhBB', st['key'], int(bx0), int(by0), int(bx1), int(by1), len(draws), 1 if coll else 0)
if coll:
rec += struct.pack('<hhhh', *(int(round(v)) for v in coll))
rec += b''.join(draws)
recs.append(rec)
- boxes.append((bx0, by0, bx1, by1) if draws else None)
+ boxes.append((bx0, by0, bx1, by1) if draws or coll else None)
gx0 = int(min(b[0] for b in boxes if b)) // WORLD_CELL * WORLD_CELL
gy0 = int(min(b[1] for b in boxes if b)) // WORLD_CELL * WORLD_CELL
gw = (int(max(b[2] for b in boxes if b)) - gx0) // WORLD_CELL + 1