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.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Hollow Knight: first enemies, corpses and geo
Mason Chen70b9090a3db6
diff --git a/games/hollowknight/Makefile b/games/hollowknight/Makefileindex ba715ece..51a8eee9 100644--- a/games/hollowknight/Makefile+++ b/games/hollowknight/Makefile@@ -9,7 +9,7 @@ CC = arm-none-eabi-gccNWLINK ?= npx --yes -- [email protected]STRIP ?= arm-none-eabi-strip --strip-unneededBUILD_DIR = output-GAME = src/res.c src/tex.c src/room.c src/gfx.c src/phys.c src/anim.c src/hero.c src/camera.c src/game.c src/world.c src/obj.c src/lzma/LzmaDec.c+GAME = src/res.c src/tex.c src/room.c src/gfx.c src/phys.c src/anim.c src/hero.c src/camera.c src/game.c src/world.c src/obj.c src/enemy.c src/lzma/LzmaDec.cSRC = $(GAME) src/plat_eadk.c src/main.cHEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.hdiff --git a/games/hollowknight/src/data.bin b/games/hollowknight/src/data.binindex 33df4cce..1b08b26d 100644Binary files a/games/hollowknight/src/data.bin and b/games/hollowknight/src/data.bin differdiff --git a/games/hollowknight/src/data.h b/games/hollowknight/src/data.hindex 71f32c4b..2c75ebb6 100644--- a/games/hollowknight/src/data.h+++ b/games/hollowknight/src/data.h@@ -134,3 +134,23 @@#define CLIP_KNIGHT_COLLECT_HEART_PIECE_END 77#define CLIP_KNIGHT_COLLECT_STANDTOIDLE 78#define CLIP_KNIGHT_GETUPTOIDLE 79+#define CLIP_CRAWLER_WALK 80+#define CLIP_CRAWLER_TURN 81+#define CLIP_CRAWLER_IDLE 82+#define CLIP_CRAWLER_DEATH_AIR 83+#define CLIP_CRAWLER_DEATH_LAND 84+#define CLIP_BUZZER_CHASE 85+#define CLIP_BUZZER_IDLE 86+#define CLIP_BUZZER_STARTLE 87+#define CLIP_BUZZER_DEATH_AIR 88+#define CLIP_BUZZER_DEATH_LAND 89+#define CLIP_BUZZER_FLY 90+#define CLIP_BUZZER_TURNTOFLY 91+#define CLIP_BUZZER_TURNTOIDLE 92+#define CLIP_GEO_SMALL_IDLE 93+#define CLIP_GEO_SMALL_AIR 94+#define CLIP_GEO_MED_IDLE 95+#define CLIP_GEO_MED_AIR 96+#define CLIP_GEO_LARGE_IDLE 97+#define CLIP_GEO_LARGE_AIR 98+#define SPRITE_HERO_LIGHT 405diff --git a/games/hollowknight/src/enemy.c b/games/hollowknight/src/enemy.cnew file mode 100644index 00000000..02431ff7--- /dev/null+++ b/games/hollowknight/src/enemy.c@@ -0,0 +1,585 @@+/* Enemies (tools/ents.py: OK_ENEMY): HealthManager, Recoil, SpriteFlash, DamageHero and EnemyDeathEffects, each kind's+ * FSM, the corpses they leave and the geo they drop. */+#include <math.h>+#include "game.h"++#define DT 0.02f+#define MAX_ENEMIES 16+#define MAX_GEO 24+#define TERRAIN_FRICTION 0.2f /* (the Terrain material; with another, their geometric mean) */++/* ---------------------------------------------------------------- what each kind is */+enum { EK_CRAWLER = 1, EK_BUZZER };+typedef struct {+ /* Recoil */+ float recoil_speed, recoil_time;+ bool stop_vx_up;+ /* the corpse (EnemyDeathEffects, its Corpse prefab) */+ float corpse_spawn_y, corpse_fling, corpse_gravity, corpse_ox, corpse_oy, corpse_hx, corpse_hy, corpse_bounce;+ bool breaker;+ int clip_death_air, clip_death_land;+ float gravity, friction; /* its Rigidbody2D, its collider's material with the terrain's */+} Kind;+static const Kind kinds[] = {+ [EK_CRAWLER] = {15, 0.15f, true, 0.5f, 15, 0.8f, 0.0078f, -0.3906f, 1.4219f / 2, 0.9062f / 2, 0.3f, false,+ CLIP_CRAWLER_DEATH_AIR, CLIP_CRAWLER_DEATH_LAND, 1, 0.2828f},+ [EK_BUZZER] = {15, 0.25f, false, 0, 15, 0.7f, 0.1016f, -0.2188f, 1.1406f / 2, 1.3125f / 2, -1, true,+ CLIP_BUZZER_DEATH_AIR, CLIP_BUZZER_DEATH_LAND, 0, 0.2828f},+};++/* ---------------------------------------------------------------- an enemy */+enum { EM_OFF, EM_ALIVE, EM_CORPSE };+enum { RC_READY, RC_RECOILING };+enum { CS_AIR, CS_DEATH_ANIM, CS_LANDED };+typedef struct {+ uint8_t mode, kind, st, flags;+ uint16_t ent;+ Body body;+ Anim anim;+ float sx; /* its transform's x scale: which way it faces */+ int16_t hp;+ float evasion;+ /* Recoil */+ uint8_t rc_state;+ int8_t rc_dir;+ bool rc_sweep;+ float rc_time, rc_speed;+ /* SpriteFlash (flashInfected) */+ float flash_t;+ bool flashing;+ /* the FSM's state */+ float t0, t1, wait, start_x, start_y, ax, ay, pause0, pause1;+ bool b0, b1;+ /* alert range (local circle) and sight */+ float ar_x, ar_y, ar_r;+ bool in_alert, can_see;+ float cbox_ox, cbox_oy, cbox_hx, cbox_hy; /* its collider */+} Enemy;+static Enemy en[MAX_ENEMIES];+static uint16_t swing_bits; /* (a bit an enemy: hit this swing) */++/* its transform's x scale (its collider's offset with it) */+static void set_scale_x(Enemy *e, float sx) {+ if ((sx < 0) != (e->sx < 0)) e->body.ox = -e->body.ox, e->ar_x = -e->ar_x;+ e->sx = sx;+}++static const Ent *ent_at(int i) {+ int n;+ return &room_ents(&n)[i];+}++/* the collider's world box */+static void enemy_box(const Enemy *e, float *x0, float *y0, float *x1, float *y1) {+ float cx = e->body.x + e->body.ox, cy = e->body.y + e->body.oy;+ *x0 = cx - e->body.hx, *x1 = cx + e->body.hx, *y0 = cy - e->body.hy, *y1 = cy + e->body.hy;+}++/* ---------------------------------------------------------------- geo (GeoControl) */+typedef struct {+ bool on, landed;+ uint8_t type; /* 0 small (1), 1 medium (5), 2 large (25) */+ Body body;+ Anim anim;+ float pickup_t, bounce_speed;+} Geo;+static Geo geo[MAX_GEO];+static const struct {+ int air, idle, value;+ float gravity, bounce, ox, oy, hx, hy;+} geo_kinds[3] = {+ {CLIP_GEO_SMALL_AIR, CLIP_GEO_SMALL_IDLE, 1, 1.5f, 0.7f, -0.0078f, -0.0391f, 0.2969f / 2, 0.2969f / 2},+ {CLIP_GEO_MED_AIR, CLIP_GEO_MED_IDLE, 5, 1.5f, 0.6f, -0.0078f, 0, 0.3281f / 2, 0.5312f / 2},+ {CLIP_GEO_LARGE_AIR, CLIP_GEO_LARGE_IDLE, 25, 1.75f, 0.4f, 0.0078f, 0, 0.4531f / 2, 0.4688f / 2},+};+#define GEO_SCALE 1.5f++/* FlingUtils.SpawnAndFling: n of a kind, each at a random speed and angle */+static void geo_fling(int type, int n, float x, float y, float smin, float smax, float amin, float amax) {+ for (int k = 0; k < n; k++) {+ Geo *g = NULL;+ for (int i = 0; i < MAX_GEO && !g; i++)+ if (!geo[i].on) g = &geo[i];+ if (!g) return;+ memset(g, 0, sizeof *g);+ g->on = true, g->type = (uint8_t)type;+ Body *b = &g->body;+ b->x = x, b->y = y;+ b->ox = geo_kinds[type].ox * GEO_SCALE, b->oy = geo_kinds[type].oy * GEO_SCALE;+ b->hx = geo_kinds[type].hx * GEO_SCALE, b->hy = geo_kinds[type].hy * GEO_SCALE;+ b->gravity_scale = geo_kinds[type].gravity, b->friction = 0.2f, b->mask = CF_TERRAIN;+ float s = rand_range(smin, smax), a = rand_range(amin, amax) * (float)M_PI / 180;+ b->vx = cosf(a) * s, b->vy = sinf(a) * s;+ anim_play(&g->anim, geo_kinds[type].air);+ g->pickup_t = 0.25f;+ }+}++/* ObjectBounce: off what it hit, at its speed before, times the bounce factor (and a little chance) */+static void bounce(Body *b, float pvx, float pvy, int had, float factor) {+ if (factor < 0 || b->ncontacts <= had) return;+ float speed = sqrtf(pvx * pvx + pvy * pvy);+ if (speed <= 1) return;+ float nx = b->cnx[b->ncontacts - 1], ny = b->cny[b->ncontacts - 1];+ float ux = pvx / speed, uy = pvy / speed, d = ux * nx + uy * ny;+ float rx = ux - 2 * d * nx, ry = uy - 2 * d * ny, k = speed * factor * rand_range(0.8f, 1.2f);+ b->vx = rx * k, b->vy = ry * k;+}++static void geo_tick(void) {+ const Hero *h = &g_hero;+ float k = h->cs.facing_right ? -1.0f : 1.0f;+ float hx = h->body.x + 0.0055733f * k, hy = h->body.y - 0.6942673f; /* (the HeroBox) */+ for (int i = 0; i < MAX_GEO; i++) {+ Geo *g = &geo[i];+ if (!g->on) continue;+ float pvx = g->body.vx, pvy = g->body.vy;+ int had = g->body.ncontacts;+ body_step(&g->body, DT);+ if (g->body.ncontacts > had) {+ bounce(&g->body, pvx, pvy, had, geo_kinds[g->type].bounce);+ /* (OnCollisionEnter2D: the idle animation from a random frame) */+ anim_play_from_frame(&g->anim, geo_kinds[g->type].idle, (int)rand_range(0, (float)clip_frames_count(geo_kinds[g->type].idle) - 0.001f));+ }+ g->anim.events = 0;+ anim_update(&g->anim, DT);+ if (g->pickup_t > 0) g->pickup_t -= DT;+ float x0 = g->body.x + g->body.ox - g->body.hx, x1 = g->body.x + g->body.ox + g->body.hx;+ float y0 = g->body.y + g->body.oy - g->body.hy, y1 = g->body.y + g->body.oy + g->body.hy;+ if (g->pickup_t <= 0 && !h->hidden && x1 > hx - 0.2277069f && x0 < hx + 0.2277069f && y1 > hy - 0.5848932f &&+ y0 < hy + 0.5848932f) {+ hero_add_geo(geo_kinds[g->type].value);+ g->on = false;+ }+ if (g->body.y < -10) g->on = false;+ }+}++/* ---------------------------------------------------------------- SpriteFlash */+static uint8_t flash_tint(const Enemy *e, int slot) {+ if (!e->flashing) return 0;+ /* flashInfected: up 0.01 s, stays 0.01 s, down over 0.25 s, to 0.9 of orange */+ float t = e->flash_t, k;+ if (t < 0.01f) k = t / 0.01f;+ else if (t < 0.02f) k = 1;+ else k = 1 - (t - 0.02f) / 0.25f;+ if (k < 0) k = 0;+ return gfx_dyn_flash(slot, 255, 255, 255, 255, 255, 79, 0, (uint8_t)(0.9f * k * 255));+}++/* ---------------------------------------------------------------- Recoil */+static void recoil_by_direction(Enemy *e, int dir, float magnitude) {+ const Kind *k = &kinds[e->kind];+ if (e->rc_state != RC_READY) return;+ e->rc_state = RC_RECOILING;+ e->rc_speed = k->recoil_speed * magnitude;+ e->rc_dir = (int8_t)dir;+ e->rc_sweep = true;+ e->rc_time = k->recoil_time;+}++/* Sweep.Check: three rays from the collider's side, the distance clipped by the terrain */+static void recoil_fixed(Enemy *e) {+ if (e->rc_state != RC_RECOILING) return;+ if (e->rc_sweep) {+ float dx = (float)(e->rc_dir == 0) - (float)(e->rc_dir == 2), dy = (float)(e->rc_dir == 1) - (float)(e->rc_dir == 3);+ float dist = e->rc_speed * DT, d = dist;+ float cx = e->body.x + e->body.ox + e->body.hx * dx, cy = e->body.y + e->body.oy + e->body.hy * dy;+ for (int i = 0; i < 3; i++) {+ float f = (float)i - 1;+ float x = cx + e->body.hx * fabsf(dy) * f - dx * 0.1f, y = cy + e->body.hy * fabsf(dx) * f - dy * 0.1f;+ PhysHit hit;+ if (phys_ray(x, y, dx, dy, d + 0.1f, CF_TERRAIN, &hit) && hit.dist - 0.1f < d) d = hit.dist - 0.1f;+ }+ if (dist - d > 1e-6f) e->rc_sweep = false;+ if (d > 1e-6f) e->body.x += dx * d, e->body.y += dy * d;+ }+ e->rc_time -= DT;+ if (e->rc_time <= 0) e->rc_state = RC_READY;+}++/* ---------------------------------------------------------------- death */+static void corpse_start(Enemy *e, float direction, bool has_direction) {+ const Kind *k = &kinds[e->kind];+ e->mode = EM_CORPSE, e->st = CS_AIR;+ e->body.y += k->corpse_spawn_y;+ e->body.ox = k->corpse_ox, e->body.oy = k->corpse_oy, e->body.hx = k->corpse_hx, e->body.hy = k->corpse_hy;+ e->body.gravity_scale = k->corpse_gravity, e->body.friction = 0.2f, e->body.mask = CF_SOLID;+ e->body.ncontacts = 0;+ float speed = k->corpse_fling, angle = 90, sign = e->sx < 0 ? -1.0f : 1.0f;+ switch (cardinal(direction)) {+ case 0: angle = 60, e->sx = sign; break; /* (corpseFacesRight: no) */+ case 2: angle = 120, e->sx = -sign; break;+ case 3: angle = 270; break;+ default: angle = rand_range(75, 105), speed *= 1.3f; break;+ }+ if (!has_direction) speed = 0;+ float a = angle * (float)M_PI / 180;+ e->body.vx = cosf(a) * speed, e->body.vy = sinf(a) * speed;+ anim_play(&e->anim, k->clip_death_air);+ e->flashing = true, e->flash_t = 0; /* (EmitInfectedEffects: the corpse flashes) */+}++/* HealthManager.Die, EnemyDeathEffects */+static void enemy_die(Enemy *e, float direction, bool has_direction) {+ const Ent *d = ent_at(e->ent);+ /* the geo: SpawnAndFling, small, medium then large */+ float x = e->body.x, y = e->body.y;+ geo_fling(0, (int)d->p2, x, y, 15, 30, 80, 100);+ geo_fling(1, (int)d->p3, x, y, 15, 30, 80, 100);+ geo_fling(2, d->group, x, y, 15, 30, 80, 100);+ persist_set(d->persist);+ corpse_start(e, direction, has_direction);+ cam_shake(SHAKE_ENEMY_KILL);+ FREEZE_MOMENT_1();+}++/* HealthManager.Hit (a nail's): evasion, damage, recoil, flash, soul */+static void enemy_hit(Enemy *e, float direction, int damage) {+ if (e->mode != EM_ALIVE || e->evasion > 0 || damage <= 0) return;+ int dir = cardinal(direction);+ recoil_by_direction(e, dir, 1);+ hero_soul_gain();+ e->flashing = true, e->flash_t = 0;+ e->hp = (int16_t)(e->hp - damage < -50 ? -50 : e->hp - damage);+ if (e->kind == EK_BUZZER && e->st == 0) e->b1 = true; /* (TOOK DAMAGE, in Idle) */+ if (e->hp > 0)+ e->evasion = 0.2f;+ else+ enemy_die(e, direction, true);+}++/* ---------------------------------------------------------------- PlayMaker actions */+/* the hero's position (its transform) */+static float hero_x(void) { return g_hero.body.x; }+static float hero_y(void) { return g_hero.body.y; }++/* FaceDirection (sprite facing left): turns to its velocity, playing a clip, pausing between turns */+static void face_direction(Enemy *e, float *pause, int clip) {+ if (*pause > 0) {+ *pause -= DT;+ return;+ }+ float want = e->body.vx > 0 ? -fabsf(e->sx) : fabsf(e->sx);+ if (e->sx != want) {+ *pause = 0.5f;+ set_scale_x(e, want);+ if (clip >= 0) anim_play_from_frame(&e->anim, clip, 0);+ }+}++/* LineOfSightDetector, AlertRange: the hero in the circle, and no terrain between */+static void sight_update(Enemy *e) {+ float cx = g_hero.body.x + g_hero.body.ox, cy = g_hero.body.y + g_hero.body.oy;+ float ax = e->body.x + e->ar_x, ay = e->body.y + e->ar_y;+ /* circle against the Knight's box */+ float qx = ax < cx - g_hero.body.hx ? cx - g_hero.body.hx : ax > cx + g_hero.body.hx ? cx + g_hero.body.hx : ax;+ float qy = ay < cy - g_hero.body.hy ? cy - g_hero.body.hy : ay > cy + g_hero.body.hy ? cy + g_hero.body.hy : ay;+ e->in_alert = !g_hero.hidden && e->ar_r > 0 && (qx - ax) * (qx - ax) + (qy - ay) * (qy - ay) < e->ar_r * e->ar_r;+ if (!e->in_alert) {+ e->can_see = false;+ return;+ }+ float dx = hero_x() - e->body.x, dy = hero_y() - e->body.y, l = sqrtf(dx * dx + dy * dy);+ e->can_see = l < 1e-4f || !phys_ray(e->body.x, e->body.y, dx / l, dy / l, l, CF_TERRAIN, NULL);+}++/* ---------------------------------------------------------------- Crawler: WalkLeftRight (sprite facing left) */+enum { CR_WALK, CR_WAIT, CR_TURN };+static float crawl_dir(const Enemy *e) { return e->sx < 0 ? 1.0f : -1.0f; }++static bool crawl_ray(const Enemy *e, float x, float dx, float dy, float len) {+ float y0 = e->body.y + e->body.oy - e->body.hy;+ return phys_ray(x, y0 + 0.5f, dx, dy, len, CF_TERRAIN, NULL);+}++static void crawler_start(Enemy *e, const Ent *d) {+ if (d->s1 & 1) {+ e->st = CR_WAIT; /* (First Crawler: waits for GO LEFT or GO RIGHT) */+ anim_play(&e->anim, CLIP_CRAWLER_WALK);+ return;+ }+ e->st = CR_WALK;+ e->b0 = rand_range(0, 100) <= 50; /* (shouldTurn: half the time) */+ anim_play(&e->anim, CLIP_CRAWLER_WALK);+}++static void crawler_fixed(Enemy *e) {+ if (e->st == CR_TURN) {+ e->t0 -= DT;+ if (e->t0 <= 0) {+ set_scale_x(e, -e->sx);+ anim_play(&e->anim, CLIP_CRAWLER_WALK);+ e->st = CR_WALK;+ }+ return;+ }+ if (e->st != CR_WALK) return;+ float dir = crawl_dir(e);+ e->body.vx = 4 * dir;+ float cx = e->body.x + e->body.ox, w = e->body.hx;+ bool grounded = crawl_ray(e, cx, 0, -1, 1);+ bool wall = crawl_ray(e, cx, dir, 0, w + 0.1f);+ bool edge = !crawl_ray(e, cx + (w + 0.1f) * dir, 0, -1, 1);+ if (e->b0 || (grounded && (wall || edge) && g_game.time >= e->t1)) {+ e->b0 = false;+ e->t1 = g_game.time + 1; /* (turnDelay) */+ e->body.vx = 0;+ anim_play(&e->anim, CLIP_CRAWLER_TURN);+ e->t0 = clip_duration(CLIP_CRAWLER_TURN);+ e->st = CR_TURN;+ }+}++/* ---------------------------------------------------------------- Buzzer: the chaser FSM */+enum { BZ_IDLE, BZ_STARTLE, BZ_CHASE, BZ_STOP };++static void buzzer_idle_enter(Enemy *e) {+ e->st = BZ_IDLE;+ anim_play(&e->anim, CLIP_BUZZER_IDLE);+ e->start_x = e->body.x, e->start_y = e->body.y; /* (IdleBuzz) */+ e->wait = 0, e->ax = e->ay = 0;+}++static void chase_start(Enemy *e) {+ anim_play_from_frame(&e->anim, CLIP_BUZZER_CHASE, 3);+ e->st = BZ_CHASE, e->t0 = 0;+}++static void buzzer_alerted(Enemy *e, const Ent *d) {+ if (d->s1 & 2) {+ /* Startle: still, facing the hero, till the clip ends */+ e->st = BZ_STARTLE;+ e->body.vx = e->body.vy = 0;+ anim_play(&e->anim, CLIP_BUZZER_STARTLE);+ set_scale_x(e, hero_x() > e->body.x ? -fabsf(e->sx) : fabsf(e->sx));+ } else+ chase_start(e);+}++static void buzzer_start(Enemy *e, const Ent *d) {+ if (d->s1 & 1) chase_start(e);+ else buzzer_idle_enter(e);+}++/* IdleBuzz: drifts about its start, accelerating at random */+static void idle_buzz(Enemy *e) {+ const float wmin = 0.75f, wmax = 1, vmax = 1.75f, amax = 15, range = 1;+ float vx = e->body.vx, vy = e->body.vy, x = e->body.x, y = e->body.y;+ if (y < e->start_y - range) {+ if (vy < 0) e->ay = amax / 2000, vy /= 1.125f, e->wait = rand_range(wmin, wmax);+ } else if (y > e->start_y + range && vy > 0)+ e->ay = -amax / 2000, vy /= 1.125f, e->wait = rand_range(wmin, wmax);+ if (x < e->start_x - range) {+ if (vx < 0) e->ax = amax / 2000, vx /= 1.125f, e->wait = rand_range(wmin, wmax);+ } else if (x > e->start_x + range && vx > 0)+ e->ax = -amax / 2000, vx /= 1.125f, e->wait = rand_range(wmin, wmax);+ if (e->wait <= 1.1920929e-7f) {+ e->ay = y < e->start_y - range ? rand_range(0, amax) : y > e->start_y + range ? rand_range(-amax, 0) : rand_range(-amax, amax);+ e->ax = x < e->start_x - range ? rand_range(0, amax) : x > e->start_x + range ? rand_range(-amax, 0) : rand_range(-amax, amax);+ e->ay /= 2000, e->ax /= 2000;+ e->wait = rand_range(wmin, wmax);+ }+ if (e->wait > 1.1920929e-7f) e->wait -= DT;+ vx += e->ax, vy += e->ay;+ e->body.vx = vx > vmax ? vmax : vx < -vmax ? -vmax : vx;+ e->body.vy = vy > vmax ? vmax : vy < -vmax ? -vmax : vy;+}++/* ChaseObject: towards the hero, a little faster each step */+static void chase_object(Enemy *e, float vmax, float accel) {+ float vx = e->body.vx + (e->body.x < hero_x() ? accel : -accel);+ float vy = e->body.vy + (e->body.y < hero_y() ? accel : -accel);+ e->body.vx = vx > vmax ? vmax : vx < -vmax ? -vmax : vx;+ e->body.vy = vy > vmax ? vmax : vy < -vmax ? -vmax : vy;+}++static void decelerate(Enemy *e, float d) {+ float vx = e->body.vx, vy = e->body.vy;+ vx = vx < 0 ? (vx + d > 0 ? 0 : vx + d) : vx > 0 ? (vx - d < 0 ? 0 : vx - d) : 0;+ vy = vy < 0 ? (vy + d > 0 ? 0 : vy + d) : vy > 0 ? (vy - d < 0 ? 0 : vy - d) : 0;+ e->body.vx = vx, e->body.vy = vy;+}++static void buzzer_fixed(Enemy *e) {+ if (e->st == BZ_IDLE) idle_buzz(e);+ else if (e->st == BZ_CHASE) chase_object(e, 5, 0.045f);+ else if (e->st == BZ_STOP) decelerate(e, 0.12f);+}++static void buzzer_update(Enemy *e, const Ent *d) {+ switch (e->st) {+ case BZ_IDLE:+ face_direction(e, &e->pause0, CLIP_BUZZER_TURNTOIDLE);+ if ((e->can_see && e->in_alert) || e->b1) {+ e->b1 = false;+ buzzer_alerted(e, d);+ }+ break;+ case BZ_STARTLE:+ if (e->anim.events & ANIM_DONE) chase_start(e);+ break;+ case BZ_CHASE:+ /* (In Sight and Out of Sight in turn: the attention span counts while it cannot see the hero) */+ face_direction(e, &e->pause1, CLIP_BUZZER_TURNTOFLY);+ if (e->can_see && e->in_alert) e->t0 = 0;+ else if ((e->t0 += DT) >= 10) {+ e->st = BZ_STOP, e->t0 = 0;+ anim_play_from_frame(&e->anim, CLIP_BUZZER_IDLE, 3);+ }+ break;+ case BZ_STOP:+ if ((e->t0 += DT) >= 1) buzzer_idle_enter(e);+ break;+ }+}++/* ---------------------------------------------------------------- the room's */+void enemies_enter(void) {+ memset(en, 0, sizeof en);+ memset(geo, 0, sizeof geo);+ int n, k = 0;+ const Ent *es = room_ents(&n);+ for (int i = 0; i < n && k < MAX_ENEMIES; i++) {+ const Ent *d = &es[i];+ if (d->type != ENT_OBJ || d->flags != OK_ENEMY || persist_get(d->persist)) continue;+ Enemy *e = &en[k++];+ e->mode = EM_ALIVE, e->kind = (uint8_t)d->a, e->ent = (uint16_t)i;+ e->sx = d->y1 ? d->y1 : 1;+ e->hp = (int16_t)d->p0;+ Body *b = &e->body;+ b->x = d->x0, b->y = d->y0;+ const Ent *box = d + 1;+ b->ox = box->x0 * (e->sx < 0 ? -1 : 1), b->oy = box->y0, b->hx = box->x1, b->hy = box->y1;+ b->gravity_scale = kinds[e->kind].gravity, b->friction = kinds[e->kind].friction, b->mask = CF_SOLID;+ if (d->s0 > 1) e->ar_x = (d + 2)->x0 * (e->sx < 0 ? -1 : 1), e->ar_y = (d + 2)->y0, e->ar_r = (d + 2)->x1;+ if (e->kind == EK_CRAWLER) crawler_start(e, d);+ else if (e->kind == EK_BUZZER) buzzer_start(e, d);+ }+}++/* FixedUpdate and the physics step */+void enemies_fixed(void) {+ for (int i = 0; i < MAX_ENEMIES; i++) {+ Enemy *e = &en[i];+ if (e->mode == EM_OFF) continue;+ if (e->mode == EM_ALIVE) {+ if (e->kind == EK_CRAWLER) crawler_fixed(e);+ else if (e->kind == EK_BUZZER) buzzer_fixed(e);+ recoil_fixed(e);+ body_step(&e->body, DT);+ } else {+ /* Corpse: falls, lands (or smashes, a breaker) and stays */+ const Kind *k = &kinds[e->kind];+ float pvx = e->body.vx, pvy = e->body.vy;+ int had = e->body.ncontacts;+ if (e->st != CS_LANDED || e->body.vx || e->body.vy) body_step(&e->body, DT);+ if (e->st == CS_AIR) {+ bool ground = false;+ for (int c = 0; c < e->body.ncontacts; c++) ground |= e->body.cny[c] > 0.5f;+ if (ground) {+ if (k->breaker) {+ anim_play(&e->anim, k->clip_death_land);+ e->body.vx = e->body.vy = 0;+ e->st = CS_DEATH_ANIM;+ } else {+ bounce(&e->body, pvx, pvy, had, k->corpse_bounce);+ anim_play(&e->anim, k->clip_death_land);+ e->st = CS_LANDED;+ }+ } else+ bounce(&e->body, pvx, pvy, had, k->corpse_bounce);+ if (e->body.y < -10) e->mode = EM_OFF;+ }+ }+ }+ geo_tick();+}++/* Update: the FSMs' every-frame actions, the animations, the timers */+void enemies_update(void) {+ for (int i = 0; i < MAX_ENEMIES; i++) {+ Enemy *e = &en[i];+ if (e->mode == EM_OFF) continue;+ e->anim.events = 0;+ anim_update(&e->anim, DT);+ if (e->flashing && (e->flash_t += DT) > 0.27f) e->flashing = false;+ if (e->mode == EM_ALIVE) {+ if (e->evasion > 0) e->evasion -= DT;+ if (e->ar_r > 0) sight_update(e);+ if (e->kind == EK_BUZZER) buzzer_update(e, ent_at(e->ent));+ } else if (e->st == CS_DEATH_ANIM && !e->anim.playing)+ e->mode = EM_OFF;+ }+}++void enemies_draw(void) {+ for (int i = 0; i < MAX_ENEMIES; i++) {+ const Enemy *e = &en[i];+ if (e->mode == EM_OFF) continue;+ Inst in;+ const Ent *d = ent_at(e->ent);+ float z = e->mode == EM_CORPSE ? 0.0085f : d->x1;+ sprite_inst(e->anim.sprite, e->body.x, e->body.y, z, e->sx, 1, flash_tint(e, 2 + i % 8), &in);+ gfx_actor(&in, SORT_KEY(0, 0));+ }+ for (int i = 0; i < MAX_GEO; i++) {+ const Geo *g = &geo[i];+ if (!g->on) continue;+ Inst in;+ sprite_inst(g->anim.sprite, g->body.x, g->body.y, 0.0015f, GEO_SCALE, GEO_SCALE, 0, &in);+ gfx_actor(&in, SORT_KEY(0, 0));+ }+}++/* ---------------------------------------------------------------- what touches them */+void enemies_swing_start(void) { swing_bits = 0; }++/* the slash's shape: enemies it touches are hit, once a swing -> HB_* */+int enemies_nail(const float *pts, int npts, float direction, int damage) {+ int out = 0;+ for (int i = 0; i < MAX_ENEMIES; i++) {+ Enemy *e = &en[i];+ if (e->mode != EM_ALIVE) continue;+ float x0, y0, x1, y1;+ enemy_box(e, &x0, &y0, &x1, &y1);+ if (!box_meets_shape(x0, y0, x1, y1, pts, npts)) continue;+ out |= HB_BOUNCE | HB_RECOIL;+ if (swing_bits >> i & 1) continue;+ swing_bits |= (uint16_t)(1 << i);+ enemy_hit(e, direction, damage);+ }+ return out;+}++/* DamageHero: the first enemy touching the HeroBox -> its damage (0: none), which side it is on */+int enemies_touch_hero(float x0, float y0, float x1, float y1, int *side) {+ for (int i = 0; i < MAX_ENEMIES; i++) {+ const Enemy *e = &en[i];+ if (e->mode != EM_ALIVE) continue;+ const Ent *d = ent_at(e->ent);+ if (d->p1 <= 0) continue;+ float a0, b0, a1, b1;+ enemy_box(e, &a0, &b0, &a1, &b1);+ if (x1 > a0 && x0 < a1 && y1 > b0 && y0 < b1) {+ *side = e->body.x > g_hero.body.x ? SIDE_RIGHT : SIDE_LEFT;+ return (int)d->p1;+ }+ }+ return 0;+}++#ifdef HOST+#include <stdio.h>+void enemies_debug(void) {+ for (int i = 0; i < MAX_ENEMIES; i++) {+ const Enemy *e = &en[i];+ if (e->mode == EM_OFF) continue;+ printf(" enemy %d kind %d mode %d st %d hp %d pos %.2f,%.2f v %.2f,%.2f sx %.0f rc %d see %d/%d\n", i, e->kind, e->mode,+ e->st, e->hp, e->body.x, e->body.y, e->body.vx, e->body.vy, e->sx, e->rc_state, e->in_alert, e->can_see);+ }+ int ng = 0;+ for (int i = 0; i < MAX_GEO; i++) ng += geo[i].on;+ printf(" geo %d pieces, %d in purse, mp %d\n", ng, g_pd.geo, g_pd.mp);+}+#endifdiff --git a/games/hollowknight/src/game.c b/games/hollowknight/src/game.cindex c7c2db9a..c3f8abff 100644--- a/games/hollowknight/src/game.c+++ b/games/hollowknight/src/game.c@@ -11,6 +11,7 @@ void game_new(void) {g_game.time_scale = 1;g_pd.health = g_pd.max_health = 5;g_pd.max_mp = 99;+ g_pd.nail_damage = 5;g_pd.can_dash = false;}@@ -73,30 +74,45 @@ static void triggers_tick(void) {}/* ---------------------------------------------------------------- GameManager's coroutines */-#define FREEZE_WAIT 0.25f /* (HeroController's DAMAGE_FREEZE_WAIT, UP) */-#define FREEZE_UP 0.05f-enum { FZ_NONE, FZ_WAIT, FZ_UP };--/* FreezeMoment(DAMAGE_FREEZE_DOWN, WAIT, UP, 0.0001): time stops (in unscaled time), then comes back */-void game_freeze_moment(void) {- g_game.time_scale = 0; /* (the 0.001 s ramp down) */- g_game.freeze_phase = FZ_WAIT, g_game.freeze_t = 0;+enum { FZ_NONE, FZ_DOWN, FZ_WAIT, FZ_UP };++/* FreezeMoment(rampDownTime, waitTime, rampUpTime, targetSpeed): time slows to the target (in unscaled time), stays,+ * then comes back; hero: the Knight's recoil goes on after (StartRecoil waits for it) */+void game_freeze(float down, float wait, float up, float target, bool hero) {+ Game *g = &g_game;+ g->freeze_phase = FZ_DOWN, g->freeze_t = 0, g->freeze_from = g->time_scale;+ g->freeze_down = down, g->freeze_wait = wait, g->freeze_up = up, g->freeze_target = target;+ g->freeze_hero = g->freeze_hero || hero;}+void game_freeze_moment(void) { game_freeze(0.001f, 0.25f, 0.05f, 0.0001f, true); } /* (DAMAGE_FREEZE_*) */++static void set_time_scale(float s) { g_game.time_scale = s > 0.01f ? s : 0; }+static void freeze_tick(float real_dt) {Game *g = &g_game;+ if (g->freeze_phase == FZ_NONE) return;+ /* (SetTimeScale's loop: the scale for this frame, then the timer) */+ if (g->freeze_phase == FZ_DOWN) {+ if (g->freeze_t >= g->freeze_down) {+ set_time_scale(g->freeze_target);+ g->freeze_phase = FZ_WAIT, g->freeze_t = 0;+ } else+ set_time_scale(g->freeze_from + (g->freeze_target - g->freeze_from) * (g->freeze_t / g->freeze_down));+ }if (g->freeze_phase == FZ_WAIT) {- g->freeze_t += real_dt;- if (g->freeze_t >= FREEZE_WAIT) g->freeze_phase = FZ_UP, g->freeze_t = 0;- } else if (g->freeze_phase == FZ_UP) {- g->freeze_t += real_dt;- g->time_scale = g->freeze_t >= FREEZE_UP ? 1 : g->freeze_t / FREEZE_UP;- if (g->time_scale > 0 && g->time_scale <= 0.01f) g->time_scale = 0;- if (g->freeze_t >= FREEZE_UP) {- g->time_scale = 1, g->freeze_phase = FZ_NONE;- hero_recoil_unfreeze();+ if (g->freeze_t >= g->freeze_wait) g->freeze_phase = FZ_UP, g->freeze_t = 0, g->freeze_from = g->time_scale;+ }+ if (g->freeze_phase == FZ_UP) {+ if (g->freeze_t >= g->freeze_up) {+ set_time_scale(1);+ g->freeze_phase = FZ_NONE;+ if (g->freeze_hero) g->freeze_hero = false, hero_recoil_unfreeze();+ return;}+ set_time_scale(g->freeze_from + (1 - g->freeze_from) * (g->freeze_t / g->freeze_up));}+ g->freeze_t += real_dt;}/* the camera's fades (its Blanker): to black and back */@@ -141,6 +157,7 @@ static void hazard_tick(void) {static void step(uint32_t keys) {g_game.time += 0.02f;hero_fixed(keys);+ enemies_fixed();triggers_tick();hero_check_damage();hero_update();diff --git a/games/hollowknight/src/game.h b/games/hollowknight/src/game.hindex 6fe7ca80..7294bba5 100644--- a/games/hollowknight/src/game.h+++ b/games/hollowknight/src/game.h@@ -7,8 +7,9 @@typedef struct {uint8_t persist[MAX_PERSIST / 8]; /* the objects' states (PersistentBoolItem) */int8_t health, max_health, health_blue;- int16_t mp, mp_reserve, max_mp;+ int16_t mp, mp_reserve, max_mp, mp_reserve_max;int32_t geo;+ int8_t nail_damage;bool can_dash, has_spell, has_dash;uint8_t fireball_level;bool disable_pause;@@ -18,7 +19,7 @@ extern PlayerData g_pd;/* ---------------------------------------------------------------- the room's game objects (tools/ents.py) */enum { ENT_CAMLOCK = 1, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK, ENT_DAMAGE, ENT_SHAPE,ENT_BOX, ENT_OBJ, ENT_PIECE }; /* (shape, box, piece: more of the record before) */-enum { OK_BREAKABLE = 1 }; /* objects (ENT_OBJ's flags) */+enum { OK_BREAKABLE = 1, OK_ENEMY }; /* objects (ENT_OBJ's flags) */enum { HB_BOUNCE = 1, HB_RECOIL = 2 }; /* a hit box (ENT_BOX's flags): a down slash bounces off it, a slash recoils */enum { HAZ_NONE, HAZ_NORMAL, HAZ_SPIKES, HAZ_ACID, HAZ_LAVA, HAZ_PIT }; /* DamageHero.hazardType */enum { MK_SECRET = 1, MK_REMASK = 2, MK_SIMPLE = 4 }; /* masks: the unmasker, remasker and inverse FSMs */@@ -52,6 +53,15 @@ void obj_draw(void);void obj_swing_start(void); /* a slash's hit shape on: what it hits, once */int obj_nail(const float *pts, int npts, float direction); /* -> HB_* of what it touches */float rand_range(float lo, float hi); /* Random.Range (floats) */++/* enemies, their corpses, geo (enemy.c) */+void enemies_enter(void);+void enemies_fixed(void); /* FixedUpdate and their physics */+void enemies_update(void); /* Update */+void enemies_draw(void);+void enemies_swing_start(void);+int enemies_nail(const float *pts, int npts, float direction, int damage);+int enemies_touch_hero(float x0, float y0, float x1, float y1, int *side); /* -> its damage, 0: none */int cardinal(float degrees); /* DirectionUtils.GetCardinalDirection */const Ent *room_ents(int *n);#define MAX_ENTS 320@@ -66,13 +76,16 @@ typedef struct {bool hazard_facing_right;/* GameManager's coroutines */uint8_t freeze_phase;- float freeze_t, freeze_from;+ bool freeze_hero;+ float freeze_t, freeze_from, freeze_down, freeze_wait, freeze_up, freeze_target;uint8_t hazard_phase;float hazard_t;/* the camera's fade to black */float fade, fade_from, fade_to, fade_t, fade_time, fade_delay;} Game;-void game_freeze_moment(void); /* GameManager.FreezeMoment (a hit) */+void game_freeze_moment(void); /* the Knight hit: FreezeMoment with HeroController's DAMAGE_FREEZE_* */+void game_freeze(float down, float wait, float up, float target, bool hero); /* GameManager.FreezeMoment */+#define FREEZE_MOMENT_1() game_freeze(0.04f, 0.03f, 0.04f, 0, false) /* FreezeMoment(1): a kill */void game_player_dead_from_hazard(void);void game_fade(float to, float time, float delay);extern Game g_game;@@ -140,6 +153,8 @@ void hero_recoil_unfreeze(void); /* the end of StartRecoil, after the freevoid hero_hazard_respawn(void); /* HeroController.HazardRespawn */void hero_check_damage(void); /* HeroBox: the hazards and enemies touching it */void hero_late_update(void); /* (HeroBox.LateUpdate: a buffered hit) */+void hero_soul_gain(void); /* a nail's hit on an enemy */+void hero_add_geo(int amount);/* the nail's slashes (NailSlash), children of the Knight */void slash_start(int kind);diff --git a/games/hollowknight/src/gfx.c b/games/hollowknight/src/gfx.cindex 45a9b12c..7fa09b2e 100644--- a/games/hollowknight/src/gfx.c+++ b/games/hollowknight/src/gfx.c@@ -104,17 +104,25 @@ static uint32_t grade(float r, float g, float b, float a) {uint8_t g_group_alpha[MAX_GROUPS];uint8_t g_screen_fade; /* how black the screen is (the camera's fade) */-/* tints: the room's, then colors the game sets (gfx_dyn_tint) */+/* tints: the room's, then colors the game sets (gfx_dyn_tint): a color, and a flash color and amount (SpriteFlash) */#define DYN_TINT 240-static uint8_t dyn_tints[256 - DYN_TINT][4];+static uint8_t dyn_tints[256 - DYN_TINT][8];static inline const uint8_t *tint_rgba(int tint) { return tint >= DYN_TINT ? dyn_tints[tint - DYN_TINT] : g_room.tints + 4 * tint; }+static void pals_forget_tint(int tint);-uint8_t gfx_dyn_tint(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a) {+uint8_t gfx_dyn_flash(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a, uint8_t fr, uint8_t fg, uint8_t fb, uint8_t amount) {uint8_t *t = dyn_tints[slot & 15];- t[0] = r, t[1] = g, t[2] = b, t[3] = a;+ uint8_t v[8] = {r, g, b, a, fr, fg, fb, amount};+ if (memcmp(t, v, 8)) {+ /* (the colors made with its old values are stale) */+ memcpy(t, v, 8);+ pals_forget_tint(DYN_TINT + (slot & 15));+ }return (uint8_t)(DYN_TINT + (slot & 15));}+uint8_t gfx_dyn_tint(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a) { return gfx_dyn_flash(slot, r, g, b, a, 0, 0, 0, 0); }+/* the instance's alpha: its tint's, times its render group's */static inline uint32_t inst_alpha(const Inst *in) {uint32_t a = tint_rgba(in->tint)[3];@@ -164,13 +172,17 @@ static int pal_get(uint16_t tex, uint8_t tint, uint8_t flags, uint32_t alpha) {for (int i = 1; i < 4; i++) p->c[i] = (uint32_t)(ta * i / 3.0f * 255 + 0.5f) << 24;} else {const uint8_t *pc = section(SEC_PAL) + r->pal_off;+ /* (a flash: towards its color by its amount, the alpha kept) */+ float fk = tint >= DYN_TINT ? t[7] / 255.0f : 0, fr = fk ? t[4] / 255.0f * fk : 0, fg = fk ? t[5] / 255.0f * fk : 0,+ fb = fk ? t[6] / 255.0f * fk : 0;for (int i = 0; i < 15; i++)- p->c[i + 1] = grade(pc[4 * i] / 255.0f * tr, pc[4 * i + 1] / 255.0f * tg, pc[4 * i + 2] / 255.0f * tb,- pc[4 * i + 3] / 255.0f * ta);+ p->c[i + 1] = grade(pc[4 * i] / 255.0f * tr * (1 - fk) + fr, pc[4 * i + 1] / 255.0f * tg * (1 - fk) + fg,+ pc[4 * i + 2] / 255.0f * tb * (1 - fk) + fb, pc[4 * i + 3] / 255.0f * ta);}return s;}+/* ---------------------------------------------------------------- smooth textures: a few texels, graded for a tint (those of* one color are alpha only, read in place) */#ifndef SOFT_POOL@@ -187,6 +199,13 @@ typedef struct {static SoftEnt soft_ent[NSOFT];static int nsoft, soft_top;+static void pals_forget_tint(int tint) {+ for (int i = 0; i < NPAL; i++)+ if ((pals[i].key >> 1 & 255) == (uint32_t)tint && pals[i].key < 0xFFFC0000u) pals[i].key = 0xFFFFFFFFu;+ for (int i = 0; i < nsoft; i++)+ if ((soft_ent[i].key >> 1 & 255) == (uint32_t)tint) soft_ent[i].key = 0xFFFFFFFFu;+}+static void soft_reset(void) { nsoft = 0, soft_top = 0; }uint32_t g_soft_misses;diff --git a/games/hollowknight/src/hero.c b/games/hollowknight/src/hero.cindex ae7f5268..90d411cd 100644--- a/games/hollowknight/src/hero.c+++ b/games/hollowknight/src/hero.c@@ -751,7 +751,9 @@ static void animation(void) {/* ---------------------------------------------------------------- the tick */void hero_init(float x, float y, bool facing_right) {Hero *h = &g_hero;+ static BodyEvent events[MAX_EVENTS];memset(h, 0, sizeof *h);+ h->body.events = events;h->body.x = x, h->body.y = y;h->body.ox = 0, h->body.oy = -0.75f, h->body.hx = 0.25f, h->body.hy = 0.640625f; /* the Knight's BoxCollider2D */h->body.gravity_scale = DEFAULT_GRAVITY;@@ -803,6 +805,13 @@ void hero_update(void) {void hero_draw(void) {Hero *h = &g_hero;+ /* HeroLight: a child glow in the room's hero light color (SceneManager), blended as linear light */+ const float *hl = g_room.h->hero_light;+ Inst li;+ sprite_inst(SPRITE_HERO_LIGHT, h->body.x, h->body.y - 0.6f, 0.004f + 0.0312f, 1, 1,+ gfx_dyn_tint(1, (uint8_t)(hl[0] * 255), (uint8_t)(hl[1] * 255), (uint8_t)(hl[2] * 255), (uint8_t)(hl[3] * 255)), &li);+ li.flags = (uint8_t)((li.flags & ~F_BLEND) | BL_LINEARLIGHT);+ gfx_actor(&li, SORT_KEY(0, 0));if (h->hidden) return;Inst in;/* (InvulnerablePulse: the color towards its invulnerable one) */@@ -1132,8 +1141,27 @@ void hero_check_damage(void) {} elsehero_take_damage(side, damage, hazard);}+ int side, damage = enemies_touch_hero(x0, y0, x1, y1, &side);+ if (damage) hero_take_damage(side, damage, HAZ_NORMAL);}+/* PlayerData.AddMPCharge: the vessel fills, then the reserve */+static void add_mp_charge(int amount) {+ PlayerData *p = &g_pd;+ if (p->mp + amount > p->max_mp) {+ if (p->mp_reserve < p->mp_reserve_max) {+ p->mp_reserve = (int16_t)(p->mp_reserve + amount - (p->max_mp - p->mp));+ if (p->mp_reserve > p->mp_reserve_max) p->mp_reserve = p->mp_reserve_max;+ }+ p->mp = p->max_mp;+ } else+ p->mp = (int16_t)(p->mp + amount);+}++void hero_soul_gain(void) { add_mp_charge(g_pd.mp < g_pd.max_mp ? 11 : 6); }++void hero_add_geo(int amount) { g_pd.geo += amount; }+void hero_late_update(void) {Hero *h = &g_hero;if (h->hit_buffered) {diff --git a/games/hollowknight/src/hk.h b/games/hollowknight/src/hk.hindex c0e416cc..42d57d9c 100644--- a/games/hollowknight/src/hk.h+++ b/games/hollowknight/src/hk.h@@ -178,12 +178,13 @@ typedef struct {float x, y, vx, vy; /* its position (the transform's) and velocity */float ox, oy, hx, hy; /* the box: its center from the position, half its size */float gravity_scale;+ float friction; /* (with the ground's: the materials' combined) */uint8_t mask; /* the colliders that stop it (CF_*) */int ncontacts;uint8_t ccol[MAX_CONTACTS];float cnx[MAX_CONTACTS], cny[MAX_CONTACTS];- int nevents; /* the last step's: OnCollisionEnter2D, Stay, Exit */- BodyEvent events[MAX_EVENTS];+ int nevents; /* the last step's: OnCollisionEnter2D, Stay, Exit (into events, if it wants them) */+ BodyEvent *events;} Body;void body_step(Body *b, float dt);@@ -194,5 +195,7 @@ void gfx_frame(void); /* draws the room at the camera into the screen* (SORT_KEY), then depth */bool gfx_actor(const Inst *in, uint32_t group);uint8_t gfx_dyn_tint(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a); /* a tint (for Inst.tint) of that color */+/* the same, flashing: its colors towards (fr, fg, fb) by amount (SpriteFlash) */+uint8_t gfx_dyn_flash(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a, uint8_t fr, uint8_t fg, uint8_t fb, uint8_t amount);extern uint8_t g_screen_fade; /* 0 .. 255: the screen faded to black */extern uint32_t g_gfx_items, g_gfx_pixels;diff --git a/games/hollowknight/src/obj.c b/games/hollowknight/src/obj.cindex 165f32be..ff57128b 100644--- a/games/hollowknight/src/obj.c+++ b/games/hollowknight/src/obj.c@@ -142,6 +142,7 @@ static void breakable_hit(Obj *o, const Ent *e, float direction) {void obj_enter(void) {nobjs = 0;phys_colliders_reset();+ enemies_enter();memset(pieces, 0, sizeof pieces);memset(swing_hit, 0, sizeof swing_hit);int n;@@ -154,17 +155,26 @@ void obj_enter(void) {}}-void obj_tick(void) { pieces_tick(); }+void obj_tick(void) {+ pieces_tick();+ enemies_update();+}-void obj_draw(void) { pieces_draw(); }+void obj_draw(void) {+ pieces_draw();+ enemies_draw();+}/* ---------------------------------------------------------------- the nail */-void obj_swing_start(void) { memset(swing_hit, 0, sizeof swing_hit); }+void obj_swing_start(void) {+ memset(swing_hit, 0, sizeof swing_hit);+ enemies_swing_start();+}/* the slash's shape this step (world, convex): what it touches is hit (once a swing), the direction (degrees) the* blow goes; -> what the Knight does (HB_*: bounce, recoil) */int obj_nail(const float *pts, int npts, float direction) {- int out = 0;+ int out = enemies_nail(pts, npts, direction, g_pd.nail_damage);for (int k = 0; k < nobjs; k++) {Obj *o = &objs[k];const Ent *e = ent_at(o->ent);diff --git a/games/hollowknight/src/phys.c b/games/hollowknight/src/phys.cindex b4398763..cf18514d 100644--- a/games/hollowknight/src/phys.c+++ b/games/hollowknight/src/phys.c@@ -218,8 +218,15 @@ void body_step(Body *b, float dt) {if (b->gravity_scale) b->vy += GRAVITY * b->gravity_scale * dt;/* resting contacts take away the velocity into them (the solver), then the box moves and slides */for (int i = 0; i < b->ncontacts; i++) {- float vn = b->vx * b->cnx[i] + b->vy * b->cny[i];- if (vn < 0) b->vx -= vn * b->cnx[i], b->vy -= vn * b->cny[i];+ float nx = b->cnx[i], ny = b->cny[i], vn = b->vx * nx + b->vy * ny;+ if (vn >= 0) continue;+ b->vx -= vn * nx, b->vy -= vn * ny;+ if (b->friction > 0) {+ /* (Coulomb: the tangent velocity less up to the friction times the normal impulse) */+ float vt = b->vx * -ny + b->vy * nx, f = -vn * b->friction;+ float d = vt > f ? f : vt < -f ? -f : vt;+ b->vx -= d * -ny, b->vy -= d * nx;+ }}float left = 1;for (int it = 0; it < 4 && left > 0; it++) {@@ -272,12 +279,12 @@ void body_step(Body *b, float dt) {for (int i = 0; i < b->ncontacts; i++) {int j = 0;while (j < n && cols[j] != b->ccol[i]) j++;- if (j == n && b->nevents < MAX_EVENTS) b->events[b->nevents++] = (BodyEvent){EV_EXIT, b->ccol[i], b->cnx[i], b->cny[i]};+ if (j == n && b->events && b->nevents < MAX_EVENTS) b->events[b->nevents++] = (BodyEvent){EV_EXIT, b->ccol[i], b->cnx[i], b->cny[i]};}for (int j = 0; j < n; j++) {int i = 0;while (i < b->ncontacts && b->ccol[i] != cols[j]) i++;- if (b->nevents < MAX_EVENTS) b->events[b->nevents++] = (BodyEvent){i == b->ncontacts ? EV_ENTER : EV_STAY, cols[j], nxs[j], nys[j]};+ if (b->events && b->nevents < MAX_EVENTS) b->events[b->nevents++] = (BodyEvent){i == b->ncontacts ? EV_ENTER : EV_STAY, cols[j], nxs[j], nys[j]};}b->ncontacts = n;for (int j = 0; j < n; j++) b->ccol[j] = cols[j], b->cnx[j] = nxs[j], b->cny[j] = nys[j];diff --git a/games/hollowknight/tests/play.c b/games/hollowknight/tests/play.cindex c32c2ca2..da9d5641 100644--- a/games/hollowknight/tests/play.c+++ b/games/hollowknight/tests/play.c@@ -70,6 +70,10 @@ int main(int argc, char **argv) {printf("%4d keys %02x pos %.3f,%.3f v %.3f,%.3f state %d ground %d jump %d fall %d clip %d frame %d cam %.2f,%.2f\n", tick,keys, g_hero.body.x, g_hero.body.y, g_hero.body.vx, g_hero.body.vy, g_hero.state, g_hero.cs.on_ground,g_hero.cs.jumping, g_hero.cs.falling, g_hero.anim.clip, g_hero.anim.frame, g_cam_x, g_cam_y);+ if (trace && getenv("ENEMIES")) {+ extern void enemies_debug(void);+ enemies_debug();+ }if (shots && shot_every && tick % shot_every == 0) {char path[256];snprintf(path, sizeof path, "%s/%05d.ppm", shots, tick);diff --git a/games/hollowknight/tools/actors.py b/games/hollowknight/tools/actors.pyindex 8b30b828..4450f393 100644--- a/games/hollowknight/tools/actors.py+++ b/games/hollowknight/tools/actors.py@@ -20,9 +20,31 @@ KNIGHT = ("resources.assets", 20600, ["Collect Heart Piece", "Collect Heart Piece End", "Collect StandToIdle", "GetUpToIdle",])-ACTORS = {"knight": KNIGHT}+# enemies: their libraries (all their clips)+ACTORS = {"knight": KNIGHT,+ "crawler": ("sharedassets6.assets", 1113, None),+ "buzzer": ("sharedassets6.assets", 1150, None),+ "geo": ("resources.assets", 23266, ["Small Idle", "Small Air", "Med Idle", "Med Air", "Large Idle", "Large Air"])}++# sprites of prefab objects the game draws itself: name -> (file, prefab, object, resolution)+NAMED = {+ "HERO_LIGHT": ("resources.assets", 3916, "Knight/HeroLight", 1.0),+}+++def named_sprites(sprites):+ """Registers NAMED in sprites (ents.Sprites) -> {name: sprite id}."""+ out = {}+ for name, (path, gid, opath, res) in NAMED.items():+ d = unity.prefab(path, gid)+ o = next(o for o in d["objects"] if o["path"] == opath)+ v = next(c["v"] for c in o["c"] if c["type"] == "SpriteRenderer")+ m = np.array(o["m3"]).reshape(3, 3)+ out[name] = sprites.id(d, v["m_Sprite"], float(max(np.hypot(m[0, 0], m[1, 0]), np.hypot(m[0, 1], m[1, 1]))), res)+ return out# clips drawn bigger than their sprites (the object's scale): their frames are kept that much finer-DRAWN_SCALE = {"SlashEffect": 1.645, "SlashEffectAlt": 1.422, "UpSlashEffect": 1.4, "DownSlashEffect": 1.28}+DRAWN_SCALE = {"SlashEffect": 1.645, "SlashEffectAlt": 1.422, "UpSlashEffect": 1.4, "DownSlashEffect": 1.28,+ "Small Idle": 1.5, "Small Air": 1.5, "Med Idle": 1.5, "Med Air": 1.5, "Large Idle": 1.5, "Large Air": 1.5}K0 = scene.FOCAL / (0.004 - scene.CAMZ) # screen pixels a unit, where actors are (z near 0)@@ -37,7 +59,7 @@ def build():for actor, (path, pid, names) in ACTORS.items():lib = tk2d.animation(path, pid)byname = {unity.S(c["name"]): c for c in lib["clips"]}- for name in names:+ for name in names or [unity.S(c["name"]) for c in lib["clips"]]:c = byname[name]frames = []for f in c["frames"]:@@ -64,11 +86,11 @@ def unity_sprites(keys):"""Unity sprites objects show as actors (ents.Sprites: debris...) -> sprite records like build()'s; each at itsobject's scale."""out = []- for level, exts, fid, pid, scale in keys:+ for level, exts, fid, pid, scale, res in keys:s = unity.sprite(level, list(exts), fid, pid)img = unity.sprite_image(s)wu, hu = s.w / s.ppu * scale, s.h / s.ppu * scale- w, h = max(1, round(wu * K0)), max(1, round(hu * K0))+ w, h = max(1, round(wu * K0 * res)), max(1, round(hu * K0 * res))arr = np.asarray(img.resize((w, h), Image.BOX)).copy()out.append({"key": (level, fid, pid), "job": art.ImageJob(arr, "piece/%s" % s.name),"lx": -s.px * wu, "ty": (1 - s.py) * hu, "tu": wu / w, "tv": hu / h})diff --git a/games/hollowknight/tools/ents.py b/games/hollowknight/tools/ents.pyindex 074894a9..7440752b 100644--- a/games/hollowknight/tools/ents.py+++ b/games/hollowknight/tools/ents.py@@ -8,7 +8,11 @@ import numpy as npENT_CAMLOCK, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK, ENT_DAMAGE, ENT_SHAPE, ENT_BOX, \ENT_OBJ, ENT_PIECE = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11# objects (ENT_OBJ's flags: src/obj.c)-OK_BREAKABLE = 1+OK_BREAKABLE, OK_ENEMY = 1, 2+# enemies (an OK_ENEMY's a: src/enemy.c), by their FSM and animation library+EK_CRAWLER, EK_BUZZER = 1, 2+ENEMIES = {("Crawler", 1113): EK_CRAWLER, ("chaser", 1150): EK_BUZZER}+EF_START, EF_STARTLES = 1, 2 # (FSM bools: First Crawler or Start Alert; Startles)# the layers the nail's slashes touch (Physics2D's collision matrix, layer 17 Attack)ATTACK_HITS = {3, 6, 7, 8, 11, 12, 17, 19, 20, 21, 25, 31}MAX_GROUPS = 256@@ -54,8 +58,9 @@ class Sprites:def __init__(self):self.list, self.index, self.base = [], {}, 0- def id(self, d, ref, scale):- key = (d["level"], tuple(d["externals"]), ref[0], ref[1], round(scale, 3))+ def id(self, d, ref, scale, res=1.0):+ """(res: its texture's resolution, as a part of the screen's: smooth sprites can be stretched)"""+ key = (d["level"], tuple(d["externals"]), ref[0], ref[1], round(scale, 3), res)if key not in self.index:self.index[key] = len(self.list)self.list.append(key)@@ -259,6 +264,50 @@ def _pieces(d, o, ids, by_id, sprites):return out+def _enemy(o, by_id, persist, name):+ """An enemy -> its records: ENT_OBJ (OK_ENEMY: its kind, place (x, y, z, x scale), hp, damage, small and medium+ geo; large geo in group), then ENT_BOX its collider (local offset and half size, scaled) and ENT_BOX its alert+ range (a circle: local center and radius), or None."""+ an = next((c.get("v") for c in o["c"] if c.get("class") == "tk2dSpriteAnimator" and c.get("v")), None)+ hm = next((c.get("v") for c in o["c"] if c.get("class") == "HealthManager" and c.get("v")), None)+ if not an or not hm:+ return None+ kind = None+ for c in o["c"]:+ f = c.get("fsm")+ if f and (f["name"], an["library"][1]) in ENEMIES:+ kind, fsm = ENEMIES[(f["name"], an["library"][1])], f+ if kind is None:+ return None+ dh = next((c.get("v") or {} for c in o["c"] if c.get("class") == "DamageHero"), {})+ box = next((c["v"] for c in o["c"] if c["type"] == "BoxCollider2D" and c.get("v") and not c["v"].get("m_IsTrigger")), None)+ if box is None:+ return None+ sx, sy = o["lscale"][0], o["lscale"][1]+ var = fsm.get("vars", {})+ fl = 0+ if (var.get("First Crawler") or var.get("Start Alert") or [0, False])[1]:+ fl |= EF_START+ if (var.get("Startles") or [0, False])[1]:+ fl |= EF_STARTLES+ out = [rec(ENT_BOX, box=(box["m_Offset"]["x"] * abs(sx), box["m_Offset"]["y"] * abs(sy),+ box["m_Size"]["x"] / 2 * abs(sx), box["m_Size"]["y"] / 2 * abs(sy)))]+ for ch in o.get("children", []):+ q = by_id[ch]+ if q["name"] == "Alert Range New":+ cc = next((c["v"] for c in q["c"] if c["type"] == "CircleCollider2D" and c.get("v")), None)+ if cc:+ k = max(abs(q["lscale"][0]), abs(q["lscale"][1]))+ out.append(rec(ENT_BOX, box=(q["lpos"][0] + cc["m_Offset"]["x"] * k, q["lpos"][1] + cc["m_Offset"]["y"] * k,+ cc["m_Radius"] * k, 0)))+ persistent = any(c.get("class") == "PersistentBoolItem" for c in o["c"])+ head = rec(ENT_OBJ, OK_ENEMY, (o["pos"][0], o["pos"][1], o["pos"][2], sx),+ (hm.get("hp", 1), dh.get("damageDealt", 0), hm.get("smallGeoDrops", 0), hm.get("mediumGeoDrops", 0)),+ a=kind, group=hm.get("largeGeoDrops", 0), persist=persist.id(name, o["path"]) if persistent else NO_PERSIST,+ s0=len(out), s1=fl)+ return [head] + out++def room(d, rooms, strings, persist, name, sprites=None, owners=None):"""-> (packed records, {object id: render group}). owners: each collider's object (coll.room); sprites: where theobjects' own sprites go (Sprites)."""@@ -309,6 +358,9 @@ def room(d, rooms, strings, persist, name, sprites=None, owners=None):persist=persist.id(name, o["path"]) if persistent else NO_PERSIST))recs += _more_boxes(o)classes = {c.get("class") for c in o["c"]}+ en = _enemy(o, by_id, persist, name)+ if en:+ recs += enbr = next((c for c in o["c"] if c.get("class") == "Breakable" and c.get("v") is not None), None)if br is not None:v = br["v"]diff --git a/games/hollowknight/tools/pack.py b/games/hollowknight/tools/pack.pyindex 08dbcb74..a15dbc20 100644--- a/games/hollowknight/tools/pack.py+++ b/games/hollowknight/tools/pack.py@@ -290,6 +290,7 @@ def main():sprites, clips = actors.build()# the rooms' objects, and the sprites they show (after the actors')SPRITES.base = len(sprites)+ named = actors.named_sprites(SPRITES)for r in ROOMS:room_data(r)sprites += actors.unity_sprites(SPRITES.list)@@ -403,6 +404,8 @@ def main():f.write("#define ROOM_%s %d\n" % (r.upper(), i))for i, c in enumerate(clips):f.write("#define %s %d\n" % (c["id"], i))+ for k, v in named.items():+ f.write("#define SPRITE_%s %d\n" % (k, v))if __name__ == "__main__":