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.

Sonic: the engine, Green Hill drawn with Sonic in it

Mason363007146220ba5
diff --git a/games/sonic/.gitignore b/games/sonic/.gitignore
new file mode 100644
index 00000000..342d9dda
--- /dev/null
+++ b/games/sonic/.gitignore
@@ -0,0 +1,2 @@
+output/
+build/
diff --git a/games/sonic/Makefile b/games/sonic/Makefile
new file mode 100644
index 00000000..b1e7e0ac
--- /dev/null
+++ b/games/sonic/Makefile
@@ -0,0 +1,79 @@
+# Sonic the Hedgehog (1991) on the NumWorks calculator.
+# make output/sonic.nwa
+# make check link it like the calculator does (output/sonic.bin)
+# make host build/play: the game on a computer, for tests and screenshots
+# make test the game played on a computer (tests/check.py, with the sanitizers)
+# make data src/data.bin, src/data.h and src/s1const.h from the Sonic Retro disassembly
+# (REF=its folder, see tools/fetch.py; Python 3)
+Q ?= @
+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>
+TOOLCHAIN ?=
+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)
+CC = $(BIN)arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded
+SIZE = $(BIN)arm-none-eabi-size
+BUILD_DIR = output
+REF ?=
+
+# the picture is drawn every frame at -O2; the game's logic is small at -Os
+HOT = src/vdp.c
+COLD = $(filter-out $(HOT) src/plat_host.c src/plat_eadk.c,$(wildcard src/*.c))
+COLD_OBJ = $(patsubst src/%.c,$(BUILD_DIR)/cold/%.o,$(COLD))
+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DDATA_BIN='"src/data.bin"'
+CFLAGS += -O2 -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean host test data
+build: $(BUILD_DIR)/sonic.nwa
+
+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)
+check: $(BUILD_DIR)/sonic.nwa
+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/sonic.bin
+ @echo "BIN $(BUILD_DIR)/sonic.bin: $$(wc -c < $(BUILD_DIR)/sonic.bin) bytes"
+
+$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)
+ $(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@
+
+$(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS)
+ @mkdir -p $(@D)
+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@
+
+$(BUILD_DIR)/sonic.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@
+ $(Q) $(STRIP) $@
+ $(Q) $(SIZE) $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+# on a computer: tests/play.c plays it with scripted keys and saves screenshots
+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST -DDATA_BIN='"src/data.bin"'
+HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined
+HOST_SRC = $(filter-out src/plat_eadk.c src/main.c,$(wildcard src/*.c))
+host: build/play
+build/play: $(HOST_SRC) src/main.c tests/play.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) src/main.c tests/play.c src/data.S -lm -o $@
+ @echo "HOST $@"
+
+test: build/play
+ python3 tests/check.py build/play
+
+data:
+ @test -n "$(REF)" || { echo "make data REF=<the folder tools/fetch.py filled>"; exit 1; }
+ python3 -I tools/pack.py $(REF)
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR) build/play build/shots
diff --git a/games/sonic/src/collide.c b/games/sonic/src/collide.c
new file mode 100644
index 00000000..2090db9c
--- /dev/null
+++ b/games/sonic/src/collide.c
@@ -0,0 +1,163 @@
+/* Collision with the level: the 16x16 block at a point, and the distance from a point to the
+ * surface in it (or in the next block) along one of the four directions, from each block's height
+ * map (16 heights, one a column, or one a row for walls) and its angle. Blocks can be flipped; a
+ * chunk marked as a loop has a twin that Sonic uses when he is "behind" it (the render flag $40). */
+#include "s1.h"
+#include "collide.h"
+
+static const uint16_t chunk0; /* (the original's blank chunk reads a word that is always 0) */
+
+const uint16_t *FindNearestTile(Obj *o, int16_t y, int16_t x) {
+ int idx = (((uint16_t)y >> 1) & 0x380) + (((uint16_t)x >> 8) & 0x7F);
+ uint8_t c = (&lvllayout[0][0][0])[idx];
+ if (!c) return &chunk0;
+ if (c & 0x80) {
+ c &= 0x7F;
+ if (o->render & 0x40) {
+ c++;
+ if (c == 0x29) c = 0x51;
+ }
+ }
+ int n = (uint8_t)(c - 1);
+ extern int level_nchunks(void);
+ if (n >= level_nchunks()) return &chunk0;
+ return &chunks256[n * 256 + (((uint16_t)y >> 4) & 15) * 16 + (((uint16_t)x >> 4) & 15)];
+}
+
+static uint8_t col_index(uint16_t block) { return V.collindex[block]; }
+static const uint8_t *angle_map(void) { return DATA(D_ANGLEMAP); }
+
+/* (FindFloor2 and FindWall2: the same for the next block, without looking further) */
+static int16_t floor2(Obj *o, int16_t y, int16_t x, int bit, uint16_t eor, uint8_t *angle, uint16_t *d4out) {
+ uint16_t d4 = *FindNearestTile(o, y, x), id = d4 & 0x7FF;
+ *d4out = d4;
+ uint8_t h;
+ if (!id || !(d4 >> bit & 1) || !(h = col_index(id))) return (int16_t)(0xF - (y & 0xF));
+ *angle = angle_map()[h];
+ int16_t d1 = x;
+ if (d4 & 0x800) d1 = (int16_t)~d1, *angle = (uint8_t)-*angle;
+ if (d4 & 0x1000) *angle = (uint8_t)(-(uint8_t)(*angle + 0x40) - 0x40);
+ int16_t d0 = ((const int8_t *)DATA(D_COLLARRAY1))[h * 16 + (d1 & 0xF)];
+ d4 ^= eor;
+ *d4out = d4;
+ if (d4 & 0x1000) d0 = (int16_t)-d0;
+ if (!d0) return (int16_t)(0xF - (y & 0xF));
+ if (d0 < 0) {
+ if ((int16_t)((y & 0xF) + d0) >= 0) return (int16_t)(0xF - (y & 0xF));
+ return (int16_t)~(y & 0xF);
+ }
+ return (int16_t)(0xF - ((y & 0xF) + d0));
+}
+
+int16_t FindFloor(Obj *o, int16_t y, int16_t x, int bit, uint16_t eor, int16_t step, uint8_t *angle, uint16_t *d4out) {
+ uint16_t d4 = *FindNearestTile(o, y, x), id = d4 & 0x7FF, tmp;
+ if (!d4out) d4out = &tmp;
+ *d4out = d4;
+ uint8_t h;
+ if (!id || !(d4 >> bit & 1) || !(h = col_index(id))) goto blank;
+ *angle = angle_map()[h];
+ int16_t d1 = x;
+ if (d4 & 0x800) d1 = (int16_t)~d1, *angle = (uint8_t)-*angle;
+ if (d4 & 0x1000) *angle = (uint8_t)(-(uint8_t)(*angle + 0x40) - 0x40);
+ int16_t d0 = ((const int8_t *)DATA(D_COLLARRAY1))[h * 16 + (d1 & 0xF)];
+ d4 ^= eor;
+ *d4out = d4;
+ if (d4 & 0x1000) d0 = (int16_t)-d0;
+ if (!d0) goto blank;
+ if (d0 < 0) {
+ if ((int16_t)((y & 0xF) + d0) >= 0) goto blank;
+ goto max;
+ }
+ if (d0 == 0x10) goto max;
+ return (int16_t)(0xF - ((y & 0xF) + d0));
+blank:
+ return (int16_t)(floor2(o, (int16_t)(y + step), x, bit, eor, angle, d4out) + 0x10);
+max:
+ return (int16_t)(floor2(o, (int16_t)(y - step), x, bit, eor, angle, d4out) - 0x10);
+}
+
+static int16_t wall2(Obj *o, int16_t y, int16_t x, int bit, uint16_t eor, uint8_t *angle, uint16_t *d4out) {
+ uint16_t d4 = *FindNearestTile(o, y, x), id = d4 & 0x7FF;
+ *d4out = d4;
+ uint8_t h;
+ if (!id || !(d4 >> bit & 1) || !(h = col_index(id))) return (int16_t)(0xF - (x & 0xF));
+ *angle = angle_map()[h];
+ int16_t d1 = y;
+ if (d4 & 0x1000) d1 = (int16_t)~d1, *angle = (uint8_t)(-(uint8_t)(*angle + 0x40) - 0x40);
+ if (d4 & 0x800) *angle = (uint8_t)-*angle;
+ int16_t d0 = ((const int8_t *)DATA(D_COLLARRAY2))[h * 16 + (d1 & 0xF)];
+ d4 ^= eor;
+ *d4out = d4;
+ if (d4 & 0x800) d0 = (int16_t)-d0;
+ if (!d0) return (int16_t)(0xF - (x & 0xF));
+ if (d0 < 0) {
+ if ((int16_t)((x & 0xF) + d0) >= 0) return (int16_t)(0xF - (x & 0xF));
+ return (int16_t)~(x & 0xF);
+ }
+ return (int16_t)(0xF - ((x & 0xF) + d0));
+}
+
+int16_t FindWall(Obj *o, int16_t y, int16_t x, int bit, uint16_t eor, int16_t step, uint8_t *angle, uint16_t *d4out) {
+ uint16_t d4 = *FindNearestTile(o, y, x), id = d4 & 0x7FF, tmp;
+ if (!d4out) d4out = &tmp;
+ *d4out = d4;
+ uint8_t h;
+ if (!id || !(d4 >> bit & 1) || !(h = col_index(id))) goto blank;
+ *angle = angle_map()[h];
+ int16_t d1 = y;
+ if (d4 & 0x1000) d1 = (int16_t)~d1, *angle = (uint8_t)(-(uint8_t)(*angle + 0x40) - 0x40);
+ if (d4 & 0x800) *angle = (uint8_t)-*angle;
+ int16_t d0 = ((const int8_t *)DATA(D_COLLARRAY2))[h * 16 + (d1 & 0xF)];
+ d4 ^= eor;
+ *d4out = d4;
+ if (d4 & 0x800) d0 = (int16_t)-d0;
+ if (!d0) goto blank;
+ if (d0 < 0) {
+ if ((int16_t)((x & 0xF) + d0) >= 0) goto blank;
+ goto max;
+ }
+ if (d0 == 0x10) goto max;
+ return (int16_t)(0xF - ((x & 0xF) + d0));
+blank:
+ return (int16_t)(wall2(o, y, (int16_t)(x + step), bit, eor, angle, d4out) + 0x10);
+max:
+ return (int16_t)(wall2(o, y, (int16_t)(x - step), bit, eor, angle, d4out) - 0x10);
+}
+
+/* ------------------------------------------------------------------ the object helpers */
+/* ObjFloorDist: from the bottom of the object to the floor below its x; *angle_out the floor's angle */
+int16_t ObjFloorDist2(Obj *o, int16_t x, uint8_t *angle_out) {
+ int16_t y = (int16_t)(o->y.w.i + (int8_t)o->height);
+ V.anglebuffer = 0;
+ int16_t d1 = FindFloor(o, y, x, 0xD, 0, 0x10, &V.anglebuffer, NULL);
+ uint8_t a = V.anglebuffer;
+ if (a & 1) a = 0;
+ if (angle_out) *angle_out = a;
+ return d1;
+}
+int16_t ObjFloorDist(Obj *o, uint8_t *angle_out) { return ObjFloorDist2(o, o->x.w.i, angle_out); }
+
+int16_t ObjHitWallRight(Obj *o, int16_t dx, uint8_t *angle_out) {
+ V.anglebuffer = 0;
+ int16_t d1 = FindWall(o, o->y.w.i, (int16_t)(o->x.w.i + dx), 0xE, 0, 0x10, &V.anglebuffer, NULL);
+ uint8_t a = V.anglebuffer;
+ if (a & 1) a = 0xC0;
+ if (angle_out) *angle_out = a;
+ return d1;
+}
+int16_t ObjHitWallLeft(Obj *o, int16_t dx, uint8_t *angle_out) {
+ V.anglebuffer = 0;
+ int16_t d1 = FindWall(o, o->y.w.i, (int16_t)(o->x.w.i + dx), 0xE, 0x800, -0x10, &V.anglebuffer, NULL);
+ uint8_t a = V.anglebuffer;
+ if (a & 1) a = 0x40;
+ if (angle_out) *angle_out = a;
+ return d1;
+}
+int16_t ObjHitCeiling(Obj *o, uint8_t *angle_out) {
+ int16_t y = (int16_t)((o->y.w.i - (int8_t)o->height) ^ 0xF);
+ int16_t d1 = FindFloor(o, y, o->x.w.i, 0xE, 0x1000, -0x10, &V.anglebuffer, NULL);
+ uint8_t a = V.anglebuffer;
+ if (a & 1) a = 0x80;
+ if (angle_out) *angle_out = a;
+ return d1;
+}
diff --git a/games/sonic/src/collide.h b/games/sonic/src/collide.h
new file mode 100644
index 00000000..f436c03f
--- /dev/null
+++ b/games/sonic/src/collide.h
@@ -0,0 +1,16 @@
+/* Collision with the level (collide.c). Distances are in pixels from the point to the surface
+ * (negative: inside it); bit is $D for floors you can stand on from above, $E for solid all round;
+ * eor flips the block's reading ($800 for walls to the left, $1000 for ceilings); step goes to the
+ * next block ($10, or -$10 the other way). */
+#ifndef S1_COLLIDE_H
+#define S1_COLLIDE_H
+#include "s1.h"
+const uint16_t *FindNearestTile(Obj *o, int16_t y, int16_t x);
+int16_t FindFloor(Obj *o, int16_t y, int16_t x, int bit, uint16_t eor, int16_t step, uint8_t *angle, uint16_t *d4);
+int16_t FindWall(Obj *o, int16_t y, int16_t x, int bit, uint16_t eor, int16_t step, uint8_t *angle, uint16_t *d4);
+int16_t ObjFloorDist(Obj *o, uint8_t *angle);
+int16_t ObjFloorDist2(Obj *o, int16_t x, uint8_t *angle);
+int16_t ObjHitWallRight(Obj *o, int16_t dx, uint8_t *angle);
+int16_t ObjHitWallLeft(Obj *o, int16_t dx, uint8_t *angle);
+int16_t ObjHitCeiling(Obj *o, uint8_t *angle);
+#endif
diff --git a/games/sonic/src/data.S b/games/sonic/src/data.S
new file mode 100644
index 00000000..a577c027
--- /dev/null
+++ b/games/sonic/src/data.S
@@ -0,0 +1,19 @@
+/* data.bin (tools/pack.py) in the app's read-only data */
+#ifdef __APPLE__
+ .const_data
+ .p2align 2
+ .globl _s1_data
+_s1_data:
+ .incbin DATA_BIN
+ .p2align 2
+#else
+ .section .rodata.s1_data,"a"
+ .balign 4
+ .global s1_data
+s1_data:
+ .incbin DATA_BIN
+ .balign 4
+#endif
+#ifdef __ELF__
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/games/sonic/src/data.bin b/games/sonic/src/data.bin
new file mode 100644
index 00000000..70f28902
Binary files /dev/null and b/games/sonic/src/data.bin differ
diff --git a/games/sonic/src/data.h b/games/sonic/src/data.h
new file mode 100644
index 00000000..d4a88dea
--- /dev/null
+++ b/games/sonic/src/data.h
@@ -0,0 +1,614 @@
+/* made by tools/pack.py: what is where in data.bin */
+#ifndef S1_DATA_H
+#define S1_DATA_H
+#define D_TILES 0
+#define D_ARTS 411008
+#define D_MAPS 433696
+#define D_ANIS 436192
+#define D_ANI_CAT 436388
+#define D_SONICDPLC 436516
+#define D_BLK16_GHZ 437388
+#define N_BLK256_GHZ 63
+#define D_BLK256_GHZ 440900
+#define D_BLK16_LZ 473156
+#define N_BLK256_LZ 78
+#define D_BLK256_LZ 474724
+#define D_BLK16_MZ 514660
+#define N_BLK256_MZ 74
+#define D_BLK256_MZ 517636
+#define D_BLK16_SLZ 555524
+#define N_BLK256_SLZ 82
+#define D_BLK256_SLZ 558836
+#define D_BLK16_SYZ 600820
+#define N_BLK256_SYZ 74
+#define D_BLK256_SYZ 604268
+#define D_BLK16_SBZ 642156
+#define N_BLK256_SBZ 75
+#define D_BLK256_SBZ 646972
+#define D_COL_GHZ 685372
+#define D_COL_LZ 685782
+#define D_COL_MZ 685982
+#define D_COL_SLZ 686382
+#define D_COL_SYZ 686882
+#define D_COL_SBZ 687382
+#define D_COLS 685372
+#define D_ANGLEMAP 687984
+#define D_COLLARRAY1 688240
+#define D_COLLARRAY2 692336
+#define D_LEVEL_ENDING 696432
+#define D_LEVEL_GHZ1 696464
+#define D_LEVEL_GHZ2 696706
+#define D_LEVEL_GHZ3 696906
+#define D_LEVEL_GHZBG 697196
+#define D_LEVEL_LZ1 697230
+#define D_LEVEL_LZ2 697488
+#define D_LEVEL_LZ3 697642
+#define D_LEVEL_LZBG 697924
+#define D_LEVEL_MZ1 698182
+#define D_LEVEL_MZ1BG 698340
+#define D_LEVEL_MZ2 698462
+#define D_LEVEL_MZ2BG 698626
+#define D_LEVEL_MZ3 698772
+#define D_LEVEL_MZ3BG 698998
+#define D_LEVEL_SBZ1 699162
+#define D_LEVEL_SBZ1BG 699452
+#define D_LEVEL_SBZ2 699514
+#define D_LEVEL_SBZ2BG 699836
+#define D_LEVEL_SBZ3 700198
+#define D_LEVEL_SLZ1 700384
+#define D_LEVEL_SLZ2 700658
+#define D_LEVEL_SLZ3 700898
+#define D_LEVEL_SLZBG 701180
+#define D_LEVEL_SYZ1 701302
+#define D_LEVEL_SYZ2 701490
+#define D_LEVEL_SYZ3 701750
+#define D_LEVEL_SYZBG 702096
+#define OBJPOS_START_ENDING 702154
+#define D_OBJPOS_ENDING 702160
+#define OBJPOS_START_FZ 702514
+#define D_OBJPOS_FZ 702520
+#define OBJPOS_START_GHZ1 702544
+#define D_OBJPOS_GHZ1 702550
+#define OBJPOS_START_GHZ2 703846
+#define D_OBJPOS_GHZ2 703852
+#define OBJPOS_START_GHZ3_REV01 705328
+#define D_OBJPOS_GHZ3 705334
+#define OBJPOS_START_LZ1_REV01 707062
+#define D_OBJPOS_LZ1 707068
+#define OBJPOS_START_LZ2 708214
+#define D_OBJPOS_LZ2 708220
+#define OBJPOS_START_LZ3_REV01 709060
+#define D_OBJPOS_LZ3 709066
+#define OBJPOS_START_MZ1_REV01 710548
+#define D_OBJPOS_MZ1 710554
+#define OBJPOS_START_MZ2 711436
+#define D_OBJPOS_MZ2 711442
+#define OBJPOS_START_MZ3 712642
+#define D_OBJPOS_MZ3 712648
+#define OBJPOS_START_SBZ1_REV01 714052
+#define D_OBJPOS_SBZ1 714058
+#define OBJPOS_START_SBZ2 715918
+#define D_OBJPOS_SBZ2 715924
+#define OBJPOS_START_SBZ3 717688
+#define D_OBJPOS_SBZ3 717694
+#define OBJPOS_START_SLZ1 718876
+#define D_OBJPOS_SLZ1 718882
+#define OBJPOS_START_SLZ2 720232
+#define D_OBJPOS_SLZ2 720238
+#define OBJPOS_START_SLZ3 721372
+#define D_OBJPOS_SLZ3 721378
+#define OBJPOS_START_SYZ1 722890
+#define D_OBJPOS_SYZ1 722896
+#define OBJPOS_START_SYZ2 724066
+#define D_OBJPOS_SYZ2 724072
+#define OBJPOS_START_SYZ3_REV01 725464
+#define D_OBJPOS_SYZ3 725470
+#define D_START_END1 727024
+#define D_START_END2 727028
+#define D_START_FZ 727032
+#define D_START_GHZ1 727036
+#define D_START_GHZ2 727040
+#define D_START_GHZ3 727044
+#define D_START_LZ1 727048
+#define D_START_LZ2 727052
+#define D_START_LZ3 727056
+#define D_START_MZ1 727060
+#define D_START_MZ2 727064
+#define D_START_MZ3 727068
+#define D_START_SBZ1 727072
+#define D_START_SBZ2 727076
+#define D_START_SBZ3 727080
+#define D_START_SLZ1 727084
+#define D_START_SLZ2 727088
+#define D_START_SLZ3 727092
+#define D_START_SYZ1 727096
+#define D_START_SYZ2 727100
+#define D_START_SYZ3 727104
+#define D_START_CREDITS_DEMOS_GHZ1_CREDITS_DEMO_1 727108
+#define D_START_CREDITS_DEMOS_GHZ1_CREDITS_DEMO_2 727112
+#define D_START_CREDITS_DEMOS_LZ3_CREDITS_DEMO 727116
+#define D_START_CREDITS_DEMOS_MZ2_CREDITS_DEMO 727120
+#define D_START_CREDITS_DEMOS_SBZ1_CREDITS_DEMO 727124
+#define D_START_CREDITS_DEMOS_SBZ2_CREDITS_DEMO 727128
+#define D_START_CREDITS_DEMOS_SLZ3_CREDITS_DEMO 727132
+#define D_START_CREDITS_DEMOS_SYZ3_CREDITS_DEMO 727136
+#define D_START_SPECIAL_STAGES_SS1 727140
+#define D_START_SPECIAL_STAGES_SS2 727144
+#define D_START_SPECIAL_STAGES_SS3 727148
+#define D_START_SPECIAL_STAGES_SS4 727152
+#define D_START_SPECIAL_STAGES_SS5 727156
+#define D_START_SPECIAL_STAGES_SS6 727160
+#define D_PAL_CYCLE_GHZ 727164
+#define N_PAL_CYCLE_GHZ 16
+#define D_PAL_CYCLE_LZ_CONVEYOR_BELT_UNDERWATER 727196
+#define N_PAL_CYCLE_LZ_CONVEYOR_BELT_UNDERWATER 9
+#define D_PAL_CYCLE_LZ_CONVEYOR_BELT 727214
+#define N_PAL_CYCLE_LZ_CONVEYOR_BELT 9
+#define D_PAL_CYCLE_LZ_WATERFALL 727232
+#define N_PAL_CYCLE_LZ_WATERFALL 16
+#define D_PAL_CYCLE_MZ_UNUSED 727264
+#define N_PAL_CYCLE_MZ_UNUSED 36
+#define D_PAL_CYCLE_SBZ_1 727336
+#define N_PAL_CYCLE_SBZ_1 8
+#define D_PAL_CYCLE_SBZ_10 727352
+#define N_PAL_CYCLE_SBZ_10 6
+#define D_PAL_CYCLE_SBZ_2 727364
+#define N_PAL_CYCLE_SBZ_2 8
+#define D_PAL_CYCLE_SBZ_3 727380
+#define N_PAL_CYCLE_SBZ_3 8
+#define D_PAL_CYCLE_SBZ_4 727396
+#define N_PAL_CYCLE_SBZ_4 6
+#define D_PAL_CYCLE_SBZ_5 727408
+#define N_PAL_CYCLE_SBZ_5 8
+#define D_PAL_CYCLE_SBZ_6 727424
+#define N_PAL_CYCLE_SBZ_6 8
+#define D_PAL_CYCLE_SBZ_7 727440
+#define N_PAL_CYCLE_SBZ_7 16
+#define D_PAL_CYCLE_SBZ_8 727472
+#define N_PAL_CYCLE_SBZ_8 5
+#define D_PAL_CYCLE_SBZ_9 727482
+#define N_PAL_CYCLE_SBZ_9 8
+#define D_PAL_CYCLE_SBZ3_WATERFALL 727498
+#define N_PAL_CYCLE_SBZ3_WATERFALL 16
+#define D_PAL_CYCLE_SLZ 727530
+#define N_PAL_CYCLE_SLZ 18
+#define D_PAL_CYCLE_SYZ1 727566
+#define N_PAL_CYCLE_SYZ1 16
+#define D_PAL_CYCLE_SYZ2 727598
+#define N_PAL_CYCLE_SYZ2 8
+#define D_PAL_CYCLE_SPECIAL_STAGE_1 727614
+#define N_PAL_CYCLE_SPECIAL_STAGE_1 36
+#define D_PAL_CYCLE_SPECIAL_STAGE_2 727686
+#define N_PAL_CYCLE_SPECIAL_STAGE_2 105
+#define D_PAL_CYCLE_TITLE_SCREEN_WATER 727896
+#define N_PAL_CYCLE_TITLE_SCREEN_WATER 16
+#define D_PAL_ENDING 727928
+#define N_PAL_ENDING 64
+#define D_PAL_GREEN_HILL_ZONE 728056
+#define N_PAL_GREEN_HILL_ZONE 48
+#define D_PAL_LABYRINTH_ZONE_UNDERWATER 728152
+#define N_PAL_LABYRINTH_ZONE_UNDERWATER 64
+#define D_PAL_LABYRINTH_ZONE 728280
+#define N_PAL_LABYRINTH_ZONE 48
+#define D_PAL_LEVEL_SELECT 728376
+#define N_PAL_LEVEL_SELECT 64
+#define D_PAL_MARBLE_ZONE 728504
+#define N_PAL_MARBLE_ZONE 48
+#define D_PAL_SBZ_ACT_1 728600
+#define N_PAL_SBZ_ACT_1 48
+#define D_PAL_SBZ_ACT_2 728696
+#define N_PAL_SBZ_ACT_2 48
+#define D_PAL_SBZ_ACT_3_UNDERWATER 728792
+#define N_PAL_SBZ_ACT_3_UNDERWATER 64
+#define D_PAL_SBZ_ACT_3 728920
+#define N_PAL_SBZ_ACT_3 48
+#define D_PAL_SEGA_BACKGROUND 729016
+#define N_PAL_SEGA_BACKGROUND 64
+#define D_PAL_SEGA1 729144
+#define N_PAL_SEGA1 6
+#define D_PAL_SEGA2 729156
+#define N_PAL_SEGA2 24
+#define D_PAL_SONIC_LZ_UNDERWATER 729204
+#define N_PAL_SONIC_LZ_UNDERWATER 16
+#define D_PAL_SONIC_SBZ3_UNDERWATER 729236
+#define N_PAL_SONIC_SBZ3_UNDERWATER 16
+#define D_PAL_SONIC 729268
+#define N_PAL_SONIC 16
+#define D_PAL_SPECIAL_STAGE_CONTINUE_BONUS 729300
+#define N_PAL_SPECIAL_STAGE_CONTINUE_BONUS 32
+#define D_PAL_SPECIAL_STAGE_RESULTS 729364
+#define N_PAL_SPECIAL_STAGE_RESULTS 64
+#define D_PAL_SPECIAL_STAGE 729492
+#define N_PAL_SPECIAL_STAGE 64
+#define D_PAL_SPRING_YARD_ZONE 729620
+#define N_PAL_SPRING_YARD_ZONE 48
+#define D_PAL_STAR_LIGHT_ZONE 729716
+#define N_PAL_STAR_LIGHT_ZONE 48
+#define D_PAL_TITLE_SCREEN 729812
+#define N_PAL_TITLE_SCREEN 64
+#define D_ENI_TITLE 729940
+#define N_ENI_TITLE 748
+#define D_ENI_SEGALOGO 731436
+#define N_ENI_SEGALOGO 1318
+#define D_ENI_SSBG1 734072
+#define N_ENI_SSBG1 512
+#define D_ENI_SSBG2 735096
+#define N_ENI_SSBG2 4096
+#define D_ENI_JAPNAMES 743288
+#define N_ENI_JAPNAMES 1120
+#define D_SS_1 745528
+#define N_SS_1 2048
+#define D_SS_2 749624
+#define N_SS_2 2048
+#define D_SS_3 753720
+#define N_SS_3 2048
+#define D_SS_4 757816
+#define N_SS_4 2048
+#define D_SS_5 761912
+#define N_SS_5 2048
+#define D_SS_6 766008
+#define N_SS_6 2048
+#define D_DEMO_ENDING_GHZ1 770104
+#define D_DEMO_ENDING_GHZ2 770150
+#define D_DEMO_ENDING_LZ 770198
+#define D_DEMO_ENDING_MZ 770246
+#define D_DEMO_ENDING_SBZ1 770310
+#define D_DEMO_ENDING_SBZ2 770342
+#define D_DEMO_ENDING_SLZ 770390
+#define D_DEMO_ENDING_SYZ 770422
+#define D_DEMO_INTRO_GHZ 770470
+#define D_DEMO_INTRO_MZ 770598
+#define D_DEMO_INTRO_SYZ 770902
+#define D_DEMO_INTRO_SPECIAL_STAGE 771030
+#define D_DEMO_UNUSED_DEMO 771286
+#define D_PLC 771336
+#define D_TAB_SINE_DATA 772210
+#define D_TAB_ANGLE_DATA 772850
+#define D_TAB_DROWN_WOBBLEDATA 773108
+#define ART_Art_BigRing 0
+#define ART_Art_GhzFlower1 1
+#define ART_Art_GhzFlower2 2
+#define ART_Art_GhzWater 3
+#define ART_Art_Hud 4
+#define ART_Art_LivesNums 5
+#define ART_Art_MzLava1 6
+#define ART_Art_MzLava2 7
+#define ART_Art_MzTorch 8
+#define ART_Art_SbzSmoke 9
+#define ART_Art_Sonic 10
+#define ART_Art_Text 11
+#define ART_Nem_Ball 12
+#define ART_Nem_BallHog 13
+#define ART_Nem_Basaran 14
+#define ART_Nem_BigFlash 15
+#define ART_Nem_Bomb 16
+#define ART_Nem_Bonus 17
+#define ART_Nem_Bridge 18
+#define ART_Nem_Bubbles 19
+#define ART_Nem_Bumper 20
+#define ART_Nem_Burrobot 21
+#define ART_Nem_Buzz 22
+#define ART_Nem_Cater 23
+#define ART_Nem_Chicken 24
+#define ART_Nem_Chopper 25
+#define ART_Nem_ContSonic 26
+#define ART_Nem_Cork 27
+#define ART_Nem_Crabmeat 28
+#define ART_Nem_CreditText 29
+#define ART_Nem_Cutter 30
+#define ART_Nem_Eggman 31
+#define ART_Nem_Electric 32
+#define ART_Nem_EndEm 33
+#define ART_Nem_EndFlower 34
+#define ART_Nem_EndSonic 35
+#define ART_Nem_EndStH 36
+#define ART_Nem_Exhaust 37
+#define ART_Nem_Explode 38
+#define ART_Nem_Fan 39
+#define ART_Nem_FlamePipe 40
+#define ART_Nem_FlapDoor 41
+#define ART_Nem_Flicky 42
+#define ART_Nem_FzBoss 43
+#define ART_Nem_FzEggman 44
+#define ART_Nem_GHZ_1st 45
+#define ART_Nem_GHZ_2nd 46
+#define ART_Nem_GameOver 47
+#define ART_Nem_Gargoyle 48
+#define ART_Nem_GhzLog 49
+#define ART_Nem_GhzUnkBlock 50
+#define ART_Nem_GhzWall1 51
+#define ART_Nem_GhzWall2 52
+#define ART_Nem_Girder 53
+#define ART_Nem_HSpring 54
+#define ART_Nem_Harpoon 55
+#define ART_Nem_Hud 56
+#define ART_Nem_JapNames 57
+#define ART_Nem_Jaws 58
+#define ART_Nem_LZ 59
+#define ART_Nem_Lamp 60
+#define ART_Nem_Lava 61
+#define ART_Nem_Lives 62
+#define ART_Nem_LzBlock1 63
+#define ART_Nem_LzBlock2 64
+#define ART_Nem_LzBlock3 65
+#define ART_Nem_LzDoor1 66
+#define ART_Nem_LzDoor2 67
+#define ART_Nem_LzPlatfm 68
+#define ART_Nem_LzPole 69
+#define ART_Nem_LzSpikeBall 70
+#define ART_Nem_LzSwitch 71
+#define ART_Nem_LzWheel 72
+#define ART_Nem_MZ 73
+#define ART_Nem_MiniSonic 74
+#define ART_Nem_Monitors 75
+#define ART_Nem_Motobug 76
+#define ART_Nem_MzBlock 77
+#define ART_Nem_MzFire 78
+#define ART_Nem_MzGlass 79
+#define ART_Nem_MzMetal 80
+#define ART_Nem_MzSwitch 81
+#define ART_Nem_MzUnkBlock 82
+#define ART_Nem_Newtron 83
+#define ART_Nem_Orbinaut 84
+#define ART_Nem_Penguin 85
+#define ART_Nem_Pig 86
+#define ART_Nem_Points 87
+#define ART_Nem_PplRock 88
+#define ART_Nem_Prison 89
+#define ART_Nem_Pylon 90
+#define ART_Nem_Rabbit 91
+#define ART_Nem_ResultEm 92
+#define ART_Nem_Ring 93
+#define ART_Nem_Roller 94
+#define ART_Nem_SBZ 95
+#define ART_Nem_SLZ 96
+#define ART_Nem_SS1UpBlock 97
+#define ART_Nem_SSBgCloud 98
+#define ART_Nem_SSBgFish 99
+#define ART_Nem_SSEmStars 100
+#define ART_Nem_SSEmerald 101
+#define ART_Nem_SSGOAL 102
+#define ART_Nem_SSGhost 103
+#define ART_Nem_SSGlass 104
+#define ART_Nem_SSRBlock 105
+#define ART_Nem_SSRedWhite 106
+#define ART_Nem_SSUpDown 107
+#define ART_Nem_SSWBlock 108
+#define ART_Nem_SSWalls 109
+#define ART_Nem_SSZone1 110
+#define ART_Nem_SSZone2 111
+#define ART_Nem_SSZone3 112
+#define ART_Nem_SSZone4 113
+#define ART_Nem_SSZone5 114
+#define ART_Nem_SSZone6 115
+#define ART_Nem_SYZ 116
+#define ART_Nem_Sbz2Eggman 117
+#define ART_Nem_SbzBlock 118
+#define ART_Nem_SbzDoor1 119
+#define ART_Nem_SbzDoor2 120
+#define ART_Nem_SbzFloor 121
+#define ART_Nem_SbzWheel1 122
+#define ART_Nem_SbzWheel2 123
+#define ART_Nem_Seal 124
+#define ART_Nem_Seesaw 125
+#define ART_Nem_SegaLogo 126
+#define ART_Nem_Shield 127
+#define ART_Nem_SignPost 128
+#define ART_Nem_SlideFloor 129
+#define ART_Nem_SlzBlock 130
+#define ART_Nem_SlzCannon 131
+#define ART_Nem_SlzSpike 132
+#define ART_Nem_SlzSwing 133
+#define ART_Nem_SlzWall 134
+#define ART_Nem_SpikePole 135
+#define ART_Nem_Spikes 136
+#define ART_Nem_SpinPform 137
+#define ART_Nem_Splash 138
+#define ART_Nem_Splats 139
+#define ART_Nem_Squirrel 140
+#define ART_Nem_Stalk 141
+#define ART_Nem_Stars 142
+#define ART_Nem_Stomper 143
+#define ART_Nem_Swing 144
+#define ART_Nem_SyzSpike1 145
+#define ART_Nem_SyzSpike2 146
+#define ART_Nem_TitleCard 147
+#define ART_Nem_TitleFg 148
+#define ART_Nem_TitleSonic 149
+#define ART_Nem_TitleTM 150
+#define ART_Nem_TrapDoor 151
+#define ART_Nem_TryAgain 152
+#define ART_Nem_UnkExplode 153
+#define ART_Nem_UnkGrass 154
+#define ART_Nem_VSpring 155
+#define ART_Nem_Water 156
+#define ART_Nem_Weapons 157
+#define ART_Nem_Yadrin 158
+#define ART_Kos_EndFlowers 159
+#define MAP_Animal1 0
+#define MAP_Animal2 1
+#define MAP_Animal3 2
+#define MAP_Hog 3
+#define MAP_Bas 4
+#define MAP_BBall 5
+#define MAP_Bomb 6
+#define MAP_BossItems 7
+#define MAP_Bri 8
+#define MAP_Bub 9
+#define MAP_Bump 10
+#define MAP_Burro 11
+#define MAP_But 12
+#define MAP_Missile 13
+#define MAP_Buzz 14
+#define MAP_Cat 15
+#define MAP_CSto 16
+#define MAP_Chop 17
+#define MAP_CFlo 18
+#define MAP_Ledge 19
+#define MAP_ContScr 20
+#define MAP_Crab 21
+#define MAP_Cred 22
+#define MAP_SEgg 23
+#define MAP_Eggman 24
+#define MAP_Elec 25
+#define MAP_ECha 26
+#define MAP_ESth 27
+#define MAP_ESon 28
+#define MAP_ExplodeItem 29
+#define MAP_ExplodeBomb 30
+#define MAP_FZDamaged 31
+#define MAP_EggCyl 32
+#define MAP_FZLegs 33
+#define MAP_Fan 34
+#define MAP_Fire 35
+#define MAP_Flame 36
+#define MAP_Flap 37
+#define MAP_FBlock 38
+#define MAP_GBall 39
+#define MAP_Edge 40
+#define MAP_Over 41
+#define MAP_Gar 42
+#define MAP_GRing 43
+#define MAP_Gird 44
+#define MAP_HUD 45
+#define MAP_Harp 46
+#define MAP_Bonus 47
+#define MAP_Invis 48
+#define MAP_Jaws 49
+#define MAP_LBlock 50
+#define MAP_LConv 51
+#define MAP_Lamp 52
+#define MAP_Geyser 53
+#define MAP_LTag 54
+#define MAP_Light 55
+#define MAP_Brick 56
+#define MAP_LGrass 57
+#define MAP_Glass 58
+#define MAP_Monitor 59
+#define MAP_Moto 60
+#define MAP_MBlockLZ 61
+#define MAP_MBlock 62
+#define MAP_Newt 63
+#define MAP_Orb 64
+#define MAP_PLaunch 65
+#define MAP_Plasma 66
+#define MAP_Plat_GHZ 67
+#define MAP_Plat_SLZ 68
+#define MAP_Plat_SYZ 69
+#define MAP_Plat_Unused 70
+#define MAP_Poi 71
+#define MAP_Pole 72
+#define MAP_PSB 73
+#define MAP_Pri 74
+#define MAP_PRock 75
+#define MAP_Push 76
+#define MAP_Pylon 77
+#define MAP_Flash 78
+#define MAP_Ring 79
+#define MAP_Roll 80
+#define MAP_Jun 81
+#define MAP_Disc 82
+#define MAP_FFloor 83
+#define MAP_ADoor 84
+#define MAP_Spin 85
+#define MAP_Stomp 86
+#define MAP_VanP 87
+#define MAP_BSBall 88
+#define MAP_Circ 89
+#define MAP_Elev 90
+#define MAP_SS_Chaos1 91
+#define MAP_SS_Chaos2 92
+#define MAP_SS_Chaos3 93
+#define MAP_SS_Down 94
+#define MAP_SS_Glass 95
+#define MAP_SSRC 96
+#define MAP_SS_Shared 97
+#define MAP_SS_Up 98
+#define MAP_SSWalls 99
+#define MAP_BossBlock 100
+#define MAP_Saw 101
+#define MAP_Scen 102
+#define MAP_SSawBall 103
+#define MAP_Seesaw 104
+#define MAP_Shield 105
+#define MAP_SSto 106
+#define MAP_Sign 107
+#define MAP_Smab 108
+#define MAP_Smash 109
+#define MAP_Sonic 110
+#define MAP_Vanish 111
+#define MAP_SBall2 112
+#define MAP_SBall 113
+#define MAP_Hel 114
+#define MAP_Spike 115
+#define MAP_Spring 116
+#define MAP_Stair 117
+#define MAP_Swing_GHZ 118
+#define MAP_Swing_SLZ 119
+#define MAP_Card 120
+#define MAP_Got 121
+#define MAP_SSR 122
+#define MAP_TSon 123
+#define MAP_Trap 124
+#define MAP_EEgg 125
+#define MAP_UnkExplode 126
+#define MAP_UnusedFace 127
+#define MAP_Swi 128
+#define MAP_LWall 129
+#define MAP_Splash 130
+#define MAP_Surf 131
+#define MAP_WFall 132
+#define MAP_Yad 133
+#define ANI_Hog 0
+#define ANI_Bas 1
+#define ANI_Bomb 2
+#define ANI_Bub 3
+#define ANI_Bump 4
+#define ANI_GFire 5
+#define ANI_Burro 6
+#define ANI_Missile 7
+#define ANI_Buzz 8
+#define ANI_Chop 9
+#define ANI_CSon 10
+#define ANI_Crab 11
+#define ANI_Drown 12
+#define ANI_SEgg 13
+#define ANI_Eggman 14
+#define ANI_Elec 15
+#define ANI_ESon 16
+#define ANI_FZEgg 17
+#define ANI_Fire 18
+#define ANI_Flame 19
+#define ANI_Flap 20
+#define ANI_Harp 21
+#define ANI_Jaws 22
+#define ANI_Geyser 23
+#define ANI_Monitor 24
+#define ANI_Moto 25
+#define ANI_Newt 26
+#define ANI_Orb 27
+#define ANI_PLaunch 28
+#define ANI_Plasma 29
+#define ANI_PSBTM 30
+#define ANI_Pri 31
+#define ANI_Ring 32
+#define ANI_Roll 33
+#define ANI_ADoor 34
+#define ANI_SpinConvey 35
+#define ANI_Spin 36
+#define ANI_Van 37
+#define ANI_Shield 38
+#define ANI_Sign 39
+#define ANI_Sonic 40
+#define ANI_Vanish 41
+#define ANI_Spring 42
+#define ANI_TSon 43
+#define ANI_EEgg 44
+#define ANI_LWall 45
+#define ANI_Splash 46
+#define ANI_WFall 47
+#define ANI_Yad 48
+#define N_ARTS 160
+#define N_MAPS 134
+#define N_ANIS 49
+#endif
diff --git a/games/sonic/src/dle.c b/games/sonic/src/dle.c
new file mode 100644
index 00000000..68d65749
--- /dev/null
+++ b/games/sonic/src/dle.c
@@ -0,0 +1,287 @@
+/* Dynamic level events: each act's camera limits as Sonic goes through it (the bottom boundary
+ * moves 2 pixels a frame towards its target, 8 when he falls), and the bosses set off when the
+ * camera reaches their arena: the screen locks and the boss art is loaded. */
+#include "s1.h"
+#include "game.h"
+
+static void spawn_boss(uint8_t id, int16_t x, int16_t y, bool place) {
+ Obj *a1 = FindFreeObj();
+ if (a1) {
+ a1->id = id;
+ if (place) a1->x.w.i = x, a1->y.w.i = y;
+ }
+ V.f_lockscreen = 1;
+ V.dle_routine += 2;
+ AddPLC(plcid_Boss);
+}
+
+static void dle_ghz(void) {
+ int16_t cx = V.cam[0].x.w.i, cy = V.cam[0].y.w.i;
+ switch (V.act) {
+ case 0:
+ V.limitbtm1 = 0x300;
+ if ((uint16_t)cx >= 0x1780) V.limitbtm1 = 0x400;
+ break;
+ case 1:
+ V.limitbtm1 = 0x300;
+ if ((uint16_t)cx < 0xED0) break;
+ V.limitbtm1 = 0x200;
+ if ((uint16_t)cx < 0x1600) break;
+ V.limitbtm1 = 0x400;
+ if ((uint16_t)cx < 0x1D60) break;
+ V.limitbtm1 = 0x300;
+ break;
+ default:
+ switch (V.dle_routine) {
+ case 0:
+ V.limitbtm1 = 0x300;
+ if ((uint16_t)cx < 0x380) return;
+ V.limitbtm1 = 0x310;
+ if ((uint16_t)cx < 0x960) return;
+ if ((uint16_t)cy >= 0x280) {
+ V.limitbtm1 = 0x400;
+ if ((uint16_t)cx < 0x1380) V.limitbtm1 = V.limitbtm2 = 0x4C0;
+ if ((uint16_t)cx < 0x1700) return;
+ }
+ V.limitbtm1 = boss_ghz_y;
+ V.dle_routine += 2;
+ return;
+ case 2:
+ if ((uint16_t)cx < 0x960) V.dle_routine -= 2;
+ if ((uint16_t)cx < boss_ghz_x) return;
+ spawn_boss(id_BossGreenHill, boss_ghz_x + 0x100, boss_ghz_y - 0x80, true);
+ return;
+ default: V.limitleft2 = cx; return;
+ }
+ }
+}
+
+static void dle_lz(void) {
+ int16_t cx = V.cam[0].x.w.i, cy = V.cam[0].y.w.i;
+ if (V.act == 2) {
+ if (V.f_switch[0xF]) {
+ uint8_t *a1 = &lvllayout[2][0][6]; /* (v_lvllayout_fg + layout_row * 2 + 6) */
+ if (*a1 != 7) *a1 = 7;
+ }
+ if (V.dle_routine) return;
+ if ((uint16_t)cx < boss_lz_x - 0x140 || (uint16_t)cy >= boss_lz_y + 0x540) return;
+ spawn_boss(id_BossLabyrinth, 0, 0, false);
+ } else if (V.act == 3) {
+ if ((uint16_t)cx < 0xD00 || (uint16_t)player->y.w.i >= 0x18) return;
+ V.lastlamp = 0;
+ V.f_restart = 1;
+ V.zone = id_SBZ, V.act = 2;
+ V.f_playerctrl = 1;
+ }
+}
+
+static void dle_mz(void) {
+ int16_t cx = V.cam[0].x.w.i, cy = V.cam[0].y.w.i;
+ if (V.act == 0) {
+ switch (V.dle_routine) {
+ case 0:
+ V.limitbtm1 = 0x1D0;
+ if ((uint16_t)cx < 0x700) return;
+ V.limitbtm1 = 0x220;
+ if ((uint16_t)cx < 0xD00) return;
+ V.limitbtm1 = 0x340;
+ if ((uint16_t)cy < 0x340) return;
+ V.dle_routine += 2;
+ return;
+ case 2:
+ if ((uint16_t)cy < 0x340) {
+ V.dle_routine -= 2;
+ return;
+ }
+ V.limittop2 = 0;
+ if ((uint16_t)cx >= 0xE00) return;
+ V.limittop2 = V.limitbtm1 = 0x340;
+ if ((uint16_t)cx >= 0xA90) return;
+ V.limitbtm1 = 0x500;
+ if ((uint16_t)cy < 0x370) return;
+ V.dle_routine += 2;
+ return;
+ case 4:
+ if ((uint16_t)cy < 0x370) {
+ V.dle_routine -= 2;
+ return;
+ }
+ if ((uint16_t)cy < 0x500 || (uint16_t)cx < 0xB80) return;
+ V.limittop2 = 0x500;
+ V.dle_routine += 2;
+ return;
+ default:
+ if ((uint16_t)cx < 0xB80) {
+ if (V.limittop2 == 0x340) return;
+ V.limittop2 -= 2;
+ return;
+ }
+ if (V.limittop2 != 0x500) {
+ if ((uint16_t)cy < 0x500) return;
+ V.limittop2 = 0x500;
+ }
+ if ((uint16_t)cx < 0xE70) return;
+ V.limittop2 = 0;
+ V.limitbtm1 = 0x500;
+ if ((uint16_t)cx < 0x1430) return;
+ V.limitbtm1 = 0x210;
+ return;
+ }
+ }
+ if (V.act == 1) {
+ V.limitbtm1 = 0x520;
+ if ((uint16_t)cx >= 0x1700) V.limitbtm1 = 0x200;
+ return;
+ }
+ if (V.dle_routine == 0) {
+ V.limitbtm1 = 0x720;
+ if ((uint16_t)cx < boss_mz_x - 0x2A0) return;
+ V.limitbtm1 = boss_mz_y;
+ if ((uint16_t)cx < boss_mz_x - 0x10) return;
+ spawn_boss(id_BossMarble, boss_mz_x + 0x1F0, boss_mz_y + 0x1C, true);
+ return;
+ }
+ V.limitleft2 = cx;
+}
+
+static void dle_slz(void) {
+ int16_t cx = V.cam[0].x.w.i;
+ if (V.act != 2) return;
+ switch (V.dle_routine) {
+ case 0:
+ if ((uint16_t)cx < boss_slz_x - 0x190) return;
+ V.limitbtm1 = boss_slz_y;
+ V.dle_routine += 2;
+ return;
+ case 2:
+ if ((uint16_t)cx < boss_slz_x) return;
+ spawn_boss(id_BossStarLight, 0, 0, false);
+ return;
+ default: V.limitleft2 = cx; return;
+ }
+}
+
+static void dle_syz(void) {
+ int16_t cx = V.cam[0].x.w.i;
+ if (V.act == 1) {
+ V.limitbtm1 = 0x520;
+ if ((uint16_t)cx < 0x25A0) return;
+ V.limitbtm1 = 0x420;
+ if ((uint16_t)player->y.w.i < 0x4D0) return;
+ V.limitbtm1 = 0x520;
+ return;
+ }
+ if (V.act != 2) return;
+ switch (V.dle_routine) {
+ case 0: {
+ if ((uint16_t)cx < boss_syz_x - 0x140) return;
+ Obj *a1 = FindFreeObj();
+ if (!a1) return;
+ a1->id = id_BossBlock;
+ V.dle_routine += 2;
+ return;
+ }
+ case 2: {
+ if ((uint16_t)cx < boss_syz_x) return;
+ V.limitbtm1 = boss_syz_y;
+ Obj *a1 = FindFreeObj();
+ if (a1) a1->id = id_BossSpringYard, V.dle_routine += 2;
+ V.f_lockscreen = 1;
+ AddPLC(plcid_Boss);
+ return;
+ }
+ default: V.limitleft2 = cx; return;
+ }
+}
+
+static void dle_sbz(void) {
+ int16_t cx = V.cam[0].x.w.i;
+ if (V.act == 0) {
+ V.limitbtm1 = 0x720;
+ if ((uint16_t)cx < 0x1880) return;
+ V.limitbtm1 = 0x620;
+ if ((uint16_t)cx < 0x2000) return;
+ V.limitbtm1 = 0x2A0;
+ return;
+ }
+ if (V.act == 1) {
+ switch (V.dle_routine) {
+ case 0:
+ V.limitbtm1 = 0x800;
+ if ((uint16_t)cx < 0x1800) return;
+ V.limitbtm1 = boss_sbz2_y;
+ if ((uint16_t)cx < 0x1E00) return;
+ V.dle_routine += 2;
+ return;
+ case 2: {
+ if ((uint16_t)cx < boss_sbz2_x - 0x1A0) return;
+ Obj *a1 = FindFreeObj();
+ if (!a1) return;
+ a1->id = id_FalseFloor;
+ V.dle_routine += 2;
+ AddPLC(plcid_EggmanSBZ2);
+ return;
+ }
+ case 4:
+ if ((uint16_t)cx >= boss_sbz2_x - 0xF0) {
+ Obj *a1 = FindFreeObj();
+ if (a1) a1->id = id_ScrapEggman, V.dle_routine += 2;
+ V.f_lockscreen = 1;
+ }
+ V.limitleft2 = V.cam[0].x.w.i;
+ return;
+ default:
+ if ((uint16_t)cx < boss_sbz2_x) V.limitleft2 = cx;
+ return;
+ }
+ }
+ /* the Final Zone */
+ switch (V.dle_routine) {
+ case 0:
+ if ((uint16_t)cx >= boss_fz_x - 0x308) {
+ V.dle_routine += 2;
+ AddPLC(plcid_FZBoss);
+ }
+ break;
+ case 2:
+ if ((uint16_t)cx >= boss_fz_x - 0x150) {
+ Obj *a1 = FindFreeObj();
+ if (a1) {
+ a1->id = id_BossFinal;
+ V.dle_routine += 2;
+ V.f_lockscreen = 1;
+ }
+ }
+ break;
+ case 4:
+ if ((uint16_t)cx >= boss_fz_x) V.dle_routine += 2;
+ break;
+ case 6: return;
+ default: break;
+ }
+ V.limitleft2 = V.cam[0].x.w.i;
+}
+
+void DynamicLevelEvents(void) {
+ switch (V.zone) {
+ case id_GHZ: dle_ghz(); break;
+ case id_LZ: dle_lz(); break;
+ case id_MZ: dle_mz(); break;
+ case id_SLZ: dle_slz(); break;
+ case id_SYZ: dle_syz(); break;
+ case id_SBZ: dle_sbz(); break;
+ default: break;
+ }
+ int16_t d1 = 2;
+ int16_t diff = (int16_t)(V.limitbtm1 - V.limitbtm2);
+ if (!diff) return;
+ if ((uint16_t)V.limitbtm1 >= (uint16_t)V.limitbtm2) {
+ if ((uint16_t)(V.cam[0].y.w.i + 8) >= (uint16_t)V.limitbtm2 && (player->status & 2)) d1 = 8;
+ V.limitbtm2 += d1;
+ V.f_bgscrollvert = 1;
+ return;
+ }
+ if ((uint16_t)V.cam[0].y.w.i > (uint16_t)V.limitbtm1) V.limitbtm2 = (int16_t)(V.cam[0].y.w.i & 0xFFFE);
+ V.limitbtm2 -= 2;
+ V.f_bgscrollvert = 1;
+}
diff --git a/games/sonic/src/game.c b/games/sonic/src/game.c
new file mode 100644
index 00000000..3bc4eaa8
--- /dev/null
+++ b/games/sonic/src/game.c
@@ -0,0 +1,227 @@
+/* The level game mode, as the original runs it: the title card while the art loads, the level's
+ * size, layout and palette, Sonic, the HUD and the objects, a fade in, then the main loop (objects,
+ * camera and background, sprites, the object manager, colour cycles) until the level restarts or
+ * the game mode changes; demos replay their recorded buttons. And pausing. */
+#include "s1.h"
+#include "game.h"
+#include "plat.h"
+
+static const uint32_t demo_data[8] = {D_DEMO_INTRO_GHZ, D_DEMO_INTRO_GHZ, D_DEMO_INTRO_MZ, D_DEMO_INTRO_MZ,
+ D_DEMO_INTRO_SYZ, D_DEMO_INTRO_SYZ, D_DEMO_INTRO_SPECIAL_STAGE,
+ D_DEMO_INTRO_SPECIAL_STAGE};
+static const uint32_t demo_end_data[8] = {D_DEMO_ENDING_GHZ1, D_DEMO_ENDING_MZ, D_DEMO_ENDING_SYZ, D_DEMO_ENDING_LZ,
+ D_DEMO_ENDING_SLZ, D_DEMO_ENDING_SBZ1, D_DEMO_ENDING_SBZ2,
+ D_DEMO_ENDING_GHZ2};
+
+static const uint8_t *demo_ptr(void) {
+ if (V.f_demo < 0) return DATA(demo_end_data[(V.creditsnum - 1) & 7]);
+ int z = V.zone;
+ if (V.gamemode == id_Special) z = 6;
+ return DATA(demo_data[z & 7]);
+}
+
+void MoveSonicInDemo(void) {
+ if (!V.f_demo) return;
+ if ((V.jpadhold1 & btnStart) && V.f_demo > 0) V.gamemode = id_Title;
+ const uint8_t *a1 = demo_ptr() + V.btnpushtime1;
+ uint8_t d0 = a1[0];
+ V.jpadhold1 = d0;
+ V.jpadpress1 = d0; /* (REV01: d2 is 0, so every held button reads as pressed) */
+ uint8_t t = (uint8_t)V.btnpushtime2;
+ V.btnpushtime2 = (uint8_t)(t - 1);
+ if (!t) {
+ V.btnpushtime2 = a1[3];
+ V.btnpushtime1 += 2;
+ }
+}
+
+static void clear_level_ram(void) {
+ memset(objs, 0, sizeof objs);
+ /* v_misc_variables, v_levelvariables, v_timingandscreenvariables */
+ V.vblank_routine = 0;
+ V.pcyc_num = V.pcyc_time = 0;
+ V.f_pause = 0;
+ V.f_hblank_pal = 0;
+ V.waterpos1 = V.waterpos2 = V.waterpos3 = 0;
+ V.f_water = V.wtr_routine = V.f_wtr_state = V.f_doupdatesinhblank = 0;
+ memset(V.cam, 0, sizeof V.cam);
+ V.limitleft1 = V.limitright1 = V.limittop1 = V.limitbtm1 = 0;
+ V.limitleft2 = V.limitright2 = V.limittop2 = V.limitbtm2 = 0;
+ V.scrshiftx = V.scrshifty = 0;
+ V.lookshift = 0;
+ V.dle_routine = 0;
+ V.f_nobgscroll = 0;
+ V.fg_xblock = V.fg_yblock = V.bg1_xblock = V.bg1_yblock = V.bg2_xblock = V.bg2_yblock = V.bg3_xblock = V.bg3_yblock = 0;
+ memset(V.scroll_flags, 0, sizeof V.scroll_flags);
+ V.f_bgscrollvert = 0;
+ V.sonframenum = 0, V.f_sonframechg = 0;
+ V.anglebuffer = V.anglebuffer2 = 0;
+ V.opl_routine = 0;
+ V.opl_screen = 0;
+ V.ssangle = V.ssrotate = 0;
+ V.btnpushtime1 = V.btnpushtime2 = 0;
+ V.palchgspeed = 0;
+ V.obj31ypos = 0;
+ V.bossstatus = 0;
+ V.trackpos = 0;
+ V.f_lockscreen = 0;
+ memset(V.lani, 0, sizeof V.lani);
+ V.gfxbigring = 0;
+ V.f_conveyrev = 0;
+ memset(V.obj63, 0, sizeof V.obj63);
+ V.f_wtunnelmode = V.f_playerctrl = V.f_wtunneldisallow = V.f_slidemode = 0;
+ V.obj6B = V.f_lockctrl = V.f_bigring = V.f_obj56 = 0;
+ V.itembonus = V.timebonus = V.ringbonus = 0;
+ V.f_endactbonus = V.sonicend = 0;
+ V.lz_deform = 0;
+ memset(V.f_switch, 0, sizeof V.f_switch);
+ V.oscillate = 0;
+ memset(V.osc, 0, sizeof V.osc);
+ memset(V.ani_time, 0, sizeof V.ani_time);
+ memset(V.ani_frame, 0, sizeof V.ani_frame);
+ V.ani3_buf = 0;
+ memset(V.cam_dup, 0, sizeof V.cam_dup);
+ memset(V.scroll_flags_dup, 0, sizeof V.scroll_flags_dup);
+ memset(&bgscroll, 0, sizeof bgscroll);
+ memset(spritequeue, 0, sizeof spritequeue);
+ palette_cycles_reset();
+}
+
+static const uint16_t water_height[4] = {0xB8, 0x328, 0x900, 0x228};
+
+void GM_Level(void) {
+ V.gamemode |= 0x80;
+ ClearPLC();
+ PaletteFadeOut();
+ if (V.f_demo >= 0) {
+ vdp_load_art(ART_Nem_TitleCard, ArtTile_Title_Card);
+ AddPLC(level_plc1());
+ AddPLC(plcid_Main2);
+ }
+ clear_level_ram();
+ ClearScreen();
+ vdp_backdrop = 0x20;
+ V.hblank_line = 223;
+ if (V.zone == id_LZ) {
+ V.waterpos1 = V.waterpos2 = V.waterpos3 = (int16_t)water_height[V.act & 3];
+ V.wtr_routine = 0;
+ V.f_wtr_state = 0;
+ V.f_water = 1;
+ }
+ V.air = 30;
+ PalLoad(palid_Sonic);
+ if (V.zone == id_LZ) {
+ PalLoad_Fade_Water(V.act == 3 ? palid_SBZ3SonWat : palid_LZSonWater);
+ if (V.lastlamp) V.f_wtr_state = V.lamp_wtrstat;
+ }
+ if (V.f_demo >= 0) {
+ OBJ(2)->id = id_TitleCard;
+ do {
+ V.vblank_routine = id_VBlank_TitleCards;
+ WaitForVBlank();
+ ExecuteObjects();
+ BuildSprites();
+ RunPLC();
+ } while (OBJ(4)->x.w.i != OW(OBJ(4), 0x30) || plc_pending());
+ Hud_Base();
+ }
+ PalLoad_Fade(palid_Sonic);
+ LevelSizeLoad();
+ DeformLayers();
+ V.scroll_flags[0] |= 4;
+ LevelDataLoad();
+ LoadTilesFromStart();
+ ColIndexLoad();
+ LZWaterFeatures();
+ player->id = id_SonicPlayer;
+ if (V.f_demo >= 0) OBJ(1)->id = id_HUD;
+ if (V.f_debugcheat && (V.jpadhold1 & btnA)) V.f_debugmode = 1;
+ V.jpadhold2 = V.jpadpress2 = 0;
+ V.jpadhold1 = V.jpadpress1 = 0;
+ if (V.zone == id_LZ) {
+ OBJ(30)->id = id_WaterSurface, OBJ(30)->x.w.i = 0x60;
+ OBJ(31)->id = id_WaterSurface, OBJ(31)->x.w.i = 0x120;
+ }
+ ObjPosLoad();
+ ExecuteObjects();
+ BuildSprites();
+ if (!V.lastlamp) {
+ V.rings = 0;
+ V.timemin = V.timesec = V.timecent = 0;
+ V.lifecount = 0;
+ }
+ V.f_timeover = 0;
+ V.shield = V.invinc = V.shoes = V.unused1 = 0;
+ V.debuguse = 0;
+ V.f_restart = 0;
+ V.framecount = 0;
+ OscillateNumInit();
+ V.f_scorecount = V.f_ringcount = V.f_timecount = 1;
+ V.btnpushtime1 = 0;
+ const uint8_t *demo = demo_ptr();
+ V.btnpushtime2 = (uint16_t)(uint8_t)(demo[1] - 1);
+ V.generictimer = 1800;
+ if (V.f_demo < 0) V.generictimer = V.creditsnum == 4 ? 510 : 540;
+ if (V.zone == id_LZ) PalLoad_Water(V.act == 3 ? palid_SBZ3Water : palid_LZWater);
+ for (int i = 0; i < 4; i++) {
+ V.vblank_routine = id_VBlank_Levels;
+ WaitForVBlank();
+ }
+ V.pfade_start = 0x20, V.pfade_size = 0x2F;
+ PalFadeIn_Alt();
+ if (V.f_demo >= 0) {
+ OBJ(2)->routine += 2;
+ OBJ(3)->routine += 4;
+ OBJ(4)->routine += 4;
+ OBJ(5)->routine += 4;
+ } else {
+ AddPLC(plcid_Explode);
+ AddPLC(plcid_GHZAnimals + V.zone);
+ }
+ V.gamemode &= 0x7F;
+ for (;;) {
+ PauseGame();
+ V.vblank_routine = id_VBlank_Levels;
+ WaitForVBlank();
+ V.framecount++;
+ MoveSonicInDemo();
+ LZWaterFeatures();
+ ExecuteObjects();
+ if (V.f_restart) return; /* (REV01: GM_Level again, from the main loop) */
+ if (V.debuguse || player->routine < 6) DeformLayers();
+ BuildSprites();
+ ObjPosLoad();
+ PaletteCycle();
+ RunPLC();
+ OscillateNumDo();
+ SynchroAnimate();
+ SignpostArtLoad();
+ if (V.gamemode == id_Demo) {
+ if (V.f_restart || !V.generictimer) goto end_demo;
+ if (V.gamemode == id_Demo) continue;
+ V.gamemode = id_Sega;
+ return;
+ }
+ if (V.gamemode != id_Level) return;
+ }
+end_demo:
+ if (V.gamemode == id_Demo) {
+ V.gamemode = id_Sega;
+ if (V.f_demo < 0) V.gamemode = id_Credits;
+ }
+ V.generictimer = 60;
+ V.pfade_start = 0, V.pfade_size = 0x3F;
+ V.palchgspeed = 0;
+ while (V.generictimer) {
+ V.vblank_routine = id_VBlank_Levels;
+ WaitForVBlank();
+ MoveSonicInDemo();
+ ExecuteObjects();
+ BuildSprites();
+ ObjPosLoad();
+ if ((int16_t)--V.palchgspeed < 0) {
+ V.palchgspeed = 2;
+ FadeOut_ToBlack();
+ }
+ }
+}
diff --git a/games/sonic/src/game.h b/games/sonic/src/game.h
new file mode 100644
index 00000000..f5fa7351
--- /dev/null
+++ b/games/sonic/src/game.h
@@ -0,0 +1,61 @@
+/* Sonic the Hedgehog: the parts that call each other across files. */
+#ifndef S1_GAME_H
+#define S1_GAME_H
+#include "s1.h"
+
+/* game modes (game.c, screens.c, special.c, ending.c) */
+void game_init(void);
+void GM_Sega(void);
+void GM_Title(void);
+void GM_Level(void);
+void GM_Special(void);
+void GM_Continue(void);
+void GM_Ending(void);
+void GM_Credits(void);
+void PauseGame(void);
+void pause_overlay_draw(void);
+
+/* saves (save.c) */
+void save_restore_copy(void);
+void game_save_on_quit(void);
+void save_progress(void);
+bool save_load_progress(void);
+bool save_exists(void);
+
+/* Sonic (sonic.c, react.c) */
+void SonicPlayer(Obj *o);
+void Sonic_ResetOnFloor(Obj *o);
+void Sonic_AnglePos(Obj *o);
+void Sonic_LoadGfx(Obj *o);
+int ReactToItem(Obj *o);
+int HurtSonic(Obj *o, Obj *by);
+void KillSonic(Obj *o, Obj *by);
+void DebugMode(Obj *o);
+extern uint16_t tracksonic[64][2];
+
+/* solid objects and platforms (solid.c) */
+int SolidObject(Obj *o, int16_t d1, int16_t d2, int16_t d3, int16_t d4);
+int SolidObject_NoRenderChk(Obj *o, int16_t d1, int16_t d2, int16_t d3, int16_t d4);
+int SolidObject_Heightmap(Obj *o, int16_t d1, int16_t d2, const uint8_t *heights);
+void PlatformObject(Obj *o, int16_t d1);
+void PlatformObject_CustomHeight(Obj *o, int16_t d1, int16_t d3);
+void Plat_NoXCheck(Obj *o);
+void Plat_NoXCheck_AltY(Obj *o, int16_t y);
+void Plat_NoCheck_ext(Obj *o);
+void SlopeObject(Obj *o, int16_t d1, const uint8_t *heights);
+void ExitPlatform(Obj *o, int16_t d1);
+void ExitPlatform2(Obj *o, int16_t d1, int16_t d2);
+void MvSonicOnPtfm(Obj *o, int16_t d2, int16_t d3);
+void MvSonicOnPtfm2(Obj *o, int16_t d2);
+
+/* the HUD, water, level art (hud.c, water.c, anim.c) */
+void HUD_Update(void);
+void Hud_Base(void);
+void ResumeMusic(void);
+void PalCycle_SS(void);
+void Lamp_LoadInfo(void);
+int level_plc1(void);
+void palette_cycles_reset(void);
+bool obj_far_x(int16_t x);
+extern const int8_t *const drown_wobble_ptr;
+#endif
diff --git a/games/sonic/src/icon.png b/games/sonic/src/icon.png
new file mode 100644
index 00000000..608fe4b0
Binary files /dev/null and b/games/sonic/src/icon.png differ
diff --git a/games/sonic/src/level.c b/games/sonic/src/level.c
new file mode 100644
index 00000000..6f641551
--- /dev/null
+++ b/games/sonic/src/level.c
@@ -0,0 +1,749 @@
+/* The level: its size and start, its layout, 16x16 blocks and 256x256 chunks; drawing them into
+ * the two planes as the camera moves (a column or a row of blocks each time it crosses 16 pixels,
+ * the background in sections that scroll at their own speeds); the camera following Sonic; each
+ * zone's background deformation (the scroll table: a scroll a line); the boundaries that move as
+ * Sonic goes through an act; the art loaded for each zone; the oscillating numbers platforms swing
+ * by, and the frames of animations shared by all objects of a kind (rings, signposts...). */
+#include "s1.h"
+
+uint8_t lvllayout[8][2][0x40];
+static int nchunks; /* (in the zone's 256x256 chunks) */
+const uint16_t *blocks16;
+const uint16_t *chunks256;
+union bgscroll_u bgscroll;
+HScroll hscroll[256];
+
+/* ------------------------------------------------------------------ size and start */
+static const int16_t level_size[8][4][4] = {
+ {{0, 0x24BF, 0, 0x300}, {0, 0x1EBF, 0, 0x300}, {0, 0x2960, 0, 0x300}, {0, 0x2ABF, 0, 0x300}},
+ {{0, 0x19BF, 0, 0x530}, {0, 0x10AF, 0, 0x720}, {0, 0x202F, -0x100, 0x800}, {0, 0x20BF, 0, 0x720}},
+ {{0, 0x17BF, 0, 0x1D0}, {0, 0x17BF, 0, 0x520}, {0, 0x1800, 0, 0x720}, {0, 0x16BF, 0, 0x720}},
+ {{0, 0x1FBF, 0, 0x640}, {0, 0x1FBF, 0, 0x640}, {0, 0x2000, 0, 0x6C0}, {0, 0x3EC0, 0, 0x720}},
+ {{0, 0x22C0, 0, 0x420}, {0, 0x28C0, 0, 0x520}, {0, 0x2C00, 0, 0x620}, {0, 0x2EC0, 0, 0x620}},
+ {{0, 0x21C0, 0, 0x720}, {0, 0x1E40, -0x100, 0x800}, {0x2080, 0x2460, 0x510, 0x510}, {0, 0x3EC0, 0, 0x720}},
+ {{0, 0x500, 0x110, 0x110}, {0, 0xDC0, 0x110, 0x110}, {0, 0x2FFF, 0, 0x320}, {0, 0x2FFF, 0, 0x320}},
+ {{0}},
+};
+
+static const uint32_t start_loc[7][4] = {
+ {D_START_GHZ1, D_START_GHZ2, D_START_GHZ3, 0},
+ {D_START_LZ1, D_START_LZ2, D_START_LZ3, D_START_SBZ3},
+ {D_START_MZ1, D_START_MZ2, D_START_MZ3, 0},
+ {D_START_SLZ1, D_START_SLZ2, D_START_SLZ3, 0},
+ {D_START_SYZ1, D_START_SYZ2, D_START_SYZ3, 0},
+ {D_START_SBZ1, D_START_SBZ2, D_START_FZ, 0},
+ {D_START_END1, D_START_END2, 0, 0},
+};
+static const uint32_t ending_start[8] = {
+ D_START_CREDITS_DEMOS_GHZ1_CREDITS_DEMO_1, D_START_CREDITS_DEMOS_MZ2_CREDITS_DEMO,
+ D_START_CREDITS_DEMOS_SYZ3_CREDITS_DEMO, D_START_CREDITS_DEMOS_LZ3_CREDITS_DEMO,
+ D_START_CREDITS_DEMOS_SLZ3_CREDITS_DEMO, D_START_CREDITS_DEMOS_SBZ1_CREDITS_DEMO,
+ D_START_CREDITS_DEMOS_SBZ2_CREDITS_DEMO, D_START_CREDITS_DEMOS_GHZ1_CREDITS_DEMO_2,
+};
+static const uint8_t loop_chunks[7][4] = {
+ {0xB5, 0x7F, 0x1F, 0x20}, {0x7F, 0x7F, 0x7F, 0x7F}, {0x7F, 0x7F, 0x7F, 0x7F}, {0xAA, 0xB4, 0x7F, 0x7F},
+ {0x7F, 0x7F, 0x7F, 0x7F}, {0x7F, 0x7F, 0x7F, 0x7F}, {0x7F, 0x7F, 0x7F, 0x7F},
+};
+
+void Lamp_LoadInfo(void);
+static void BgScrollSpeed(int16_t y, int16_t x);
+
+void LevelSizeLoad(void) {
+ V.dle_routine = 0;
+ const int16_t *s = level_size[V.zone][V.act & 3];
+ V.limitleft2 = V.limitleft1 = s[0];
+ V.limitright2 = V.limitright1 = s[1];
+ V.limittop2 = V.limittop1 = s[2];
+ V.limitbtm2 = V.limitbtm1 = s[3];
+ V.limitleft3 = (int16_t)(V.limitleft2 + 0x240);
+ V.fg_xblock = V.fg_yblock = 0x10;
+ V.lookshift = 0x60;
+ int16_t x, y;
+ if (V.lastlamp) {
+ Lamp_LoadInfo();
+ x = player->x.w.i, y = player->y.w.i;
+ } else {
+ const uint16_t *p = DATAW(start_loc[V.zone][V.act & 3]);
+ if (V.f_demo < 0) p = DATAW(ending_start[(V.creditsnum - 1) & 7]);
+ x = (int16_t)p[0], y = (int16_t)p[1];
+ player->x.w.i = x, player->y.w.i = y;
+ }
+ uint16_t cx = (uint16_t)(x - 160);
+ if ((uint16_t)x < 160) cx = 0;
+ if (cx >= (uint16_t)V.limitright2) cx = (uint16_t)V.limitright2;
+ V.cam[0].x.w.i = (int16_t)cx;
+ uint16_t cy = (uint16_t)(y - 96);
+ if ((uint16_t)y < 96) cy = 0;
+ if ((int16_t)cy >= V.limitbtm2) cy = (uint16_t)V.limitbtm2;
+ V.cam[0].y.w.i = (int16_t)cy;
+ BgScrollSpeed((int16_t)cy, (int16_t)cx);
+ memcpy(V.loop256, loop_chunks[V.zone > 6 ? 6 : V.zone], 4);
+}
+
+static void BgScrollSpeed(int16_t y, int16_t x) {
+ if (!V.lastlamp) {
+ V.cam[1].y.w.i = V.cam[2].y.w.i = y;
+ V.cam[1].x.w.i = V.cam[2].x.w.i = V.cam[3].x.w.i = x;
+ }
+ int32_t d0 = y;
+ switch (V.zone) {
+ case id_GHZ:
+ V.cam[1].x.l = V.cam[1].y.l = V.cam[2].y.l = V.cam[3].y.l = 0;
+ bgscroll.l[0] = bgscroll.l[1] = bgscroll.l[2] = 0;
+ break;
+ case id_LZ: V.cam[1].y.w.i = (int16_t)(d0 >> 1); break;
+ case id_MZ: break;
+ case id_SLZ:
+ V.cam[1].y.w.i = (int16_t)((d0 >> 1) + 0xC0);
+ V.cam[1].x.l = 0;
+ break;
+ case id_SYZ:
+ d0 = (d0 * 0x30) >> 8;
+ V.cam[1].y.w.i = (int16_t)(d0 + 1);
+ V.cam[1].x.l = 0;
+ break;
+ case id_SBZ: V.cam[1].y.w.i = (int16_t)(((y & 0x7F8) >> 3) + 1); break;
+ default: { /* the ending */
+ int16_t bx = (int16_t)(V.cam[0].x.w.i >> 1);
+ V.cam[1].x.w.i = V.cam[2].x.w.i = bx;
+ bx = (int16_t)(bx >> 2);
+ V.cam[3].x.w.i = (int16_t)(bx * 3);
+ V.cam[1].y.l = V.cam[2].y.l = V.cam[3].y.l = 0;
+ bgscroll.l[0] = bgscroll.l[1] = bgscroll.l[2] = 0;
+ break;
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ layout and blocks */
+static const uint32_t layouts[7][4][2] = {
+ {{D_LEVEL_GHZ1, D_LEVEL_GHZBG}, {D_LEVEL_GHZ2, D_LEVEL_GHZBG}, {D_LEVEL_GHZ3, D_LEVEL_GHZBG}, {0, 0}},
+ {{D_LEVEL_LZ1, D_LEVEL_LZBG}, {D_LEVEL_LZ2, D_LEVEL_LZBG}, {D_LEVEL_LZ3, D_LEVEL_LZBG}, {D_LEVEL_SBZ3, D_LEVEL_LZBG}},
+ {{D_LEVEL_MZ1, D_LEVEL_MZ1BG}, {D_LEVEL_MZ2, D_LEVEL_MZ2BG}, {D_LEVEL_MZ3, D_LEVEL_MZ3BG}, {0, 0}},
+ {{D_LEVEL_SLZ1, D_LEVEL_SLZBG}, {D_LEVEL_SLZ2, D_LEVEL_SLZBG}, {D_LEVEL_SLZ3, D_LEVEL_SLZBG}, {0, 0}},
+ {{D_LEVEL_SYZ1, D_LEVEL_SYZBG}, {D_LEVEL_SYZ2, D_LEVEL_SYZBG}, {D_LEVEL_SYZ3, D_LEVEL_SYZBG}, {0, 0}},
+ {{D_LEVEL_SBZ1, D_LEVEL_SBZ1BG}, {D_LEVEL_SBZ2, D_LEVEL_SBZ2BG}, {D_LEVEL_SBZ2, D_LEVEL_SBZ2BG}, {0, 0}},
+ {{D_LEVEL_ENDING, D_LEVEL_GHZBG}, {D_LEVEL_ENDING, D_LEVEL_GHZBG}, {0, 0}, {0, 0}},
+};
+
+static void layout_load(int plane, uint32_t off) {
+ if (!off) return;
+ const uint8_t *p = DATA(off);
+ int w = p[0] + 1, h = p[1] + 1;
+ p += 2;
+ for (int r = 0; r < h && r < 8; r++)
+ for (int c = 0; c < w; c++) {
+ /* (rows longer than $40 run into the next plane's, as in the original) */
+ int at = r * 0x80 + plane * 0x40 + c;
+ if (at < 0x400) (&lvllayout[0][0][0])[at] = p[r * w + c];
+ }
+}
+
+void LevelLayoutLoad(void) {
+ memset(lvllayout, 0, sizeof lvllayout);
+ layout_load(0, layouts[V.zone][V.act & 3][0]);
+ layout_load(1, layouts[V.zone][V.act & 3][1]);
+}
+
+static const struct {
+ uint32_t blocks, chunks, col;
+ uint8_t nchunks, plc1, plc2, pal;
+} headers[7] = {
+ {D_BLK16_GHZ, D_BLK256_GHZ, D_COL_GHZ, N_BLK256_GHZ, plcid_GHZ, plcid_GHZ2, palid_GHZ},
+ {D_BLK16_LZ, D_BLK256_LZ, D_COL_LZ, N_BLK256_LZ, plcid_LZ, plcid_LZ2, palid_LZ},
+ {D_BLK16_MZ, D_BLK256_MZ, D_COL_MZ, N_BLK256_MZ, plcid_MZ, plcid_MZ2, palid_MZ},
+ {D_BLK16_SLZ, D_BLK256_SLZ, D_COL_SLZ, N_BLK256_SLZ, plcid_SLZ, plcid_SLZ2, palid_SLZ},
+ {D_BLK16_SYZ, D_BLK256_SYZ, D_COL_SYZ, N_BLK256_SYZ, plcid_SYZ, plcid_SYZ2, palid_SYZ},
+ {D_BLK16_SBZ, D_BLK256_SBZ, D_COL_SBZ, N_BLK256_SBZ, plcid_SBZ, plcid_SBZ2, palid_SBZ1},
+ {D_BLK16_GHZ, D_BLK256_GHZ, D_COL_GHZ, N_BLK256_GHZ, 0xFF, 0xFF, palid_Ending},
+};
+int level_plc1(void) { return headers[V.zone].plc1; }
+int level_nchunks(void) { return nchunks; }
+
+void LevelDataLoad(void) {
+ blocks16 = DATAW(headers[V.zone].blocks);
+ chunks256 = DATAW(headers[V.zone].chunks);
+ nchunks = headers[V.zone].nchunks;
+ LevelLayoutLoad();
+ int pal = headers[V.zone].pal;
+ if (V.zone == id_LZ && V.act == 3) pal = palid_SBZ3;
+ if ((V.zone == id_SBZ && V.act == 1) || (V.zone == id_SBZ && V.act == 2)) pal = palid_SBZ2;
+ PalLoad_Fade(pal);
+ if (headers[V.zone].plc2 != 0xFF) AddPLC(headers[V.zone].plc2);
+}
+
+void ColIndexLoad(void) { V.collindex = DATA(headers[V.zone > 5 ? 0 : V.zone].col); }
+
+/* ------------------------------------------------------------------ drawing blocks into the planes */
+/* the block at (x, y) of a layout (0 foreground, 1 background), and the chunk word holding it */
+static const uint16_t *block_at(int plane, int x, int y, uint16_t *word) {
+ /* (the layout index can reach into the other plane's row: x up to $7F chunks, as in the original) */
+ int c = (&lvllayout[0][0][0])[(((uint16_t)y >> 1) & 0x380) + (((uint16_t)x >> 8) & 0x7F) + plane * 0x40];
+ *word = 0;
+ if (!c || ((c - 1) & 0x7F) >= nchunks) return blocks16;
+ uint16_t w = chunks256[((c - 1) & 0x7F) * 256 + ((y >> 4) & 15) * 16 + ((x >> 4) & 15)];
+ *word = w;
+ return blocks16 + (w & 0x3FF) * 4;
+}
+
+static void draw_block(uint16_t (*pl)[64], int col, int row, const uint16_t *b, uint16_t w) {
+ uint16_t t0 = b[0], t1 = b[1], t2 = b[2], t3 = b[3];
+ if (w & 0x1000) { /* flipped vertically: bottom pair on top */
+ uint16_t a = t0, c = t1;
+ t0 = t2 ^ 0x1000, t1 = t3 ^ 0x1000, t2 = a ^ 0x1000, t3 = c ^ 0x1000;
+ }
+ if (w & 0x800) {
+ uint16_t a = t0, c = t2;
+ t0 = t1 ^ 0x800, t1 = a ^ 0x800, t2 = t3 ^ 0x800, t3 = c ^ 0x800;
+ }
+ pl[row & 31][col & 63] = t0;
+ pl[row & 31][(col + 1) & 63] = t1;
+ pl[(row + 1) & 31][col & 63] = t2;
+ pl[(row + 1) & 31][(col + 1) & 63] = t3;
+}
+
+/* a block of the layout at camera + (dx, dy), into the plane where the camera puts it */
+static void draw_at(uint16_t (*pl)[64], int plane, const Cam *cam, int dy, int dx) {
+ int x = (int16_t)(cam->x.w.i + dx), y = (int16_t)(cam->y.w.i + dy);
+ uint16_t w;
+ const uint16_t *b = block_at(plane, x, y, &w);
+ draw_block(pl, (x & 0x1F0) >> 3, (y & 0xF0) >> 3, b, w);
+}
+/* at layout x = dx (not following the camera), camera y + dy */
+static void draw_at_x0(uint16_t (*pl)[64], int plane, const Cam *cam, int dy, int x) {
+ int y = (int16_t)(cam->y.w.i + dy);
+ uint16_t w;
+ const uint16_t *b = block_at(plane, x, y, &w);
+ draw_block(pl, (x & 0x1F0) >> 3, (y & 0xF0) >> 3, b, w);
+}
+
+static void blocks_lr(uint16_t (*pl)[64], int plane, const Cam *cam, int dy, int dx, int n) {
+ for (int i = 0; i < n; i++) draw_at(pl, plane, cam, dy, dx + i * 16);
+}
+static void blocks_lr_all(uint16_t (*pl)[64], int plane, const Cam *cam, int dy) {
+ for (int i = 0; i < 32; i++) draw_at_x0(pl, plane, cam, dy, i * 16);
+}
+static void blocks_tb(uint16_t (*pl)[64], int plane, const Cam *cam, int dy, int dx, int n) {
+ for (int i = 0; i < n; i++) draw_at(pl, plane, cam, dy + i * 16, dx);
+}
+
+static void draw_fg(const Cam *cam, uint8_t *flags) {
+ if (!*flags) return;
+ if (*flags & 1) blocks_lr(plane_a, 0, cam, -16, -16, 22);
+ if (*flags & 2) blocks_lr(plane_a, 0, cam, 224, -16, 22);
+ if (*flags & 4) blocks_tb(plane_a, 0, cam, -16, -16, 16);
+ if (*flags & 8) blocks_tb(plane_a, 0, cam, -16, 320, 16);
+ *flags &= (uint8_t)~0x0F;
+}
+
+static void draw_bg_top(const Cam *cam, uint8_t *flags) {
+ if (!*flags) return;
+ if (*flags & 1) blocks_lr(plane_b, 1, cam, -16, -16, 22);
+ if (*flags & 2) blocks_lr(plane_b, 1, cam, 224, -16, 22);
+ if (*flags & 4) blocks_tb(plane_b, 1, cam, -16, -16, 16);
+ if (*flags & 8) blocks_tb(plane_b, 1, cam, -16, 320, 16);
+ if (*flags & 0x10) blocks_lr_all(plane_b, 1, cam, -16);
+ if (*flags & 0x20) blocks_lr_all(plane_b, 1, cam, 224);
+ *flags &= (uint8_t)~0x3F;
+}
+
+/* (Scrap Brain and Marble: which camera each row of 16 pixels of the background follows) */
+static const uint8_t scrollmap_sbz[0x22] = {0, 0, 0, 0, 0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 4, 4, 4, 4, 4, 4, 4,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0};
+static const uint8_t scrollmap_mz[0x62] = {
+ 0, 0, 0, 0, 0, 0, 6, 6, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0};
+static const uint8_t scrollmap_ghz[16] = {0, 0, 0, 0, 6, 6, 6, 4, 4, 4, 0, 0, 0, 0, 0, 0};
+
+static const Cam *bg_cam(const Cam *cams, int sel) { return sel <= 2 ? &cams[1] : sel == 4 ? &cams[2] : &cams[3]; }
+
+/* a background row whose section follows the camera chosen by sel (0: the whole width of the layout) */
+static void bg_row(const Cam *cams, int sel, int dy) {
+ if (!sel) blocks_lr_all(plane_b, 1, &cams[1], dy);
+ else blocks_lr(plane_b, 1, bg_cam(cams, sel), dy, -16, 22);
+}
+
+static void draw_scrollmap(const Cam *cams, uint8_t *flags, const uint8_t *map, int ybase, int ymask) {
+ int dy = -16;
+ bool row = false;
+ if (*flags & 1) *flags &= (uint8_t)~1, row = true;
+ else if (*flags & 2) *flags &= (uint8_t)~2, row = true, dy = 224;
+ if (row) bg_row(cams, map[1 + (((cams[1].y.w.i - ybase + dy) & ymask) >> 4)], dy);
+ if (!*flags) return;
+ int dx = -16;
+ uint8_t f = *flags & 0xA8;
+ if (f) *flags = (uint8_t)(f >> 1), dx = 320;
+ const uint8_t *m = map + (((cams[1].y.w.i - ybase) & ymask) >> 4);
+ for (int i = 0; i < 16; i++) {
+ int sel = m[i];
+ if (*flags >> sel & 1) draw_at(plane_b, 1, bg_cam(cams, sel), -16 + i * 16, dx);
+ }
+ *flags = 0;
+}
+
+static void draw_bg_bottom(const Cam *cams, const Cam *cam, uint8_t *flags) {
+ if (!*flags) return;
+ if (V.zone == id_SBZ) {
+ draw_scrollmap(cams, flags, scrollmap_sbz, 0, 0x1F0);
+ return;
+ }
+ if (*flags & 1) *flags &= (uint8_t)~1, blocks_tb(plane_b, 1, cam, 112, -16, 3);
+ if (*flags & 2) *flags &= (uint8_t)~2, blocks_tb(plane_b, 1, cam, 112, 320, 3);
+}
+
+static void draw_bg_block3(const Cam *cams, const Cam *cam, uint8_t *flags) {
+ if (!*flags) return;
+ if (V.zone == id_MZ) {
+ draw_scrollmap(cams, flags, scrollmap_mz, 0x200, 0x7F0);
+ return;
+ }
+ if (*flags & 1) *flags &= (uint8_t)~1, blocks_tb(plane_b, 1, cam, 64, -16, 3);
+ if (*flags & 2) *flags &= (uint8_t)~2, blocks_tb(plane_b, 1, cam, 64, 320, 3);
+}
+
+void LoadTilesAsYouMove_BGOnly(void) {
+ draw_bg_top(&V.cam[1], &V.scroll_flags[1]);
+ draw_bg_bottom(V.cam, &V.cam[2], &V.scroll_flags[2]);
+}
+
+void LoadTilesAsYouMove(void) {
+ draw_bg_top(&V.cam_dup[1], &V.scroll_flags_dup[1]);
+ draw_bg_bottom(V.cam_dup, &V.cam_dup[2], &V.scroll_flags_dup[2]);
+ draw_bg_block3(V.cam_dup, &V.cam_dup[3], &V.scroll_flags_dup[3]);
+ draw_fg(&V.cam_dup[0], &V.scroll_flags_dup[0]);
+}
+
+/* the whole plane's width from the camera on, every row on screen and one more each side */
+static void draw_chunks(uint16_t (*pl)[64], int plane, const Cam *cam) {
+ for (int r = 0; r < 16; r++)
+ for (int i = 0; i < 32; i++) draw_at(pl, plane, cam, -16 + r * 16, i * 16);
+}
+
+static void bg_rows_by_map(const uint8_t *map, int ybase, int ymask, int from) {
+ for (int r = 0; r < 16; r++) {
+ int dy = from + r * 16;
+ bg_row(V.cam, map[((V.cam[1].y.w.i - ybase + dy) & ymask) >> 4], dy);
+ }
+}
+
+void LoadTilesFromStart(void) {
+ draw_chunks(plane_a, 0, &V.cam[0]);
+ if (V.zone == id_GHZ || V.zone == 6) bg_rows_by_map(scrollmap_ghz, 0, 0xF0, 0);
+ else if (V.zone == id_MZ) bg_rows_by_map(scrollmap_mz + 1, 0x200, 0x7F0, -16);
+ else if (V.zone == id_SBZ && V.act == 0) bg_rows_by_map(scrollmap_sbz + 1, 0, 0x1F0, -16);
+ else draw_chunks(plane_b, 1, &V.cam[1]);
+}
+
+/* ------------------------------------------------------------------ the camera */
+static void ScrollHoriz(void) {
+ int16_t old = V.cam[0].x.w.i;
+ int16_t d = (int16_t)(player->x.w.i - V.cam[0].x.w.i - 144);
+ int16_t nx;
+ if ((uint16_t)(player->x.w.i - V.cam[0].x.w.i) < 144) { /* (an unsigned compare, as in the original) */
+ nx = (int16_t)(V.cam[0].x.w.i + d);
+ if (nx <= V.limitleft2) nx = V.limitleft2;
+ } else if ((uint16_t)(player->x.w.i - V.cam[0].x.w.i - 144) >= 16) {
+ d = (int16_t)(d - 16);
+ if ((uint16_t)d >= 16) d = 16;
+ nx = (int16_t)(V.cam[0].x.w.i + d);
+ if (nx >= V.limitright2) nx = V.limitright2;
+ } else {
+ V.scrshiftx = 0;
+ goto blocks;
+ }
+ V.scrshiftx = (int16_t)((nx - V.cam[0].x.w.i) << 8);
+ V.cam[0].x.w.i = nx;
+blocks:
+ if (((V.cam[0].x.w.i & 0x10) ^ V.fg_xblock) == 0) {
+ V.fg_xblock ^= 0x10;
+ V.scroll_flags[0] |= (int16_t)(V.cam[0].x.w.i - old) < 0 ? 4 : 8;
+ }
+}
+
+static void sv_set(int32_t ny) {
+ int16_t old = V.cam[0].y.w.i;
+ int32_t d = ny - V.cam[0].y.l;
+ V.scrshifty = (int16_t)(d >> 8);
+ V.cam[0].y.l = ny;
+ if (((V.cam[0].y.w.i & 0x10) ^ V.fg_yblock) == 0) {
+ V.fg_yblock ^= 0x10;
+ V.scroll_flags[0] |= (int16_t)(V.cam[0].y.w.i - old) < 0 ? 1 : 2;
+ }
+}
+
+static void sv_top(int16_t y) {
+ if (y > V.limittop2) {
+ sv_set((int32_t)y << 16);
+ return;
+ }
+ if (y <= -0x100) {
+ y &= 0x7FF;
+ player->y.w.i &= 0x7FF;
+ V.cam[0].y.w.i &= 0x7FF;
+ V.cam[1].y.w.i &= 0x3FF;
+ } else y = V.limittop2;
+ sv_set((int32_t)y << 16);
+}
+
+static void sv_bottom(int16_t y) {
+ if (y < V.limitbtm2) {
+ sv_set((int32_t)y << 16);
+ return;
+ }
+ if ((uint16_t)y >= 0x800) {
+ player->y.w.i &= 0x7FF;
+ V.cam[0].y.w.i = (int16_t)(V.cam[0].y.w.i - 0x800);
+ V.cam[1].y.w.i &= 0x3FF;
+ y = (int16_t)(y - 0x800);
+ } else y = V.limitbtm2;
+ sv_set((int32_t)y << 16);
+}
+
+static void ScrollVertical(void) {
+ int16_t d = (int16_t)(player->y.w.i - V.cam[0].y.w.i);
+ int16_t px;
+ if (player->status & 4) d -= 5; /* (sonic_height - sonic_roll_height) */
+ if (player->status & 2) {
+ d = (int16_t)(d + 32 - V.lookshift);
+ if (d < 0) goto fast;
+ d = (int16_t)(d - 64);
+ if (d >= 0) goto fast;
+ if (V.f_bgscrollvert) goto boundary_moving;
+ goto no_update;
+ }
+ d = (int16_t)(d - V.lookshift);
+ if (d == 0) {
+ if (V.f_bgscrollvert) goto boundary_moving;
+ no_update:
+ V.scrshifty = 0;
+ return;
+ }
+ if (V.lookshift != 0x60) {
+ px = 2;
+ } else {
+ int16_t s = player->inertia < 0 ? (int16_t)-player->inertia : player->inertia;
+ if ((uint16_t)s >= 0x800) goto fast;
+ px = 6;
+ }
+ goto move;
+fast:
+ px = 16;
+move:
+ if (d > px) {
+ sv_bottom((int16_t)((V.cam[0].y.l + ((int32_t)px << 16)) >> 16));
+ return;
+ }
+ if (d < -px) {
+ sv_top((int16_t)((V.cam[0].y.l - ((int32_t)px << 16)) >> 16));
+ return;
+ }
+ goto sweet;
+boundary_moving:
+ d = 0;
+ V.f_bgscrollvert = 0;
+sweet: {
+ int16_t y = (int16_t)(V.cam[0].y.w.i + d);
+ if (d >= 0) sv_bottom(y);
+ else sv_top(y);
+}
+}
+
+/* ------------------------------------------------------------------ background scrolling */
+static void bgscroll_x(int cam, uint8_t *block, uint8_t *flags, int32_t d, int bit) {
+ int32_t old = V.cam[cam].x.l, n = old + d;
+ V.cam[cam].x.l = n;
+ if ((((n >> 16) & 0x10) ^ *block) != 0) return;
+ *block ^= 0x10;
+ *flags |= (uint8_t)(1 << (n - old < 0 ? bit : bit + 1));
+}
+static void BGScroll_Block1(int32_t d, int bit) { bgscroll_x(1, &V.bg1_xblock, &V.scroll_flags[1], d, bit); }
+static void BGScroll_Block2(int32_t d, int bit) { bgscroll_x(2, &V.bg2_xblock, &V.scroll_flags[2], d, bit); }
+static void BGScroll_Block3(int32_t d, int bit) { bgscroll_x(3, &V.bg3_xblock, &V.scroll_flags[3], d, bit); }
+
+static void BGScroll_YRelative(int32_t d5) {
+ int32_t old = V.cam[1].y.l, n = old + d5;
+ V.cam[1].y.l = n;
+ if ((((n >> 16) & 0x10) ^ V.bg1_yblock) != 0) return;
+ V.bg1_yblock ^= 0x10;
+ V.scroll_flags[1] |= n - old < 0 ? 1 : 2;
+}
+static void BGScroll_XY(int32_t d4, int32_t d5) {
+ int32_t old = V.cam[1].x.l, n = old + d4;
+ V.cam[1].x.l = n;
+ if ((((n >> 16) & 0x10) ^ V.bg1_xblock) == 0) {
+ V.bg1_xblock ^= 0x10;
+ V.scroll_flags[1] |= n - old < 0 ? 4 : 8;
+ }
+ BGScroll_YRelative(d5);
+}
+static void BGScroll_Y(int32_t d5) {
+ int32_t old = V.cam[1].y.l, n = old + d5;
+ V.cam[1].y.l = n;
+ if ((((n >> 16) & 0x10) ^ V.bg1_yblock) != 0) return;
+ V.bg1_yblock ^= 0x10;
+ V.scroll_flags[1] |= n - old < 0 ? 0x10 : 0x20;
+}
+static void BGScroll_YAbsolute(int16_t y) {
+ int16_t old = V.cam[1].y.w.i;
+ V.cam[1].y.w.i = y;
+ if (((y & 0x10) ^ V.bg1_yblock) != 0) return;
+ V.bg1_yblock ^= 0x10;
+ V.scroll_flags[1] |= (int16_t)(y - old) < 0 ? 1 : 2;
+}
+
+/* the scroll table from the background scroll buffer: a value for each 16 lines of background */
+static void BGScroll_X(const int16_t *a2, int16_t d2) {
+ int16_t fg = (int16_t)-V.cam[0].x.w.i;
+ int skip = d2 & 0xF, line = 0;
+ int16_t v = *a2++;
+ for (int k = skip; k < 16 && line < 224; k++) hscroll[line].fg = fg, hscroll[line].bg = v, line++;
+ for (int b = 0; b < 14; b++) {
+ v = *a2++;
+ for (int k = 0; k < 16 && line < 240; k++) hscroll[line].fg = fg, hscroll[line].bg = v, line++;
+ }
+}
+
+/* a sequence of n values going from start (16.16) by step */
+static void ramp(int16_t *to, int n, int16_t start, int32_t step) {
+ int32_t d3 = (uint16_t)start;
+ for (int i = 0; i < n; i++) {
+ to[i] = (int16_t)d3;
+ /* (swap, add.l, swap: the step adds to the value with its fraction above it) */
+ uint32_t sw = ((uint32_t)d3 << 16) | ((uint32_t)d3 >> 16);
+ sw += (uint32_t)step;
+ d3 = (int32_t)((sw << 16) | (sw >> 16));
+ }
+}
+
+static void deform_ghz(void) {
+ int32_t d4 = (int32_t)V.scrshiftx * 0x60;
+ BGScroll_Block3(d4, 0);
+ d4 = (int32_t)V.scrshiftx * 0x80;
+ BGScroll_Block2(d4, 0);
+ int16_t y = (int16_t)(-((V.cam[0].y.w.i & 0x7FF) >> 5) + 0x20);
+ if (y < 0) y = 0;
+ V.bgscrposy_vdp = y;
+ int16_t fg = (int16_t)(V.gamemode == id_Title ? 0 : -V.cam[0].x.w.i);
+ bgscroll.l[0] += 0x10000, bgscroll.l[1] += 0xC000, bgscroll.l[2] += 0x8000;
+ int line = 0;
+ int16_t v = (int16_t)-((int16_t)(bgscroll.l[0] >> 16) + V.cam[3].x.w.i);
+ for (int n = 32 - y; n > 0; n--) hscroll[line].fg = fg, hscroll[line++].bg = v;
+ v = (int16_t)-((int16_t)(bgscroll.l[1] >> 16) + V.cam[3].x.w.i);
+ for (int n = 0; n < 16; n++) hscroll[line].fg = fg, hscroll[line++].bg = v;
+ v = (int16_t)-((int16_t)(bgscroll.l[2] >> 16) + V.cam[3].x.w.i);
+ for (int n = 0; n < 16; n++) hscroll[line].fg = fg, hscroll[line++].bg = v;
+ v = (int16_t)-V.cam[3].x.w.i;
+ for (int n = 0; n < 48; n++) hscroll[line].fg = fg, hscroll[line++].bg = v;
+ v = (int16_t)-V.cam[2].x.w.i;
+ for (int n = 0; n < 40; n++) hscroll[line].fg = fg, hscroll[line++].bg = v;
+ /* the water: faster the lower, from the hills' speed to the camera's */
+ int16_t d0 = V.cam[2].x.w.i;
+ int32_t d2 = (int16_t)(V.cam[0].x.w.i - d0);
+ d2 = (int16_t)((d2 << 8) / 0x68);
+ d2 <<= 8;
+ uint32_t d3 = (uint16_t)d0;
+ for (int n = 72 + y; n > 0 && line < 256; n--) {
+ hscroll[line].fg = fg, hscroll[line++].bg = (int16_t)-(int16_t)d3;
+ uint32_t sw = (d3 << 16) | (d3 >> 16);
+ sw += (uint32_t)d2;
+ d3 = (sw << 16) | (sw >> 16);
+ }
+}
+
+#define drown_wobble ((const int8_t *)DATA(D_TAB_DROWN_WOBBLEDATA))
+static const int8_t lz_scroll[256] = {
+ 1, 1, 2, 2, 3, 3, 3, 3, 2, 2, 1, 1, [128] = -1, -1, -2, -2, -3, -3, -3, -3, -2, -2, -1, -1,
+ [160] = 1, 1, 2, 2, 3, 3, 3, 3, 2, 2, 1, 1};
+
+static void deform_lz(void) {
+ BGScroll_XY((int32_t)V.scrshiftx << 7, (int32_t)V.scrshifty << 7);
+ V.bgscrposy_vdp = V.cam[1].y.w.i;
+ uint8_t d2 = (uint8_t)(V.lz_deform >> 8), d3 = d2;
+ V.lz_deform += 0x80;
+ d2 = (uint8_t)(d2 + V.cam[1].y.w.i);
+ d3 = (uint8_t)(d3 + V.cam[0].y.w.i);
+ int16_t fg = (int16_t)-V.cam[0].x.w.i, bg = (int16_t)-V.cam[1].x.w.i;
+ int16_t wy = V.waterpos1, sy = V.cam[0].y.w.i;
+ for (int line = 0; line < 224; line++, sy++, d2++, d3++) {
+ if (sy < wy) hscroll[line].fg = fg, hscroll[line].bg = bg;
+ else {
+ hscroll[line].fg = (int16_t)(fg + lz_scroll[d3]);
+ hscroll[line].bg = (int16_t)(bg + drown_wobble[d2]);
+ }
+ }
+}
+
+static void deform_mz(void) {
+ BGScroll_Block1((int32_t)V.scrshiftx * 0xC0, 2);
+ BGScroll_Block3((int32_t)V.scrshiftx * 0x40, 6);
+ BGScroll_Block2((int32_t)V.scrshiftx * 0x80, 4);
+ int16_t d0 = 512;
+ int16_t d1 = (int16_t)(V.cam[0].y.w.i - 456);
+ if ((uint16_t)V.cam[0].y.w.i >= 456) d0 = (int16_t)(d0 + ((d1 * 3) >> 2));
+ V.cam[2].y.w.i = V.cam[3].y.w.i = d0;
+ BGScroll_YAbsolute(d0);
+ V.bgscrposy_vdp = V.cam[1].y.w.i;
+ V.scroll_flags[3] |= V.scroll_flags[1] | V.scroll_flags[2];
+ V.scroll_flags[1] = V.scroll_flags[2] = 0;
+ int16_t d2 = (int16_t)-V.cam[0].x.w.i, *a1 = bgscroll.w;
+ int32_t st = (int16_t)(((d2 >> 2) - d2) * 8 / 5);
+ st <<= 12;
+ ramp(a1, 5, (int16_t)(d2 >> 1), st), a1 += 5;
+ for (int i = 0; i < 2; i++) *a1++ = (int16_t)-V.cam[3].x.w.i;
+ for (int i = 0; i < 9; i++) *a1++ = (int16_t)-V.cam[2].x.w.i;
+ for (int i = 0; i < 16; i++) *a1++ = (int16_t)-V.cam[1].x.w.i;
+ int16_t y = (int16_t)(V.cam[1].y.w.i - 512);
+ int16_t idx = (uint16_t)y >= 0x100 ? 0x100 : y;
+ BGScroll_X(bgscroll.w + ((idx & 0x1F0) >> 4), y);
+}
+
+static void deform_slz(void) {
+ BGScroll_Y((int32_t)V.scrshifty << 7);
+ V.bgscrposy_vdp = V.cam[1].y.w.i;
+ int16_t d2 = (int16_t)-V.cam[0].x.w.i, *a1 = bgscroll.w;
+ int32_t st = (int16_t)((((d2 >> 3) - d2) << 4) / 0x1C);
+ st <<= 12;
+ ramp(a1, 28, d2, st), a1 += 28;
+ int16_t d0 = (int16_t)(d2 >> 3);
+ d0 = (int16_t)(d0 + (d0 >> 1));
+ for (int i = 0; i < 5; i++) *a1++ = d0;
+ for (int i = 0; i < 5; i++) *a1++ = (int16_t)(d2 >> 2);
+ for (int i = 0; i < 30; i++) *a1++ = (int16_t)(d2 >> 1);
+ int16_t y = V.cam[1].y.w.i;
+ BGScroll_X(bgscroll.w + (((y - 0xC0) & 0x3F0) >> 4), y);
+}
+
+static void deform_syz(void) {
+ BGScroll_Y((int32_t)V.scrshifty * 0x30);
+ V.bgscrposy_vdp = V.cam[1].y.w.i;
+ int16_t d2 = (int16_t)-V.cam[0].x.w.i, *a1 = bgscroll.w;
+ int32_t st = (int16_t)((((d2 >> 3) - d2) << 3) / 8);
+ st <<= 12;
+ ramp(a1, 8, (int16_t)(d2 >> 1), st), a1 += 8;
+ for (int i = 0; i < 5; i++) *a1++ = (int16_t)(d2 >> 3);
+ for (int i = 0; i < 6; i++) *a1++ = (int16_t)(d2 >> 2);
+ st = (int16_t)(((d2 - (d2 >> 1)) << 4) / 0xE);
+ st <<= 12;
+ ramp(a1, 14, (int16_t)(d2 >> 1), st);
+ int16_t y = V.cam[1].y.w.i;
+ BGScroll_X(bgscroll.w + ((y & 0x1F0) >> 4), y);
+}
+
+static void deform_sbz(void) {
+ if (V.act) {
+ BGScroll_XY((int32_t)V.scrshiftx << 6, (int32_t)V.scrshifty << 5);
+ V.bgscrposy_vdp = V.cam[1].y.w.i;
+ for (int i = 0; i < 224; i++) hscroll[i].fg = (int16_t)-V.cam[0].x.w.i, hscroll[i].bg = (int16_t)-V.cam[1].x.w.i;
+ return;
+ }
+ BGScroll_Block1((int32_t)V.scrshiftx << 7, 2);
+ BGScroll_Block3((int32_t)V.scrshiftx << 6, 6);
+ BGScroll_Block2((int32_t)V.scrshiftx * 0x60, 4);
+ BGScroll_YRelative((int32_t)V.scrshifty << 5);
+ V.cam[2].y.w.i = V.cam[3].y.w.i = V.bgscrposy_vdp = V.cam[1].y.w.i;
+ V.scroll_flags[2] |= V.scroll_flags[1] | V.scroll_flags[3];
+ V.scroll_flags[1] = V.scroll_flags[3] = 0;
+ int16_t d2 = (int16_t)(-V.cam[0].x.w.i >> 2), *a1 = bgscroll.w;
+ int32_t st = (int16_t)((((d2 >> 1) - d2) << 3) / 4);
+ st <<= 12;
+ ramp(a1, 4, d2, st), a1 += 4;
+ for (int i = 0; i < 10; i++) *a1++ = (int16_t)-V.cam[3].x.w.i;
+ for (int i = 0; i < 7; i++) *a1++ = (int16_t)-V.cam[2].x.w.i;
+ for (int i = 0; i < 11; i++) *a1++ = (int16_t)-V.cam[1].x.w.i;
+ int16_t y = V.cam[1].y.w.i;
+ BGScroll_X(bgscroll.w + ((y & 0x1F0) >> 4), y);
+}
+
+void DeformLayers(void) {
+ if (V.f_nobgscroll) return;
+ memset(V.scroll_flags, 0, sizeof V.scroll_flags);
+ ScrollHoriz();
+ ScrollVertical();
+ DynamicLevelEvents();
+ V.scrposy_vdp = V.cam[0].y.w.i;
+ V.bgscrposy_vdp = V.cam[1].y.w.i;
+ switch (V.zone) {
+ case id_LZ: deform_lz(); break;
+ case id_MZ: deform_mz(); break;
+ case id_SLZ: deform_slz(); break;
+ case id_SYZ: deform_syz(); break;
+ case id_SBZ: deform_sbz(); break;
+ default: deform_ghz(); break;
+ }
+}
+
+/* ------------------------------------------------------------------ art (pattern load cues) */
+/* The original decompresses the art a few tiles a frame; here it is in place, so a cue loads at once. */
+void AddPLC(int id) {
+ const uint16_t *t = DATAW(D_PLC);
+ const uint16_t *l = DATAW(D_PLC + t[1 + id]);
+ for (int i = 0; i < l[0]; i++) vdp_load_art(l[1 + i * 2], l[2 + i * 2]);
+}
+void NewPLC(int id) { AddPLC(id); }
+void QuickPLC(int id) { AddPLC(id); }
+void ClearPLC(void) {}
+void RunPLC(void) {}
+bool plc_pending(void) { return false; }
+
+void ClearScreen(void) {
+ vdp_clear_planes();
+ memset(hscroll, 0, sizeof hscroll);
+ memset(spritetable, 0, sizeof spritetable);
+ V.scrposy_vdp = V.bgscrposy_vdp = 0;
+}
+
+/* ------------------------------------------------------------------ oscillating numbers, shared animations */
+void OscillateNumInit(void) {
+ static const uint16_t base[0x21] = {0x7C, 0x80, 0, 0x80, 0, 0x80, 0, 0x80, 0, 0x80, 0, 0x80, 0, 0x80, 0, 0x80, 0,
+ 0x80, 0, 0x50F0, 0x11E, 0x2080, 0xB4, 0x3080, 0x10E, 0x5080, 0x1C2, 0x7080,
+ 0x276, 0x80, 0, 0x80, 0};
+ V.oscillate = base[0];
+ memcpy(V.osc, base + 1, sizeof V.osc);
+}
+
+void OscillateNumDo(void) {
+ static const uint16_t settings[16][2] = {{2, 0x10}, {2, 0x18}, {2, 0x20}, {2, 0x30}, {4, 0x20}, {8, 8},
+ {8, 0x40}, {4, 0x40}, {2, 0x50}, {2, 0x50}, {2, 0x20}, {3, 0x30},
+ {5, 0x50}, {7, 0x70}, {2, 0x10}, {2, 0x10}};
+ if (player->routine >= 6) return;
+ uint16_t d3 = V.oscillate;
+ for (int i = 0, bit = 15; i < 16; i++, bit--) {
+ uint16_t *val = &V.osc[i * 2], *spd = &V.osc[i * 2 + 1];
+ uint8_t lim = (uint8_t)settings[i][1];
+ if (!(d3 >> bit & 1)) {
+ *spd = (uint16_t)(*spd + settings[i][0]);
+ *val = (uint16_t)(*val + *spd);
+ if (lim <= (uint8_t)(*val >> 8)) d3 |= (uint16_t)(1 << bit);
+ } else {
+ *spd = (uint16_t)(*spd - settings[i][0]);
+ *val = (uint16_t)(*val + *spd);
+ if (lim > (uint8_t)(*val >> 8)) d3 &= (uint16_t)~(1 << bit);
+ }
+ }
+ V.oscillate = d3;
+}
+
+void SynchroAnimate(void) {
+ if ((int8_t)--V.ani_time[0] < 0) V.ani_time[0] = 11, V.ani_frame[0] = (uint8_t)((V.ani_frame[0] - 1) & 7);
+ if ((int8_t)--V.ani_time[1] < 0) V.ani_time[1] = 7, V.ani_frame[1] = (uint8_t)((V.ani_frame[1] + 1) & 3);
+ if ((int8_t)--V.ani_time[2] < 0) {
+ V.ani_time[2] = 7;
+ if (++V.ani_frame[2] >= 6) V.ani_frame[2] = 0;
+ }
+ if (V.ani_time[3]) {
+ uint16_t d0 = (uint16_t)(V.ani_time[3] + V.ani3_buf);
+ V.ani3_buf = d0;
+ d0 = (uint16_t)(d0 << 7 | d0 >> 9);
+ V.ani_frame[3] = (uint8_t)(d0 & 3);
+ V.ani_time[3]--;
+ }
+}
+
+void SignpostArtLoad(void) {
+ if (V.debuguse || V.act == 2) return;
+ int16_t d1 = (int16_t)(V.limitright2 - 0x100);
+ if (V.cam[0].x.w.i < d1 || !V.f_timecount || d1 == V.limitleft2) return;
+ V.limitleft2 = d1;
+ NewPLC(plcid_Signpost);
+}
diff --git a/games/sonic/src/main.c b/games/sonic/src/main.c
new file mode 100644
index 00000000..b8ae099d
--- /dev/null
+++ b/games/sonic/src/main.c
@@ -0,0 +1,185 @@
+/* Sonic the Hedgehog: the frame (VBlank's work: the joypad, the colours, the planes drawn as the
+ * camera moves, the animated art and the HUD's numbers; then the picture and real time), the game
+ * modes one after another as the original's main loop runs them, and Home, which saves and quits
+ * from anywhere. */
+#include <setjmp.h>
+#include "s1.h"
+#include "game.h"
+#include "plat.h"
+
+#ifdef HOST /* (tests/play.c has the computer's main) */
+#define main game_main
+void host_frame(void);
+#endif
+
+Vars V;
+Obj objs[NOBJ];
+
+/* ------------------------------------------------------------------ data access */
+const uint8_t *map_get(int id) { return DATA(((const uint32_t *)DATA(D_MAPS))[id]); }
+const uint8_t *map_frame(const uint8_t *map, int f) { return map + ((const uint16_t *)(const void *)map)[1 + f]; }
+const uint8_t *ani_get(int id) { return DATA(((const uint32_t *)DATA(D_ANIS))[id]); }
+
+/* ------------------------------------------------------------------ numbers */
+uint32_t RandomNumber(void) {
+ uint32_t d1 = V.random;
+ if (!d1) d1 = 0x2A6D365A;
+ uint32_t d0 = d1;
+ d1 = (d1 << 2) + d0;
+ d1 = (d1 << 3) + d0;
+ uint16_t lo = (uint16_t)((d1 & 0xFFFF) + (d1 >> 16));
+ d1 = (d1 & 0xFFFF0000u) | lo;
+ d1 = (d1 << 16) | (d1 >> 16);
+ d1 = (d1 & 0xFFFF0000u) | lo;
+ d1 = (d1 << 16) | (d1 >> 16);
+ V.random = d1;
+ /* (d0: its low word the sum, its high word the original's d0 high word) */
+ return (d0 & 0xFFFF0000u) | lo;
+}
+
+int16_t CalcSine(uint8_t angle, int16_t *cos) {
+ const int16_t *t = (const int16_t *)DATA(D_TAB_SINE_DATA);
+ if (cos) *cos = t[angle + 0x40];
+ return t[angle];
+}
+
+uint8_t CalcAngle(int16_t x, int16_t y) {
+ if (!x && !y) return 0x40;
+ const uint8_t *t = DATA(D_TAB_ANGLE_DATA);
+ uint16_t ax = (uint16_t)(x < 0 ? -x : x), ay = (uint16_t)(y < 0 ? -y : y);
+ int a;
+ if (ay < ax) a = t[(uint16_t)(((uint32_t)ay << 8) / ax)];
+ else a = 0x40 - t[(uint16_t)(((uint32_t)ax << 8) / ay)];
+ if (x < 0) a = 0x80 - a;
+ if (y < 0) a = 0x100 - a;
+ return (uint8_t)a;
+}
+
+/* ------------------------------------------------------------------ the frame */
+static jmp_buf quit_jump;
+static uint32_t next_frame; /* when the next frame is due (ms * 60, to keep fractions) */
+static uint32_t frame_ms60;
+static int skipped;
+uint32_t sonic_gfx_pending[23]; /* (the patterns Sonic_LoadGfx asked for, for VBlank) */
+int sonic_gfx_count;
+
+static void ReadJoypads(void) {
+ uint32_t k = plat_keys();
+ if (k & K_HOME) game_quit();
+ uint8_t held = (uint8_t)(k & 0xFF);
+ V.jpadpress1 = (uint8_t)(held & ~V.jpadhold1);
+ V.jpadhold1 = held;
+}
+
+static void transfers(void) {
+ memcpy(cram, V.f_wtr_state ? V.palette_water : V.palette, sizeof cram);
+ extern uint16_t vdp_water_cram[64];
+ memcpy(vdp_water_cram, V.palette_water, sizeof vdp_water_cram);
+ vdp_vscroll_a = V.scrposy_vdp;
+ vdp_vscroll_b = V.bgscrposy_vdp;
+}
+
+void sonic_gfx_apply(void) {
+ if (!V.f_sonframechg) return;
+ extern void sonic_dplc_apply(void);
+ sonic_dplc_apply();
+ V.f_sonframechg = 0;
+}
+
+static void level_updates(void) {
+ memcpy(V.cam_dup, V.cam, sizeof V.cam);
+ memcpy(V.scroll_flags_dup, V.scroll_flags, sizeof V.scroll_flags);
+ LoadTilesAsYouMove();
+ AnimateLevelGfx();
+ HUD_Update();
+}
+
+static void timer(void) {
+ if (V.generictimer) V.generictimer--;
+}
+
+static void vblank(uint8_t r) {
+ switch (r) {
+ case id_VBlank_Sega: ReadJoypads(); transfers(); timer(); break;
+ case id_VBlank_SegaPCM: timer(); break;
+ case id_VBlank_Title: ReadJoypads(); transfers(); LoadTilesAsYouMove_BGOnly(); timer(); break;
+ case id_VBlank_Paused:
+ if (V.gamemode == id_Special) goto special;
+ /* fall through */
+ case id_VBlank_Levels:
+ ReadJoypads(), transfers(), sonic_gfx_apply(), level_updates(), timer();
+ break;
+ case id_VBlank_SpecialStage:
+ special:
+ ReadJoypads(), transfers(), PalCycle_SS(), sonic_gfx_apply(), timer();
+ break;
+ case id_VBlank_TitleCards: case id_VBlank_Ending:
+ ReadJoypads(), transfers(), sonic_gfx_apply(), level_updates();
+ break;
+ case id_VBlank_PaletteFade: ReadJoypads(); transfers(); break;
+ case id_VBlank_Continue: ReadJoypads(); transfers(); sonic_gfx_apply(); timer(); break;
+ default: /* a lag frame (never here: the game always has the time) */
+ break;
+ }
+}
+
+/* whether the picture can be left out this frame to keep up (the N0110 and N0115) */
+static bool keep_up(void) {
+ uint32_t now = plat_millis() * 60;
+ if ((int32_t)(now - next_frame) > 1000 * 4) next_frame = now; /* far behind (a long load): start again */
+ return (int32_t)(now - next_frame) > (int32_t)frame_ms60 && skipped < 3;
+}
+
+void WaitForVBlank(void) {
+ uint8_t r = V.vblank_routine;
+ V.vblank_routine = 0;
+ V.f_hblank_pal = 1;
+ vblank(r);
+ V.vblank_count++;
+ vdp_hint_line = V.zone == id_LZ && (V.gamemode & 0x7F) == id_Level && V.hblank_line < 224 ? V.hblank_line : -1;
+ if (keep_up()) skipped++;
+ else {
+ skipped = 0;
+ vdp_render();
+ pause_overlay_draw();
+ }
+#ifdef HOST
+ host_frame();
+#endif
+ next_frame += frame_ms60;
+ for (;;) {
+ int32_t wait = (int32_t)(next_frame - plat_millis() * 60);
+ if (wait <= 0) break;
+ plat_sleep((uint32_t)(wait / 60 > 0 ? wait / 60 : 1));
+ if (wait < 60) break;
+ }
+}
+
+void game_quit(void) { longjmp(quit_jump, 1); }
+
+/* ------------------------------------------------------------------ the main loop */
+int main(void) {
+ plat_begin();
+ plat_fill(0, 0, SCREEN_W, SCREEN_H, 0);
+ frame_ms60 = 1000; /* 1/60 s, in ms * 60 */
+ next_frame = plat_millis() * 60;
+ vdp_clear_planes();
+ save_restore_copy();
+ if (!setjmp(quit_jump)) {
+ game_init();
+ for (;;) {
+ switch (V.gamemode & 0x1C) {
+ case id_Sega: GM_Sega(); break;
+ case id_Title: GM_Title(); break;
+ case id_Demo: case id_Level: GM_Level(); break;
+ case id_Special: GM_Special(); break;
+ case id_Continue: GM_Continue(); break;
+ case id_Ending: GM_Ending(); break;
+ case id_Credits: GM_Credits(); break;
+ }
+ }
+ }
+ game_save_on_quit();
+ plat_fill(0, 0, SCREEN_W, SCREEN_H, 0);
+ return plat_end();
+}
diff --git a/games/sonic/src/obj.c b/games/sonic/src/obj.c
new file mode 100644
index 00000000..cafc5606
--- /dev/null
+++ b/games/sonic/src/obj.c
@@ -0,0 +1,308 @@
+/* Objects: running all 128 each frame (only Sonic's 32 and those on screen keep moving or showing
+ * while he dies), the sprite list built from the display queue's 8 layers, the object manager that
+ * places the act's objects as the camera reaches them (and remembers the ones that must not come
+ * back), animation scripts, and the little routines every object uses. */
+#include "s1.h"
+
+struct spritequeue_s spritequeue[8];
+
+void ExecuteObjects(void) {
+ int n = NOBJ;
+ if (player->routine >= 6) n = NRESERVED;
+ for (int i = 0; i < n; i++) {
+ Obj *o = &objs[i];
+ if (o->id && obj_index[o->id]) obj_index[o->id](o);
+ }
+ if (n == NOBJ) return;
+ for (int i = NRESERVED; i < NOBJ; i++) {
+ Obj *o = &objs[i];
+ if (o->id && (o->render & 0x80)) DisplaySprite(o);
+ }
+}
+
+void DisplaySprite(Obj *o) {
+ struct spritequeue_s *q = &spritequeue[o->priority & 7];
+ if (q->n >= 63) return;
+ q->o[q->n++] = o;
+}
+
+void DeleteObject(Obj *o) { memset(o, 0, sizeof *o); }
+
+Obj *FindFreeObj(void) {
+ for (int i = NRESERVED; i < NOBJ; i++)
+ if (!objs[i].id) return &objs[i];
+ return NULL;
+}
+
+Obj *FindNextFreeObj(Obj *parent) {
+ for (Obj *o = parent; o < objs + NOBJ; o++)
+ if (!o->id) return o;
+ return NULL;
+}
+
+void SpeedToPos(Obj *o) {
+ o->x.l += (int32_t)o->vx << 8;
+ o->y.l += (int32_t)o->vy << 8;
+}
+
+void ObjectFall(Obj *o) {
+ int16_t vy = o->vy;
+ o->vy = (int16_t)(o->vy + 0x38);
+ o->x.l += (int32_t)o->vx << 8;
+ o->y.l += (int32_t)vy << 8;
+}
+
+bool ChkObjectVisible(Obj *o) {
+ int16_t x = (int16_t)(o->x.w.i - V.cam[0].x.w.i), y = (int16_t)(o->y.w.i - V.cam[0].y.w.i);
+ return x >= 0 && x < 320 && y >= 0 && y < 224;
+}
+
+bool ChkPartiallyVisible(Obj *o) {
+ int16_t x = (int16_t)(o->x.w.i - V.cam[0].x.w.i + o->actwid);
+ if (x < 0) return false;
+ if ((int16_t)(x - o->actwid * 2) >= 320) return false;
+ int16_t y = (int16_t)(o->y.w.i - V.cam[0].y.w.i);
+ return y >= 0 && y < 224;
+}
+
+/* out_of_range: far from the camera (more than about 192 pixels beyond either side) */
+bool obj_far(Obj *o) {
+ uint16_t d = (uint16_t)((o->x.w.i & 0xFF80) - ((V.cam[0].x.w.i - 128) & 0xFF80));
+ return d > 128 + 320 + 192;
+}
+bool obj_far_x(int16_t x) {
+ uint16_t d = (uint16_t)((x & 0xFF80) - ((V.cam[0].x.w.i - 128) & 0xFF80));
+ return d > 128 + 320 + 192;
+}
+
+/* off screen for good: let the object manager place it again later */
+void RememberState(Obj *o) {
+ if (obj_far(o)) {
+ if (o->respawn) V.objstate[2 + o->respawn] &= 0x7F;
+ DeleteObject(o);
+ return;
+ }
+ DisplaySprite(o);
+}
+
+/* ------------------------------------------------------------------ animation */
+void AnimateSprite(Obj *o, const uint8_t *ani) {
+ uint8_t a = o->anim;
+ if (a != o->prevani) {
+ o->prevani = a;
+ o->aniframe = 0;
+ o->timeframe = 0;
+ }
+ if ((int8_t)--o->timeframe >= 0) return;
+ const uint8_t *s = ani + ((const uint16_t *)(const void *)ani)[1 + a];
+ o->timeframe = s[0];
+ int i = o->aniframe;
+ uint8_t f = s[1 + i];
+ if (f & 0x80) {
+ switch (f) {
+ case 0xFF: o->aniframe = 0, f = s[1]; break;
+ case 0xFE: {
+ uint8_t back = s[2 + i];
+ o->aniframe = (uint8_t)(o->aniframe - back);
+ f = s[1 + (uint8_t)(i - back)];
+ break;
+ }
+ case 0xFD: o->anim = s[2 + i]; return;
+ case 0xFC: o->routine += 2; return;
+ case 0xFB: o->aniframe = 0, o->routine2 = 0; return;
+ case 0xFA: o->routine2 += 2; return;
+ default: return;
+ }
+ }
+ o->frame = f & 0x1F;
+ uint8_t flip = (uint8_t)(((f >> 5) | (f << 3)) & 0xFF); /* rol.b #3 */
+ flip = (uint8_t)((flip ^ o->status) & 3);
+ o->render = (uint8_t)((o->render & ~3) | flip);
+ o->aniframe++;
+}
+
+/* ------------------------------------------------------------------ the sprite list */
+void BuildSprites(void) {
+ int n = 0;
+ for (int layer = 0; layer < 8; layer++) {
+ struct spritequeue_s *q = &spritequeue[layer];
+ for (int k = 0; k < q->n; k++) {
+ Obj *o = q->o[k];
+ if (!o->id) continue;
+ o->render &= 0x7F;
+ uint8_t r = o->render;
+ int16_t x, y;
+ if (r & 0x0C) {
+ const Cam *c = (r & 0x0C) == 4 ? &V.cam[0] : (r & 0x0C) == 8 ? &V.cam[1] : &V.cam[3];
+ int16_t d3 = (int16_t)(o->x.w.i - c->x.w.i);
+ if ((int16_t)(d3 + o->actwid) < 0 || (int16_t)(d3 - o->actwid) >= 320) continue;
+ x = (int16_t)(d3 + 0x80);
+ if (r & 0x10) {
+ int16_t d2 = (int16_t)(o->y.w.i - c->y.w.i);
+ if ((int16_t)(d2 + o->height) < 0 || (int16_t)(d2 - o->height) >= 224) continue;
+ y = (int16_t)(d2 + 0x80);
+ } else {
+ y = (int16_t)(o->y.w.i - c->y.w.i + 0x80);
+ if ((uint16_t)y < 0x80 - 32 || (uint16_t)y >= 0x80 + 224 + 32) continue;
+ }
+ } else {
+ y = obScreenY(o);
+ x = o->x.w.i;
+ }
+ const uint8_t *p;
+ int count;
+ if (r & 0x20) {
+ p = o->map; /* a single piece */
+ count = 1;
+ } else {
+ p = map_frame(o->map, o->frame);
+ count = p[0];
+ p += 2;
+ }
+ for (int i = 0; i < count && n < 80; i++, p += 6) {
+ int8_t py = (int8_t)p[0], px = (int8_t)p[4];
+ uint8_t size = p[1];
+ uint16_t tile = (uint16_t)(p[2] | p[3] << 8);
+ int16_t sy = py, sx = px;
+ if (r & 2) sy = (int16_t)(-sy - (((size << 3) & 0x18) + 8));
+ if (r & 1) sx = (int16_t)(-sx - (((size << 1) & 0x18) + 8));
+ tile = (uint16_t)(tile + o->gfx);
+ tile ^= (uint16_t)((r & 1) << 11 | (r & 2) << 11);
+ Sprite *s = &spritetable[n];
+ s->y = (int16_t)(sy + y);
+ s->size = size;
+ s->tile = tile;
+ int16_t fx = (int16_t)((sx + x) & 0x1FF);
+ s->x = fx ? fx : 1;
+ n++;
+ s->link = (uint8_t)n;
+ }
+ o->render |= 0x80;
+ }
+ q->n = 0;
+ }
+ if (n == 80) spritetable[79].link = 0;
+ else spritetable[n].link = 0, spritetable[n].y = 0, spritetable[n].size = 0, spritetable[n].tile = 0, spritetable[n].x = 0;
+ if (n == 0) spritetable[0].y = 0;
+}
+
+/* ------------------------------------------------------------------ the object manager */
+typedef struct {
+ uint16_t x, y;
+ uint8_t id, sub;
+} ObjPos;
+#define OP(off) ((const ObjPos *)DATA(off))
+
+static const uint32_t objpos_index[7][4] = {
+ {D_OBJPOS_GHZ1, D_OBJPOS_GHZ2, D_OBJPOS_GHZ3, D_OBJPOS_GHZ1},
+ {D_OBJPOS_LZ1, D_OBJPOS_LZ2, D_OBJPOS_LZ3, D_OBJPOS_SBZ3},
+ {D_OBJPOS_MZ1, D_OBJPOS_MZ2, D_OBJPOS_MZ3, D_OBJPOS_MZ1},
+ {D_OBJPOS_SLZ1, D_OBJPOS_SLZ2, D_OBJPOS_SLZ3, D_OBJPOS_SLZ1},
+ {D_OBJPOS_SYZ1, D_OBJPOS_SYZ2, D_OBJPOS_SYZ3, D_OBJPOS_SYZ1},
+ {D_OBJPOS_SBZ1, D_OBJPOS_SBZ2, D_OBJPOS_FZ, D_OBJPOS_SBZ1},
+ {D_OBJPOS_ENDING, D_OBJPOS_ENDING, D_OBJPOS_ENDING, D_OBJPOS_ENDING},
+};
+
+/* places the object at a (true), or, if its slot in the state list says it was used, skips it */
+static bool spawn(uint32_t *a, uint8_t d2) {
+ const ObjPos *e = OP(*a);
+ uint8_t *st = V.objstate;
+ if (e->id & 0x80) {
+ uint8_t old = st[2 + d2] & 0x80;
+ st[2 + d2] |= 0x80;
+ if (old) {
+ *a += 6;
+ return true;
+ }
+ }
+ Obj *o = FindFreeObj();
+ if (!o) return false;
+ *a += 6;
+ o->x.w.i = (int16_t)e->x;
+ o->y.w.i = (int16_t)(e->y & 0xFFF);
+ uint8_t flip = (uint8_t)((uint16_t)(e->y << 2 | e->y >> 14) & 3);
+ o->render = o->status = flip;
+ uint8_t id = e->id;
+ if (id & 0x80) id &= 0x7F, o->respawn = d2;
+ o->id = id;
+ obSubtype(o) = e->sub;
+ return true;
+}
+
+void ObjPosLoad(void) {
+ uint8_t *st = V.objstate;
+ uint8_t d2 = 0;
+ uint32_t a;
+ if (V.opl_routine == 0) {
+ V.opl_routine = 2;
+ uint32_t l = objpos_index[V.zone > 6 ? 6 : V.zone][V.act & 3];
+ V.opl_data[0] = V.opl_data[1] = l;
+ memset(st, 0, sizeof V.objstate);
+ st[0] = st[1] = 1;
+ int16_t d6 = (int16_t)(V.cam[0].x.w.i - 128);
+ if ((uint16_t)V.cam[0].x.w.i < 128) d6 = 0;
+ d6 &= (int16_t)0xFF80;
+ a = V.opl_data[0];
+ while ((uint16_t)d6 > OP(a)->x) {
+ if (OP(a)->id & 0x80) d2 = st[0]++;
+ a += 6;
+ }
+ V.opl_data[0] = a;
+ a = V.opl_data[1];
+ uint16_t d6l = (uint16_t)(d6 - 128);
+ if ((uint16_t)d6 >= 128) {
+ while (d6l > OP(a)->x) {
+ if (OP(a)->id & 0x80) st[1]++;
+ a += 6;
+ }
+ }
+ V.opl_data[1] = a;
+ V.opl_screen = -1;
+ }
+ d2 = 0;
+ int16_t d6 = (int16_t)(V.cam[0].x.w.i & 0xFF80);
+ if (d6 == V.opl_screen) return;
+ if (d6 < V.opl_screen) {
+ V.opl_screen = d6;
+ a = V.opl_data[1];
+ int16_t l = (int16_t)(d6 - 128);
+ if ((uint16_t)d6 >= 128) {
+ while (!(l >= (int16_t)OP(a - 6)->x)) {
+ a -= 6;
+ if (OP(a)->id & 0x80) d2 = --st[1];
+ if (!spawn(&a, d2)) {
+ if (OP(a)->id & 0x80) st[1]++;
+ a += 6;
+ break;
+ }
+ a -= 6;
+ }
+ }
+ V.opl_data[1] = a;
+ a = V.opl_data[0];
+ l = (int16_t)(d6 + 320 + 320);
+ while (!(l > (int16_t)OP(a - 6)->x)) {
+ if (OP(a - 6)->id & 0x80) st[0]--;
+ a -= 6;
+ }
+ V.opl_data[0] = a;
+ return;
+ }
+ V.opl_screen = d6;
+ a = V.opl_data[0];
+ uint16_t r = (uint16_t)(d6 + 320 + 320);
+ while (r > OP(a)->x) {
+ if (OP(a)->id & 0x80) d2 = st[0]++;
+ if (!spawn(&a, d2)) break;
+ }
+ V.opl_data[0] = a;
+ a = V.opl_data[1];
+ uint16_t l = (uint16_t)(d6 + 320 + 320 - (320 + 320 + 128));
+ if ((uint16_t)(d6 + 320 + 320) >= 320 + 320 + 128) {
+ while (l > OP(a)->x) {
+ if (OP(a)->id & 0x80) st[1]++;
+ a += 6;
+ }
+ }
+ V.opl_data[1] = a;
+}
diff --git a/games/sonic/src/objects.c b/games/sonic/src/objects.c
new file mode 100644
index 00000000..709c8157
--- /dev/null
+++ b/games/sonic/src/objects.c
@@ -0,0 +1,8 @@
+/* The object pointer table: each object id's code (the original's Obj_Index). */
+#include "s1.h"
+#include "game.h"
+#include "objs.h"
+
+const ObjFn obj_index[0x8D + 1] = {
+ [id_SonicPlayer] = SonicPlayer,
+};
diff --git a/games/sonic/src/objs.h b/games/sonic/src/objs.h
new file mode 100644
index 00000000..ba86757d
--- /dev/null
+++ b/games/sonic/src/objs.h
@@ -0,0 +1,5 @@
+/* The objects' code, by file (each object is the original's object of that id). */
+#ifndef S1_OBJS_H
+#define S1_OBJS_H
+#include "s1.h"
+#endif
diff --git a/games/sonic/src/palette.c b/games/sonic/src/palette.c
new file mode 100644
index 00000000..a387fafc
--- /dev/null
+++ b/games/sonic/src/palette.c
@@ -0,0 +1,227 @@
+/* Palettes: loading them (into the colours shown, the fade-in target or their underwater twins),
+ * fading to and from black and white a step a frame as the original does (blue first in, red first
+ * out), and each zone's colour cycles: Green Hill's water, Labyrinth's waterfalls and conveyor belts,
+ * Star Light's lights, Spring Yard's signs and Scrap Brain's blinking machinery. */
+#include "s1.h"
+
+static const struct {
+ uint32_t data;
+ uint8_t dest, n;
+} pal_index[] = {
+ {D_PAL_SEGA_BACKGROUND, 0, N_PAL_SEGA_BACKGROUND},
+ {D_PAL_TITLE_SCREEN, 0, N_PAL_TITLE_SCREEN},
+ {D_PAL_LEVEL_SELECT, 0, N_PAL_LEVEL_SELECT},
+ {D_PAL_SONIC, 0, N_PAL_SONIC},
+ {D_PAL_GREEN_HILL_ZONE, 16, N_PAL_GREEN_HILL_ZONE},
+ {D_PAL_LABYRINTH_ZONE, 16, N_PAL_LABYRINTH_ZONE},
+ {D_PAL_MARBLE_ZONE, 16, N_PAL_MARBLE_ZONE},
+ {D_PAL_STAR_LIGHT_ZONE, 16, N_PAL_STAR_LIGHT_ZONE},
+ {D_PAL_SPRING_YARD_ZONE, 16, N_PAL_SPRING_YARD_ZONE},
+ {D_PAL_SBZ_ACT_1, 16, N_PAL_SBZ_ACT_1},
+ {D_PAL_SPECIAL_STAGE, 0, N_PAL_SPECIAL_STAGE},
+ {D_PAL_LABYRINTH_ZONE_UNDERWATER, 0, N_PAL_LABYRINTH_ZONE_UNDERWATER},
+ {D_PAL_SBZ_ACT_3, 16, N_PAL_SBZ_ACT_3},
+ {D_PAL_SBZ_ACT_3_UNDERWATER, 0, N_PAL_SBZ_ACT_3_UNDERWATER},
+ {D_PAL_SBZ_ACT_2, 16, N_PAL_SBZ_ACT_2},
+ {D_PAL_SONIC_LZ_UNDERWATER, 0, N_PAL_SONIC_LZ_UNDERWATER},
+ {D_PAL_SONIC_SBZ3_UNDERWATER, 0, N_PAL_SONIC_SBZ3_UNDERWATER},
+ {D_PAL_SPECIAL_STAGE_RESULTS, 0, N_PAL_SPECIAL_STAGE_RESULTS},
+ {D_PAL_SPECIAL_STAGE_CONTINUE_BONUS, 0, N_PAL_SPECIAL_STAGE_CONTINUE_BONUS},
+ {D_PAL_ENDING, 0, N_PAL_ENDING},
+};
+
+static void load(int id, uint16_t *to) {
+ const uint16_t *src = DATAW(pal_index[id].data);
+ int n = pal_index[id].n, d = pal_index[id].dest;
+ for (int i = 0; i < n && d + i < 64; i++) to[d + i] = src[i];
+}
+void PalLoad(int id) { load(id, V.palette); }
+void PalLoad_Fade(int id) { load(id, V.palette_fading); }
+void PalLoad_Fade_Water(int id) { load(id, V.palette_water); }
+void PalLoad_Water(int id) { load(id, V.palette_water_fading); }
+
+/* ------------------------------------------------------------------ fading */
+static void add_color(uint16_t *a, uint16_t target) {
+ uint16_t c = *a;
+ if (c == target) return;
+ if ((uint16_t)(c + 0x200) <= target) *a = (uint16_t)(c + 0x200);
+ else if ((uint16_t)(c + 0x20) <= target) *a = (uint16_t)(c + 0x20);
+ else *a = (uint16_t)(c + 2);
+}
+static void dec_color(uint16_t *a) {
+ uint16_t c = *a;
+ if (!c) return;
+ if (c & 0x00E) *a = (uint16_t)(c - 2);
+ else if (c & 0x0E0) *a = (uint16_t)(c - 0x20);
+ else if (c & 0xE00) *a = (uint16_t)(c - 0x200);
+}
+static void white_dec(uint16_t *a, uint16_t target) {
+ uint16_t c = *a;
+ if (c == target) return;
+ if (c >= 0x200 && (uint16_t)(c - 0x200) >= target) *a = (uint16_t)(c - 0x200);
+ else if (c >= 0x20 && (uint16_t)(c - 0x20) >= target) *a = (uint16_t)(c - 0x20);
+ else *a = (uint16_t)(c - 2);
+}
+static void white_add(uint16_t *a) {
+ uint16_t c = *a;
+ if (c == 0xEEE) return;
+ if ((c & 0x00E) != 0x00E) *a = (uint16_t)(c + 2);
+ else if ((c & 0x0E0) != 0x0E0) *a = (uint16_t)(c + 0x20);
+ else if ((c & 0xE00) != 0xE00) *a = (uint16_t)(c + 0x200);
+}
+
+void FadeIn_FromBlack(void) {
+ int s = V.pfade_start / 2, n = V.pfade_size + 1;
+ for (int i = 0; i < n && s + i < 64; i++) add_color(&V.palette[s + i], V.palette_fading[s + i]);
+ if (V.zone == id_LZ)
+ for (int i = 0; i < n && s + i < 64; i++) add_color(&V.palette_water[s + i], V.palette_water_fading[s + i]);
+}
+void FadeOut_ToBlack(void) {
+ int s = V.pfade_start / 2, n = V.pfade_size + 1;
+ for (int i = 0; i < n && s + i < 64; i++) dec_color(&V.palette[s + i]);
+ for (int i = 0; i < n && s + i < 64; i++) dec_color(&V.palette_water[s + i]);
+}
+void WhiteIn_FromWhite(void) {
+ int s = V.pfade_start / 2, n = V.pfade_size + 1;
+ for (int i = 0; i < n && s + i < 64; i++) white_dec(&V.palette[s + i], V.palette_fading[s + i]);
+ if (V.zone == id_LZ)
+ for (int i = 0; i < n && s + i < 64; i++) white_dec(&V.palette_water[s + i], V.palette_water_fading[s + i]);
+}
+void WhiteOut_ToWhite(void) {
+ int s = V.pfade_start / 2, n = V.pfade_size + 1;
+ for (int i = 0; i < n && s + i < 64; i++) white_add(&V.palette[s + i]);
+ for (int i = 0; i < n && s + i < 64; i++) white_add(&V.palette_water[s + i]);
+}
+
+static void fade_loop(void (*step)(void)) {
+ for (int i = 0; i < 22; i++) {
+ V.vblank_routine = id_VBlank_PaletteFade;
+ WaitForVBlank();
+ step();
+ RunPLC();
+ }
+}
+void PalFadeIn_Alt(void) {
+ int s = V.pfade_start / 2;
+ for (int i = 0; i <= V.pfade_size && s + i < 64; i++) V.palette[s + i] = 0;
+ fade_loop(FadeIn_FromBlack);
+}
+void PaletteFadeIn(void) {
+ V.pfade_start = 0, V.pfade_size = 0x3F;
+ PalFadeIn_Alt();
+}
+void PaletteFadeOut(void) {
+ V.pfade_start = 0, V.pfade_size = 0x3F;
+ fade_loop(FadeOut_ToBlack);
+}
+void PaletteWhiteIn(void) {
+ V.pfade_start = 0, V.pfade_size = 0x3F;
+ for (int i = 0; i < 64; i++) V.palette[i] = 0xEEE;
+ fade_loop(WhiteIn_FromWhite);
+}
+void PaletteWhiteOut(void) {
+ V.pfade_start = 0, V.pfade_size = 0x3F;
+ fade_loop(WhiteOut_ToWhite);
+}
+
+/* ------------------------------------------------------------------ colour cycles */
+static uint16_t lz_conveyor; /* (the original keeps it in v_pal_buffer) */
+
+static void cycle4(const uint16_t *src, uint16_t *to, uint16_t period) {
+ if ((int16_t)--V.pcyc_time >= 0) return;
+ V.pcyc_time = (uint16_t)(period - 1);
+ int n = V.pcyc_num++ & 3;
+ for (int i = 0; i < 4; i++) to[i] = src[n * 4 + i];
+}
+
+void PalCycle_Title(void) { cycle4(DATAW(D_PAL_CYCLE_TITLE_SCREEN_WATER), &V.palette[32 + 8], 6); }
+
+static void cycle_lz(void) {
+ if ((int16_t)--V.pcyc_time < 0) {
+ V.pcyc_time = 2;
+ int n = V.pcyc_num++ & 3;
+ const uint16_t *src = DATAW(V.act == 3 ? D_PAL_CYCLE_SBZ3_WATERFALL : D_PAL_CYCLE_LZ_WATERFALL);
+ for (int i = 0; i < 4; i++) V.palette[32 + 0xB + i] = V.palette_water[32 + 0xB + i] = src[n * 4 + i];
+ }
+ static const uint8_t seq[8] = {1, 0, 0, 1, 0, 0, 1, 0};
+ if (!seq[V.framecount & 7]) return;
+ int d = V.f_conveyrev ? -1 : 1, n = (lz_conveyor & 3) + d;
+ if ((unsigned)n >= 3) n = d < 0 ? 2 : 0;
+ lz_conveyor = (uint16_t)n;
+ const uint16_t *dry = DATAW(D_PAL_CYCLE_LZ_CONVEYOR_BELT), *wet = DATAW(D_PAL_CYCLE_LZ_CONVEYOR_BELT_UNDERWATER);
+ for (int i = 0; i < 3; i++) V.palette[48 + 0xB + i] = dry[n * 3 + i], V.palette_water[48 + 0xB + i] = wet[n * 3 + i];
+}
+
+static void cycle_slz(void) {
+ if ((int16_t)--V.pcyc_time >= 0) return;
+ V.pcyc_time = 7;
+ int n = V.pcyc_num + 1;
+ if (n >= 6) n = 0;
+ V.pcyc_num = (uint16_t)n;
+ const uint16_t *src = DATAW(D_PAL_CYCLE_SLZ) + n * 3;
+ V.palette[32 + 0xB] = src[0];
+ V.palette[32 + 0xD] = src[1];
+ V.palette[32 + 0xE] = src[2];
+}
+
+static void cycle_syz(void) {
+ if ((int16_t)--V.pcyc_time >= 0) return;
+ V.pcyc_time = 5;
+ int n = V.pcyc_num++ & 3;
+ const uint16_t *by = DATAW(D_PAL_CYCLE_SYZ1) + n * 4, *rw = DATAW(D_PAL_CYCLE_SYZ2) + n * 2;
+ for (int i = 0; i < 4; i++) V.palette[48 + 7 + i] = by[i];
+ V.palette[48 + 0xB] = rw[0];
+ V.palette[48 + 0xD] = rw[1];
+}
+
+static uint8_t sbz_buf[0x30];
+static void cycle_sbz(void) {
+ static const struct {
+ uint8_t time, colours;
+ uint32_t src;
+ uint8_t dest;
+ } list1[] = {
+ {8, 8, D_PAL_CYCLE_SBZ_1, 32 + 8}, {14, 8, D_PAL_CYCLE_SBZ_2, 32 + 9}, {15, 8, D_PAL_CYCLE_SBZ_3, 48 + 7},
+ {12, 8, D_PAL_CYCLE_SBZ_5, 48 + 8}, {8, 8, D_PAL_CYCLE_SBZ_6, 48 + 9}, {29, 16, D_PAL_CYCLE_SBZ_7, 48 + 0xF},
+ {4, 3, D_PAL_CYCLE_SBZ_8, 48 + 0xC}, {4, 3, D_PAL_CYCLE_SBZ_8 + 2, 48 + 0xD}, {4, 3, D_PAL_CYCLE_SBZ_8 + 4, 48 + 0xE},
+ }, list2[] = {
+ {8, 8, D_PAL_CYCLE_SBZ_1, 32 + 8}, {14, 8, D_PAL_CYCLE_SBZ_2, 32 + 9}, {10, 8, D_PAL_CYCLE_SBZ_9, 48 + 8},
+ {8, 8, D_PAL_CYCLE_SBZ_6, 48 + 9}, {4, 3, D_PAL_CYCLE_SBZ_8, 48 + 0xC}, {4, 3, D_PAL_CYCLE_SBZ_8 + 2, 48 + 0xD},
+ {4, 3, D_PAL_CYCLE_SBZ_8 + 4, 48 + 0xE},
+ };
+ const __typeof__(list1[0]) *list = V.act ? list2 : list1;
+ int n = V.act ? (int)(sizeof list2 / sizeof list2[0]) : (int)(sizeof list1 / sizeof list1[0]);
+ for (int i = 0; i < n; i++) {
+ uint8_t *b = &sbz_buf[i * 2];
+ if ((int8_t)--b[0] >= 0) continue;
+ b[0] = (uint8_t)(list[i].time - 1);
+ uint8_t c = (uint8_t)(b[1] + 1);
+ if (c >= list[i].colours) c = 0;
+ b[1] = c;
+ V.palette[list[i].dest] = *(const uint16_t *)DATA(list[i].src + (c & 15) * 2u);
+ }
+ if ((int16_t)--V.pcyc_time >= 0) return;
+ const uint16_t *src = DATAW(D_PAL_CYCLE_SBZ_4);
+ V.pcyc_time = 1;
+ if (V.act) src = DATAW(D_PAL_CYCLE_SBZ_10), V.pcyc_time = 0;
+ int d = V.f_conveyrev ? 1 : -1, c = (V.pcyc_num & 3) + d;
+ if ((unsigned)c >= 3) c = d < 0 ? 2 : 0;
+ V.pcyc_num = (uint16_t)c;
+ for (int i = 0; i < 3; i++) V.palette[32 + 0xC + i] = src[c + i];
+}
+
+void PaletteCycle(void) {
+ switch (V.zone) {
+ case id_GHZ: case 6: cycle4(DATAW(D_PAL_CYCLE_GHZ), &V.palette[32 + 8], 6); break;
+ case id_LZ: cycle_lz(); break;
+ case id_SLZ: cycle_slz(); break;
+ case id_SYZ: cycle_syz(); break;
+ case id_SBZ: cycle_sbz(); break;
+ default: break;
+ }
+}
+
+void palette_cycles_reset(void) {
+ lz_conveyor = 0;
+ memset(sbz_buf, 0, sizeof sbz_buf);
+}
diff --git a/games/sonic/src/plat.h b/games/sonic/src/plat.h
new file mode 100644
index 00000000..8776b1b7
--- /dev/null
+++ b/games/sonic/src/plat.h
@@ -0,0 +1,35 @@
+/* Sonic the Hedgehog: the platform (the calculator, or a computer for tests).
+ *
+ * plat_eadk.c: the calculator's display, keyboard, time and files.
+ * plat_host.c: a frame buffer that tests save as images, scripted keys and simulated time. */
+#ifndef S1_PLAT_H
+#define S1_PLAT_H
+#include <stdbool.h>
+#include <stdint.h>
+
+#define SCREEN_W 320
+#define SCREEN_H 240
+
+/* keys held now, as the Mega Drive pad's buttons (and Home) */
+enum {
+ K_UP = 0x01, K_DOWN = 0x02, K_LEFT = 0x04, K_RIGHT = 0x08,
+ K_B = 0x10, K_C = 0x20, K_A = 0x40, K_START = 0x80,
+ K_HOME = 0x100, /* Home, On/Off: save and quit */
+ K_ANY = 0x200
+};
+uint32_t plat_keys(void);
+uint32_t plat_millis(void);
+void plat_sleep(uint32_t ms);
+void plat_push(int x, int y, int w, int h, const uint16_t *px);
+void plat_fill(int x, int y, int w, int h, uint16_t c);
+bool plat_save(const char *name, const void *data, uint32_t len);
+const uint8_t *plat_load(const char *name, uint32_t *len); /* NULL if absent */
+/* a file of len bytes to write in place: plat_reserve gives its bytes, plat_reserved says they are
+ * written; NULL if there is no room */
+uint8_t *plat_reserve(const char *name, uint32_t len);
+void plat_reserved(const char *name, uint32_t len);
+bool plat_remove(const char *name);
+void plat_begin(void);
+int plat_end(void);
+bool plat_slow(void); /* an N0110 or N0115 (216 MHz, the N0120 has 550) */
+#endif
diff --git a/games/sonic/src/plat_eadk.c b/games/sonic/src/plat_eadk.c
new file mode 100644
index 00000000..20f787fd
--- /dev/null
+++ b/games/sonic/src/plat_eadk.c
@@ -0,0 +1,46 @@
+/* The calculator: EADK display, keyboard, time and files.
+ *
+ * The keys as a Mega Drive pad: the arrows (or 8 4 6 2) are the pad, OK, EXE and 5 are A, B and C
+ * (all three jump), Back is Start (pause). */
+#include <eadk.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+#include "plat.h"
+
+#define KEY(k) ((uint64_t)1 << (k))
+
+uint32_t plat_keys(void) {
+ uint64_t k = eadk_keyboard_scan();
+ uint32_t r = 0;
+ if (k & (KEY(eadk_key_left) | KEY(eadk_key_four))) r |= K_LEFT;
+ if (k & (KEY(eadk_key_right) | KEY(eadk_key_six))) r |= K_RIGHT;
+ if (k & (KEY(eadk_key_up) | KEY(eadk_key_eight))) r |= K_UP;
+ if (k & (KEY(eadk_key_down) | KEY(eadk_key_two))) r |= K_DOWN;
+ if (k & KEY(eadk_key_ok)) r |= K_A;
+ if (k & KEY(eadk_key_exe)) r |= K_B;
+ if (k & (KEY(eadk_key_five) | KEY(eadk_key_zero) | KEY(eadk_key_shift))) r |= K_C;
+ if (k & (KEY(eadk_key_back) | KEY(eadk_key_backspace))) r |= K_START;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= K_HOME;
+ if (k) r |= K_ANY;
+ return r;
+}
+
+uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }
+void plat_sleep(uint32_t ms) { eadk_timing_msleep(ms); }
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
+}
+void plat_fill(int x, int y, int w, int h, uint16_t c) {
+ if (w > 0 && h > 0) eadk_display_push_rect_uniform((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, c);
+}
+bool plat_save(const char *name, const void *data, uint32_t len) { return ef_write(name, data, len); }
+const uint8_t *plat_load(const char *name, uint32_t *len) { return ef_read(name, len); }
+uint8_t *plat_reserve(const char *name, uint32_t len) {
+ uint32_t n;
+ return ef_write(name, NULL, len) ? (uint8_t *)(uintptr_t)ef_read(name, &n) : NULL; /* (the storage is RAM) */
+}
+void plat_reserved(const char *name, uint32_t len) { (void)name, (void)len; }
+bool plat_remove(const char *name) { return ef_remove(name); }
+void plat_begin(void) { np_app_begin(); }
+int plat_end(void) { return np_app_end(); }
+bool plat_slow(void) { return epsilon_slow_model(); }
diff --git a/games/sonic/src/plat_host.c b/games/sonic/src/plat_host.c
new file mode 100644
index 00000000..047ec744
--- /dev/null
+++ b/games/sonic/src/plat_host.c
@@ -0,0 +1,76 @@
+/* A computer: the screen goes to a frame buffer that tests save as images,
+ * keys come from a script, time is simulated. */
+#include <stdio.h>
+#include <stdlib.h>
+#include "plat.h"
+
+uint16_t host_fb[SCREEN_W * SCREEN_H];
+uint32_t host_time; /* ms */
+uint32_t host_keys;
+
+uint32_t plat_keys(void) { return host_keys; }
+uint32_t plat_millis(void) { return host_time; }
+void plat_sleep(uint32_t ms) { host_time += ms; }
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ for (int r = 0; r < h; r++)
+ for (int c = 0; c < w; c++)
+ if ((unsigned)(x + c) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + c] = px[r * w + c];
+}
+void plat_fill(int x, int y, int w, int h, uint16_t c) {
+ for (int r = 0; r < h; r++)
+ for (int k = 0; k < w; k++)
+ if ((unsigned)(x + k) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + k] = c;
+}
+
+static char save_dir[256] = "build/host-saves";
+void host_save_dir(const char *d) { snprintf(save_dir, sizeof save_dir, "%s", d); }
+bool plat_save(const char *name, const void *data, uint32_t len) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ FILE *f = fopen(p, "wb");
+ if (!f) return false;
+ bool ok = fwrite(data, 1, len, f) == len;
+ fclose(f);
+ return ok;
+}
+/* (each file read gets its own buffer: callers may hold two at once) */
+static uint8_t loaded[4][1 << 16];
+static int next_load;
+const uint8_t *plat_load(const char *name, uint32_t *len) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ FILE *f = fopen(p, "rb");
+ if (!f) return NULL;
+ uint8_t *b = loaded[next_load++ & 3];
+ *len = (uint32_t)fread(b, 1, sizeof loaded[0], f);
+ fclose(f);
+ return b;
+}
+static uint8_t reserved[1 << 16];
+bool host_storage_full; /* tests: no room for any file */
+uint8_t *plat_reserve(const char *name, uint32_t len) {
+ (void)name;
+ return len <= sizeof reserved && !host_storage_full ? reserved : NULL;
+}
+void plat_reserved(const char *name, uint32_t len) { plat_save(name, reserved, len); }
+bool plat_remove(const char *name) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ return remove(p) == 0;
+}
+void plat_begin(void) {}
+int plat_end(void) { return 0; }
+bool plat_slow(void) { return false; }
+
+/* writes the screen as a PPM image */
+void host_shot(const char *path) {
+ FILE *f = fopen(path, "wb");
+ if (!f) return;
+ fprintf(f, "P6\n%d %d\n255\n", SCREEN_W, SCREEN_H);
+ for (int i = 0; i < SCREEN_W * SCREEN_H; i++) {
+ uint16_t c = host_fb[i];
+ uint8_t rgb[3] = {(uint8_t)((c >> 11) * 255 / 31), (uint8_t)(((c >> 5) & 63) * 255 / 63), (uint8_t)((c & 31) * 255 / 31)};
+ fwrite(rgb, 1, 3, f);
+ }
+ fclose(f);
+}
diff --git a/games/sonic/src/react.c b/games/sonic/src/react.c
new file mode 100644
index 00000000..0360891f
--- /dev/null
+++ b/games/sonic/src/react.c
@@ -0,0 +1,167 @@
+/* Sonic touching objects: each object on screen with a collision type has a box from a table of
+ * 36 sizes; the first one Sonic's box overlaps decides. An enemy is destroyed if he rolls into it
+ * (or is invincible), else he is hurt; an item (ring, monitor) is collected; a hurting thing hurts.
+ * Hurt with rings, he drops them and is knocked back; with none, he dies. Points for enemies grow
+ * with each one destroyed without landing: 100, 200, 500, then 1000. */
+#include "s1.h"
+#include "game.h"
+
+#define flashtime 0x30
+#define exitem_pointsframe 0x3E
+
+static const uint8_t react_sizes[][2] = {
+ {20, 20}, {12, 20}, {20, 12}, {4, 16}, {12, 18}, {16, 16}, {6, 6}, {24, 12}, {12, 16}, {16, 12},
+ {8, 8}, {20, 16}, {20, 8}, {14, 14}, {24, 24}, {40, 16}, {16, 24}, {8, 16}, {32, 112}, {64, 32},
+ {128, 32}, {32, 32}, {8, 8}, {4, 4}, {32, 8}, {12, 12}, {8, 4}, {24, 4}, {40, 4}, {4, 8},
+ {4, 24}, {4, 40}, {4, 32}, {24, 24}, {12, 24}, {72, 8},
+};
+enum { col_32x32 = 6, col_16x16 = 11, col_40x32 = 12, col_16x16_alt = 23, col_8x64 = 33 };
+
+void AddPoints(int points) {
+ V.f_scorecount = 1;
+ V.score += (uint32_t)points;
+ if (V.score >= 999999) V.score = 999999;
+ if (V.score < V.scorelife) return;
+ V.scorelife += 5000;
+ /* (only a Japanese Mega Drive gives a life for points: the game plays as on the others) */
+}
+
+
+int HurtSonic(Obj *o, Obj *a2) {
+ if (!V.shield) {
+ if (!V.rings) {
+ if (!V.f_debugmode) {
+ KillSonic(o, a2);
+ return -1;
+ }
+ } else {
+ Obj *a1 = FindFreeObj();
+ if (a1) {
+ a1->id = id_RingLoss;
+ a1->x.w.i = o->x.w.i, a1->y.w.i = o->y.w.i;
+ }
+ }
+ }
+ V.shield = 0;
+ o->routine = 4;
+ Sonic_ResetOnFloor(o);
+ o->status |= 2;
+ o->vy = -0x400, o->vx = -0x200;
+ if (o->status & 0x40) o->vy = -0x200, o->vx = -0x100;
+ if ((uint16_t)o->x.w.i >= (uint16_t)a2->x.w.i) o->vx = (int16_t)-o->vx;
+ o->inertia = 0;
+ o->anim = id_Hurt;
+ OW(o, flashtime) = 2 * 60;
+ return -1;
+}
+
+void KillSonic(Obj *o, Obj *a2) {
+ (void)a2;
+ if (V.debuguse) return;
+ V.invinc = 0;
+ o->routine = 6;
+ Sonic_ResetOnFloor(o);
+ o->status |= 2;
+ o->vy = -0x700, o->vx = 0, o->inertia = 0;
+ OW(o, 0x38) = o->y.w.i;
+ o->anim = id_Death;
+ o->gfx |= 0x8000;
+}
+
+static int chk_hurt(Obj *o, Obj *a1) {
+ if (V.invinc) return -1;
+ if (OW(o, flashtime)) return -1;
+ return HurtSonic(o, a1);
+}
+
+static int react_enemy(Obj *o, Obj *a1) {
+ if (!V.invinc && o->anim != id_Roll) return chk_hurt(o, a1);
+ if (a1->colprop) { /* a boss: obBossHits */
+ o->vx = (int16_t)(-o->vx >> 1);
+ o->vy = (int16_t)(-o->vy >> 1);
+ a1->coltype = 0;
+ if (!--a1->colprop) a1->status |= 0x80;
+ return 0;
+ }
+ a1->status |= 0x80;
+ uint16_t d0 = V.itembonus;
+ V.itembonus += 2;
+ if (d0 >= 6) d0 = 6;
+ OW(a1, exitem_pointsframe) = (int16_t)d0;
+ static const uint16_t combo[4] = {10, 20, 50, 100};
+ int pts = combo[d0 >> 1];
+ if (V.itembonus >= 32) pts = 1000, OW(a1, exitem_pointsframe) = 10;
+ AddPoints(pts);
+ a1->id = id_ExplosionItem;
+ a1->routine = 0;
+ if (o->vy < 0) o->vy += 0x100;
+ else if ((uint16_t)o->y.w.i >= (uint16_t)a1->y.w.i) o->vy -= 0x100;
+ else o->vy = (int16_t)-o->vy;
+ return 0;
+}
+
+int ReactToItem(Obj *o) {
+ int16_t d2 = (int16_t)(o->x.w.i - 8), d3 = o->y.w.i;
+ int16_t d5 = (int16_t)((uint8_t)(o->height - 3));
+ d3 = (int16_t)(d3 - d5);
+ if (o->frame == fr_Duck) { /* (the original checks the frame: the box is lower while he ducks) */
+ d3 = (int16_t)(d3 + ((19 - 3) - 10) * 2);
+ d5 = 10;
+ }
+ int16_t d4 = 16;
+ d5 = (int16_t)(d5 * 2);
+ for (int i = NRESERVED; i < NOBJ; i++) {
+ Obj *a1 = &objs[i];
+ if (!(a1->render & 0x80) || !a1->coltype) continue;
+ const uint8_t *sz = react_sizes[(a1->coltype & 0x3F) - 1];
+ int16_t d1 = sz[0], d0 = (int16_t)(a1->x.w.i - d1 - d2);
+ if ((uint16_t)(a1->x.w.i - d1) >= (uint16_t)d2) {
+ if ((uint16_t)d0 > (uint16_t)d4) continue;
+ } else if ((uint32_t)(uint16_t)d0 + (uint16_t)(d1 * 2) <= 0xFFFF) continue;
+ d1 = sz[1];
+ d0 = (int16_t)(a1->y.w.i - d1 - d3);
+ if ((uint16_t)(a1->y.w.i - d1) >= (uint16_t)d3) {
+ if ((uint16_t)d0 > (uint16_t)d5) continue;
+ } else if ((uint32_t)(uint16_t)d0 + (uint16_t)(d1 * 2) <= 0xFFFF) continue;
+ /* a hit */
+ uint8_t kind = a1->coltype & 0xC0, size = a1->coltype & 0x3F;
+ if (!kind) return react_enemy(o, a1);
+ if (kind == 0xC0) {
+ if (size == col_16x16) {
+ a1->status |= 0x80;
+ return chk_hurt(o, a1);
+ }
+ if (size == col_40x32) { /* the Yadrin: its spiked top hurts */
+ if ((uint16_t)(d5 - d0) < 8) {
+ int16_t x = (int16_t)(a1->x.w.i - 4);
+ if (a1->status & 1) x -= 16;
+ int16_t e = (int16_t)(x - d2);
+ if ((uint16_t)x >= (uint16_t)d2) {
+ if ((uint16_t)e <= (uint16_t)d4) return chk_hurt(o, a1);
+ } else if ((uint32_t)(uint16_t)e + 24 > 0xFFFF) return chk_hurt(o, a1);
+ }
+ return react_enemy(o, a1);
+ }
+ if (size == col_16x16_alt || size == col_8x64) a1->colprop++;
+ return 0;
+ }
+ if (kind & 0x80) return chk_hurt(o, a1);
+ if (size == col_32x32) { /* a monitor */
+ if (o->vy < 0) {
+ if ((uint16_t)(o->y.w.i - 16) < (uint16_t)a1->y.w.i) return 0;
+ o->vy = (int16_t)-o->vy;
+ a1->vy = -0x180;
+ if (!a1->routine2) a1->routine2 += 4;
+ return 0;
+ }
+ if (o->anim != id_Roll) return 0;
+ o->vy = (int16_t)-o->vy;
+ a1->routine += 2;
+ return 0;
+ }
+ if ((uint16_t)OW(o, flashtime) >= 90) return 0;
+ a1->routine += 2;
+ return 0;
+ }
+ return 0;
+}
diff --git a/games/sonic/src/s1.h b/games/sonic/src/s1.h
new file mode 100644
index 00000000..544abb23
--- /dev/null
+++ b/games/sonic/src/s1.h
@@ -0,0 +1,336 @@
+/* Sonic the Hedgehog (1991) on the NumWorks calculator: what every part of the game shares.
+ *
+ * The game keeps the Mega Drive original's own design, so that it plays the same: 128 objects of 64
+ * bytes run one after another each frame, with a routine number each; the level is a layout of
+ * 256x256 chunks made of 16x16 blocks made of 8x8 patterns, drawn into two 64x32 tile planes as the
+ * camera moves; a sprite list and a scroll table go to the video chip (vdp.c) once a frame, which
+ * draws the 320x224 picture line by line. Its numbers, tables and orders follow the Sonic Retro
+ * disassembly, which gives every variable its name: v_screenposx is V.screenposx here. */
+#ifndef S1_H
+#define S1_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+#include "data.h"
+#include "s1const.h"
+
+/* ------------------------------------------------------------------ data (tools/pack.py) */
+extern const uint8_t s1_data[];
+#define DATA(off) ((const void *)(s1_data + (off)))
+#define DATAW(off) ((const uint16_t *)(const void *)(s1_data + (off)))
+
+/* ------------------------------------------------------------------ fixed point */
+/* a 16.16 position: whole pixels in the high half, as the original's long obX */
+typedef union {
+ int32_t l;
+ struct {
+ uint16_t f;
+ int16_t i;
+ } w;
+} fix_t;
+
+/* ------------------------------------------------------------------ objects */
+typedef struct Obj {
+ uint8_t id; /* $00: 0 for a free slot */
+ uint8_t render; /* $01: sprite_* flags */
+ uint16_t gfx; /* $02: first art tile, palette line, priority */
+ const uint8_t *map; /* $04: sprite mappings */
+ fix_t x; /* $08 (for objects fixed on screen, x.w.f is their screen y, obScreenY) */
+ fix_t y; /* $0C */
+ int16_t vx, vy; /* $10, $12: 8.8 pixels a frame */
+ int16_t inertia; /* $14: speed along the ground */
+ uint8_t height; /* $16: half height */
+ uint8_t width; /* $17: half width */
+ uint8_t priority; /* $18: sprite layer, 0 in front */
+ uint8_t actwid; /* $19: half width on screen */
+ uint8_t frame; /* $1A */
+ uint8_t aniframe; /* $1B */
+ uint8_t anim; /* $1C */
+ uint8_t prevani; /* $1D */
+ uint8_t timeframe; /* $1E */
+ uint8_t delayani; /* $1F */
+ uint8_t coltype; /* $20: what touching it does */
+ uint8_t colprop; /* $21 */
+ uint8_t status; /* $22 */
+ uint8_t respawn; /* $23: its entry in the object state list */
+ uint8_t routine; /* $24 */
+ uint8_t routine2; /* $25 */
+ uint8_t angle; /* $26 */
+ uint8_t x27; /* $27 */
+ union { /* $28-$3F: the subtype, then each object's own */
+ uint8_t b[24];
+ int16_t w[12];
+ uint16_t uw[12];
+ int32_t l[6];
+ } s;
+} Obj;
+
+#define obSubtype(o) ((o)->s.b[0])
+/* the object's own bytes, words and longs, by the original's offsets ($28-$3F) */
+#define OB(o, off) ((o)->s.b[(off) - 0x28])
+#define OW(o, off) ((o)->s.w[((off) - 0x28) >> 1])
+#define OUW(o, off) ((o)->s.uw[((off) - 0x28) >> 1])
+#define OL(o, off) ((o)->s.l[((off) - 0x28) >> 2])
+#define obScreenY(o) (*(int16_t *)&(o)->x.w.f)
+
+#define NOBJ 128
+#define NRESERVED 32
+extern Obj objs[NOBJ];
+#define player (&objs[0])
+#define OBJ(n) (&objs[n])
+/* objects keep others' places as the original kept their RAM addresses */
+#define OADDR(p) ((uint16_t)(0xD000 + ((p) - objs) * 0x40))
+#define OPTR(a) (&objs[((uint16_t)(a) - 0xD000) >> 6])
+
+typedef void (*ObjFn)(Obj *);
+extern const ObjFn obj_index[];
+
+/* ------------------------------------------------------------------ the video chip (vdp.c) */
+extern const uint8_t *vram[2048]; /* each tile of video memory: its 32-byte pattern */
+extern uint16_t plane_a[32][64], plane_b[32][64];
+extern uint16_t cram[64]; /* the colours shown, Mega Drive words */
+typedef struct {
+ int16_t y;
+ uint8_t size, link;
+ uint16_t tile;
+ int16_t x;
+} Sprite;
+extern Sprite spritetable[80]; /* v_spritetablebuffer */
+extern uint8_t vdp_backdrop; /* colour shown where nothing is drawn */
+extern int16_t vdp_vscroll_a, vdp_vscroll_b;
+extern bool vdp_line_scroll; /* a scroll per line, or per 8 lines (title) */
+extern int vdp_hint_line; /* the water palette from this line on (or none: -1) */
+extern bool vdp_display; /* the picture is on */
+void vdp_load_art(int art, int tile); /* art from data.bin into video memory, at this tile */
+void vdp_load_art_part(int art, int first, int count, int tile);
+void vdp_clear_planes(void);
+void vdp_render(void);
+void vdp_fill_plane(uint16_t (*plane)[64], int col, int row, int w, int h, const uint16_t *words, uint16_t add);
+
+/* ------------------------------------------------------------------ data access */
+const uint8_t *map_get(int id); /* a mappings table */
+const uint8_t *map_frame(const uint8_t *map, int f); /* its frame: a count, then 6-byte pieces */
+const uint8_t *ani_get(int id); /* an animation table */
+
+/* ------------------------------------------------------------------ the game's variables (RAM) */
+typedef struct {
+ fix_t x, y;
+} Cam;
+
+typedef struct {
+ /* game */
+ uint8_t gamemode;
+ uint8_t jpadhold2, jpadpress2, jpadhold1, jpadpress1;
+ uint16_t generictimer;
+ int16_t scrposy_vdp, bgscrposy_vdp;
+ uint8_t hblank_line;
+ uint8_t pfade_start, pfade_size;
+ uint8_t vblank_routine;
+ uint16_t pcyc_num, pcyc_time;
+ uint32_t random;
+ uint16_t f_pause;
+ uint16_t f_hblank_pal;
+ int16_t waterpos1, waterpos2, waterpos3;
+ uint8_t f_water, wtr_routine, f_wtr_state, f_doupdatesinhblank;
+ uint16_t pal_buffer[0x18];
+ /* level */
+ Cam cam[4]; /* v_screenposx/y, v_bgscreenposx/y, v_bg2..., v_bg3... */
+ int16_t limitleft1, limitright1, limittop1, limitbtm1;
+ int16_t limitleft2, limitright2, limittop2, limitbtm2;
+ int16_t limitleft3;
+ int16_t scrshiftx, scrshifty;
+ int16_t lookshift;
+ uint8_t dle_routine;
+ uint8_t f_nobgscroll;
+ uint8_t fg_xblock, fg_yblock, bg1_xblock, bg1_yblock, bg2_xblock, bg2_yblock, bg3_xblock, bg3_yblock;
+ uint8_t scroll_flags[4]; /* v_fg_scroll_flags, bg1, bg2, bg3 (their high bytes) */
+ uint8_t f_bgscrollvert;
+ int16_t sonspeedmax, sonspeedacc, sonspeeddec;
+ uint8_t sonframenum, f_sonframechg;
+ uint8_t anglebuffer, anglebuffer2;
+ uint8_t opl_routine;
+ int16_t opl_screen;
+ uint32_t opl_data[4]; /* (offsets into data.bin of the object lists) */
+ int16_t ssangle, ssrotate;
+ uint16_t btnpushtime1, btnpushtime2;
+ int16_t palchgspeed;
+ const uint8_t *collindex;
+ uint16_t palss_num, palss_time, palss_index;
+ uint16_t ssbganim;
+ int16_t obj31ypos;
+ uint8_t bossstatus;
+ uint16_t trackpos;
+ uint8_t f_lockscreen;
+ uint8_t loop256[4]; /* v_256loop1, v_256loop2, v_256roll1, v_256roll2 */
+ uint8_t lani[6][2]; /* level art animations: frame, time */
+ uint16_t gfxbigring;
+ uint8_t f_conveyrev;
+ uint8_t obj63[6];
+ uint8_t f_wtunnelmode, f_playerctrl, f_wtunneldisallow, f_slidemode;
+ uint8_t obj6B, f_lockctrl, f_bigring, f_obj56;
+ uint16_t itembonus, timebonus, ringbonus;
+ uint8_t f_endactbonus, sonicend;
+ uint16_t lz_deform;
+ uint8_t f_switch[16];
+ /* screens */
+ uint16_t palette_water[64], palette[64], palette_fading[64], palette_water_fading[64];
+ uint8_t objstate[0x102]; /* (0xC0 in the original, with the stack after it) */
+ /* kept across levels */
+ uint16_t f_restart;
+ uint16_t framecount;
+ uint8_t debugitem;
+ uint16_t debuguse;
+ uint8_t debugspeedtimer, debugspeed;
+ uint32_t vblank_count;
+ uint8_t zone, act;
+ uint8_t lives;
+ uint16_t air;
+ uint8_t lastspecial;
+ uint8_t continues;
+ uint8_t f_timeover;
+ uint8_t lifecount, f_lifecount, f_ringcount, f_timecount, f_scorecount;
+ uint16_t rings;
+ uint8_t timemin, timesec, timecent; /* v_time: (unused), minutes, seconds, frames */
+ uint32_t score;
+ uint8_t shield, invinc, shoes, unused1;
+ uint8_t lastlamp;
+ int16_t lamp_xpos, lamp_ypos;
+ uint16_t lamp_rings;
+ uint8_t lamp_timemin, lamp_timesec, lamp_timecent;
+ uint8_t lamp_dle;
+ int16_t lamp_limitbtm;
+ int16_t lamp_scrx, lamp_scry, lamp_bgscrx, lamp_bgscry, lamp_bg2scrx, lamp_bg2scry, lamp_bg3scrx, lamp_bg3scry;
+ int16_t lamp_wtrpos;
+ uint8_t lamp_wtrrout, lamp_wtrstat, lamp_lives;
+ uint8_t emeralds;
+ uint8_t emldlist[6];
+ uint16_t oscillate;
+ uint16_t osc[0x20]; /* v_oscillate+2: value and speed pairs */
+ uint8_t ani_time[4], ani_frame[4];
+ uint16_t ani3_buf;
+ int16_t limittopdb, limitbtmdb;
+ Cam cam_dup[4];
+ uint8_t scroll_flags_dup[4];
+ uint16_t levselitem;
+ uint32_t scorelife;
+ uint8_t f_levselcheat, f_slomocheat, f_debugcheat, f_creditscheat;
+ uint16_t title_dcount, title_ccount;
+ int16_t f_demo;
+ uint16_t demonum;
+ uint16_t creditsnum;
+ uint16_t f_debugmode;
+} Vars;
+extern Vars V;
+
+/* the background scroll buffer and the scroll table */
+extern union bgscroll_u {
+ int32_t l[128];
+ int16_t w[256];
+} bgscroll;
+typedef struct {
+ int16_t fg, bg;
+} HScroll;
+extern HScroll hscroll[256]; /* v_hscrolltablebuffer (with room for spills) */
+
+/* sprite display queue: 8 layers of up to 63 objects */
+extern struct spritequeue_s {
+ uint16_t n;
+ Obj *o[63];
+} spritequeue[8];
+
+/* the level layout: 8 rows of $40 chunks, foreground and background interleaved as in the original */
+extern uint8_t lvllayout[8][2][0x40];
+extern const uint16_t *blocks16; /* v_16x16: 4 tile words a block */
+extern const uint16_t *chunks256; /* v_256x256: 256 block words a chunk */
+
+/* ------------------------------------------------------------------ game modes */
+enum {
+ id_Sega = 0x00, id_Title = 0x04, id_Demo = 0x08, id_Level = 0x0C, id_Special = 0x10, id_Continue = 0x14,
+ id_Ending = 0x18, id_Credits = 0x1C
+};
+enum {
+ id_VBlank_Lag = 0x00, id_VBlank_Sega = 0x02, id_VBlank_Title = 0x04, id_VBlank_Levels = 0x08,
+ id_VBlank_SpecialStage = 0x0A, id_VBlank_TitleCards = 0x0C, id_VBlank_Paused = 0x10,
+ id_VBlank_PaletteFade = 0x12, id_VBlank_SegaPCM = 0x14, id_VBlank_Continue = 0x16, id_VBlank_Ending = 0x18
+};
+
+/* ------------------------------------------------------------------ main.c */
+void WaitForVBlank(void);
+uint32_t RandomNumber(void);
+int16_t CalcSine(uint8_t angle, int16_t *cos);
+uint8_t CalcAngle(int16_t x, int16_t y);
+void game_quit(void); /* Home: save and leave, from anywhere */
+
+/* ------------------------------------------------------------------ palettes (palette.c) */
+void PalLoad(int id); /* palid_*: straight to v_palette */
+void PalLoad_Fade(int id); /* to the fade-in buffer */
+void PalLoad_Water(int id);
+void PalLoad_Fade_Water(int id);
+void PaletteFadeIn(void);
+void PalFadeIn_Alt(void);
+void PaletteFadeOut(void);
+void PaletteWhiteIn(void);
+void PaletteWhiteOut(void);
+void FadeIn_FromBlack(void);
+void FadeOut_ToBlack(void);
+void WhiteIn_FromWhite(void);
+void WhiteOut_ToWhite(void);
+void PaletteCycle(void);
+void PalCycle_Sega(void);
+void PalCycle_Title(void);
+enum {
+ palid_SegaBG, palid_Title, palid_LevelSel, palid_Sonic, palid_GHZ, palid_LZ, palid_MZ, palid_SLZ, palid_SYZ,
+ palid_SBZ1, palid_Special, palid_LZWater, palid_SBZ3, palid_SBZ3Water, palid_SBZ2, palid_LZSonWater,
+ palid_SBZ3SonWat, palid_SSResult, palid_Continue, palid_Ending
+};
+
+/* ------------------------------------------------------------------ level (level.c) */
+void LevelSizeLoad(void);
+void LevelDataLoad(void);
+void LevelLayoutLoad(void);
+void LoadTilesFromStart(void);
+void LoadTilesAsYouMove(void);
+void LoadTilesAsYouMove_BGOnly(void);
+void DeformLayers(void);
+void ColIndexLoad(void);
+void AddPLC(int id);
+void NewPLC(int id);
+void ClearPLC(void);
+void RunPLC(void);
+void QuickPLC(int id);
+bool plc_pending(void);
+void DynamicLevelEvents(void);
+void OscillateNumInit(void);
+void OscillateNumDo(void);
+void SynchroAnimate(void);
+void SignpostArtLoad(void);
+void AnimateLevelGfx(void);
+void LZWaterFeatures(void);
+void ClearScreen(void);
+enum {
+ plcid_Main, plcid_Main2, plcid_Explode, plcid_GameOver, plcid_GHZ, plcid_GHZ2, plcid_LZ, plcid_LZ2, plcid_MZ,
+ plcid_MZ2, plcid_SLZ, plcid_SLZ2, plcid_SYZ, plcid_SYZ2, plcid_SBZ, plcid_SBZ2, plcid_TitleCard, plcid_Boss,
+ plcid_Signpost, plcid_Warp, plcid_SpecialStage, plcid_GHZAnimals, plcid_LZAnimals, plcid_MZAnimals,
+ plcid_SLZAnimals, plcid_SYZAnimals, plcid_SBZAnimals, plcid_SSResult, plcid_Ending, plcid_TryAgain,
+ plcid_EggmanSBZ2, plcid_FZBoss
+};
+
+/* ------------------------------------------------------------------ objects (obj.c) */
+void ExecuteObjects(void);
+void BuildSprites(void);
+void DisplaySprite(Obj *o);
+void DeleteObject(Obj *o);
+Obj *FindFreeObj(void);
+Obj *FindNextFreeObj(Obj *parent);
+void ObjPosLoad(void);
+void AnimateSprite(Obj *o, const uint8_t *ani);
+void ObjectFall(Obj *o);
+void SpeedToPos(Obj *o);
+bool ChkObjectVisible(Obj *o);
+bool ChkPartiallyVisible(Obj *o);
+void RememberState(Obj *o);
+void obj_out_of_range(Obj *o); /* out_of_range: deletes it when far from the camera */
+bool obj_far(Obj *o);
+void AddPoints(int points);
+#endif
diff --git a/games/sonic/src/s1const.h b/games/sonic/src/s1const.h
new file mode 100644
index 00000000..28e7ffec
--- /dev/null
+++ b/games/sonic/src/s1const.h
@@ -0,0 +1,547 @@
+/* made by tools/pack.py: the disassembly's names for its numbers */
+#ifndef S1_CONST_H
+#define S1_CONST_H
+#define ArtTile_Animal_1 1408
+#define ArtTile_Animal_2 1426
+#define ArtTile_Ball_Hog 770
+#define ArtTile_Basaran 1208
+#define ArtTile_Bomb 1024
+#define ArtTile_Bonuses 1392
+#define ArtTile_Burrobot 1190
+#define ArtTile_Button 1295
+#define ArtTile_Button_Main 1299
+#define ArtTile_Buzz_Bomber 1092
+#define ArtTile_Chopper 1147
+#define ArtTile_Continue_Number 1788
+#define ArtTile_Continue_Sonic 1280
+#define ArtTile_Crabmeat 1024
+#define ArtTile_Credits_Font 1440
+#define ArtTile_Eggman 1024
+#define ArtTile_Eggman_Button 1188
+#define ArtTile_Eggman_Exhaust 1322
+#define ArtTile_Eggman_Spikeball 1304
+#define ArtTile_Eggman_Trap_Floor 1304
+#define ArtTile_Eggman_Weapons 1132
+#define ArtTile_Ending_Chicken 1381
+#define ArtTile_Ending_Eggman 1316
+#define ArtTile_Ending_Emeralds 965
+#define ArtTile_Ending_Flicky 1445
+#define ArtTile_Ending_Flowers 928
+#define ArtTile_Ending_Penguin 1395
+#define ArtTile_Ending_Pig 1427
+#define ArtTile_Ending_Rabbit 1363
+#define ArtTile_Ending_STH 1477
+#define ArtTile_Ending_Seal 1413
+#define ArtTile_Ending_Sonic 993
+#define ArtTile_Ending_Squirrel 1459
+#define ArtTile_Error_Handler_Font 1984
+#define ArtTile_Explosion 1440
+#define ArtTile_FZ_Boss 768
+#define ArtTile_FZ_Eggman_Fleeing 928
+#define ArtTile_FZ_Eggman_No_Vehicle 1136
+#define ArtTile_GHZ_Big_Flower_1 860
+#define ArtTile_GHZ_Big_Flower_2 912
+#define ArtTile_GHZ_Bridge 910
+#define ArtTile_GHZ_Edge_Wall 844
+#define ArtTile_GHZ_Flower_3 896
+#define ArtTile_GHZ_Flower_4 832
+#define ArtTile_GHZ_Flower_Stalk 856
+#define ArtTile_GHZ_Giant_Ball 938
+#define ArtTile_GHZ_MZ_Swing 896
+#define ArtTile_GHZ_Purple_Rock 976
+#define ArtTile_GHZ_SLZ_Smashable_Wall 1295
+#define ArtTile_GHZ_Small_Flower 876
+#define ArtTile_GHZ_Spike_Pole 920
+#define ArtTile_GHZ_Waterfall 888
+#define ArtTile_Game_Over 1374
+#define ArtTile_Giant_Ring 1024
+#define ArtTile_Giant_Ring_Flash 1122
+#define ArtTile_HUD 1738
+#define ArtTile_HUDRings 1786
+#define ArtTile_HUDScore 1764
+#define ArtTile_HUDScore_E 1762
+#define ArtTile_HUDTimeMins 1778
+#define ArtTile_HUDTimeSecs 1782
+#define ArtTile_Hidden_Points 1206
+#define ArtTile_Invincibility 1372
+#define ArtTile_Jaws 1158
+#define ArtTile_LZ_Block_1 480
+#define ArtTile_LZ_Block_2 496
+#define ArtTile_LZ_Blocks 998
+#define ArtTile_LZ_Bubbles 840
+#define ArtTile_LZ_Conveyor_Belt 1014
+#define ArtTile_LZ_Cork 1280
+#define ArtTile_LZ_Door 964
+#define ArtTile_LZ_Flapping_Door 808
+#define ArtTile_LZ_Gargoyle 745
+#define ArtTile_LZ_Harpoon 972
+#define ArtTile_LZ_Moving_Block 956
+#define ArtTile_LZ_Orbinaut 1127
+#define ArtTile_LZ_Pole 990
+#define ArtTile_LZ_Push_Block 990
+#define ArtTile_LZ_Rising_Platform 1103
+#define ArtTile_LZ_Spikeball_Chain 784
+#define ArtTile_LZ_Splash 601
+#define ArtTile_LZ_UnusedFace 1088
+#define ArtTile_LZ_Water_Surface 768
+#define ArtTile_Lamppost 1952
+#define ArtTile_Level 0
+#define ArtTile_Level_Select_Font 1664
+#define ArtTile_Lives_Counter 2004
+#define ArtTile_Lives_Counter_Num 2013
+#define ArtTile_MZ_Animated_Lava 738
+#define ArtTile_MZ_Animated_Magma 722
+#define ArtTile_MZ_Block 696
+#define ArtTile_MZ_Fireball 837
+#define ArtTile_MZ_Glass_Pillar 910
+#define ArtTile_MZ_Lava 936
+#define ArtTile_MZ_SYZ_Caterkiller 1279
+#define ArtTile_MZ_Spike_Stomper 768
+#define ArtTile_MZ_Torch 754
+#define ArtTile_Mini_Sonic 1361
+#define ArtTile_Monitor 1664
+#define ArtTile_Moto_Bug 1264
+#define ArtTile_Newtron 1179
+#define ArtTile_Points 1943
+#define ArtTile_Prison_Capsule 1181
+#define ArtTile_Ring 1970
+#define ArtTile_Roller 1208
+#define ArtTile_SBZ_Caterkiller 688
+#define ArtTile_SBZ_Collapsing_Floor 1013
+#define ArtTile_SBZ_Disc 836
+#define ArtTile_SBZ_Door 744
+#define ArtTile_SBZ_Electric_Orb 1150
+#define ArtTile_SBZ_Flamethrower 985
+#define ArtTile_SBZ_Girder 752
+#define ArtTile_SBZ_Horizontal_Door 1135
+#define ArtTile_SBZ_Junction 840
+#define ArtTile_SBZ_Moving_Block_Long 1120
+#define ArtTile_SBZ_Moving_Block_Short 704
+#define ArtTile_SBZ_Orbinaut 1065
+#define ArtTile_SBZ_Saw 949
+#define ArtTile_SBZ_Smoke_Puff_1 1096
+#define ArtTile_SBZ_Smoke_Puff_2 1108
+#define ArtTile_SBZ_Spinning_Platform 1247
+#define ArtTile_SBZ_Swing 913
+#define ArtTile_SBZ_Trap_Door 1170
+#define ArtTile_SBZ_Vanishing_Block 1219
+#define ArtTile_SLZ_Collapsing_Floor 1248
+#define ArtTile_SLZ_Fan 928
+#define ArtTile_SLZ_Fireball 1152
+#define ArtTile_SLZ_Fireball_Launcher 1240
+#define ArtTile_SLZ_Orbinaut 1065
+#define ArtTile_SLZ_Pylon 972
+#define ArtTile_SLZ_Seesaw 884
+#define ArtTile_SLZ_Spikeball 1264
+#define ArtTile_SLZ_Swing 988
+#define ArtTile_SS_Background_Clouds 0
+#define ArtTile_SS_Background_Fish 81
+#define ArtTile_SS_Bumper 571
+#define ArtTile_SS_Emerald 1904
+#define ArtTile_SS_Emerald_Sparkle 1008
+#define ArtTile_SS_Extra_Life 880
+#define ArtTile_SS_Ghost_Block 1264
+#define ArtTile_SS_Glass 1520
+#define ArtTile_SS_Goal 593
+#define ArtTile_SS_Plane_1 512
+#define ArtTile_SS_Plane_2 768
+#define ArtTile_SS_Plane_3 1024
+#define ArtTile_SS_Plane_4 1280
+#define ArtTile_SS_Plane_5 1536
+#define ArtTile_SS_Plane_6 1792
+#define ArtTile_SS_R_Block 752
+#define ArtTile_SS_Red_White_Block 1136
+#define ArtTile_SS_Results_Emeralds 1345
+#define ArtTile_SS_Up_Down 611
+#define ArtTile_SS_W_Block 1392
+#define ArtTile_SS_Wall 322
+#define ArtTile_SS_Zone_1 1943
+#define ArtTile_SS_Zone_2 1952
+#define ArtTile_SS_Zone_3 1961
+#define ArtTile_SS_Zone_4 1943
+#define ArtTile_SS_Zone_5 1952
+#define ArtTile_SS_Zone_6 1961
+#define ArtTile_SYZ_Big_Spikeball 918
+#define ArtTile_SYZ_Bumper 896
+#define ArtTile_SYZ_Spikeball_Chain 954
+#define ArtTile_Sega_Tiles 0
+#define ArtTile_Shield 1345
+#define ArtTile_Signpost 1664
+#define ArtTile_Sonic 1920
+#define ArtTile_Sonic_Team_Font 166
+#define ArtTile_Spikes 1307
+#define ArtTile_Spring_Horizontal 1315
+#define ArtTile_Spring_Vertical 1331
+#define ArtTile_Title_Card 1408
+#define ArtTile_Title_Foreground 512
+#define ArtTile_Title_Japanese_Text 0
+#define ArtTile_Title_Sonic 768
+#define ArtTile_Title_Trademark 1296
+#define ArtTile_Try_Again_Eggman 993
+#define ArtTile_Try_Again_Emeralds 965
+#define ArtTile_UnusedExplosion 1052
+#define ArtTile_Warp 1345
+#define ArtTile_Yadrin 1147
+#define aniXFlip 32
+#define aniYFlip 64
+#define bitA 6
+#define bitB 4
+#define bitC 5
+#define bitDn 1
+#define bitL 2
+#define bitR 3
+#define bitStart 7
+#define bitUp 0
+#define boss_fz_end 9984
+#define boss_fz_x 9296
+#define boss_fz_y 1296
+#define boss_ghz_end 10944
+#define boss_ghz_x 10592
+#define boss_ghz_y 768
+#define boss_lz_end 8240
+#define boss_lz_x 7648
+#define boss_lz_y 192
+#define boss_mz_end 6496
+#define boss_mz_x 6144
+#define boss_mz_y 528
+#define boss_sbz2_x 8272
+#define boss_sbz2_y 1296
+#define boss_slz_end 8544
+#define boss_slz_x 8192
+#define boss_slz_y 528
+#define boss_syz_end 11584
+#define boss_syz_x 11264
+#define boss_syz_y 1228
+#define btnA 64
+#define btnABC 112
+#define btnB 16
+#define btnC 32
+#define btnDir 15
+#define btnDn 2
+#define btnL 4
+#define btnR 8
+#define btnStart 128
+#define btnUp 1
+#define fr_Balance1 58
+#define fr_Balance2 59
+#define fr_BubStand 74
+#define fr_Burnt 75
+#define fr_Death 77
+#define fr_Drown 76
+#define fr_Duck 57
+#define fr_Float1 60
+#define fr_Float2 61
+#define fr_Float3 62
+#define fr_Float4 63
+#define fr_Float5 83
+#define fr_Float6 84
+#define fr_GetAir 86
+#define fr_Hang1 65
+#define fr_Hang2 66
+#define fr_Injury 85
+#define fr_Leap1 67
+#define fr_Leap2 68
+#define fr_LookUp 5
+#define fr_Null 0
+#define fr_Push1 69
+#define fr_Push2 70
+#define fr_Push3 71
+#define fr_Push4 72
+#define fr_Roll1 46
+#define fr_Roll2 47
+#define fr_Roll3 48
+#define fr_Roll4 49
+#define fr_Roll5 50
+#define fr_Run11 30
+#define fr_Run12 31
+#define fr_Run13 32
+#define fr_Run14 33
+#define fr_Run21 34
+#define fr_Run22 35
+#define fr_Run23 36
+#define fr_Run24 37
+#define fr_Run31 38
+#define fr_Run32 39
+#define fr_Run33 40
+#define fr_Run34 41
+#define fr_Run41 42
+#define fr_Run42 43
+#define fr_Run43 44
+#define fr_Run44 45
+#define fr_Shrink1 78
+#define fr_Shrink2 79
+#define fr_Shrink3 80
+#define fr_Shrink4 81
+#define fr_Shrink5 82
+#define fr_Slide 87
+#define fr_Spring 64
+#define fr_Stand 1
+#define fr_Stop1 55
+#define fr_Stop2 56
+#define fr_Surf 73
+#define fr_Wait1 2
+#define fr_Wait2 3
+#define fr_Wait3 4
+#define fr_Walk11 6
+#define fr_Walk12 7
+#define fr_Walk13 8
+#define fr_Walk14 9
+#define fr_Walk15 10
+#define fr_Walk16 11
+#define fr_Walk21 12
+#define fr_Walk22 13
+#define fr_Walk23 14
+#define fr_Walk24 15
+#define fr_Walk25 16
+#define fr_Walk26 17
+#define fr_Walk31 18
+#define fr_Walk32 19
+#define fr_Walk33 20
+#define fr_Walk34 21
+#define fr_Walk35 22
+#define fr_Walk36 23
+#define fr_Walk41 24
+#define fr_Walk42 25
+#define fr_Walk43 26
+#define fr_Walk44 27
+#define fr_Walk45 28
+#define fr_Walk46 29
+#define fr_Warp1 51
+#define fr_Warp2 52
+#define fr_Warp3 53
+#define fr_Warp4 54
+#define id_AnimTest 16
+#define id_Animals 40
+#define id_AutoDoor 42
+#define id_Balance 6
+#define id_BallHog 30
+#define id_Basaran 85
+#define id_BasicPlatform 24
+#define id_BigSpikeBall 88
+#define id_Bomb 95
+#define id_BossBall 72
+#define id_BossBlock 118
+#define id_BossFinal 133
+#define id_BossFire 116
+#define id_BossGreenHill 61
+#define id_BossLabyrinth 119
+#define id_BossMarble 115
+#define id_BossPlasma 134
+#define id_BossSpikeball 123
+#define id_BossSpringYard 117
+#define id_BossStarLight 122
+#define id_Bridge 17
+#define id_Bubble 100
+#define id_Bumper 71
+#define id_Burnt 22
+#define id_Burrobot 45
+#define id_Button 50
+#define id_BuzzBomber 34
+#define id_Cannonball 32
+#define id_Caterkiller 120
+#define id_ChainStomp 49
+#define id_Chopper 43
+#define id_CirclingPlatform 90
+#define id_CollapseFloor 83
+#define id_CollapseLedge 26
+#define id_ContScrItem 128
+#define id_ContSonic 129
+#define id_Conveyor 104
+#define id_Crabmeat 31
+#define id_CreditsText 138
+#define id_Death 24
+#define id_Drown 23
+#define id_DrownCount 10
+#define id_Duck 8
+#define id_EdgeWalls 68
+#define id_EggmanCylinder 132
+#define id_Electro 110
+#define id_Elevator 89
+#define id_EndChaos 136
+#define id_EndEggman 139
+#define id_EndSTH 137
+#define id_EndSonic 135
+#define id_EndZ 6
+#define id_EndZ_bad 1537
+#define id_EndZ_good 1536
+#define id_Explosion 63
+#define id_ExplosionItem 39
+#define id_FZ 1282
+#define id_FalseFloor 131
+#define id_Fan 93
+#define id_Flamethrower 109
+#define id_FlapDoor 12
+#define id_Float1 14
+#define id_Float2 15
+#define id_Float3 29
+#define id_Float4 30
+#define id_FloatingBlock 86
+#define id_GHZ 0
+#define id_GHZ_act1 0
+#define id_GHZ_act2 1
+#define id_GHZ_act3 2
+#define id_GameOverCard 57
+#define id_Gargoyle 98
+#define id_GetAir 21
+#define id_GeyserMaker 76
+#define id_GiantRing 75
+#define id_Girder 112
+#define id_GlassBlock 48
+#define id_GotThroughCard 58
+#define id_GrassFire 53
+#define id_HUD 33
+#define id_Hang 17
+#define id_Harpoon 22
+#define id_Helix 23
+#define id_HiddenBonus 125
+#define id_Hurt 26
+#define id_Invisibarrier 113
+#define id_Jaws 44
+#define id_Junction 102
+#define id_LZ 1
+#define id_LZ_act1 256
+#define id_LZ_act2 257
+#define id_LZ_act3 258
+#define id_LZ_act4 259
+#define id_LabyrinthBlock 97
+#define id_LabyrinthConvey 99
+#define id_Lamppost 121
+#define id_LargeGrass 47
+#define id_LavaBall 20
+#define id_LavaGeyser 77
+#define id_LavaMaker 19
+#define id_LavaTag 84
+#define id_LavaWall 78
+#define id_Leap1 18
+#define id_Leap2 19
+#define id_LookUp 7
+#define id_MZ 2
+#define id_MZ_act1 512
+#define id_MZ_act2 513
+#define id_MZ_act3 514
+#define id_MagicSwitch 29
+#define id_MarbleBrick 70
+#define id_Missile 35
+#define id_Monitor 38
+#define id_MotoBug 64
+#define id_MovingBlock 82
+#define id_Newtron 66
+#define id_Null 28
+#define id_Obj02 2
+#define id_Obj03 3
+#define id_Obj04 4
+#define id_Obj05 5
+#define id_Obj06 6
+#define id_Obj07 7
+#define id_Orbinaut 96
+#define id_PSBTM 15
+#define id_Points 41
+#define id_Pole 11
+#define id_PowerUp 46
+#define id_Prison 62
+#define id_PurpleRock 59
+#define id_Push 4
+#define id_PushBlock 51
+#define id_Pylon 92
+#define id_RingFlash 124
+#define id_RingLoss 55
+#define id_Rings 37
+#define id_Roll 2
+#define id_Roll2 3
+#define id_Roller 67
+#define id_RollingBall 25
+#define id_Run 1
+#define id_RunningDisc 103
+#define id_SBZ 5
+#define id_SBZ_act1 1280
+#define id_SBZ_act2 1281
+#define id_SLZ 3
+#define id_SLZ_act1 768
+#define id_SLZ_act2 769
+#define id_SLZ_act3 770
+#define id_SS 7
+#define id_SSRChaos 127
+#define id_SSResult 126
+#define id_SYZ 4
+#define id_SYZ_act1 1024
+#define id_SYZ_act2 1025
+#define id_SYZ_act3 1026
+#define id_Saws 106
+#define id_Scenery 28
+#define id_ScrapEggman 130
+#define id_ScrapStomp 107
+#define id_Seesaw 94
+#define id_ShieldItem 56
+#define id_Shrink 25
+#define id_SideStomp 69
+#define id_Signpost 13
+#define id_Slide 27
+#define id_SmashBlock 81
+#define id_SmashWall 60
+#define id_SonicPlayer 1
+#define id_SonicSpecial 9
+#define id_SpikeBall 87
+#define id_Spikes 54
+#define id_SpinConvey 111
+#define id_SpinPlatform 105
+#define id_SpinningLight 18
+#define id_Splash 8
+#define id_Splats 79
+#define id_Spring 16
+#define id_Springs 65
+#define id_Staircase 91
+#define id_Stop 13
+#define id_Surf 20
+#define id_SwingingPlatform 21
+#define id_Teleport 114
+#define id_TitleCard 52
+#define id_TitleSonic 14
+#define id_TryChaos 140
+#define id_UnusedExplosion 36
+#define id_VanishPlatform 108
+#define id_VanishSonic 74
+#define id_Wait 5
+#define id_Walk 0
+#define id_Warp1 9
+#define id_Warp2 10
+#define id_Warp3 11
+#define id_Warp4 12
+#define id_WaterSound 73
+#define id_WaterSurface 27
+#define id_Waterfall 101
+#define id_Yadrin 80
+#define sprite_cam_bg 8
+#define sprite_cam_bg_bit 3
+#define sprite_cam_field 4
+#define sprite_cam_field_bit 2
+#define sprite_cam_screen 0
+#define sprite_looping_bit 6
+#define sprite_rawmappings 32
+#define sprite_rawmappings_bit 5
+#define sprite_rendered 128
+#define sprite_rendered_bit 7
+#define sprite_xflip 1
+#define sprite_xflip_bit 0
+#define sprite_yflip 2
+#define sprite_yflip_bit 1
+#define status_defeated 128
+#define status_defeated_bit 7
+#define status_in_air 2
+#define status_in_air_bit 1
+#define status_no_balance 128
+#define status_no_balance_bit 7
+#define status_on_object 8
+#define status_on_object_bit 3
+#define status_pushing 32
+#define status_pushing_bit 5
+#define status_rolling 4
+#define status_rolling_bit 2
+#define status_rolljumping 16
+#define status_rolljumping_bit 4
+#define status_underwater 64
+#define status_underwater_bit 6
+#define status_xflip 1
+#define status_xflip_bit 0
+#define status_yflip 2
+#define status_yflip_bit 1
+#endif
diff --git a/games/sonic/src/solid.c b/games/sonic/src/solid.c
new file mode 100644
index 00000000..95a4c444
--- /dev/null
+++ b/games/sonic/src/solid.c
@@ -0,0 +1,217 @@
+/* Objects Sonic can stand on or bump into. A solid object pushes him out of its box by the
+ * shortest way (to a side: he pushes against it; on top: he stands on it and moves with it;
+ * from below: he stops, or is squashed against the floor); a platform only holds him from above,
+ * and a slope reads its top from a table of heights. The results are the original's: 0 nothing,
+ * 1 at a side, -1 on top or below. */
+#include "s1.h"
+#include "game.h"
+
+#define standonobject 0x3D
+
+static void Solid_ResetFloor(Obj *o, Obj *a1) {
+ if (a1->status & 8) {
+ Obj *a2 = &objs[OB(a1, standonobject)];
+ a2->status &= (uint8_t)~8;
+ a2->routine2 = 0;
+ }
+ OB(a1, standonobject) = (uint8_t)((o - objs) & 0x7F);
+ a1->angle = 0;
+ a1->vy = 0;
+ a1->inertia = a1->vx;
+ if (a1->status & 2) Sonic_ResetOnFloor(a1);
+ a1->status |= 8;
+ o->status |= 8;
+}
+
+static int no_collision(Obj *o, Obj *a1) {
+ if (o->status & 0x20) {
+ a1->anim = 0, a1->prevani = id_Run; /* (a word written over both) */
+ o->status &= (uint8_t)~0x20;
+ a1->status &= (uint8_t)~0x20;
+ }
+ return 0;
+}
+
+static int solid_collision(Obj *o, Obj *a1, int16_t d0, int16_t d1, int16_t d2, int16_t d3, int16_t d4) {
+ if (V.f_playerctrl & 0x80) return no_collision(o, a1);
+ if (player->routine >= 6 || V.debuguse) return 0;
+ int16_t d5 = d0;
+ if ((uint16_t)d1 < (uint16_t)d0) {
+ d0 = (int16_t)(d0 - d1 * 2);
+ d5 = (int16_t)-d0;
+ }
+ int16_t e1 = d3;
+ if ((uint16_t)d2 < (uint16_t)d3) {
+ d3 = (int16_t)(d3 - 4 - d4);
+ e1 = (int16_t)-d3;
+ }
+ if ((uint16_t)d5 > (uint16_t)e1) { /* above or below */
+ if (d3 < 0) {
+ if (a1->vy == 0) {
+ if (!(a1->status & 2)) KillSonic(a1, o);
+ return -1;
+ }
+ if (a1->vy < 0) {
+ a1->y.w.i -= d3;
+ a1->vy = 0;
+ }
+ return -1;
+ }
+ if ((uint16_t)d3 >= 0x10) return no_collision(o, a1);
+ d3 -= 4;
+ int16_t w = o->actwid, x = (int16_t)(w + a1->x.w.i - o->x.w.i);
+ if (x < 0 || (uint16_t)x >= (uint16_t)(w * 2) || a1->vy < 0) return 0;
+ a1->y.w.i -= d3;
+ a1->y.w.i -= 1;
+ Solid_ResetFloor(o, a1);
+ o->routine2 = 2;
+ o->status |= 8;
+ return -1;
+ }
+ if ((uint16_t)e1 <= 4) goto side_air;
+ if (d0 > 0) {
+ if (a1->vx >= 0) a1->inertia = 0, a1->vx = 0;
+ } else if (d0 < 0) {
+ if (a1->vx < 0) a1->inertia = 0, a1->vx = 0;
+ }
+ a1->x.w.i -= d0;
+ if (a1->status & 2) goto side_air;
+ a1->status |= 0x20;
+ o->status |= 0x20;
+ return 1;
+side_air:
+ o->status &= (uint8_t)~0x20;
+ a1->status &= (uint8_t)~0x20;
+ return 1;
+}
+
+static int solid_check(Obj *o, int16_t d1, int16_t d2) {
+ Obj *a1 = player;
+ int16_t d0 = (int16_t)(a1->x.w.i - o->x.w.i + d1);
+ if (d0 < 0 || (uint16_t)d0 > (uint16_t)(d1 * 2)) return no_collision(o, a1);
+ d2 = (int16_t)(d2 + (int8_t)a1->height);
+ int16_t d3 = (int16_t)(a1->y.w.i - o->y.w.i + 4 + d2);
+ int16_t d4 = (int16_t)(d2 * 2);
+ if (d3 < 0 || (uint16_t)d3 >= (uint16_t)d4) return no_collision(o, a1);
+ return solid_collision(o, a1, d0, d1, d2, d3, d4);
+}
+
+void MvSonicOnPtfm(Obj *o, int16_t d2, int16_t d3) {
+ Obj *a1 = player;
+ if ((V.f_playerctrl & 0x80) || player->routine >= 6 || V.debuguse) return;
+ a1->y.w.i = (int16_t)(o->y.w.i - d3 - a1->height);
+ a1->x.w.i = (int16_t)(a1->x.w.i - (d2 - o->x.w.i));
+}
+void MvSonicOnPtfm2(Obj *o, int16_t d2) { MvSonicOnPtfm(o, d2, 9); }
+
+static int solid_standing(Obj *o, int16_t d1, int16_t d3, int16_t d4) {
+ Obj *a1 = player;
+ int16_t d0 = (int16_t)(a1->x.w.i - o->x.w.i + d1);
+ if (!(a1->status & 2) && d0 >= 0 && (uint16_t)d0 < (uint16_t)(d1 * 2)) {
+ MvSonicOnPtfm(o, d4, d3);
+ return 0;
+ }
+ a1->status &= (uint8_t)~8;
+ o->status &= (uint8_t)~8;
+ o->routine2 = 0;
+ return 0;
+}
+
+int SolidObject(Obj *o, int16_t d1, int16_t d2, int16_t d3, int16_t d4) {
+ if (o->routine2) return solid_standing(o, d1, d3, d4);
+ if (!(o->render & 0x80)) return no_collision(o, player);
+ return solid_check(o, d1, d2);
+}
+
+int SolidObject_NoRenderChk(Obj *o, int16_t d1, int16_t d2, int16_t d3, int16_t d4) {
+ if (o->routine2) return solid_standing(o, d1, d3, d4);
+ return solid_check(o, d1, d2);
+}
+
+int SolidObject_Heightmap(Obj *o, int16_t d1, int16_t d2, const uint8_t *heights) {
+ Obj *a1 = player;
+ if (!(o->render & 0x80)) return no_collision(o, a1);
+ int16_t d0 = (int16_t)(a1->x.w.i - o->x.w.i + d1);
+ if (d0 < 0) return no_collision(o, a1);
+ int16_t d3 = (int16_t)(d1 * 2);
+ if ((uint16_t)d0 > (uint16_t)d3) return no_collision(o, a1);
+ int16_t d5 = d0;
+ if (o->render & 1) d5 = (int16_t)(~d5 + d3);
+ uint8_t h = (uint8_t)(heights[(uint16_t)d5 >> 1] - heights[0]);
+ int16_t top = (int16_t)(o->y.w.i - h);
+ d2 = (int16_t)(d2 + (int8_t)a1->height);
+ d3 = (int16_t)(a1->y.w.i - top + 4 + d2);
+ int16_t d4 = (int16_t)(d2 * 2);
+ if (d3 < 0 || (uint16_t)d3 >= (uint16_t)d4) return no_collision(o, a1);
+ return solid_collision(o, a1, d0, d1, d2, d3, d4);
+}
+
+/* ------------------------------------------------------------------ platforms */
+static void Plat_NoCheck(Obj *o, Obj *a1) {
+ if (a1->status & 8) {
+ Obj *a2 = &objs[OB(a1, standonobject)];
+ a2->status &= (uint8_t)~8;
+ a2->routine2 = 0;
+ if (a2->routine == 4) a2->routine -= 2;
+ }
+ OB(a1, standonobject) = (uint8_t)((o - objs) & 0x7F);
+ a1->angle = 0;
+ a1->vy = 0;
+ a1->inertia = a1->vx;
+ if (a1->status & 2) Sonic_ResetOnFloor(a1);
+ a1->status |= 8;
+ o->status |= 8;
+}
+
+static void plat_alt_y(Obj *o, int16_t d0) {
+ Obj *a1 = player;
+ int16_t d2 = a1->y.w.i, d1 = (int16_t)(d2 + (int8_t)a1->height + 4);
+ if ((uint16_t)d0 > (uint16_t)d1) return;
+ d0 = (int16_t)(d0 - d1);
+ if ((uint16_t)d0 < (uint16_t)-16) return;
+ if ((V.f_playerctrl & 0x80) || a1->routine >= 6) return;
+ a1->y.w.i = (int16_t)(d2 + d0 + 3);
+ o->routine += 2;
+ Plat_NoCheck(o, a1);
+}
+
+static bool plat_x(Obj *o, int16_t d1) {
+ Obj *a1 = player;
+ if (a1->vy < 0) return false;
+ int16_t d0 = (int16_t)(a1->x.w.i - o->x.w.i + d1);
+ return d0 >= 0 && (uint16_t)d0 < (uint16_t)(d1 * 2);
+}
+
+void PlatformObject(Obj *o, int16_t d1) {
+ if (plat_x(o, d1)) plat_alt_y(o, (int16_t)(o->y.w.i - 8));
+}
+void Plat_NoXCheck(Obj *o) { plat_alt_y(o, (int16_t)(o->y.w.i - 8)); }
+void Plat_NoXCheck_AltY(Obj *o, int16_t y) { plat_alt_y(o, y); }
+void PlatformObject_CustomHeight(Obj *o, int16_t d1, int16_t d3) {
+ if (plat_x(o, d1)) plat_alt_y(o, (int16_t)(o->y.w.i - d3));
+}
+void Plat_NoCheck_ext(Obj *o) { Plat_NoCheck(o, player); }
+
+void SlopeObject(Obj *o, int16_t d1, const uint8_t *heights) {
+ Obj *a1 = player;
+ if (a1->vy < 0) return;
+ int16_t d0 = (int16_t)(a1->x.w.i - o->x.w.i + d1);
+ if (d0 < 0) return;
+ d1 = (int16_t)(d1 * 2);
+ if ((uint16_t)d0 >= (uint16_t)d1) return;
+ if (o->render & 1) d0 = (int16_t)(~d0 + d1);
+ plat_alt_y(o, (int16_t)(o->y.w.i - heights[(uint16_t)d0 >> 1]));
+}
+
+void ExitPlatform2(Obj *o, int16_t d1, int16_t d2) {
+ Obj *a1 = player;
+ d2 = (int16_t)(d2 * 2);
+ if (!(a1->status & 2)) {
+ int16_t d0 = (int16_t)(a1->x.w.i - o->x.w.i + d1);
+ if (d0 >= 0 && (uint16_t)d0 < (uint16_t)d2) return;
+ }
+ a1->status &= (uint8_t)~8;
+ o->routine = 2;
+ o->status &= (uint8_t)~8;
+}
+void ExitPlatform(Obj *o, int16_t d1) { ExitPlatform2(o, d1, d1); }
diff --git a/games/sonic/src/sonic.c b/games/sonic/src/sonic.c
new file mode 100644
index 00000000..93241b35
--- /dev/null
+++ b/games/sonic/src/sonic.c
@@ -0,0 +1,968 @@
+/* Sonic: the player object, as the original moves him. On the ground his speed along it (inertia)
+ * grows by $C a frame up to $600 and turns into x and y speeds by the floor's angle; he sticks to
+ * the floor by two sensors at his feet (or at his side on walls, at his head on ceilings), slows on
+ * slopes, rolls with Down, jumps at $680 perpendicular to the floor; in the air gravity pulls $38 a
+ * frame, a jump is cut short when the button is let go, and he lands by sensors in the direction
+ * he moves. Then the hurt and death states, loops, the animations (walking and running frames
+ * chosen by angle and speed) and the art of each frame copied to video memory. */
+#include "s1.h"
+#include "collide.h"
+#include "game.h"
+
+#define son_maxspeed 0x600
+#define son_acceleration 0xC
+#define son_deceleration 0x80
+#define son_jumpspeed 0x680
+#define sonic_width 9
+#define sonic_height 19
+#define sonic_roll_width 7
+#define sonic_roll_height 14
+#define sonic_quick_size 10
+#define flashtime 0x30
+#define invtime 0x32
+#define shoetime 0x34
+#define angleright 0x36
+#define angleleft 0x37
+#define sticktoconvex 0x38
+#define restartime 0x3A
+#define jumping 0x3C
+#define standonobject 0x3D
+#define locktime 0x3E
+
+uint16_t tracksonic[64][2]; /* v_tracksonic: where he was, for the invincibility stars */
+
+/* ------------------------------------------------------------------ collision probes */
+typedef struct {
+ int16_t d1, d0; /* the nearer distance, and the other */
+ uint8_t d3; /* the angle of the nearer surface */
+} Probe;
+
+static Probe find_smaller(int16_t d1, int16_t d0, uint8_t snap) {
+ Probe p;
+ uint8_t a = V.anglebuffer2;
+ if (d1 > d0) {
+ a = V.anglebuffer;
+ int16_t t = d0;
+ d0 = d1, d1 = t;
+ }
+ if (a & 1) a = snap;
+ p.d1 = d1, p.d0 = d0, p.d3 = a;
+ return p;
+}
+
+Probe Sonic_FindFloor(Obj *o) {
+ int16_t y = (int16_t)(o->y.w.i + (int8_t)o->height);
+ int16_t a = FindFloor(o, y, (int16_t)(o->x.w.i + (int8_t)o->width), 0xD, 0, 0x10, &V.anglebuffer, NULL);
+ int16_t b = FindFloor(o, y, (int16_t)(o->x.w.i - (int8_t)o->width), 0xD, 0, 0x10, &V.anglebuffer2, NULL);
+ return find_smaller(b, a, 0);
+}
+static Probe Sonic_FindCeiling(Obj *o) {
+ int16_t y = (int16_t)((o->y.w.i - (int8_t)o->height) ^ 0xF);
+ int16_t a = FindFloor(o, y, (int16_t)(o->x.w.i + (int8_t)o->width), 0xE, 0x1000, -0x10, &V.anglebuffer, NULL);
+ int16_t b = FindFloor(o, y, (int16_t)(o->x.w.i - (int8_t)o->width), 0xE, 0x1000, -0x10, &V.anglebuffer2, NULL);
+ return find_smaller(b, a, 0x80);
+}
+static Probe Sonic_FindWallRight(Obj *o) {
+ int16_t x = (int16_t)(o->x.w.i + (int8_t)o->height);
+ int16_t a = FindWall(o, (int16_t)(o->y.w.i - (int8_t)o->width), x, 0xE, 0, 0x10, &V.anglebuffer, NULL);
+ int16_t b = FindWall(o, (int16_t)(o->y.w.i + (int8_t)o->width), x, 0xE, 0, 0x10, &V.anglebuffer2, NULL);
+ return find_smaller(b, a, 0xC0);
+}
+static Probe Sonic_FindWallLeft(Obj *o) {
+ int16_t x = (int16_t)((o->x.w.i - (int8_t)o->height) ^ 0xF);
+ int16_t a = FindWall(o, (int16_t)(o->y.w.i - (int8_t)o->width), x, 0xE, 0x800, -0x10, &V.anglebuffer, NULL);
+ int16_t b = FindWall(o, (int16_t)(o->y.w.i + (int8_t)o->width), x, 0xE, 0x800, -0x10, &V.anglebuffer2, NULL);
+ return find_smaller(b, a, 0x40);
+}
+
+static Probe snap(int16_t d1, uint8_t to) {
+ Probe p;
+ p.d1 = d1, p.d0 = 0, p.d3 = V.anglebuffer & 1 ? to : V.anglebuffer;
+ return p;
+}
+static Probe floor_quick(Obj *o, int16_t y, int16_t x) {
+ return snap(FindFloor(o, (int16_t)(y + sonic_quick_size), x, 0xE, 0, 0x10, &V.anglebuffer, NULL), 0);
+}
+static Probe ceiling_quick(Obj *o, int16_t y, int16_t x) {
+ return snap(FindFloor(o, (int16_t)((y - sonic_quick_size) ^ 0xF), x, 0xE, 0x1000, -0x10, &V.anglebuffer, NULL), 0x80);
+}
+static Probe wallright_quick(Obj *o, int16_t y, int16_t x) {
+ return snap(FindWall(o, y, (int16_t)(x + sonic_quick_size), 0xE, 0, 0x10, &V.anglebuffer, NULL), 0xC0);
+}
+static Probe wallleft_quick(Obj *o, int16_t y, int16_t x) {
+ return snap(FindWall(o, y, (int16_t)((x - sonic_quick_size) ^ 0xF), 0xE, 0x800, -0x10, &V.anglebuffer, NULL), 0x40);
+}
+
+/* the room ahead in the direction angle, from where he will be next frame */
+static Probe Sonic_CalcRoomAhead(Obj *o, uint8_t d0) {
+ int16_t x = (int16_t)((o->x.l + ((int32_t)o->vx << 8)) >> 16);
+ int16_t y = (int16_t)((o->y.l + ((int32_t)o->vy << 8)) >> 16);
+ V.anglebuffer = V.anglebuffer2 = d0;
+ uint8_t d1 = d0;
+ uint8_t q;
+ if ((int8_t)(uint8_t)(d0 + 0x20) >= 0) q = (uint8_t)(((int8_t)d1 < 0 ? d1 + 1 : d1) + 0x1F);
+ else q = (uint8_t)(((int8_t)d1 < 0 ? d1 - 1 : d1) + 0x20);
+ q &= 0xC0;
+ if (q == 0) return floor_quick(o, y, x);
+ if (q == 0x80) return ceiling_quick(o, y, x);
+ if (!(d1 & 0x38)) y += 8;
+ if (q == 0x40) return wallleft_quick(o, y, x);
+ return wallright_quick(o, y, x);
+}
+
+static Probe Sonic_CalcHeadroom(Obj *o, uint8_t d0) {
+ V.anglebuffer = V.anglebuffer2 = d0;
+ switch ((uint8_t)(d0 + 0x20) & 0xC0) {
+ case 0x40: return Sonic_FindWallLeft(o);
+ case 0x80: return Sonic_FindCeiling(o);
+ case 0xC0: return Sonic_FindWallRight(o);
+ default: return Sonic_FindFloor(o);
+ }
+}
+
+/* ------------------------------------------------------------------ on the ground */
+static void Sonic_SetAngle(Obj *o, int16_t *d1, int16_t d0) {
+ uint8_t a = V.anglebuffer2;
+ if (*d1 > d0) a = V.anglebuffer, *d1 = d0;
+ if (a & 1) o->angle = (uint8_t)((o->angle + 0x20) & 0xC0);
+ else o->angle = a;
+}
+
+static void off_ledge(Obj *o) {
+ o->status |= 2;
+ o->status &= (uint8_t)~0x20;
+ o->prevani = id_Run;
+}
+
+void Sonic_AnglePos(Obj *o) {
+ if (o->status & 8) {
+ V.anglebuffer = V.anglebuffer2 = 0;
+ return;
+ }
+ V.anglebuffer = V.anglebuffer2 = 3;
+ uint8_t a = o->angle, q;
+ if ((int8_t)(uint8_t)(a + 0x20) >= 0) q = (uint8_t)(((int8_t)a < 0 ? a + 1 : a) + 0x1F);
+ else q = (uint8_t)(((int8_t)a < 0 ? a - 1 : a) + 0x20);
+ q &= 0xC0;
+ int8_t h = (int8_t)o->height, w = (int8_t)o->width;
+ int16_t d1, d0;
+ if (q == 0x40) { /* walking up a wall on his left */
+ int16_t x = (int16_t)((o->x.w.i - h) ^ 0xF);
+ d0 = FindWall(o, (int16_t)(o->y.w.i - w), x, 0xD, 0x800, -0x10, &V.anglebuffer, NULL);
+ d1 = FindWall(o, (int16_t)(o->y.w.i + w), x, 0xD, 0x800, -0x10, &V.anglebuffer2, NULL);
+ Sonic_SetAngle(o, &d1, d0);
+ if (!d1) return;
+ if (d1 < 0) {
+ if (d1 >= -0xE) o->x.w.i -= d1;
+ return;
+ }
+ if (d1 > 0xE && !OB(o, sticktoconvex)) off_ledge(o);
+ else o->x.w.i -= d1;
+ return;
+ }
+ if (q == 0x80) { /* on the ceiling */
+ int16_t y = (int16_t)((o->y.w.i - h) ^ 0xF);
+ d0 = FindFloor(o, y, (int16_t)(o->x.w.i + w), 0xD, 0x1000, -0x10, &V.anglebuffer, NULL);
+ d1 = FindFloor(o, y, (int16_t)(o->x.w.i - w), 0xD, 0x1000, -0x10, &V.anglebuffer2, NULL);
+ Sonic_SetAngle(o, &d1, d0);
+ if (!d1) return;
+ if (d1 < 0) {
+ if (d1 >= -0xE) o->y.w.i -= d1;
+ return;
+ }
+ if (d1 > 0xE && !OB(o, sticktoconvex)) off_ledge(o);
+ else o->y.w.i -= d1;
+ return;
+ }
+ if (q == 0xC0) { /* up a wall on his right */
+ int16_t x = (int16_t)(o->x.w.i + h);
+ d0 = FindWall(o, (int16_t)(o->y.w.i - w), x, 0xD, 0, 0x10, &V.anglebuffer, NULL);
+ d1 = FindWall(o, (int16_t)(o->y.w.i + w), x, 0xD, 0, 0x10, &V.anglebuffer2, NULL);
+ Sonic_SetAngle(o, &d1, d0);
+ if (!d1) return;
+ if (d1 < 0) {
+ if (d1 >= -0xE) o->x.w.i += d1;
+ return;
+ }
+ if (d1 > 0xE && !OB(o, sticktoconvex)) off_ledge(o);
+ else o->x.w.i += d1;
+ return;
+ }
+ int16_t y = (int16_t)(o->y.w.i + h);
+ d0 = FindFloor(o, y, (int16_t)(o->x.w.i + w), 0xD, 0, 0x10, &V.anglebuffer, NULL);
+ d1 = FindFloor(o, y, (int16_t)(o->x.w.i - w), 0xD, 0, 0x10, &V.anglebuffer2, NULL);
+ Sonic_SetAngle(o, &d1, d0);
+ if (!d1) return;
+ if (d1 < 0) {
+ if (d1 >= -0xE) o->y.w.i += d1;
+ return;
+ }
+ if (d1 > 0xE && !OB(o, sticktoconvex)) off_ledge(o);
+ else o->y.w.i += d1;
+}
+
+/* ------------------------------------------------------------------ the modes */
+static void look_reset(void) {
+ if (V.lookshift == 0x60) return;
+ if ((uint16_t)V.lookshift < 0x60) V.lookshift += 4;
+ V.lookshift -= 2;
+}
+
+static void Sonic_WallSpeedAdjust(Obj *o) {
+ if ((int8_t)(uint8_t)(o->angle + 0x40) < 0) return;
+ if (!o->inertia) return;
+ uint8_t d1 = o->inertia < 0 ? 0x40 : 0xC0;
+ uint8_t d0 = (uint8_t)(o->angle + d1);
+ Probe p = Sonic_CalcRoomAhead(o, d0);
+ if (p.d1 >= 0) return;
+ int16_t d = (int16_t)(p.d1 << 8);
+ switch ((uint8_t)(d0 + 0x20) & 0xC0) {
+ case 0x00: o->vy += d; break;
+ case 0x40: o->vx -= d, o->status |= 0x20, o->inertia = 0; break;
+ case 0x80: o->vy -= d; break;
+ default: o->vx += d, o->status |= 0x20, o->inertia = 0; break;
+ }
+}
+
+static void Sonic_AngleSpeed(Obj *o) {
+ int16_t c, s = CalcSine(o->angle, &c);
+ o->vx = (int16_t)(((int32_t)c * o->inertia) >> 8);
+ o->vy = (int16_t)(((int32_t)s * o->inertia) >> 8);
+ Sonic_WallSpeedAdjust(o);
+}
+
+static void Sonic_MoveLeft(Obj *o, int16_t d4, int16_t d5, int16_t d6) {
+ int16_t d0 = o->inertia;
+ if (d0 > 0) {
+ uint16_t u = (uint16_t)d0;
+ d0 = u < (uint16_t)d4 ? -0x80 : (int16_t)(u - d4);
+ o->inertia = d0;
+ /* (the angle's quadrant overwrites the low byte of the speed before it is compared) */
+ uint8_t q = (uint8_t)((o->angle + 0x20) & 0xC0);
+ d0 = (int16_t)((d0 & 0xFF00) | q);
+ if (q) return;
+ if (d0 < 0x400) return;
+ o->anim = id_Stop;
+ o->status &= (uint8_t)~1;
+ return;
+ }
+ if (!(o->status & 1)) {
+ o->status |= 1;
+ o->status &= (uint8_t)~0x20;
+ o->prevani = id_Run;
+ }
+ d0 = (int16_t)(d0 - d5);
+ if (d0 <= -d6) d0 = (int16_t)-d6;
+ o->inertia = d0;
+ o->anim = id_Walk;
+}
+
+static void Sonic_MoveRight(Obj *o, int16_t d4, int16_t d5, int16_t d6) {
+ int16_t d0 = o->inertia;
+ if (d0 < 0) {
+ uint32_t s = (uint32_t)(uint16_t)d0 + (uint16_t)d4;
+ d0 = s > 0xFFFF ? 0x80 : (int16_t)s;
+ o->inertia = d0;
+ uint8_t q = (uint8_t)((o->angle + 0x20) & 0xC0);
+ d0 = (int16_t)((d0 & 0xFF00) | q);
+ if (q) return;
+ if (d0 > -0x400) return;
+ o->anim = id_Stop;
+ o->status |= 1;
+ return;
+ }
+ if (o->status & 1) {
+ o->status &= (uint8_t)~1;
+ o->status &= (uint8_t)~0x20;
+ o->prevani = id_Run;
+ }
+ d0 = (int16_t)(d0 + d5);
+ if (d0 >= d6) d0 = d6;
+ o->inertia = d0;
+ o->anim = id_Walk;
+}
+
+static void Sonic_Move(Obj *o) {
+ int16_t d6 = V.sonspeedmax, d5 = V.sonspeedacc, d4 = V.sonspeeddec;
+ if (V.f_slidemode) {
+ Sonic_AngleSpeed(o);
+ return;
+ }
+ if (!OW(o, locktime)) {
+ if (V.jpadhold2 & btnL) Sonic_MoveLeft(o, d4, d5, d6);
+ if (V.jpadhold2 & btnR) Sonic_MoveRight(o, d4, d5, d6);
+ if (((o->angle + 0x20) & 0xC0) || o->inertia) goto reset;
+ o->status &= (uint8_t)~0x20;
+ o->anim = id_Wait;
+ if (o->status & 8) {
+ Obj *a1 = &objs[OB(o, standonobject)];
+ if (a1->status & 0x80) goto lookup;
+ int16_t d1 = a1->actwid, d2 = (int16_t)(d1 * 2 - 4);
+ d1 = (int16_t)(d1 + o->x.w.i - a1->x.w.i);
+ if (d1 < 4) goto leftbalance;
+ if (d1 >= d2) goto rightbalance;
+ goto lookup;
+ }
+ if (ObjFloorDist(o, NULL) < 12) goto lookup;
+ if (OB(o, angleright) == 3) goto rightbalance;
+ if (OB(o, angleleft) != 3) goto lookup;
+ leftbalance:
+ o->status |= 1;
+ goto balance;
+ rightbalance:
+ o->status &= (uint8_t)~1;
+ balance:
+ o->anim = id_Balance;
+ goto reset;
+ lookup:
+ if (V.jpadhold2 & btnUp) {
+ o->anim = id_LookUp;
+ if (V.lookshift != 0xC8) V.lookshift += 2;
+ goto letgo;
+ }
+ if (V.jpadhold2 & btnDn) {
+ o->anim = id_Duck;
+ if (V.lookshift != 8) V.lookshift -= 2;
+ goto letgo;
+ }
+ }
+reset:
+ look_reset();
+letgo:
+ if (!(V.jpadhold2 & (btnL | btnR))) {
+ int16_t d0 = o->inertia;
+ if (d0 > 0) o->inertia = (uint16_t)d0 < (uint16_t)d5 ? 0 : (int16_t)(d0 - d5);
+ else if (d0 < 0) {
+ uint32_t s = (uint32_t)(uint16_t)d0 + (uint16_t)d5;
+ o->inertia = s > 0xFFFF ? 0 : (int16_t)s;
+ }
+ }
+ Sonic_AngleSpeed(o);
+}
+
+static void Sonic_AngledRollSpeed(Obj *o) {
+ int16_t c, s = CalcSine(o->angle, &c);
+ o->vy = (int16_t)(((int32_t)s * o->inertia) >> 8);
+ int16_t d1 = (int16_t)(((int32_t)c * o->inertia) >> 8);
+ if (d1 > 0x1000) d1 = 0x1000;
+ if (d1 < -0x1000) d1 = -0x1000;
+ o->vx = d1;
+ Sonic_WallSpeedAdjust(o);
+}
+
+static void Sonic_RollSpeed(Obj *o) {
+ int16_t d6 = (int16_t)(V.sonspeedmax << 1), d5 = (int16_t)(V.sonspeedacc >> 1), d4 = (int16_t)(V.sonspeeddec >> 2);
+ (void)d6;
+ if (V.f_slidemode) {
+ Sonic_AngledRollSpeed(o);
+ return;
+ }
+ if (!OW(o, locktime)) {
+ if (V.jpadhold2 & btnL) {
+ int16_t d0 = o->inertia;
+ if (d0 > 0) {
+ o->inertia = (uint16_t)d0 < (uint16_t)d4 ? -0x80 : (int16_t)(d0 - d4);
+ } else {
+ o->status |= 1;
+ o->anim = id_Roll;
+ }
+ }
+ if (V.jpadhold2 & btnR) {
+ int16_t d0 = o->inertia;
+ if (d0 < 0) {
+ uint32_t s = (uint32_t)(uint16_t)d0 + (uint16_t)d4;
+ o->inertia = s > 0xFFFF ? 0x80 : (int16_t)s;
+ } else {
+ o->status &= (uint8_t)~1;
+ o->anim = id_Roll;
+ }
+ }
+ }
+ int16_t d0 = o->inertia;
+ if (d0 > 0) o->inertia = (uint16_t)d0 < (uint16_t)d5 ? 0 : (int16_t)(d0 - d5);
+ else if (d0 < 0) {
+ uint32_t s = (uint32_t)(uint16_t)d0 + (uint16_t)d5;
+ o->inertia = s > 0xFFFF ? 0 : (int16_t)s;
+ }
+ if (!o->inertia) {
+ o->status &= (uint8_t)~4;
+ o->height = sonic_height, o->width = sonic_width;
+ o->anim = id_Wait;
+ o->y.w.i -= sonic_height - sonic_roll_height;
+ }
+ Sonic_AngledRollSpeed(o);
+}
+
+static void Sonic_JumpDirection(Obj *o) {
+ int16_t d6 = V.sonspeedmax, d5 = (int16_t)(V.sonspeedacc << 1);
+ if (!(o->status & 0x10)) {
+ int16_t d0 = o->vx;
+ if (V.jpadhold2 & btnL) {
+ o->status |= 1;
+ d0 = (int16_t)(d0 - d5);
+ if (d0 <= -d6) d0 = (int16_t)-d6;
+ }
+ if (V.jpadhold2 & btnR) {
+ o->status &= (uint8_t)~1;
+ d0 = (int16_t)(d0 + d5);
+ if (d0 >= d6) d0 = d6;
+ }
+ o->vx = d0;
+ }
+ look_reset();
+ /* air drag: only while going up slower than 4 pixels a frame */
+ if ((uint16_t)o->vy < (uint16_t)-0x400) return;
+ int16_t d0 = o->vx, d1 = (int16_t)(d0 >> 5);
+ if (!d1) return;
+ if (d1 > 0) o->vx = (uint16_t)d0 < (uint16_t)d1 ? 0 : (int16_t)(d0 - d1);
+ else o->vx = (uint16_t)d0 < (uint16_t)d1 ? (int16_t)(d0 - d1) : 0;
+}
+
+void KillSonic(Obj *o, Obj *killer);
+
+static void Sonic_LevelBound(Obj *o) {
+ int16_t x = (int16_t)((o->x.l + ((int32_t)o->vx << 8)) >> 16);
+ int16_t d0 = (int16_t)(V.limitleft2 + 16);
+ if ((uint16_t)d0 > (uint16_t)x) goto sides;
+ d0 = (int16_t)(V.limitright2 + 320 - 24);
+ if (!V.f_lockscreen) d0 += 64;
+ if ((uint16_t)d0 <= (uint16_t)x) goto sides;
+bottom:
+ if ((int16_t)(V.limitbtm2 + 224) < o->y.w.i) {
+ if (V.zone == id_SBZ && V.act == 1 && (uint16_t)player->x.w.i >= 0x2000) {
+ V.lastlamp = 0;
+ V.f_restart = 1;
+ V.zone = id_LZ, V.act = 3;
+ return;
+ }
+ KillSonic(o, o);
+ }
+ return;
+sides:
+ o->x.w.i = d0;
+ o->x.w.f = 0;
+ o->vx = 0;
+ o->inertia = 0;
+ goto bottom;
+}
+
+static void Sonic_ChkRoll(Obj *o) {
+ if (o->status & 4) return;
+ o->status |= 4;
+ o->height = sonic_roll_height, o->width = sonic_roll_width;
+ o->anim = id_Roll;
+ o->y.w.i += sonic_height - sonic_roll_height;
+ if (!o->inertia) o->inertia = 0x200;
+}
+
+static void Sonic_Roll(Obj *o) {
+ if (V.f_slidemode) return;
+ int16_t d0 = o->inertia < 0 ? (int16_t)-o->inertia : o->inertia;
+ if ((uint16_t)d0 < 0x80) return;
+ if (V.jpadhold2 & (btnL | btnR)) return;
+ if (V.jpadhold2 & btnDn) Sonic_ChkRoll(o);
+}
+
+/* true when he jumped: the rest of the mode is skipped (the original drops its return address) */
+static bool Sonic_Jump(Obj *o) {
+ if (!(V.jpadpress2 & btnABC)) return false;
+ Probe p = Sonic_CalcHeadroom(o, (uint8_t)(o->angle + 0x80));
+ if (p.d1 < 6) return false;
+ int16_t d2 = o->status & 0x40 ? son_jumpspeed - 0x300 : son_jumpspeed;
+ int16_t c, s = CalcSine((uint8_t)(o->angle - 0x40), &c);
+ o->vx = (int16_t)(o->vx + (((int32_t)c * d2) >> 8));
+ o->vy = (int16_t)(o->vy + (((int32_t)s * d2) >> 8));
+ o->status |= 2;
+ o->status &= (uint8_t)~0x20;
+ OB(o, jumping) = 1;
+ OB(o, sticktoconvex) = 0;
+ o->height = sonic_height, o->width = sonic_width;
+ if (o->status & 4) {
+ o->status |= 0x10;
+ return true;
+ }
+ o->height = sonic_roll_height, o->width = sonic_roll_width;
+ o->anim = id_Roll;
+ o->status |= 4;
+ o->y.w.i += sonic_height - sonic_roll_height;
+ return true;
+}
+
+static void Sonic_JumpHeight(Obj *o) {
+ if (OB(o, jumping)) {
+ int16_t d1 = o->status & 0x40 ? -0x200 : -0x400;
+ if (d1 <= o->vy) return;
+ if (V.jpadhold2 & btnABC) return;
+ o->vy = d1;
+ return;
+ }
+ if (o->vy < -0xFC0) o->vy = -0xFC0;
+}
+
+static void Sonic_SlopeResistWalk(Obj *o) {
+ if ((uint8_t)(o->angle + 0x60) >= 0xC0) return;
+ int16_t d0 = (int16_t)(((int32_t)CalcSine(o->angle, NULL) * 0x20) >> 8);
+ if (!o->inertia) return;
+ if (o->inertia < 0 || d0) o->inertia = (int16_t)(o->inertia + d0);
+}
+
+static void Sonic_SlopeResistRoll(Obj *o) {
+ if ((uint8_t)(o->angle + 0x60) >= 0xC0) return;
+ int32_t d0 = ((int32_t)CalcSine(o->angle, NULL) * 0x50) >> 8;
+ if (o->inertia >= 0) {
+ if ((int16_t)d0 < 0) d0 >>= 2;
+ } else {
+ if ((int16_t)d0 >= 0) d0 >>= 2;
+ }
+ o->inertia = (int16_t)(o->inertia + (int16_t)d0);
+}
+
+static void Sonic_SlopeRepel(Obj *o) {
+ if (OB(o, sticktoconvex)) return;
+ if (OW(o, locktime)) {
+ OW(o, locktime)--;
+ return;
+ }
+ if (!((o->angle + 0x20) & 0xC0)) return;
+ int16_t d0 = o->inertia < 0 ? (int16_t)-o->inertia : o->inertia;
+ if ((uint16_t)d0 >= 0x280) return;
+ o->inertia = 0;
+ o->status |= 2;
+ OW(o, locktime) = 30;
+}
+
+static void Sonic_JumpAngle(Obj *o) {
+ uint8_t a = o->angle;
+ if (!a) return;
+ if ((int8_t)a < 0) {
+ a = (uint8_t)(a + 2);
+ if (a < 2) a = 0; /* (carried past $FF) */
+ } else {
+ a = a >= 2 ? (uint8_t)(a - 2) : 0;
+ }
+ o->angle = a;
+}
+
+void Sonic_ResetOnFloor(Obj *o) {
+ o->status &= (uint8_t)~(0x20 | 2 | 0x10);
+ if (o->status & 4) {
+ o->status &= (uint8_t)~4;
+ o->height = sonic_height, o->width = sonic_width;
+ o->anim = id_Walk;
+ o->y.w.i -= sonic_height - sonic_roll_height;
+ }
+ OB(o, jumping) = 0;
+ V.itembonus = 0;
+}
+
+static void Sonic_Floor(Obj *o) {
+ uint8_t d0 = (uint8_t)((CalcAngle(o->vx, o->vy) - 0x20) & 0xC0);
+ Probe p;
+ if (d0 == 0x40) { /* moving left */
+ p = wallleft_quick(o, o->y.w.i, o->x.w.i);
+ if (p.d1 < 0) {
+ o->x.w.i -= p.d1, o->vx = 0, o->inertia = o->vy;
+ return;
+ }
+ p = Sonic_FindCeiling(o);
+ if (p.d1 < 0) {
+ o->y.w.i -= p.d1;
+ if (o->vy < 0) o->vy = 0;
+ return;
+ }
+ if (o->vy < 0) return;
+ p = Sonic_FindFloor(o);
+ if (p.d1 >= 0) return;
+ o->y.w.i += p.d1, o->angle = p.d3;
+ Sonic_ResetOnFloor(o);
+ o->anim = id_Walk, o->vy = 0, o->inertia = o->vx;
+ return;
+ }
+ if (d0 == 0x80) { /* moving up */
+ p = wallleft_quick(o, o->y.w.i, o->x.w.i);
+ if (p.d1 < 0) o->x.w.i -= p.d1, o->vx = 0;
+ p = wallright_quick(o, o->y.w.i, o->x.w.i);
+ if (p.d1 < 0) o->x.w.i += p.d1, o->vx = 0;
+ p = Sonic_FindCeiling(o);
+ if (p.d1 >= 0) return;
+ o->y.w.i -= p.d1;
+ if (!((p.d3 + 0x20) & 0x40)) {
+ o->vy = 0;
+ return;
+ }
+ o->angle = p.d3;
+ Sonic_ResetOnFloor(o);
+ o->inertia = o->vy;
+ if ((int8_t)p.d3 < 0) o->inertia = (int16_t)-o->inertia;
+ return;
+ }
+ if (d0 == 0xC0) { /* moving right */
+ p = wallright_quick(o, o->y.w.i, o->x.w.i);
+ if (p.d1 < 0) {
+ o->x.w.i += p.d1, o->vx = 0, o->inertia = o->vy;
+ return;
+ }
+ p = Sonic_FindCeiling(o);
+ if (p.d1 < 0) {
+ o->y.w.i -= p.d1;
+ if (o->vy < 0) o->vy = 0;
+ return;
+ }
+ if (o->vy < 0) return;
+ p = Sonic_FindFloor(o);
+ if (p.d1 >= 0) return;
+ o->y.w.i += p.d1, o->angle = p.d3;
+ Sonic_ResetOnFloor(o);
+ o->anim = id_Walk, o->vy = 0, o->inertia = o->vx;
+ return;
+ }
+ /* moving down */
+ p = wallleft_quick(o, o->y.w.i, o->x.w.i);
+ if (p.d1 < 0) o->x.w.i -= p.d1, o->vx = 0;
+ p = wallright_quick(o, o->y.w.i, o->x.w.i);
+ if (p.d1 < 0) o->x.w.i += p.d1, o->vx = 0;
+ p = Sonic_FindFloor(o);
+ if (p.d1 >= 0) return;
+ int8_t d2 = (int8_t)-(int8_t)((uint8_t)(o->vy >> 8) + 8);
+ if (!((int8_t)p.d1 >= d2) && (int8_t)p.d0 < d2) return;
+ o->y.w.i += p.d1, o->angle = p.d3;
+ Sonic_ResetOnFloor(o);
+ o->anim = id_Walk;
+ if ((uint8_t)(p.d3 + 0x20) & 0x40) { /* a steep slope */
+ o->vx = 0;
+ if (o->vy > 0xFC0) o->vy = 0xFC0;
+ } else if ((uint8_t)(p.d3 + 0x10) & 0x20) { /* a shallow slope */
+ o->vy >>= 1;
+ } else {
+ o->vy = 0, o->inertia = o->vx;
+ return;
+ }
+ o->inertia = o->vy;
+ if ((int8_t)p.d3 < 0) o->inertia = (int16_t)-o->inertia;
+}
+
+static void Sonic_MdNormal(Obj *o) {
+ if (Sonic_Jump(o)) return;
+ Sonic_SlopeResistWalk(o);
+ Sonic_Move(o);
+ Sonic_Roll(o);
+ Sonic_LevelBound(o);
+ SpeedToPos(o);
+ Sonic_AnglePos(o);
+ Sonic_SlopeRepel(o);
+}
+static void Sonic_MdJump(Obj *o) {
+ Sonic_JumpHeight(o);
+ Sonic_JumpDirection(o);
+ Sonic_LevelBound(o);
+ ObjectFall(o);
+ if (o->status & 0x40) o->vy -= 0x38 - 0x10;
+ Sonic_JumpAngle(o);
+ Sonic_Floor(o);
+}
+static void Sonic_MdRoll(Obj *o) {
+ if (Sonic_Jump(o)) return;
+ Sonic_SlopeResistRoll(o);
+ Sonic_RollSpeed(o);
+ Sonic_LevelBound(o);
+ SpeedToPos(o);
+ Sonic_AnglePos(o);
+ Sonic_SlopeRepel(o);
+}
+
+/* ------------------------------------------------------------------ power-ups, water */
+static void Sonic_Display(Obj *o) {
+ uint16_t t = OUW(o, flashtime);
+ if (t) {
+ OUW(o, flashtime)--;
+ if (t & 4) DisplaySprite(o);
+ } else DisplaySprite(o);
+ if (V.invinc && OUW(o, invtime)) {
+ if (!--OUW(o, invtime)) V.invinc = 0;
+ }
+ if (V.shoes && OUW(o, shoetime)) {
+ if (!--OUW(o, shoetime)) {
+ V.sonspeedmax = son_maxspeed, V.sonspeedacc = son_acceleration, V.sonspeeddec = son_deceleration;
+ V.shoes = 0;
+ }
+ }
+}
+
+static void Sonic_RecordPosition(Obj *o) {
+ int i = (V.trackpos & 0xFF) >> 2;
+ tracksonic[i][0] = (uint16_t)o->x.w.i;
+ tracksonic[i][1] = (uint16_t)o->y.w.i;
+ V.trackpos = (uint16_t)((V.trackpos & 0xFF00) | (uint8_t)(V.trackpos + 4));
+}
+
+static void Sonic_Water(Obj *o) {
+ if (V.zone != id_LZ) return;
+ if (V.waterpos1 >= o->y.w.i) {
+ if (!(o->status & 0x40)) return;
+ o->status &= (uint8_t)~0x40;
+ ResumeMusic();
+ V.sonspeedmax = son_maxspeed, V.sonspeedacc = son_acceleration, V.sonspeeddec = son_deceleration;
+ o->vy = (int16_t)(o->vy << 1);
+ if (!o->vy) return;
+ OBJ(12)->id = id_Splash;
+ if (o->vy <= -0x1000) o->vy = -0x1000;
+ return;
+ }
+ if (o->status & 0x40) return;
+ o->status |= 0x40;
+ ResumeMusic();
+ OBJ(13)->id = id_DrownCount;
+ obSubtype(OBJ(13)) = 0x81;
+ V.sonspeedmax = son_maxspeed / 2, V.sonspeedacc = son_acceleration / 2, V.sonspeeddec = son_deceleration / 2;
+ o->vx >>= 1;
+ o->vy >>= 2;
+ if (!o->vy) return;
+ OBJ(12)->id = id_Splash;
+}
+
+/* ------------------------------------------------------------------ loops */
+static void Sonic_Loops(Obj *o) {
+ if (V.zone != id_SLZ && V.zone != id_GHZ) return;
+ uint8_t c = (&lvllayout[0][0][0])[(((uint16_t)o->y.w.i >> 1) & 0x380) + ((uint8_t)(o->x.w.i >> 8) & 0x7F)];
+ if (c == V.loop256[2] || c == V.loop256[3]) {
+ Sonic_ChkRoll(o);
+ return;
+ }
+ if (c == V.loop256[0]) goto chkifleft;
+ if (c == V.loop256[1]) {
+ if (!(o->status & 2)) goto chkifleft;
+ o->render &= (uint8_t)~0x40;
+ return;
+ }
+ o->render &= (uint8_t)~0x40;
+ return;
+chkifleft: {
+ uint8_t x = (uint8_t)o->x.w.i;
+ if (x < 44) {
+ o->render &= (uint8_t)~0x40;
+ return;
+ }
+ if (x >= 224) {
+ o->render |= 0x40;
+ return;
+ }
+ if (!(o->render & 0x40)) {
+ if (!o->angle || o->angle > 0x80) return;
+ o->render |= 0x40;
+ return;
+ }
+ if (o->angle <= 0x80) return;
+ o->render &= (uint8_t)~0x40;
+}
+}
+
+/* ------------------------------------------------------------------ animation */
+static void Sonic_Animate(Obj *o) {
+ const uint8_t *tab = ani_get(ANI_Sonic);
+ uint8_t a = o->anim;
+ if (a != o->prevani) o->prevani = a, o->aniframe = 0, o->timeframe = 0;
+ const uint8_t *s = tab + ((const uint16_t *)(const void *)tab)[1 + a];
+ int8_t interval = (int8_t)s[0];
+ uint8_t d3 = 0;
+ bool add = false;
+ if (interval >= 0) {
+ o->render = (uint8_t)((o->render & ~3) | (o->status & 1));
+ if ((int8_t)--o->timeframe >= 0) return;
+ o->timeframe = (uint8_t)interval;
+ goto loadframe;
+ }
+ if ((int8_t)--o->timeframe >= 0) return;
+ if (interval == -1) { /* walking or running */
+ uint8_t d1 = 0, d0 = o->angle, d2 = o->status & 1;
+ if (!d2) d0 = (uint8_t)~d0;
+ d0 = (uint8_t)(d0 + 0x10);
+ if ((int8_t)d0 < 0) d1 = 3;
+ o->render = (uint8_t)((o->render & ~3) | (d2 ^ d1));
+ if (o->status & 0x20) goto push;
+ d0 = (uint8_t)((d0 >> 4) & 6);
+ int16_t sp = o->inertia < 0 ? (int16_t)-o->inertia : o->inertia;
+ if ((uint16_t)sp >= 0x600) s = tab + ((const uint16_t *)(const void *)tab)[1 + id_Run];
+ else {
+ s = tab + ((const uint16_t *)(const void *)tab)[1 + id_Walk];
+ d0 = (uint8_t)(d0 + (d0 >> 1));
+ }
+ d0 = (uint8_t)(d0 + d0);
+ d3 = d0;
+ int16_t t = (int16_t)(-sp + 0x800);
+ if (t < 0) t = 0;
+ o->timeframe = (uint8_t)((uint16_t)t >> 8);
+ add = true;
+ goto loadframe;
+ }
+ if (interval == -2) { /* rolling */
+ int16_t sp = o->inertia < 0 ? (int16_t)-o->inertia : o->inertia;
+ s = tab + ((const uint16_t *)(const void *)tab)[1 + ((uint16_t)sp >= 0x600 ? id_Roll2 : id_Roll)];
+ int16_t t = (int16_t)(-sp + 0x400);
+ if (t < 0) t = 0;
+ o->timeframe = (uint8_t)((uint16_t)t >> 8);
+ o->render = (uint8_t)((o->render & ~3) | (o->status & 1));
+ goto loadframe;
+ }
+push: {
+ int16_t sp = o->inertia;
+ if (sp >= 0) sp = (int16_t)-sp;
+ int16_t t = (int16_t)(sp + 0x800);
+ if (t < 0) t = 0;
+ o->timeframe = (uint8_t)((uint16_t)t >> 6);
+ s = tab + ((const uint16_t *)(const void *)tab)[1 + id_Push];
+ o->render = (uint8_t)((o->render & ~3) | (o->status & 1));
+}
+loadframe: {
+ uint8_t i = o->aniframe, f = s[1 + i];
+ if (f & 0x80) {
+ if (f == 0xFF) o->aniframe = 0, f = s[1];
+ else if (f == 0xFE) {
+ uint8_t back = s[2 + i];
+ o->aniframe = (uint8_t)(o->aniframe - back);
+ f = s[1 + (uint8_t)(i - back)];
+ } else {
+ if (f == 0xFD) o->anim = s[2 + i];
+ return;
+ }
+ }
+ o->frame = f;
+ o->aniframe++;
+ if (add) o->frame = (uint8_t)(o->frame + d3);
+}
+}
+
+/* his art for the frame: the pattern load cues, applied to video memory at VBlank */
+static uint16_t gfx_list[23];
+static int gfx_n;
+void sonic_dplc_apply(void) {
+ const uint8_t *art = (const uint8_t *)DATA(D_TILES) + (uint32_t)DATAW(D_ARTS)[ART_Art_Sonic * 2] * 32;
+ for (int i = 0; i < gfx_n; i++) vram[0x780 + i] = art + (uint32_t)gfx_list[i] * 32;
+}
+
+void Sonic_LoadGfx(Obj *o) {
+ uint8_t f = o->frame;
+ if (f == V.sonframenum) return;
+ V.sonframenum = f;
+ const uint8_t *d = DATA(D_SONICDPLC);
+ const uint8_t *e = d + ((const uint16_t *)(const void *)d)[1 + f];
+ int n = e[0];
+ if (!n) return;
+ V.f_sonframechg = 1;
+ gfx_n = 0;
+ const uint16_t *w = (const uint16_t *)(const void *)(e + 2);
+ for (int i = 0; i < n; i++) {
+ uint16_t t = w[i] & 0x0FFF, c = (uint16_t)((w[i] >> 12) + 1);
+ for (int k = 0; k < c && gfx_n < 23; k++) gfx_list[gfx_n++] = (uint16_t)(t + k);
+ }
+}
+
+/* ------------------------------------------------------------------ hurt and death */
+static void Sonic_HurtStop(Obj *o) {
+ if ((uint16_t)(V.limitbtm2 + 224) < (uint16_t)o->y.w.i) {
+ KillSonic(o, o);
+ return;
+ }
+ Sonic_Floor(o);
+ if (o->status & 2) return;
+ o->vy = o->vx = o->inertia = 0;
+ o->anim = id_Walk;
+ o->routine -= 2;
+ OW(o, flashtime) = 2 * 60;
+}
+
+static void Sonic_Hurt(Obj *o) {
+ SpeedToPos(o);
+ o->vy += 0x38 - 8;
+ if (o->status & 0x40) o->vy -= 0x38 - 0x18;
+ Sonic_HurtStop(o);
+ Sonic_LevelBound(o);
+ Sonic_RecordPosition(o);
+ Sonic_Animate(o);
+ Sonic_LoadGfx(o);
+ DisplaySprite(o);
+}
+
+static void Sonic_HandleDeath(Obj *o) {
+ if ((uint16_t)(V.limitbtm2 + 0x100) >= (uint16_t)o->y.w.i) return;
+ o->vy = -0x38;
+ o->routine += 2;
+ V.f_timecount = 0;
+ V.f_lifecount++;
+ if (--V.lives) {
+ OW(o, restartime) = 60;
+ if (!V.f_timeover) return;
+ OW(o, restartime) = 0;
+ OBJ(2)->id = OBJ(3)->id = id_GameOverCard;
+ OBJ(2)->frame = 2, OBJ(3)->frame = 3;
+ } else {
+ OW(o, restartime) = 0;
+ OBJ(2)->id = OBJ(3)->id = id_GameOverCard;
+ OBJ(3)->frame = 1;
+ V.f_timeover = 0;
+ }
+ AddPLC(plcid_GameOver);
+}
+
+static void Sonic_Death(Obj *o) {
+ Sonic_HandleDeath(o);
+ ObjectFall(o);
+ Sonic_RecordPosition(o);
+ Sonic_Animate(o);
+ Sonic_LoadGfx(o);
+ DisplaySprite(o);
+}
+
+static void Sonic_ResetLevel(Obj *o) {
+ if (!OW(o, restartime)) return;
+ if (--OW(o, restartime)) return;
+ V.f_restart = 1;
+}
+
+/* ------------------------------------------------------------------ the object */
+void SonicPlayer(Obj *o) {
+ if (V.debuguse) {
+ DebugMode(o);
+ return;
+ }
+ switch (o->routine) {
+ case 0:
+ o->routine = 2;
+ o->height = sonic_height, o->width = sonic_width;
+ o->map = map_get(MAP_Sonic);
+ o->gfx = ArtTile_Sonic;
+ o->priority = 2;
+ o->actwid = 24;
+ o->render = 4;
+ V.sonspeedmax = son_maxspeed, V.sonspeedacc = son_acceleration, V.sonspeeddec = son_deceleration;
+ /* fall through */
+ case 2:
+ if (V.f_debugmode && (V.jpadpress1 & btnB)) {
+ V.debuguse = 1;
+ V.f_lockctrl = 0;
+ return;
+ }
+ if (!V.f_lockctrl) V.jpadhold2 = V.jpadhold1, V.jpadpress2 = V.jpadpress1;
+ if (!(V.f_playerctrl & 1)) {
+ switch (o->status & 6) {
+ case 0: Sonic_MdNormal(o); break;
+ case 2: Sonic_MdJump(o); break;
+ case 4: Sonic_MdRoll(o); break;
+ default: Sonic_MdJump(o); break;
+ }
+ }
+ Sonic_Display(o);
+ Sonic_RecordPosition(o);
+ Sonic_Water(o);
+ OB(o, angleright) = V.anglebuffer;
+ OB(o, angleleft) = V.anglebuffer2;
+ if (V.f_wtunnelmode && !o->anim) o->anim = o->prevani;
+ Sonic_Animate(o);
+ if (!(V.f_playerctrl & 0x80)) ReactToItem(o);
+ Sonic_Loops(o);
+ Sonic_LoadGfx(o);
+ break;
+ case 4: Sonic_Hurt(o); break;
+ case 6: Sonic_Death(o); break;
+ case 8: Sonic_ResetLevel(o); break;
+ }
+}
diff --git a/games/sonic/src/stubs.c b/games/sonic/src/stubs.c
new file mode 100644
index 00000000..4439d4f5
--- /dev/null
+++ b/games/sonic/src/stubs.c
@@ -0,0 +1,30 @@
+/* (being written) */
+#include "s1.h"
+#include "game.h"
+
+void DebugMode(Obj *o) { (void)o; }
+void ResumeMusic(void) { V.air = 30; }
+void HUD_Update(void) {}
+void Hud_Base(void) {}
+void AnimateLevelGfx(void) {}
+void LZWaterFeatures(void) {}
+void PalCycle_SS(void) {}
+void Lamp_LoadInfo(void) {}
+void pause_overlay_draw(void) {}
+void PauseGame(void) {}
+void save_restore_copy(void) {}
+void game_save_on_quit(void) {}
+extern int host_level, host_act, host_lives;
+void game_init(void) {
+ V.gamemode = id_Level;
+ V.lives = 3;
+#ifdef HOST
+ if (host_level >= 0) V.zone = (uint8_t)host_level, V.act = (uint8_t)host_act;
+#endif
+}
+void GM_Sega(void) {}
+void GM_Title(void) {}
+void GM_Special(void) {}
+void GM_Continue(void) {}
+void GM_Ending(void) {}
+void GM_Credits(void) {}
diff --git a/games/sonic/src/vdp.c b/games/sonic/src/vdp.c
new file mode 100644
index 00000000..671b2062
--- /dev/null
+++ b/games/sonic/src/vdp.c
@@ -0,0 +1,151 @@
+/* The Mega Drive's video chip, as far as the game uses it: 2048 tiles of patterns (here each one
+ * points at its pattern in data.bin, so loading art costs no memory), two 64x32 planes of tile words
+ * scrolled by a table of a scroll a line, 80 sprites from the sprite table, 64 colours, and the
+ * water palette from a line on (the horizontal interrupt the original uses in Labyrinth Zone).
+ *
+ * vdp_render() draws the 320x224 picture line by line: plane B, plane A over it, then the sprites
+ * line, each pixel keeping the front one by the chip's rules (a high-priority tile over a low one,
+ * sprites over the planes of their priority, the first sprite in the list in front of the others);
+ * then the colours, 16 lines at a time to the screen, 8 lines below its top. */
+#include "s1.h"
+#include "plat.h"
+
+const uint8_t *vram[2048];
+uint16_t plane_a[32][64], plane_b[32][64];
+uint16_t cram[64];
+Sprite spritetable[80];
+uint8_t vdp_backdrop = 0x20;
+int16_t vdp_vscroll_a, vdp_vscroll_b;
+bool vdp_line_scroll = true;
+int vdp_hint_line = -1;
+bool vdp_display = true;
+
+static const uint8_t blank_pattern[32];
+#define PATTERNS ((const uint8_t *)DATA(D_TILES))
+#define ARTS DATAW(D_ARTS)
+
+void vdp_load_art_part(int art, int first, int count, int tile) {
+ const uint8_t *p = PATTERNS + (uint32_t)(ARTS[art * 2] + first) * 32;
+ for (int i = 0; i < count && tile + i < 2048; i++) vram[tile + i] = p + i * 32;
+}
+void vdp_load_art(int art, int tile) { vdp_load_art_part(art, 0, ARTS[art * 2 + 1], tile); }
+
+void vdp_clear_planes(void) {
+ memset(plane_a, 0, sizeof plane_a);
+ memset(plane_b, 0, sizeof plane_b);
+ for (int i = 0; i < 2048; i++)
+ if (!vram[i]) vram[i] = blank_pattern;
+}
+
+/* a rectangle of tile words into a plane, each plus add */
+void vdp_fill_plane(uint16_t (*plane)[64], int col, int row, int w, int h, const uint16_t *words, uint16_t add) {
+ for (int r = 0; r < h; r++)
+ for (int c = 0; c < w; c++) plane[(row + r) & 31][(col + c) & 63] = (uint16_t)(words[r * w + c] + add);
+}
+
+/* ------------------------------------------------------------------ the picture */
+/* the levels the Mega Drive's colour converter puts out for each of its 8 steps */
+static const uint8_t level[8] = {0, 52, 87, 116, 144, 172, 206, 255};
+static uint16_t rgb(uint16_t c) {
+ uint8_t r = level[(c >> 1) & 7], g = level[(c >> 5) & 7], b = level[(c >> 9) & 7];
+ return (uint16_t)((r >> 3) << 11 | (g >> 2) << 5 | b >> 3);
+}
+
+extern uint16_t vdp_water_cram[64];
+uint16_t vdp_water_cram[64];
+static uint16_t lut[64], lut_water[64];
+static uint8_t line[8 + 320 + 8], sline[320 + 64];
+static uint16_t band[16 * 320];
+
+/* one line of a plane: its opaque pixels as palette line, colour and priority (bit 7); over: on top of
+ what is there, but not over a high-priority pixel with a low-priority one */
+static void plane_line(uint8_t *out, uint16_t (*plane)[64], int hs, int ys, bool over) {
+ int px = -hs & 511;
+ const uint16_t *nt = plane[(ys >> 3) & 31];
+ int fy = ys & 7, col = px >> 3;
+ for (int x = -(px & 7); x < 320; x += 8, col = (col + 1) & 63) {
+ uint16_t w = nt[col];
+ const uint8_t *p = vram[w & 0x7FF] + ((w & 0x1000) ? 7 - fy : fy) * 4;
+ uint32_t bits = (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3];
+ if (!bits) continue;
+ uint8_t add = (uint8_t)((w >> 9 & 0x30) | (w >> 8 & 0x80)), hi = w & 0x8000 ? 1 : 0;
+ uint8_t *o = out + x;
+ for (int i = 0; i < 8; i++) {
+ int c = w & 0x800 ? bits >> (i * 4) & 15 : bits >> (28 - i * 4) & 15;
+ if (c && (!over || hi || !(o[i] & 0x80))) o[i] = (uint8_t)(add | c);
+ }
+ }
+}
+
+/* the sprites of the list, in list order */
+static struct {
+ int16_t x, y, w, h;
+ uint16_t tile;
+} spr[80];
+static int nspr;
+
+static void collect_sprites(void) {
+ nspr = 0;
+ for (int i = 0, n = 0; n < 80; n++) {
+ const Sprite *s = &spritetable[i];
+ spr[nspr].x = (int16_t)((s->x & 0x1FF) - 128);
+ spr[nspr].y = (int16_t)((s->y & 0x3FF) - 128);
+ spr[nspr].w = (int16_t)(((s->size >> 2) & 3) + 1);
+ spr[nspr].h = (int16_t)((s->size & 3) + 1);
+ spr[nspr].tile = s->tile;
+ nspr++;
+ if (!s->link || s->link >= 80) break;
+ i = s->link;
+ }
+}
+
+static void sprite_line(int y) {
+ memset(sline, 0, sizeof sline);
+ for (int i = 0; i < nspr; i++) {
+ int dy = y - spr[i].y, hc = spr[i].h, wc = spr[i].w;
+ if (dy < 0 || dy >= hc * 8) continue;
+ int x0 = spr[i].x;
+ if (x0 >= 320 || x0 + wc * 8 <= 0) continue;
+ uint16_t t = spr[i].tile;
+ int row = t & 0x1000 ? hc * 8 - 1 - dy : dy;
+ uint8_t add = (uint8_t)((t >> 9 & 0x30) | (t >> 8 & 0x80));
+ for (int c = 0; c < wc; c++) {
+ int tc = t & 0x800 ? wc - 1 - c : c;
+ const uint8_t *p = vram[((t & 0x7FF) + tc * hc + (row >> 3)) & 0x7FF] + (row & 7) * 4;
+ uint32_t bits = (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3];
+ if (!bits) continue;
+ int xs = x0 + c * 8;
+ for (int k = 0; k < 8; k++) {
+ int x = xs + k;
+ if ((unsigned)x >= 320 || sline[x]) continue;
+ int v = t & 0x800 ? bits >> (k * 4) & 15 : bits >> (28 - k * 4) & 15;
+ if (v) sline[x] = (uint8_t)(add | v);
+ }
+ }
+ }
+}
+
+void vdp_render(void) {
+ for (int i = 0; i < 64; i++) lut[i] = rgb(cram[i]), lut_water[i] = rgb(vdp_water_cram[i]);
+ collect_sprites();
+ uint8_t *out = line + 8;
+ for (int y = 0; y < 224; y++) {
+ uint16_t *dst = band + (y & 15) * 320;
+ if (!vdp_display) {
+ for (int x = 0; x < 320; x++) dst[x] = 0;
+ } else {
+ memset(line, 0, sizeof line);
+ plane_line(out, plane_b, hscroll[y].bg, vdp_vscroll_b + y, false);
+ plane_line(out, plane_a, hscroll[y].fg, vdp_vscroll_a + y, true);
+ sprite_line(y);
+ for (int x = 0; x < 320; x++) {
+ uint8_t s = sline[x];
+ if (s && ((s & 0x80) || !(out[x] & 0x80))) out[x] = s;
+ }
+ const uint16_t *l = vdp_hint_line >= 0 && y > vdp_hint_line ? lut_water : lut;
+ uint16_t back = l[vdp_backdrop & 63];
+ for (int x = 0; x < 320; x++) dst[x] = out[x] ? l[out[x] & 63] : back;
+ }
+ if ((y & 15) == 15) plat_push(0, 8 + y - 15, 320, 16, band);
+ }
+}
diff --git a/games/sonic/tests/play.c b/games/sonic/tests/play.c
new file mode 100644
index 00000000..1291ce81
--- /dev/null
+++ b/games/sonic/tests/play.c
@@ -0,0 +1,110 @@
+/* Plays Sonic the Hedgehog on a computer, with scripted keys, and saves frames.
+ *
+ * play [--frames N] [--keys "10-40:right,50:a,..."] [--shots 30,60|all|every:N] [--out DIR]
+ * [--saves DIR] [--level Z.A] [--lives N] [--trace]
+ *
+ * Keys: up down left right a b c start home. "a-b:key" holds the key from frame a to b, "a:key" for one
+ * frame. --level starts the act straight away (zone 0-6, act 0-3), past the SEGA and title screens.
+ * Screenshots are DIR/shot_<frame>.ppm; --trace prints Sonic's position and state every frame. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include "../src/game.h"
+#include "../src/plat.h"
+#include "../src/s1.h"
+
+extern uint32_t host_keys, host_time;
+void host_shot(const char *path);
+void host_save_dir(const char *d);
+int game_main(void);
+
+typedef struct {
+ int a, b;
+ uint32_t k;
+} Hold;
+static Hold holds[4096];
+static int nholds;
+static int frames = 600, frame, every, trace;
+static char out_dir[256] = "build/shots";
+static bool shot_all;
+static int shots[1024], nshots;
+int host_level = -1, host_act, host_lives = -1;
+
+static uint32_t key_bit(const char *k) {
+ static const struct {
+ const char *n;
+ uint32_t b;
+ } t[] = {{"up", K_UP}, {"down", K_DOWN}, {"left", K_LEFT}, {"right", K_RIGHT}, {"a", K_A}, {"b", K_B},
+ {"c", K_C}, {"start", K_START}, {"home", K_HOME}};
+ for (unsigned i = 0; i < sizeof t / sizeof t[0]; i++)
+ if (!strcmp(k, t[i].n)) return t[i].b;
+ fprintf(stderr, "unknown key %s\n", k);
+ exit(2);
+}
+
+static void parse_keys(char *s) {
+ for (char *tok = strtok(s, ","); tok; tok = strtok(NULL, ",")) {
+ char *c = strchr(tok, ':');
+ if (!c) continue;
+ *c = 0;
+ int a = atoi(tok), b = a;
+ char *d = strchr(tok, '-');
+ if (d) b = atoi(d + 1);
+ holds[nholds].a = a, holds[nholds].b = b, holds[nholds].k = key_bit(c + 1);
+ nholds++;
+ }
+}
+
+/* called by WaitForVBlank each frame, after the picture */
+void host_frame(void) {
+ frame++;
+ bool take = shot_all || (every && frame % every == 0);
+ for (int i = 0; i < nshots; i++) take |= shots[i] == frame;
+ if (take) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/shot_%05d.ppm", out_dir, frame);
+ host_shot(p);
+ }
+ if (trace)
+ printf("f%d mode %02x zone %d.%d sonic %d,%d r%d st%02x an%02x v%d,%d in%d rings %d lives %d cam %d,%d\n", frame,
+ V.gamemode, V.zone, V.act, player->x.w.i, player->y.w.i, player->routine, player->status, player->angle,
+ player->vx, player->vy, player->inertia, V.rings, V.lives, V.cam[0].x.w.i, V.cam[0].y.w.i);
+ host_keys = 0;
+ for (int i = 0; i < nholds; i++)
+ if (frame + 1 >= holds[i].a && frame + 1 <= holds[i].b) host_keys |= holds[i].k;
+ if (host_keys) host_keys |= K_ANY;
+ if (frame >= frames) host_keys |= K_HOME;
+}
+
+int main(int argc, char **argv) {
+ char saves[256] = "build/host-saves";
+ for (int i = 1; i < argc; i++) {
+ if (!strcmp(argv[i], "--frames") && i + 1 < argc) frames = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--keys") && i + 1 < argc) parse_keys(argv[++i]);
+ else if (!strcmp(argv[i], "--out") && i + 1 < argc) snprintf(out_dir, sizeof out_dir, "%s", argv[++i]);
+ else if (!strcmp(argv[i], "--saves") && i + 1 < argc) snprintf(saves, sizeof saves, "%s", argv[++i]);
+ else if (!strcmp(argv[i], "--trace")) trace = 1;
+ else if (!strcmp(argv[i], "--lives") && i + 1 < argc) host_lives = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--level") && i + 1 < argc) {
+ char *s = argv[++i];
+ host_level = atoi(s);
+ char *d = strchr(s, '.');
+ host_act = d ? atoi(d + 1) : 0;
+ } else if (!strcmp(argv[i], "--shots") && i + 1 < argc) {
+ char *s = argv[++i];
+ if (!strcmp(s, "all")) shot_all = true;
+ else if (!strncmp(s, "every:", 6)) every = atoi(s + 6);
+ else
+ for (char *t = strtok(s, ","); t && nshots < 1024; t = strtok(NULL, ",")) shots[nshots++] = atoi(t);
+ }
+ }
+ mkdir("build", 0755);
+ mkdir(out_dir, 0755);
+ mkdir(saves, 0755);
+ host_save_dir(saves);
+ int r = game_main();
+ printf("frames %d, mode %02x, zone %d.%d, rings %d, lives %d, score %u\n", frame, V.gamemode, V.zone, V.act, V.rings,
+ V.lives, (unsigned)V.score * 10);
+ return r;
+}
diff --git a/games/sonic/tools/pack.py b/games/sonic/tools/pack.py
new file mode 100644
index 00000000..491013ca
--- /dev/null
+++ b/games/sonic/tools/pack.py
@@ -0,0 +1,510 @@
+#!/usr/bin/env python3
+"""Packs what the game reads from the Sonic Retro disassembly (REF, see fetch.py) into
+src/data.bin, with src/data.h naming what is where and src/s1const.h the disassembly's numbers.
+
+ python3 -I tools/pack.py REF
+
+Everything is decompressed here, once, so the calculator reads it in place from flash:
+- the patterns of every piece of art (Nemesis, Kosinski and uncompressed), 32 bytes each, one pool;
+- sprite mappings, animation scripts and Sonic's pattern load cues, as the game keeps them, little-endian;
+- each zone's 16x16 blocks, 256x256 chunks and collision index, the angle map and height arrays;
+- the act layouts, object placement, start positions, palettes and palette cycles;
+- the special stage layouts, the tile maps of the title screen, the SEGA logo and the special stages;
+- the demos' button presses.
+"""
+import os
+import re
+import struct
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import s1 # noqa: E402
+
+REF = sys.argv[1] if len(sys.argv) > 1 else "build/ref/s1disasm"
+OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src")
+
+
+def rd(p):
+ return open(os.path.join(REF, p), "rb").read()
+
+
+def asm_lines(p):
+ return [s1.strip(l) for l in open(os.path.join(REF, p), encoding="latin1")]
+
+
+def ident(name):
+ return re.sub(r"[^A-Za-z0-9]+", "_", name).strip("_")
+
+
+# ---------------------------------------------------------------- symbols
+
+def all_asm():
+ out = []
+ for d, _, fs in os.walk(REF):
+ if "build_tools" in d or "sound" in d:
+ continue
+ out += [os.path.join(d, f) for f in fs if f.endswith(".asm")]
+ return sorted(out)
+
+
+SYM = {"Revision": 1, "FixBugs": 0}
+pending = []
+for path in all_asm():
+ for line in open(path, encoding="latin1"):
+ m = re.match(r"^\s*([A-Za-z_][A-Za-z_0-9]*):?\s+(?:=|equ)\s+(.+)$", s1.strip(line))
+ if m:
+ pending.append((m.group(1), m.group(2).strip()))
+for _ in range(6):
+ left = []
+ for n, e in pending:
+ if n in SYM:
+ continue
+ try:
+ SYM[n] = s1.number(e, SYM)
+ except Exception:
+ left.append((n, e))
+ pending = left
+
+# object ids: their order in the object pointer table
+OBJ = []
+skip = False
+for l in asm_lines("_inc/Object Pointers.asm"):
+ if re.match(r"^\s*if\s+UnusedOptimization", l):
+ skip = True
+ continue
+ if re.match(r"^\s*else\b", l):
+ skip = not skip
+ continue
+ if re.match(r"^\s*endif\b", l):
+ skip = False
+ continue
+ m = re.match(r"^(id_\w+):\s+objptr\s+(\w+)", l)
+ if m and not skip:
+ OBJ.append((m.group(1), m.group(2)))
+for i, (n, _) in enumerate(OBJ, 1):
+ SYM.setdefault(n, i)
+
+# label -> file, from the binary includes
+FILES = {}
+for path in [os.path.join(REF, "sonic.asm")] + [p for p in all_asm() if "_inc" in p]:
+ rev = None
+ for line in open(path, encoding="latin1"):
+ l = s1.strip(line)
+ if re.match(r"^\s*if\s+Revision\s*=\s*0", l):
+ rev = 0
+ elif re.match(r"^\s*if\s+\(Revision=0\)", l):
+ rev = 0
+ elif re.match(r"^\s*else\b", l) and rev == 0:
+ rev = 1
+ elif re.match(r"^\s*endif\b", l):
+ rev = None
+ m = re.match(r'^([A-Za-z_]\w*):\s*binclude(?:EndMarker)?\s+"([^"]+)"', l)
+ if m and rev != 0:
+ FILES[m.group(1)] = m.group(2)
+# (labels before a REV00/REV01 choice)
+FILES["Nem_SegaLogo"] = "artnem/Sega Logo (REV01).nem"
+FILES["Eni_SegaLogo"] = "tilemaps/Sega Logo (REV01).eni"
+FILES["Blk256_MZ"] = "map256/MZ (REV01).kos"
+FILES["Blk256_SBZ"] = "map256/SBZ (REV01).kos"
+FILES["SS_5"] = "sslayout/5 (REV01).eni"
+FILES["SS_6"] = "sslayout/6 (REV01).eni"
+
+# ---------------------------------------------------------------- the blob
+
+blob = bytearray()
+defs = [] # (name, value) for data.h
+
+
+def align(n=4):
+ while len(blob) % n:
+ blob.append(0)
+
+
+def put(name, data, a=4):
+ align(a)
+ defs.append((name, len(blob)))
+ blob.extend(data)
+ return len(blob) - len(data)
+
+
+# --- art: one pool of patterns
+pool = bytearray()
+ART = [] # (name, first, count)
+
+
+def add_art(name, tiles):
+ first = len(pool) // 32
+ pool.extend(tiles)
+ ART.append((name, first, len(tiles) // 32))
+
+
+for label in sorted(FILES):
+ f = FILES[label]
+ if label.startswith("Nem_") and f.endswith(".nem"):
+ add_art(label, s1.nemesis(rd(f)))
+ elif label.startswith("Art_") and f.endswith(".unc"):
+ add_art(label, rd(f))
+add_art("Kos_EndFlowers", s1.kosinski(rd("artkos/Flowers at Ending.kos")))
+put("D_TILES", pool)
+t = bytearray()
+for _, first, count in ART:
+ t += struct.pack("<HH", first, count)
+put("D_ARTS", t)
+
+# --- mappings: every table of every mappings file
+
+def map_tables(path):
+ """{table label: frames} of a mappings file (local labels are scoped to their table)."""
+ tables, cur, entries, frames, piece_of = {}, None, [], {}, None
+
+ def close():
+ if cur:
+ tables[cur] = [frames.get(e, []) for e in entries]
+
+ for l in asm_lines(path):
+ m = re.match(r"^([A-Za-z_][\w.]*):\s*mappingsTable\b", l)
+ if m:
+ close()
+ cur, entries, frames = re.sub(r"[_.]internal$", "", m.group(1)), [], {}
+ continue
+ m = re.match(r"^\s*mappingsTableEntry\.w\s+(\S+)", l)
+ if m:
+ entries.append(m.group(1))
+ continue
+ m = re.match(r"^([.A-Za-z_]\w*):?\s+spriteHeader\b", l)
+ if m:
+ piece_of = m.group(1)
+ frames[piece_of] = []
+ continue
+ m = re.match(r"^\s*spritePiece\s+(.*)$", l)
+ if m and piece_of:
+ x, y, w, h, tile, xf, yf, pal, pri = [s1.number(v, SYM) for v in m.group(1).split(",")]
+ word = ((pri & 1) << 15 | (pal & 3) << 13 | (yf & 1) << 12 | (xf & 1) << 11) + tile
+ frames[piece_of].append((x, y, ((w - 1) & 3) << 2 | ((h - 1) & 3), word & 0xFFFF))
+ close()
+ return tables
+
+
+MAPS = []
+for f in sorted(os.listdir(os.path.join(REF, "_maps"))):
+ if not f.endswith(".asm") or f.startswith("_") or "Dynamic Gfx" in f or "REV00" in f:
+ continue
+ for label, frames in map_tables(os.path.join("_maps", f)).items():
+ b = bytearray(struct.pack("<H", len(frames)))
+ offs, body = [], bytearray()
+ start = 2 + 2 * len(frames)
+ for fr in frames:
+ offs.append(start + len(body))
+ body += struct.pack("<BB", len(fr), 0)
+ for x, y, size, word in fr:
+ body += struct.pack("<bBHbb", y, size, word, x, 0)
+ for o in offs:
+ b += struct.pack("<H", o)
+ MAPS.append((label, bytes(b + body)))
+
+# --- animations: the scripts as the game keeps them
+
+
+def anim_tables(path):
+ tables, cur, entries, scripts, sc = {}, None, [], {}, None
+
+ def close():
+ if cur:
+ tables[cur] = [scripts[e] for e in entries]
+
+ for l in asm_lines(path):
+ m = re.match(r"^([A-Za-z_]\w*):\s*dc\.w\s+(\S+)-(\S+)", l)
+ if m:
+ close()
+ cur, entries, scripts, sc = None, [], {}, None
+ if m.group(1).startswith("Ani_"):
+ cur, entries = m.group(1), [m.group(2)]
+ continue
+ m = re.match(r"^(Ani_\w+):\s*$", l)
+ if m:
+ close()
+ cur, entries, scripts, sc = m.group(1), [], {}, None
+ continue
+ m = re.match(r"^(\w+):\s+sonani\s+(\w+)", l)
+ if m and cur:
+ SYM[m.group(1)] = len(entries)
+ entries.append(m.group(2))
+ continue
+ if re.match(r"^[A-Za-z_]\w*:", l) and not re.match(r"^[A-Za-z_]\w*:\s*dc\.b", l):
+ close()
+ cur, entries, scripts, sc = None, [], {}, None
+ continue
+ m = re.match(r"^\s*dc\.w\s+(\S+)-(\S+)", l)
+ if m and cur and sc is None:
+ entries.append(m.group(1))
+ continue
+ m = re.match(r"^([.A-Za-z_]\w*):\s*dc\.b\s+(.*)$", l)
+ if m and cur:
+ sc = m.group(1)
+ scripts[sc] = [s1.number(v, SYM) & 0xFF for v in m.group(2).split(",")]
+ continue
+ m = re.match(r"^\s*dc\.b\s+(.*)$", l)
+ if m and sc:
+ scripts[sc] += [s1.number(v, SYM) & 0xFF for v in m.group(1).split(",")]
+ close()
+ return tables
+
+
+ANIS = []
+anim_files = [os.path.join("_anim", f) for f in sorted(os.listdir(os.path.join(REF, "_anim"))) if f.endswith(".asm")]
+for f in anim_files:
+ for label, scripts in anim_tables(f).items():
+ b = bytearray(struct.pack("<H", len(scripts)))
+ start = 2 + 2 * len(scripts)
+ body = bytearray()
+ offs = []
+ for sc in scripts:
+ offs.append(start + len(body))
+ body += bytes(sc)
+ if len(body) % 2:
+ body.append(0)
+ for o in offs:
+ b += struct.pack("<H", o)
+ ANIS.append((label, bytes(b + body)))
+
+
+def table(prefix, items):
+ """A table of offsets (from the start of data.bin) to each item, and the items."""
+ offs = []
+ for name, data in items:
+ align(4)
+ offs.append(len(blob))
+ blob.extend(data)
+ t = bytearray()
+ for o in offs:
+ t += struct.pack("<I", o)
+ put("D_" + prefix, t)
+
+
+table("MAPS", MAPS)
+table("ANIS", ANIS)
+
+# (the Caterkiller's own animation: a frame for each of 128 steps)
+cat, on = bytearray(), False
+for l in asm_lines("_incObj/78 Badnik - Caterkiller.asm"):
+ if l.startswith("Ani_Cat:"):
+ on = True
+ elif on and re.match(r"^\s*dc\.b\s", l):
+ cat += bytes(s1.number(v, SYM) & 0xFF for v in l.split("dc.b", 1)[1].split(","))
+ elif on and l.strip() == "even":
+ break
+put("D_ANI_CAT", cat)
+
+# --- Sonic's pattern load cues
+dp = s1.dplcs(os.path.join(REF, "_maps", "Sonic - Dynamic Gfx Script.asm"))
+b = bytearray(struct.pack("<H", len(dp)))
+body, offs = bytearray(), []
+for fr in dp:
+ offs.append(2 + 2 * len(dp) + len(body))
+ body += struct.pack("<BB", len(fr), 0)
+ for tile, n in fr:
+ body += struct.pack("<H", (n - 1) << 12 | tile)
+for o in offs:
+ b += struct.pack("<H", o)
+put("D_SONICDPLC", b + body)
+
+# --- levels
+ZONES = ["GHZ", "LZ", "MZ", "SLZ", "SYZ", "SBZ"]
+for z in ZONES:
+ blocks = s1.enigma(rd(FILES["Blk16_" + z]))
+ put("D_BLK16_" + z, struct.pack("<%dH" % len(blocks), *blocks))
+ chunks = s1.kosinski(rd(FILES["Blk256_" + z]))
+ words = struct.unpack(">%dH" % (len(chunks) // 2), chunks)
+ # (the chunks the layouts use: the empty ones at the end are left out)
+ n = len(words) // 256
+ while n and not any(words[(n - 1) * 256:n * 256]):
+ n -= 1
+ defs.append(("N_BLK256_" + z, n))
+ put("D_BLK256_" + z, struct.pack("<%dH" % (n * 256), *words[:n * 256]))
+
+# (the collision indexes back to back, as in the original: a block past the end of one reads the next)
+cols = bytearray()
+for z in ZONES:
+ defs.append(("D_COL_" + z, len(blob) + ((-len(blob)) % 4) + len(cols)))
+ cols += rd(FILES["Col_" + z])
+put("D_COLS", cols)
+put("D_ANGLEMAP", rd(FILES["AngleMap"]))
+put("D_COLLARRAY1", rd(FILES["CollArray1"]))
+put("D_COLLARRAY2", rd(FILES["CollArray2"]))
+
+for f in sorted(os.listdir(os.path.join(REF, "levels"))):
+ if "REV00" in f:
+ continue
+ put("D_LEVEL_" + ident(f[:-4].replace(" (REV01)", "")).upper(), rd(os.path.join("levels", f)), 2)
+
+for f in sorted(os.listdir(os.path.join(REF, "objpos"))):
+ if not f.endswith(".bin") or "REV00" in f:
+ continue
+ d = rd(os.path.join("objpos", f))
+ o = bytearray()
+ for i in range(0, len(d) - 5, 6):
+ x, y, idb, sub = struct.unpack(">HHBB", d[i:i + 6])
+ o += struct.pack("<HHBB", x, y, idb, sub)
+ if x == 0xFFFF:
+ break
+ o += struct.pack("<HHBB", 0xFFFF, 0, 0, 0)
+ # (an end marker before the list too, as in the original: the object manager looks one entry back)
+ at = put("OBJPOS_START_" + ident(f[:-4]).upper(), struct.pack("<HHBB", 0xFFFF, 0, 0, 0) + o, 2)
+ defs.append(("D_OBJPOS_" + ident(f[:-4].replace(" (REV01)", "")).upper(), at + 6))
+
+for f in sorted(os.listdir(os.path.join(REF, "startpos"))):
+ if f.endswith(".bin"):
+ d = rd(os.path.join("startpos", f))
+ put("D_START_" + ident(f[:-4]).upper(), struct.pack("<2H", *struct.unpack(">2H", d[:4])), 2)
+for d_ in ("Credits Demos", "Special Stages"):
+ p = os.path.join(REF, "startpos", d_)
+ for f in sorted(os.listdir(p)):
+ d = open(os.path.join(p, f), "rb").read()
+ put("D_START_" + ident(d_ + " " + f[:-4]).upper(), struct.pack("<%dH" % (len(d) // 2), *struct.unpack(">%dH" % (len(d) // 2), d)), 2)
+
+for f in sorted(os.listdir(os.path.join(REF, "palette"))):
+ d = rd(os.path.join("palette", f))
+ put("D_PAL_" + ident(f[:-4]).upper(), struct.pack("<%dH" % (len(d) // 2), *struct.unpack(">%dH" % (len(d) // 2), d)), 2)
+ defs.append(("N_PAL_" + ident(f[:-4]).upper(), len(d) // 2))
+
+# --- tile maps and special stages
+for label, start in (("Eni_Title", 0), ("Eni_SegaLogo", 0), ("Eni_SSBg1", 0), ("Eni_SSBg2", 0), ("Eni_JapNames", 0)):
+ w = s1.enigma(rd(FILES[label]), start)
+ put("D_" + label.upper(), struct.pack("<%dH" % len(w), *w))
+ defs.append(("N_" + label.upper(), len(w)))
+for i in range(1, 7):
+ w = s1.enigma(rd(FILES["SS_%d" % i]))
+ # (the layouts are bytes: Enigma packs them as words)
+ put("D_SS_%d" % i, bytes(v & 0xFF for v in w) if max(w) < 256 else struct.pack(">%dH" % len(w), *w))
+ defs.append(("N_SS_%d" % i, len(w)))
+
+# --- demos: (buttons, frames) pairs
+BTN = {"U": 1, "D": 2, "L": 4, "R": 8, "B": 0x10, "C": 0x20, "A": 0x40, "S": 0x80}
+for f in sorted(os.listdir(os.path.join(REF, "demodata"))):
+ o = bytearray()
+ for l in asm_lines(os.path.join("demodata", f)):
+ m = re.match(r"^\s*demoinput\s+([A-Z]*)\s*,\s*(\S+)", l)
+ if m:
+ mask = 0
+ for c in m.group(1):
+ mask |= BTN[c]
+ o += bytes([mask, (s1.number(m.group(2), SYM) - 1) & 0xFF])
+ continue
+ m = re.match(r"^\s*dc\.b\s+(.*)$", l)
+ if m:
+ o += bytes(s1.number(v, SYM) & 0xFF for v in m.group(1).split(","))
+ put("D_DEMO_" + ident(f[:-4]).upper(), o, 2)
+
+# --- pattern load cues: (art, first tile) lists, in the order of their ids
+art_ids = {n: i for i, (n, _, _) in enumerate(ART)}
+plc_order, plc_lists, cur, skip = [], {}, None, False
+for l in asm_lines("_inc/Pattern Load Cues.asm"):
+ m = re.match(r"^plcid_\w+:\s+plcptr\s+(\w+)", l)
+ if m:
+ plc_order.append(m.group(1))
+ continue
+ if re.match(r"^\s*if\s+\(Revision=0\)", l):
+ skip = True
+ continue
+ if re.match(r"^\s*endif", l):
+ skip = False
+ continue
+ m = re.match(r"^(PLC_\w+):\s*(plcheader)?", l)
+ if m:
+ cur = None if m.group(1).endswith("_end") else m.group(1)
+ if cur:
+ plc_lists[cur] = []
+ continue
+ m = re.match(r"^\s*plcm\s+(\w+)\s*,\s*([^;]+)", l)
+ if m and cur and not skip:
+ plc_lists[cur].append((art_ids[m.group(1)], s1.number(m.group(2), SYM)))
+offs, body = [], bytearray()
+for name in plc_order:
+ offs.append(len(body))
+ lst = plc_lists.get(name, [])
+ body += struct.pack("<H", len(lst))
+ for a, t in lst:
+ body += struct.pack("<HH", a, t)
+b = bytearray(struct.pack("<H", len(plc_order)))
+for o in offs:
+ b += struct.pack("<H", 2 + 2 * len(plc_order) + o)
+put("D_PLC", b + body)
+
+# --- tables of numbers written in the code: (file, label, b or w)
+TABLES = [
+ ("_incObj/sub CalcSine.asm", "Sine_Data", "w"),
+ ("_incObj/sub CalcAngle.asm", "Angle_Data", "b"),
+ ("_incObj/0A LZ Drowning Countdown.asm", "Drown_WobbleData", "b"),
+]
+
+
+def asm_table(path, label, size):
+ vals, on, skip = [], False, False
+ for l in asm_lines(path):
+ if re.match(r"^\s*if\s+\(?Revision\s*=\s*0", l):
+ skip = True
+ continue
+ if re.match(r"^\s*if\s+Revision\s*<>\s*0", l):
+ continue
+ if re.match(r"^\s*else\b", l):
+ skip = not skip
+ continue
+ if re.match(r"^\s*endif\b", l):
+ skip = False
+ continue
+ if skip:
+ continue
+ m = re.match(r"^([.A-Za-z_]\w*):\s*(.*)$", l)
+ if m and m.group(1) == label:
+ on = True
+ l = m.group(2)
+ elif on and re.match(r"^[.A-Za-z_]\w*:", l):
+ break
+ if not on:
+ continue
+ m = re.match(r"^\s*rept\s+(\S+)", l)
+ if m:
+ rept_at, rept_n = len(vals), s1.number(m.group(1), SYM)
+ continue
+ if re.match(r"^\s*endr\b", l):
+ vals += vals[rept_at:] * (rept_n - 1)
+ continue
+ m = re.match(r"^\s*dc\.([bw])\s+(.*)$", l)
+ if m:
+ vals += [s1.number(v, SYM) for v in m.group(2).split(",")]
+ elif re.match(r"^\s*dcb\.b\s+", l):
+ n, v = [s1.number(x, SYM) for x in l.split("dcb.b", 1)[1].split(",")]
+ vals += [v] * n
+ elif l.strip() and l.strip() != "even":
+ break
+ if size == "b":
+ return bytes(v & 0xFF for v in vals)
+ return struct.pack("<%dh" % len(vals), *[(v + 0x8000) % 0x10000 - 0x8000 for v in vals])
+
+
+for path, label, size in TABLES:
+ put("D_TAB_" + label.upper(), asm_table(path, label, size), 2)
+
+# ---------------------------------------------------------------- output
+align(4)
+open(os.path.join(OUT, "data.bin"), "wb").write(blob)
+with open(os.path.join(OUT, "data.h"), "w") as h:
+ h.write("/* made by tools/pack.py: what is where in data.bin */\n#ifndef S1_DATA_H\n#define S1_DATA_H\n")
+ for n, v in defs:
+ h.write(f"#define {n} {v}\n")
+ for i, (n, first, count) in enumerate(ART):
+ h.write(f"#define ART_{ident(n)} {i}\n")
+ for i, (n, _) in enumerate(MAPS):
+ h.write(f"#define MAP_{ident(n.split('_', 1)[1])} {i}\n")
+ for i, (n, _) in enumerate(ANIS):
+ h.write(f"#define ANI_{ident(n.split('_', 1)[1])} {i}\n")
+ h.write(f"#define N_ARTS {len(ART)}\n#define N_MAPS {len(MAPS)}\n#define N_ANIS {len(ANIS)}\n#endif\n")
+
+KEEP = re.compile(r"^(ArtTile_|id_(?!VBlank)|status_|sprite_|fr_|btn|bit[A-Z]|aniXFlip|aniYFlip|boss_)")
+with open(os.path.join(OUT, "s1const.h"), "w") as h:
+ h.write("/* made by tools/pack.py: the disassembly's names for its numbers */\n#ifndef S1_CONST_H\n#define S1_CONST_H\n")
+ for n in sorted(SYM):
+ if KEEP.match(n) and isinstance(SYM[n], int):
+ h.write(f"#define {n} {SYM[n]}\n")
+ h.write("#endif\n")
+print(f"data.bin: {len(blob)} bytes ({len(pool) // 32} patterns, {len(MAPS)} mappings, {len(ANIS)} animations)")
diff --git a/games/sonic/tools/s1.py b/games/sonic/tools/s1.py
new file mode 100644
index 00000000..9b7977b2
--- /dev/null
+++ b/games/sonic/tools/s1.py
@@ -0,0 +1,283 @@
+"""Reading the Sonic Retro disassembly of Sonic the Hedgehog (REF, see fetch.py): its three
+compression formats, and the sprite mappings, animations and tables written as assembly.
+
+- nemesis(): 8x8 patterns (4 bits a pixel), coded with a table of variable-length codes
+- kosinski(): LZ77 with bit fields (16-by-16 block layouts of the 256x256 chunks)
+- enigma(): words of tile maps (the 16x16 blocks, the special stages, the title screen)
+"""
+import os
+import re
+
+
+def nemesis(d):
+ """The patterns of a Nemesis file, 32 bytes each."""
+ head = d[0] << 8 | d[1]
+ xor, rows = head & 0x8000, (head & 0x7FFF) * 8
+ p = 2
+ table = {}
+ pal = 0
+ b = d[p]
+ p += 1
+ while b != 0xFF:
+ if b & 0x80:
+ pal = b & 0x0F
+ b = d[p]
+ p += 1
+ continue
+ rep = (b & 0x70) >> 4
+ length = b & 0x0F
+ code = d[p]
+ p += 1
+ table[(length, code)] = (pal, rep + 1)
+ b = d[p]
+ p += 1
+ # the bits, most significant first
+ bits = []
+ for c in d[p:]:
+ for i in range(7, -1, -1):
+ bits.append(c >> i & 1)
+ out = bytearray()
+ row, n, prev, q = 0, 0, 0, 0
+ while len(out) < rows * 4:
+ if q + 6 <= len(bits) and all(bits[q:q + 6]):
+ q += 6
+ v = 0
+ for _ in range(7):
+ v = v << 1 | bits[q]
+ q += 1
+ pal, cnt = v & 0x0F, ((v >> 4) & 7) + 1
+ else:
+ code, length = 0, 0
+ while True:
+ code = code << 1 | bits[q]
+ q += 1
+ length += 1
+ if (length, code) in table:
+ pal, cnt = table[(length, code)]
+ break
+ if length > 8:
+ raise ValueError("bad Nemesis code")
+ for _ in range(cnt):
+ row = (row << 4 | pal) & 0xFFFFFFFF
+ n += 1
+ if n == 8:
+ if xor:
+ prev ^= row
+ row = prev
+ out += row.to_bytes(4, "big")
+ row, n = 0, 0
+ if len(out) >= rows * 4:
+ break
+ return bytes(out)
+
+
+def kosinski(d):
+ out = bytearray()
+ p = 2
+ desc, left = d[0] | d[1] << 8, 16
+
+ def bit():
+ nonlocal desc, left, p
+ b = desc & 1
+ desc >>= 1
+ left -= 1
+ if left == 0:
+ desc, left = d[p] | d[p + 1] << 8, 16
+ p += 2
+ return b
+
+ while True:
+ if bit():
+ out.append(d[p])
+ p += 1
+ continue
+ if bit():
+ lo, hi = d[p], d[p + 1]
+ p += 2
+ off = (0xE000 | (hi & 0xF8) << 5 | lo) - 0x10000
+ if hi & 7:
+ cnt = (hi & 7) + 2
+ else:
+ c = d[p]
+ p += 1
+ if c == 0:
+ break
+ if c == 1:
+ continue
+ cnt = c + 1
+ else:
+ cnt = (bit() << 1 | bit()) + 2
+ off = d[p] - 0x100
+ p += 1
+ for _ in range(cnt):
+ out.append(out[off])
+ return bytes(out)
+
+
+def enigma(d, start=0):
+ """The words of an Enigma tile map; start is the art tile added to each."""
+ nbits, mask = d[0], d[1]
+ inc = (d[2] << 8 | d[3]) + start
+ lit = (d[4] << 8 | d[5]) + start
+ bits = []
+ for c in d[6:]:
+ for i in range(7, -1, -1):
+ bits.append(c >> i & 1)
+ q = 0
+
+ def take(n):
+ nonlocal q
+ v = 0
+ for _ in range(n):
+ v = v << 1 | bits[q]
+ q += 1
+ return v
+
+ def inline():
+ v = start
+ for flag, value in ((0x10, 0x8000), (0x08, 0x4000), (0x04, 0x2000), (0x02, 0x1000), (0x01, 0x0800)):
+ if mask & flag and take(1):
+ v += value
+ return (v + take(nbits)) & 0xFFFF
+
+ out = []
+ while True:
+ if take(1) == 0:
+ kind = take(1)
+ cnt = take(4) + 1
+ if kind == 0:
+ for _ in range(cnt):
+ out.append(inc & 0xFFFF)
+ inc += 1
+ else:
+ out += [lit & 0xFFFF] * cnt
+ else:
+ kind = take(2)
+ cnt = take(4)
+ if kind == 3 and cnt == 0xF:
+ break
+ cnt += 1
+ if kind == 3:
+ for _ in range(cnt):
+ out.append(inline())
+ else:
+ v = inline()
+ for _ in range(cnt):
+ out.append(v & 0xFFFF)
+ v += (0, 1, -1)[kind]
+ return out
+
+
+# ---------------------------------------------------------------- assembly sources
+
+def number(s, sym=None):
+ """An assembler expression of numbers, symbols, + - * / << >> & | and parentheses."""
+ s = s.strip()
+ expr = re.sub(r"\$([0-9A-Fa-f]+)", lambda m: str(int(m.group(1), 16)), s)
+ expr = re.sub(r"%([01]+)", lambda m: str(int(m.group(1), 2)), expr)
+ if sym:
+ expr = re.sub(r"[A-Za-z_][A-Za-z_0-9.]*", lambda m: str(sym[m.group(0)]) if m.group(0) in sym else m.group(0), expr)
+ expr = re.sub(r"\b0+(\d)", r"\1", expr)
+ expr = expr.replace("/", "//")
+ return int(eval(expr, {"__builtins__": {}}))
+
+
+def strip(line):
+ """A line without its comment."""
+ out, quote = "", False
+ for c in line:
+ if c == '"':
+ quote = not quote
+ if c == ";" and not quote:
+ break
+ out += c
+ return out.rstrip()
+
+
+def constants(ref):
+ """Every `name = value` and `name equ value` of the constants files that is a number."""
+ sym = {}
+ for f in ("_Constants.asm", "_Variables.asm"):
+ for line in open(os.path.join(ref, f), encoding="latin1"):
+ m = re.match(r"^\s*([A-Za-z_][A-Za-z_0-9]*)\s*(?:=|equ)\s*([^;]+)", strip(line))
+ if not m:
+ continue
+ try:
+ sym[m.group(1)] = number(m.group(2), sym)
+ except Exception:
+ pass
+ return sym
+
+
+def mappings(path):
+ """The frames of a mappings file: each a list of (x, y, w, h, tile word) pieces."""
+ lines = [strip(l) for l in open(path, encoding="latin1")]
+ order, frames, cur = [], {}, None
+ for l in lines:
+ m = re.match(r"^\s*mappingsTableEntry\.w\s+(\S+)", l)
+ if m:
+ order.append(m.group(1))
+ continue
+ m = re.match(r"^([.A-Za-z_0-9]+):?\s+spriteHeader", l)
+ if m:
+ cur = m.group(1)
+ frames[cur] = []
+ continue
+ m = re.match(r"^\s*spritePiece\s+(.*)$", l)
+ if m and cur:
+ a = [number(x) for x in m.group(1).split(",")]
+ x, y, w, h, tile, xf, yf, pal, pri = a
+ word = (pri & 1) << 15 | (pal & 3) << 13 | (yf & 1) << 12 | (xf & 1) << 11 | (tile & 0x7FF)
+ frames[cur].append((x, y, w, h, word))
+ return [frames[o] for o in order]
+
+
+def dplcs(path):
+ """Sonic's dynamic pattern load cues: for each frame, (first tile, count) runs of his art."""
+ lines = [strip(l) for l in open(path, encoding="latin1")]
+ order, frames, cur = [], {}, None
+ for l in lines:
+ m = re.match(r"^\s*mappingsTableEntry\.w\s+(\S+)", l)
+ if m:
+ order.append(m.group(1))
+ continue
+ m = re.match(r"^([.A-Za-z_0-9]+):?\s+dplcHeader", l)
+ if m:
+ cur = m.group(1)
+ frames[cur] = []
+ continue
+ m = re.match(r"^\s*dplcEntry\s+(.*)$", l)
+ if m and cur:
+ n, t = [number(x) for x in m.group(1).split(",")]
+ frames[cur].append((t, n))
+ return [frames[o] for o in order]
+
+
+AF = {"afEnd": 0xFF, "afBack": 0xFE, "afChange": 0xFD, "afRoutine": 0xFC, "afReset": 0xFB, "af2ndRoutine": 0xFA}
+
+
+def animations(path, sym=None):
+ """The scripts of an animation file, as bytes (the game's own format)."""
+ lines = [strip(l) for l in open(path, encoding="latin1")]
+ order, scripts, cur = [], {}, None
+ s = dict(AF)
+ if sym:
+ s.update(sym)
+ for l in lines:
+ m = re.match(r"^([A-Za-z_0-9]+):\s*dc\.w\s+(\S+)-", l)
+ if m:
+ order.append(m.group(2))
+ continue
+ m = re.match(r"^\s*dc\.w\s+(\S+)-", l)
+ if m:
+ order.append(m.group(1))
+ continue
+ m = re.match(r"^([.A-Za-z_0-9]+):\s*dc\.b\s+(.*)$", l)
+ if m:
+ cur = m.group(1)
+ scripts[cur] = [number(x, s) & 0xFF for x in m.group(2).split(",")]
+ continue
+ m = re.match(r"^\s*dc\.b\s+(.*)$", l)
+ if m and cur:
+ scripts[cur] += [number(x, s) & 0xFF for x in m.group(1).split(",")]
+ return [bytes(scripts[o]) for o in order]