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.

Hollow Knight: damage, spikes and hazard respawn

Mason Chen4e2f67d201e6
diff --git a/games/hollowknight/src/anim.c b/games/hollowknight/src/anim.c
index f89f3828..b0627648 100644
--- a/games/hollowknight/src/anim.c
+++ b/games/hollowknight/src/anim.c
@@ -163,4 +163,5 @@ void sprite_inst(int sprite, float x, float y, float z, float sx, float sy, uint
out->a = to_f16(sx * s->tu);
out->b = to_f16(-sy * s->tv);
out->rot = 0;
+ out->group = 0;
}
diff --git a/games/hollowknight/src/camera.c b/games/hollowknight/src/camera.c
index c48694dc..d6d84fac 100644
--- a/games/hollowknight/src/camera.c
+++ b/games/hollowknight/src/camera.c
@@ -287,3 +287,25 @@ void cam_tick(void) {
controller_late_update();
g_cam_x = c.cx, g_cam_y = c.cy;
}
+
+/* after a respawn: the camera with the Knight (PositionToHero) */
+void cam_snap_to_hero(void) {
+ const Hero *h = &g_hero;
+ c.tmode = c.cur_lock >= 0 ? TM_LOCK_ZONE : TM_FOLLOW_HERO;
+ c.mode = c.cur_lock >= 0 ? CM_LOCKED : CM_FOLLOWING;
+ c.start_locked_timer = 0.5f;
+ c.tx = h->body.x, c.ty = h->body.y;
+ if (c.tmode == TM_LOCK_ZONE) c.tx = clampf(c.tx, c.lock_x0, c.lock_x1), c.ty = clampf(c.ty, c.lock_y0, c.lock_y1);
+ c.x_offset = h->cs.facing_right ? 1.0f : -1.0f;
+ c.vx_x = c.vy_y = c.cvx = c.cvy = 0;
+ c.cx = c.tx + c.x_offset, c.cy = c.ty;
+ keep_in_scene(&c.cx, &c.cy);
+ c.stick_x = c.stick_y = true;
+ c.prev_hx = h->body.x, c.prev_hy = h->body.y;
+ g_cam_x = c.cx, g_cam_y = c.cy;
+}
+
+void cam_freeze(void) {
+ c.mode = CM_FROZEN;
+ c.tmode = TM_FREE;
+}
diff --git a/games/hollowknight/src/data.bin b/games/hollowknight/src/data.bin
index 670fbaa7..8c7b58db 100644
Binary files a/games/hollowknight/src/data.bin and b/games/hollowknight/src/data.bin differ
diff --git a/games/hollowknight/src/game.c b/games/hollowknight/src/game.c
index 69cb8d1b..230690d0 100644
--- a/games/hollowknight/src/game.c
+++ b/games/hollowknight/src/game.c
@@ -7,6 +7,8 @@ static uint8_t inside[MAX_ENTS / 8]; /* the triggers the Knight is in */
void game_new(void) {
memset(&g_pd, 0, sizeof g_pd);
+ memset(&g_game, 0, sizeof g_game);
+ g_game.time_scale = 1;
g_pd.health = g_pd.max_health = 5;
g_pd.max_mp = 99;
g_pd.can_dash = false;
@@ -19,6 +21,7 @@ bool game_enter(int room, float x, float y, bool facing_right) {
hero_init(x, y, facing_right);
cam_init();
world_hero_in_position();
+ g_game.hazard_x = x, g_game.hazard_y = y, g_game.hazard_facing_right = facing_right;
return true;
}
@@ -59,7 +62,9 @@ static void triggers_tick(void) {
for (int i = 0; i < n; i++) {
const Ent *e = &es[i];
if (e->type != ENT_CAMLOCK && e->type != ENT_GATE && e->type != ENT_HAZARD_TRIGGER && e->type != ENT_MASK) continue;
- bool in = x1 > e->x0 && x0 < e->x1 && y1 > e->y0 && y0 < e->y1;
+ bool in = false;
+ for (int j = i; j < n && (j == i || es[j].type == ENT_BOX); j++)
+ in |= x1 > es[j].x0 && x0 < es[j].x1 && y1 > es[j].y0 && y0 < es[j].y1;
bool was = inside[i >> 3] >> (i & 7) & 1;
if (in) inside[i >> 3] |= (uint8_t)(1 << (i & 7));
else inside[i >> 3] &= (uint8_t)~(1 << (i & 7));
@@ -67,15 +72,96 @@ static void triggers_tick(void) {
}
}
-void game_tick(uint32_t keys) {
+/* ---------------------------------------------------------------- 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;
+}
+
+static void freeze_tick(float real_dt) {
+ Game *g = &g_game;
+ 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();
+ }
+ }
+}
+
+/* the camera's fades (its Blanker): to black and back */
+void game_fade(float to, float time, float delay) {
+ Game *g = &g_game;
+ g->fade_from = g->fade, g->fade_to = to, g->fade_t = 0, g->fade_time = time, g->fade_delay = delay;
+}
+
+static void fade_tick(void) {
+ Game *g = &g_game;
+ if (g->fade_delay > 0) {
+ g->fade_delay -= 0.02f;
+ return;
+ }
+ if (g->fade == g->fade_to) return;
+ g->fade_t += 0.02f;
+ float k = g->fade_time <= 0 || g->fade_t >= g->fade_time ? 1 : g->fade_t / g->fade_time;
+ g->fade = g->fade_from + (g->fade_to - g->fade_from) * k;
+ g_screen_fade = (uint8_t)(g->fade * 255 + 0.5f);
+}
+
+/* PlayerDeadFromHazard: the camera stops, the screen goes black, the Knight comes back at the hazard marker */
+enum { HZ_NONE, HZ_NEXT_FRAME, HZ_FADING };
+void game_player_dead_from_hazard(void) { g_game.hazard_phase = HZ_NEXT_FRAME, g_game.hazard_t = 0; }
+
+static void hazard_tick(void) {
+ Game *g = &g_game;
+ if (g->hazard_phase == HZ_NEXT_FRAME) {
+ cam_freeze();
+ game_fade(1, 0.75f, 0); /* (HAZARD FADE) */
+ g->hazard_phase = HZ_FADING, g->hazard_t = 0;
+ } else if (g->hazard_phase == HZ_FADING) {
+ g->hazard_t += 0.02f;
+ if (g->hazard_t >= 0.8f) {
+ g->hazard_phase = HZ_NONE;
+ hero_hazard_respawn();
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- a tick: 1/50 s of real time */
+static void step(uint32_t keys) {
g_game.time += 0.02f;
hero_fixed(keys);
triggers_tick();
+ hero_check_damage();
hero_update();
world_tick();
+ hazard_tick();
+ fade_tick();
+ hero_late_update();
cam_tick();
}
+void game_tick(uint32_t keys) {
+ Game *g = &g_game;
+ freeze_tick(0.02f);
+ /* (game time runs at the time scale: frozen, no steps) */
+ g->step_acc += 0.02f * g->time_scale;
+ if (g->step_acc >= 0.02f - 1e-6f) {
+ g->step_acc -= 0.02f;
+ step(keys);
+ }
+}
+
void game_draw(void) {
hero_draw();
gfx_frame();
diff --git a/games/hollowknight/src/game.h b/games/hollowknight/src/game.h
index 69e73b2a..3200f05d 100644
--- a/games/hollowknight/src/game.h
+++ b/games/hollowknight/src/game.h
@@ -16,7 +16,9 @@ typedef struct {
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 };
+enum { ENT_CAMLOCK = 1, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK, ENT_DAMAGE, ENT_SHAPE,
+ ENT_BOX }; /* (shape, box: more of the record before) */
+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 */
enum { CL_PREVENT_UP = 1, CL_PREVENT_DOWN = 2, CL_MAX_PRIORITY = 4 };
enum { G_DOOR = 1, G_ENTER_RIGHT = 2, G_ENTER_LEFT = 4, G_DONT_WALK_OUT = 8, G_NON_HAZARD = 16 };
@@ -44,9 +46,21 @@ const Ent *room_ents(int *n);
typedef struct {
bool paused;
float time;
+ float time_scale; /* (Time.timeScale: freezes when the Knight is hit) */
+ float step_acc;
float hazard_x, hazard_y; /* where a hazard sends the Knight back to */
bool hazard_facing_right;
+ /* GameManager's coroutines */
+ uint8_t freeze_phase;
+ float freeze_t, freeze_from;
+ 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_player_dead_from_hazard(void);
+void game_fade(float to, float time, float delay);
extern Game g_game;
/* ---------------------------------------------------------------- the Knight (hero.c) */
@@ -83,6 +97,10 @@ typedef struct {
float transition_vx, transition_vy;
bool accepting_input, control_relinquished, doing_hazard_respawn, landed_event;
bool touching_wall_l, touching_wall_r;
+ bool hidden, hit_buffered;
+ int8_t buffered_side, buffered_damage, buffered_hazard;
+ float invuln_freeze, invuln_time, pulse_t, recoil_timer2, respawn_timer;
+ bool invuln_routine, pulsing, pulse_reverse, respawning;
int8_t thunk_dir;
bool thunk_hit;
float thunk_timer;
@@ -103,6 +121,11 @@ void hero_recoil_right(void);
void hero_recoil_down(void);
void hero_bounce(void);
void hero_finished_entering_scene(void);
+void hero_take_damage(int side, int damage, int hazard); /* (side: where the damage comes from, SIDE_LEFT/RIGHT) */
+void hero_recoil_unfreeze(void); /* the end of StartRecoil, after the freeze */
+void 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) */
/* the nail's slashes (NailSlash), children of the Knight */
void slash_start(int kind);
@@ -121,5 +144,7 @@ void game_draw(void);
/* ---------------------------------------------------------------- the camera (camera.c) */
void cam_init(void);
void cam_tick(void);
+void cam_snap_to_hero(void); /* (after a respawn) */
+void cam_freeze(void); /* FreezeInPlace (both) */
void cam_lock(int ent); /* CameraController.LockToArea, the hero entering the area's trigger */
void cam_release(int ent); /* ReleaseLock */
diff --git a/games/hollowknight/src/gfx.c b/games/hollowknight/src/gfx.c
index 3fc5d649..45a9b12c 100644
--- a/games/hollowknight/src/gfx.c
+++ b/games/hollowknight/src/gfx.c
@@ -102,19 +102,32 @@ 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) */
+#define DYN_TINT 240
+static uint8_t dyn_tints[256 - DYN_TINT][4];
+static inline const uint8_t *tint_rgba(int tint) { return tint >= DYN_TINT ? dyn_tints[tint - DYN_TINT] : g_room.tints + 4 * tint; }
+
+uint8_t gfx_dyn_tint(int slot, uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
+ uint8_t *t = dyn_tints[slot & 15];
+ t[0] = r, t[1] = g, t[2] = b, t[3] = a;
+ return (uint8_t)(DYN_TINT + (slot & 15));
+}
/* the instance's alpha: its tint's, times its render group's */
static inline uint32_t inst_alpha(const Inst *in) {
- uint32_t a = g_room.tints[4 * in->tint + 3];
- return in->group ? (a * g_group_alpha[in->group] + 127) / 255 : a;
+ uint32_t a = tint_rgba(in->tint)[3];
+ return in->group ? (a * g_group_alpha[in->group & (MAX_GROUPS - 1)] + 127) / 255 : a;
}
static int pal_get(uint16_t tex, uint8_t tint, uint8_t flags, uint32_t alpha) {
- uint32_t key = (uint32_t)tex << 16 | alpha << 8 | (uint32_t)tint << 1 | ((flags & F_LIT) ? 1 : 0);
+ /* (tex << 17: solid colors' TEX_NONE comes out as 0xFFFE....; black textures' keys below those) */
+ uint32_t key = (uint32_t)tex << 17 | alpha << 9 | (uint32_t)tint << 1 | ((flags & F_LIT) ? 1 : 0);
if (tex != TEX_NONE) {
const TexRec *r = tex_rec(tex);
if (r->fmt >= FMT_SOFT) return 0; /* (no colors: soft_get) */
- if (r->fmt == FMT_ALPHA2) key = 0xFFFE0000u | alpha; /* black: only the alpha matters */
+ if (r->fmt == FMT_ALPHA2) key = 0xFFFC0000u | alpha; /* black: only the alpha matters */
}
for (int i = 0; i < NPAL; i++)
if (pals[i].key == key) {
@@ -133,7 +146,7 @@ static int pal_get(uint16_t tex, uint8_t tint, uint8_t flags, uint32_t alpha) {
pal_hand = (s + 1) % NPAL;
Pal *p = &pals[s];
p->key = key, p->frame = pal_frame;
- const uint8_t *t = g_room.tints + 4 * tint;
+ const uint8_t *t = tint_rgba(tint);
p->solid = alpha == 255;
float tr = t[0] / 255.0f, tg = t[1] / 255.0f, tb = t[2] / 255.0f, ta = alpha / 255.0f;
if (flags & F_LIT) {
@@ -180,7 +193,7 @@ uint32_t g_soft_misses;
static const uint32_t *soft_get(uint16_t tex, uint8_t tint, uint8_t flags, uint32_t alpha) {
const TexRec *rr = tex_rec(tex);
if (rr->fmt == FMT_SOFTA) return (const uint32_t *)(const void *)(section(SEC_SOFT) + rr->pal_off); /* (alpha, in place) */
- uint32_t key = (uint32_t)tex << 16 | alpha << 8 | (uint32_t)tint << 1 | ((flags & F_LIT) ? 1 : 0);
+ uint32_t key = (uint32_t)tex << 17 | alpha << 9 | (uint32_t)tint << 1 | ((flags & F_LIT) ? 1 : 0);
for (int i = 0; i < nsoft; i++)
if (soft_ent[i].key == key) {
soft_ent[i].frame = pal_frame;
@@ -206,7 +219,7 @@ static const uint32_t *soft_get(uint16_t tex, uint8_t tint, uint8_t flags, uint3
uint32_t *px = soft_pool + soft_top;
const uint8_t *src = section(SEC_SOFT) + r->pal_off;
lz_decode(src + 4, rd32(src), (uint8_t *)px, (uint32_t)n * 4);
- const uint8_t *t = g_room.tints + 4 * tint;
+ const uint8_t *t = tint_rgba(tint);
float tr = t[0] / 255.0f, tg = t[1] / 255.0f, tb = t[2] / 255.0f, ta = alpha / 255.0f;
if (flags & F_LIT) {
const float *am = g_room.h->ambient;
@@ -729,7 +742,7 @@ __attribute__((noinline)) static void draw_item(int idx, Item *it, int sy0, int
soft = soft_get(in->tex, in->tint, in->flags, inst_alpha(in));
if (!soft) return;
if (c.r->fmt == FMT_SOFTA) {
- const uint8_t *t = g_room.tints + 4 * in->tint;
+ const uint8_t *t = tint_rgba(in->tint);
float tr = t[0] / 255.0f, tg = t[1] / 255.0f, tb = t[2] / 255.0f;
if (in->flags & F_LIT) tr *= g_room.h->ambient[0], tg *= g_room.h->ambient[1], tb *= g_room.h->ambient[2];
uint32_t base = c.r->map_off;
@@ -828,7 +841,7 @@ static void draw_bg_item(Item *it) {
soft = soft_get(in->tex, in->tint, in->flags, inst_alpha(in));
if (!soft) return;
if (r->fmt == FMT_SOFTA) {
- const uint8_t *t = g_room.tints + 4 * in->tint;
+ const uint8_t *t = tint_rgba(in->tint);
float tr = t[0] / 255.0f, tg = t[1] / 255.0f, tb = t[2] / 255.0f;
if (in->flags & F_LIT) tr *= g_room.h->ambient[0], tg *= g_room.h->ambient[1], tb *= g_room.h->ambient[2];
uint32_t base = r->map_off;
@@ -927,6 +940,16 @@ __attribute__((noinline)) static void finish_strip(int sy0, int rows) {
}
#endif
uint16_t *out = (uint16_t *)(void *)arb; /* in place: each 16-bit pixel goes where its 32-bit one was read */
+ if (g_screen_fade) {
+ /* (the camera fading to black: the light, and the background, dimmed) */
+ uint32_t k = 255u - g_screen_fade;
+ for (int p = 0; p < NPX; p++) {
+ uint32_t rb = arb[p];
+ arb[p] = ((rb >> 16) * k / 255) << 16 | ((rb & 0xFFFF) * k / 255);
+ ag[p] = (uint16_t)(ag[p] * k / 255);
+ trans[p] = (uint8_t)(trans[p] * k / 255);
+ }
+ }
for (int y = 0; y < rows; y++) {
int sy = sy0 + y;
if (bg_on) {
diff --git a/games/hollowknight/src/hero.c b/games/hollowknight/src/hero.c
index 589589bc..45c70b42 100644
--- a/games/hollowknight/src/hero.c
+++ b/games/hollowknight/src/hero.c
@@ -94,6 +94,10 @@ static bool check_for_bump(int left) {
/* ---------------------------------------------------------------- state */
static void anim_update_state(int s);
+static void invulnerable_tick(void);
+static void respawn_tick(void);
+static void die_from_hazard(void);
+void hero_die(void);
static bool can_exit_no_input(void) { return !g_hero.doing_hazard_respawn && !g_hero.cs.dead; }
@@ -780,6 +784,8 @@ void hero_fixed(uint32_t keys) {
void hero_update(void) {
Hero *h = &g_hero;
update();
+ invulnerable_tick();
+ respawn_tick();
if (h->anim_control) animation();
h->anim.events = 0;
anim_update(&h->anim, DT);
@@ -791,12 +797,22 @@ void hero_update(void) {
void hero_draw(void) {
Hero *h = &g_hero;
+ if (h->hidden) return;
Inst in;
- sprite_inst(h->anim.sprite, h->body.x, h->body.y, 0.004f, h->cs.facing_right ? -1.0f : 1.0f, 1, 0, &in);
+ /* (InvulnerablePulse: the color towards its invulnerable one) */
+ uint8_t tint = 0;
+ if (h->pulsing) tint = gfx_dyn_tint(0, 255, 255, 255, (uint8_t)(255 - 255 * 0.5f * h->pulse_t / 0.1f));
+ sprite_inst(h->anim.sprite, h->body.x, h->body.y, 0.004f, h->cs.facing_right ? -1.0f : 1.0f, 1, tint, &in);
gfx_actor(&in, SORT_KEY(0, 0));
slash_draw();
}
+/* (the Knight dying: for now, as a hazard) */
+void hero_die(void) {
+ g_pd.health = g_pd.max_health;
+ die_from_hazard();
+}
+
/* ---------------------------------------------------------------- NailSlash: the slash effect, a child of the Knight */
static const struct {
int clip;
@@ -863,10 +879,223 @@ void slash_draw(void) {
void fx_dash_burst(float x, float y, bool facing_right, bool on_ground) { (void)x, (void)y, (void)facing_right, (void)on_ground; }
+/* FinishedEnteringScene */
void hero_finished_entering_scene(void) {
Hero *h = &g_hero;
- h->transition_state = TS_WAITING_TO_TRANSITION;
+ h->doing_hazard_respawn = false;
h->cs.transitioning = false;
- h->state = HS_IDLE;
- set_state(HS_GROUNDED);
+ h->transition_state = TS_WAITING_TO_TRANSITION;
+ /* SetStartingMotionState */
+ h->move_input = 0;
+ h->cs.touching_wall = false;
+ if (hero_touching_ground()) {
+ h->cs.on_ground = true;
+ set_state(HS_GROUNDED);
+ h->air_dashed = false;
+ } else {
+ h->cs.on_ground = false;
+ set_state(HS_AIRBORNE);
+ }
+ anim_update_state(h->state);
+ affected_by_gravity(true);
+ h->damage_mode = DAMAGE_FULL;
+ h->accepting_input = true;
+}
+
+/* ---------------------------------------------------------------- damage (TakeDamage, StartRecoil, Invulnerable) */
+#define RECOIL_VELOCITY 15.0f
+#define INVUL_TIME 1.3f
+#define DAMAGE_FREEZE_DOWN 0.001f
+#define PULSE_DURATION 0.1f
+
+static bool can_take_damage(void) {
+ Hero *h = &g_hero;
+ return h->damage_mode != DAMAGE_NONE && h->transition_state == TS_WAITING_TO_TRANSITION && !h->cs.invulnerable &&
+ !h->cs.recoiling && !h->cs.dead && !h->cs.hazard_death;
+}
+
+static void start_invulnerable(float duration) {
+ Hero *h = &g_hero;
+ if (!h->invuln_routine) {
+ h->cs.invulnerable = true;
+ h->invuln_freeze = DAMAGE_FREEZE_DOWN, h->invuln_time = duration;
+ h->invuln_routine = true;
+ } else if (h->invuln_freeze + h->invuln_time < duration + DAMAGE_FREEZE_DOWN) {
+ if (h->invuln_freeze > 0) h->invuln_freeze = DAMAGE_FREEZE_DOWN;
+ else duration += DAMAGE_FREEZE_DOWN;
+ h->invuln_time = duration;
+ }
+}
+
+/* (the Invulnerable coroutine, and InvulnerablePulse) */
+static void invulnerable_tick(void) {
+ Hero *h = &g_hero;
+ if (!h->invuln_routine) return;
+ if (h->invuln_freeze > 0) {
+ h->invuln_freeze -= DT;
+ if (h->invuln_freeze <= 0) h->pulsing = true, h->pulse_t = 0;
+ return;
+ }
+ h->invuln_time -= DT;
+ if (h->pulsing) {
+ if (!h->pulse_reverse) {
+ h->pulse_t += DT;
+ if (h->pulse_t > PULSE_DURATION) h->pulse_t = PULSE_DURATION, h->pulse_reverse = true;
+ } else {
+ h->pulse_t -= DT;
+ if (h->pulse_t < 0) h->pulse_t = 0, h->pulse_reverse = false;
+ }
+ }
+ if (h->invuln_time <= 0) {
+ h->pulsing = false, h->pulse_t = 0;
+ h->cs.invulnerable = false;
+ h->cs.recoiling = false;
+ h->invuln_routine = false;
+ }
+}
+
+static void die_from_hazard(void) {
+ Hero *h = &g_hero;
+ if (h->cs.hazard_death) return;
+ set_state(HS_NO_INPUT);
+ h->cs.hazard_death = true;
+ reset_motion();
+ h->hard_landing_timer = 0;
+ affected_by_gravity(false);
+ h->hidden = true;
+ game_player_dead_from_hazard();
+}
+
+static void start_recoil(int side) {
+ Hero *h = &g_hero;
+ if (h->cs.recoiling) return;
+ reset_motion();
+ affected_by_gravity(false);
+ if (side == SIDE_LEFT) {
+ h->recoil_vx = RECOIL_VELOCITY, h->recoil_vy = RECOIL_VELOCITY * 0.5f;
+ if (h->cs.facing_right) flip_sprite();
+ } else if (side == SIDE_RIGHT) {
+ h->recoil_vx = -RECOIL_VELOCITY, h->recoil_vy = RECOIL_VELOCITY * 0.5f;
+ if (!h->cs.facing_right) flip_sprite();
+ } else
+ h->recoil_vx = h->recoil_vy = 0;
+ set_state(HS_NO_INPUT);
+ h->cs.recoil_frozen = true;
+ start_invulnerable(INVUL_TIME);
+ game_freeze_moment(); /* (then hero_recoil_unfreeze) */
+}
+
+void hero_recoil_unfreeze(void) {
+ g_hero.cs.recoil_frozen = false;
+ g_hero.cs.recoiling = true;
+}
+
+void hero_take_damage(int side, int damage, int hazard) {
+ Hero *h = &g_hero;
+ if (damage <= 0) return;
+ if (can_take_damage()) {
+ if (h->damage_mode == DAMAGE_HAZARD_ONLY && hazard == HAZ_NORMAL) return;
+ cancel_attack();
+ if (h->cs.recoiling_left || h->cs.recoiling_right) cancel_recoil_horizontal();
+ if (h->cs.bouncing) cancel_bounce(), h->body.vy = 0;
+ g_pd.health = (int8_t)(g_pd.health > damage ? g_pd.health - damage : 0);
+ if (g_pd.health == 0) {
+ hero_die();
+ return;
+ }
+ if (hazard == HAZ_SPIKES || hazard == HAZ_ACID || hazard == HAZ_PIT) die_from_hazard();
+ else if (hazard != HAZ_LAVA) start_recoil(side);
+ } else if (h->cs.invulnerable && !h->cs.hazard_death && (hazard == HAZ_SPIKES || hazard == HAZ_ACID)) {
+ /* (spikes and acid hurt even through invulnerability) */
+ g_pd.health = (int8_t)(g_pd.health > damage ? g_pd.health - damage : 0);
+ if (g_pd.health == 0) hero_die();
+ else die_from_hazard();
+ }
+}
+
+/* HeroController.HazardRespawn: back at the hazard marker, standing */
+void hero_hazard_respawn(void) {
+ Hero *h = &g_hero;
+ h->doing_hazard_respawn = true;
+ set_state(HS_NO_INPUT);
+ reset_look();
+ h->cs.hazard_death = false;
+ h->cs.on_ground = true;
+ h->cs.hazard_respawning = true;
+ reset_motion();
+ h->hard_landing_timer = 0;
+ reset_attacks();
+ reset_input();
+ h->cs.recoiling = false;
+ h->air_dashed = false;
+ /* FindGroundPoint (extended) */
+ PhysHit hit;
+ float x = g_game.hazard_x, y = g_game.hazard_y;
+ if (phys_ray(x, y, 0, -1, 50, CF_TERRAIN, &hit)) y = hit.y + h->body.hy - h->body.oy + 0.01f;
+ h->body.x = x, h->body.y = y;
+ h->body.ncontacts = 0;
+ h->hidden = false;
+ if (g_game.hazard_facing_right) face_right();
+ else face_left();
+ world_hero_in_position();
+ start_invulnerable(INVUL_TIME * 2);
+ game_fade(0, 0.5f, 0.1f); /* (the camera's RESPAWN: FadeIn) */
+ h->anim_control = false;
+ anim_play(&h->anim, CLIP_KNIGHT_HAZARD_RESPAWN);
+ h->respawn_timer = clip_duration(CLIP_KNIGHT_HAZARD_RESPAWN);
+ h->respawning = true;
+ cam_snap_to_hero();
+}
+
+static void respawn_tick(void) {
+ Hero *h = &g_hero;
+ if (!h->respawning) return;
+ h->respawn_timer -= DT;
+ if (h->respawn_timer > 0) return;
+ h->respawning = false;
+ h->cs.hazard_respawning = false;
+ h->anim_control = true;
+ hero_finished_entering_scene();
+}
+
+/* HeroBox: what touches the Knight's hurt box (hazards; enemies through world.c) */
+void hero_check_damage(void) {
+ Hero *h = &g_hero;
+ if (h->hidden || h->cs.dead) return;
+ float k = h->cs.facing_right ? -1.0f : 1.0f;
+ float cx = h->body.x + 0.0055733f * k, cy = h->body.y - 0.6942673f;
+ float x0 = cx - 0.2277069f, x1 = cx + 0.2277069f, y0 = cy - 0.5848932f, y1 = cy + 0.5848932f;
+ int n;
+ const Ent *es = room_ents(&n);
+ for (int i = 0; i < n; i++) {
+ const Ent *e = &es[i];
+ if (e->type != ENT_DAMAGE) continue;
+ if (!(x1 > e->x0 && x0 < e->x1 && y1 > e->y0 && y0 < e->y1)) continue;
+ if (e->a) {
+ /* (its outline: 4 points a record after it) */
+ float pts[16];
+ int np = (int)e->p2;
+ for (int k = 0; k < np && k < 8; k++) {
+ const Ent *r = &es[i + 1 + k / 4];
+ const float *f = &r->x0;
+ pts[2 * k] = f[2 * (k & 3)], pts[2 * k + 1] = f[2 * (k & 3) + 1];
+ }
+ if (!box_meets_shape(x0, y0, x1, y1, pts, np < 8 ? np : 8)) continue;
+ }
+ int side = (e->x0 + e->x1) / 2 > h->body.x ? SIDE_RIGHT : SIDE_LEFT;
+ int hazard = (int)e->p0, damage = (int)e->p1;
+ if (hazard == HAZ_NONE) {
+ /* (buffered to LateUpdate) */
+ h->hit_buffered = true, h->buffered_side = (int8_t)side, h->buffered_damage = (int8_t)damage, h->buffered_hazard = (int8_t)hazard;
+ } else
+ hero_take_damage(side, damage, hazard);
+ }
+}
+
+void hero_late_update(void) {
+ Hero *h = &g_hero;
+ if (h->hit_buffered) {
+ h->hit_buffered = false;
+ hero_take_damage(h->buffered_side, h->buffered_damage, h->buffered_hazard);
+ }
}
diff --git a/games/hollowknight/src/hk.h b/games/hollowknight/src/hk.h
index 6c43ef2d..b4cfde4a 100644
--- a/games/hollowknight/src/hk.h
+++ b/games/hollowknight/src/hk.h
@@ -160,6 +160,8 @@ typedef struct {
bool phys_ray(float x, float y, float dx, float dy, float dist, uint8_t mask, PhysHit *hit);
uint8_t phys_col_flags(int col);
bool phys_tile_solid(int x, int y);
+/* a box and a convex polygon (n points, x y pairs): do they overlap? */
+bool box_meets_shape(float x0, float y0, float x1, float y1, const float *pts, int n);
enum { EV_ENTER, EV_STAY, EV_EXIT };
typedef struct {
@@ -188,4 +190,6 @@ void gfx_frame(void); /* draws the room at the camera into the screen
/* a sprite of the Knight, an enemy, an effect... for the next frame, among the room's by its sorting layer and order
* (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 */
+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/phys.c b/games/hollowknight/src/phys.c
index 12811e6e..57cc342d 100644
--- a/games/hollowknight/src/phys.c
+++ b/games/hollowknight/src/phys.c
@@ -273,3 +273,29 @@ void body_step(Body *b, float dt) {
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];
}
+
+/* a box (x0, y0, x1, y1) and a convex polygon of n points: do they overlap (separating axes)? */
+bool box_meets_shape(float x0, float y0, float x1, float y1, const float *pts, int n) {
+ if (n < 3) return true;
+ for (int i = 0; i < n; i++) {
+ float ax = pts[2 * i], ay = pts[2 * i + 1], bx = pts[2 * ((i + 1) % n)], by = pts[2 * ((i + 1) % n) + 1];
+ float nx = -(by - ay), ny = bx - ax;
+ if (nx == 0 && ny == 0) continue;
+ float pmin = 1e30f, pmax = -1e30f;
+ for (int j = 0; j < n; j++) {
+ float d = pts[2 * j] * nx + pts[2 * j + 1] * ny;
+ if (d < pmin) pmin = d;
+ if (d > pmax) pmax = d;
+ }
+ float c[4] = {x0 * nx + y0 * ny, x1 * nx + y0 * ny, x0 * nx + y1 * ny, x1 * nx + y1 * ny};
+ float bmin = c[0], bmax = c[0];
+ for (int k = 1; k < 4; k++) bmin = c[k] < bmin ? c[k] : bmin, bmax = c[k] > bmax ? c[k] : bmax;
+ if (bmax < pmin || bmin > pmax) return false;
+ }
+ /* (and the box's own axes) */
+ float px0 = 1e30f, px1 = -1e30f, py0 = 1e30f, py1 = -1e30f;
+ for (int j = 0; j < n; j++) {
+ px0 = fminf(px0, pts[2 * j]), px1 = fmaxf(px1, pts[2 * j]), py0 = fminf(py0, pts[2 * j + 1]), py1 = fmaxf(py1, pts[2 * j + 1]);
+ }
+ return !(px1 < x0 || px0 > x1 || py1 < y0 || py0 > y1);
+}
diff --git a/games/hollowknight/src/world.c b/games/hollowknight/src/world.c
index 1f420cf3..34adf1a5 100644
--- a/games/hollowknight/src/world.c
+++ b/games/hollowknight/src/world.c
@@ -62,13 +62,6 @@ static void mask_idle(const Ent *e, EntState *s) {
s->state = M_IDLE;
}
-static void mask_tick(const Ent *e, EntState *s) {
- if (s->state == M_PAUSE && hero_in_position) {
- s->timer += DT;
- if (s->timer >= e->p1) mask_idle(e, s);
- }
-}
-
static void mask_trigger(const Ent *e, EntState *s, int kind) {
float t = e->p0;
switch (e->flags) {
@@ -118,7 +111,16 @@ void world_enter(void) {
}
}
-void world_hero_in_position(void) { hero_in_position = true; }
+/* (Pause's WaitForHeroInPosition: the masks start as the Knight is placed; its Wait only counts when it was placed
+ * already) */
+void world_hero_in_position(void) {
+ if (hero_in_position) return;
+ hero_in_position = true;
+ int n;
+ const Ent *e = room_ents(&n);
+ for (int i = 0; i < n && i < MAX_ENTS; i++)
+ if (e[i].type == ENT_MASK && es[i].state == M_PAUSE) mask_idle(&e[i], &es[i]);
+}
void world_trigger(int i, int kind) {
int n;
@@ -126,10 +128,4 @@ void world_trigger(int i, int kind) {
if (e->type == ENT_MASK) mask_trigger(e, &es[i], kind);
}
-void world_tick(void) {
- int n;
- const Ent *e = room_ents(&n);
- for (int i = 0; i < n && i < MAX_ENTS; i++)
- if (e[i].type == ENT_MASK) mask_tick(&e[i], &es[i]);
- fades_tick();
-}
+void world_tick(void) { fades_tick(); }
diff --git a/games/hollowknight/tests/play.c b/games/hollowknight/tests/play.c
index 8584b08d..c32c2ca2 100644
--- a/games/hollowknight/tests/play.c
+++ b/games/hollowknight/tests/play.c
@@ -78,7 +78,23 @@ int main(int argc, char **argv) {
}
}
}
- if (shot) game_draw(), host_shot(shot);
+ if (shot) {
+ int nf = getenv("NF") ? atoi(getenv("NF")) : 3;
+ for (int i = 0; i < nf; i++) game_draw(); /* (the tile cache warm, as while playing) */
+ host_shot(shot);
+ }
+ if (getenv("HKGROUPS")) {
+ printf("fade %d items %u cam %.2f,%.2f groups:", g_screen_fade, g_gfx_items, g_cam_x, g_cam_y);
+ for (int g = 1; g < MAX_GROUPS; g++)
+ if (g_group_alpha[g] != 255) printf(" %d=%d", g, g_group_alpha[g]);
+ printf("\n");
+ int n;
+ const Ent *e = room_ents(&n);
+ for (int i = 0; i < n; i++)
+ if (e[i].type == ENT_MASK || e[i].type == ENT_BOX)
+ printf("ent %d type %d flags %d group %d,%d box %.1f,%.1f %.1f,%.1f p %.2f %.2f %.2f %.2f\n", i, e[i].type, e[i].flags,
+ e[i].group, e[i].group2, e[i].x0, e[i].y0, e[i].x1, e[i].y1, e[i].p0, e[i].p1, e[i].p2, e[i].p3);
+ }
printf("end: pos %.3f,%.3f state %d\n", g_hero.body.x, g_hero.body.y, g_hero.state);
return 0;
}
diff --git a/games/hollowknight/tools/coll.py b/games/hollowknight/tools/coll.py
index c0f80263..7ecfa4b5 100644
--- a/games/hollowknight/tools/coll.py
+++ b/games/hollowknight/tools/coll.py
@@ -143,7 +143,13 @@ def room(d, w, h):
if a != b:
segs.append((a[0], a[1], b[0], b[1], ci))
solid = _tilemap_solid(tm_edges, w, h)
- want, got = _unit_edges(tm_edges), tile_faces(solid)
+ # (the tilemap's chunks also outline their borders: edges inside solid ground, no faces)
+ th, tw = solid.shape
+ def s(x, y):
+ return 0 <= x < tw and 0 <= y < th and solid[y, x]
+ want = {(k, x, y) for k, x, y in _unit_edges(tm_edges)
+ if not (s(x - 1, y) and s(x, y) if k == "v" else s(x, y - 1) and s(x, y))}
+ got = tile_faces(solid)
if want != got:
print("coll: tilemap faces differ: %d missing, %d extra" % (len(want - got), len(got - want)))
return solid, segs, cols
diff --git a/games/hollowknight/tools/ents.py b/games/hollowknight/tools/ents.py
index fb2cc5d7..32d22452 100644
--- a/games/hollowknight/tools/ents.py
+++ b/games/hollowknight/tools/ents.py
@@ -5,7 +5,8 @@ import struct
import numpy as np
# record types (src/game.h: ENT_*)
-ENT_CAMLOCK, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK = 1, 2, 3, 4, 5, 6
+ENT_CAMLOCK, ENT_GATE, ENT_HAZARD_MARKER, ENT_RESPAWN, ENT_HAZARD_TRIGGER, ENT_MASK, ENT_DAMAGE, ENT_SHAPE, ENT_BOX = \
+ 1, 2, 3, 4, 5, 6, 7, 8, 9
# masks (the unmasker, remasker and remasker_inverse FSMs)
MK_SECRET, MK_REMASK, MK_SIMPLE = 1, 2, 4
# flags
@@ -65,11 +66,42 @@ def _box(o, c):
return (min(xs), min(ys), max(xs), max(ys))
+def _shape(o, c):
+ """A collider's outline in world units (a box's four corners, a polygon's first path)."""
+ v = c["v"]
+ m = np.array(o["m3"]).reshape(3, 3)
+ p = np.array(o["pos"])
+ off = (v["m_Offset"]["x"], v["m_Offset"]["y"])
+ if c["type"] == "BoxCollider2D":
+ sx, sy = v["m_Size"]["x"] / 2, v["m_Size"]["y"] / 2
+ pts = [(-sx, -sy), (sx, -sy), (sx, sy), (-sx, sy)]
+ elif c["type"] == "PolygonCollider2D":
+ paths = v["m_Points"]["m_Paths"] if isinstance(v["m_Points"], dict) else v["m_Points"]
+ pts = [(q["x"], q["y"]) for q in paths[0]]
+ else:
+ return None
+ return [tuple((m @ np.array([x + off[0], y + off[1], 0.0]) + p)[:2]) for x, y in pts]
+
+
+def _is_axis_box(pts):
+ xs, ys = sorted(set(round(q[0], 4) for q in pts)), sorted(set(round(q[1], 4) for q in pts))
+ return len(pts) == 4 and len(xs) == 2 and len(ys) == 2
+
+
+def _triggers(o):
+ """The boxes of the object's trigger colliders (the events come from any of them)."""
+ return [_box(o, c) for c in o["c"] if c["type"] in ("BoxCollider2D", "PolygonCollider2D", "CircleCollider2D") and
+ c.get("v") and c["v"].get("m_IsTrigger") and c["v"].get("m_Enabled", 1)]
+
+
def _trigger(o):
- for c in o["c"]:
- if c["type"] in ("BoxCollider2D", "PolygonCollider2D", "CircleCollider2D") and c.get("v") and c["v"].get("m_IsTrigger"):
- return _box(o, c)
- return None
+ t = _triggers(o)
+ return t[0] if t else None
+
+
+def _more_boxes(o):
+ """Records for the object's other trigger boxes: they follow its own."""
+ return [rec(ENT_BOX, box=b) for b in _triggers(o)[1:]]
def rec(type_, flags=0, box=(0, 0, 0, 0), p=(0, 0, 0, 0), a=0, group=0, group2=0, persist=NO_PERSIST, s0=0, s1=0):
@@ -195,6 +227,29 @@ def room(d, rooms, strings, persist, name):
persistent = any(c.get("class") == "PersistentBoolItem" for c in o["c"])
recs.append(rec(ENT_MASK, kind, box, (fade, pause, p2, p3), group=g, group2=g2,
persist=persist.id(name, o["path"]) if persistent else NO_PERSIST))
+ recs += _more_boxes(o)
+ classes = {c.get("class") for c in o["c"]}
+ dh = [c for c in o["c"] if c.get("class") == "DamageHero"]
+ if dh and not classes & {"HealthManager", "StalactiteControl"}:
+ # a hazard (spikes, acid): its colliders' outlines, as boxes or as shapes after it
+ v = dh[0].get("v") or {}
+ for c in o["c"]:
+ if c["type"] not in ("BoxCollider2D", "PolygonCollider2D") or not c.get("v") or not c["v"].get("m_Enabled", 1):
+ continue
+ pts = _shape(o, c)
+ if not pts:
+ continue
+ xs, ys = [q[0] for q in pts], [q[1] for q in pts]
+ box = (min(xs), min(ys), max(xs), max(ys))
+ if _is_axis_box(pts):
+ recs.append(rec(ENT_DAMAGE, box=box, p=(v.get("hazardType", 1), v.get("damageDealt", 1), 0, 0)))
+ else:
+ pts = pts[:8]
+ nrec = (len(pts) + 3) // 4
+ recs.append(rec(ENT_DAMAGE, box=box, p=(v.get("hazardType", 1), v.get("damageDealt", 1), len(pts), 0), a=nrec))
+ for i in range(nrec):
+ q = pts[4 * i:4 * i + 4] + [pts[-1]] * (4 - len(pts[4 * i:4 * i + 4]))
+ recs.append(rec(ENT_SHAPE, box=(q[0][0], q[0][1], q[1][0], q[1][1]), p=(q[2][0], q[2][1], q[3][0], q[3][1])))
for c in o["c"]:
cls, v = c.get("class"), c.get("v") or {}
if cls == "CameraLockArea":
@@ -204,6 +259,7 @@ def room(d, rooms, strings, persist, name):
fl = (CL_PREVENT_UP if v.get("preventLookUp") else 0) | (CL_PREVENT_DOWN if v.get("preventLookDown") else 0) | \
(CL_MAX_PRIORITY if v.get("maxPriority") else 0)
recs.append(rec(ENT_CAMLOCK, fl, box, (v["cameraXMin"], v["cameraYMin"], v["cameraXMax"], v["cameraYMax"])))
+ recs += _more_boxes(o)
elif cls == "TransitionPoint":
box = _trigger(o)
if box is None:
@@ -215,6 +271,7 @@ def room(d, rooms, strings, persist, name):
ti = rooms.index(target) if target in rooms else 0xFFFF
recs.append(rec(ENT_GATE, fl, box, (float(v.get("entryDelay", 0)), 0, 0, 0), a=ti, s0=strings.id(o["name"]),
s1=strings.id(v.get("entryPoint") or "")))
+ recs += _more_boxes(o)
elif cls == "HazardRespawnTrigger":
box = _trigger(o)
ref = v.get("respawnMarker")
@@ -228,5 +285,6 @@ def room(d, rooms, strings, persist, name):
if box is None or target not in marker_index:
continue
recs.append(rec(ENT_HAZARD_TRIGGER, box=box, a=marker_index[target]))
+ recs += _more_boxes(o)
assert ngroups[0] < 64, ngroups[0]
return recs, groups
diff --git a/games/hollowknight/tools/unity.py b/games/hollowknight/tools/unity.py
index f24d9226..b11874b3 100644
--- a/games/hollowknight/tools/unity.py
+++ b/games/hollowknight/tools/unity.py
@@ -165,8 +165,7 @@ def _dump(name):
v, _, _ = typetree.parse(o, sc)
ent["enabled"] = bool(v.get("m_Enabled", 1))
if sc.m_ClassName == "PlayMakerFSM":
- dfs = fsmdec.decode(v)
- ent["fsm"] = clean(dfs)
+ ent["fsm"] = clean(decode_fsm(o.assets_file, v))
else:
ent["v"] = clean({k: x for k, x in v.items() if k not in ("m_GameObject", "m_Enabled", "m_Script", "m_Name")})
except Exception as e:
@@ -190,6 +189,31 @@ def _dump(name):
return out
+def decode_fsm(f, v):
+ """A PlayMakerFSM's decoded FSM; one made from a template (FsmTemplate) takes the template's, with the
+ component's own variable values and name."""
+ t = v.get("fsmTemplate") or {}
+ tp = t.get("m_PathID", 0) if isinstance(t, dict) else 0
+ if tp:
+ try:
+ fid = t.get("m_FileID", 0)
+ tf = f if fid == 0 else asset_file(f.externals[fid - 1].path)
+ to = tf.objects[tp]
+ tmb = to.read(check_read=False)
+ tv, _, _ = typetree.parse(to, tmb.m_Script.read())
+ d = fsmdec.decode({"fsm": tv["fsm"]})
+ own = fsmdec.decode(v)
+ for k, val in (own.get("vars") or {}).items():
+ if k in d.get("vars", {}):
+ d["vars"][k] = val
+ d["name"] = own.get("name", d.get("name"))
+ d["template"] = S(tmb.m_Name) if hasattr(tmb, "m_Name") else "?"
+ return d
+ except Exception:
+ pass
+ return fsmdec.decode(v)
+
+
@functools.lru_cache(maxsize=None)
def scene(name):
"""A scene as a dict (cached as JSON in tools/cache)."""