Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Hill Climb Racing: the engine, the Hill Climber on the Countryside
Mason3630730edb4dea3
diff --git a/games/hillclimb/.gitignore b/games/hillclimb/.gitignorenew file mode 100644index 00000000..342d9dda--- /dev/null+++ b/games/hillclimb/.gitignore@@ -0,0 +1,2 @@+output/+build/diff --git a/games/hillclimb/Makefile b/games/hillclimb/Makefilenew file mode 100644index 00000000..f3f3b018--- /dev/null+++ b/games/hillclimb/Makefile@@ -0,0 +1,79 @@+# Hill Climb Racing on the NumWorks calculator.+# make output/hillclimb.nwa+# make check link it like the calculator does (output/hillclimb.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/art.h from the public material tools/fetch.py gathers+# (REF=its folder, Python + Pillow + NumPy + pngquant)+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 drawing and the physics run every frame at -O2; the rest is small at -Os+HOT = src/gfx.c src/car.c src/stage.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)/hillclimb.nwa++# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)+check: $(BUILD_DIR)/hillclimb.nwa+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/hillclimb.bin+ @echo "BIN $(BUILD_DIR)/hillclimb.bin: $$(wc -c < $(BUILD_DIR)/hillclimb.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)/hillclimb.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) tests/play.c src/data.S src/data.bin $(HEADERS)+ $(Q) mkdir -p $(dir $@)+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) 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) builddiff --git a/games/hillclimb/src/art.h b/games/hillclimb/src/art.hnew file mode 100644index 00000000..f05199c8--- /dev/null+++ b/games/hillclimb/src/art.h@@ -0,0 +1,55 @@+/* Generated by tools/pack.py from tools/art.py: the vehicles put together, in meters. */+#ifndef HC_ART_H+#define HC_ART_H+#include "data.h"++#define BILL_NECK_X -0.015f+#define BILL_NECK_Y 0.766f+#define BILL_HEAD_X 0.085f /* the head's centre from the neck */+#define BILL_HEAD_Y 0.322f+#define BILL_HEAD_R 0.288f++typedef struct {+ uint8_t chassis, wheel, naxles, legs, ntubes, nlayers, nhull;+ float axle[6][2], wheel_r[6]; /* from the chassis' origin: halfway between the first and last axles */+ float hips[2], lean; /* Bill's hips, and how far he leans back (radians) */+ float tube[2][5]; /* from (x, y) to axle (index), colour 0xRRGGBB, radius */+ float layer[2][4]; /* picture, its pivot's place (x, y), in front (1) or behind */+ float hull[16][2]; /* the chassis' outline, for the ground to push on */+} VehArt;+#define NVEH 8+static const VehArt veh_art[NVEH] = {+ {IMG_CH_JEEP, IMG_WHEEL_JEEP, 2, 0, 0, 0, 16,+ {{-1.075f, 0.000f}, {1.075f, 0.000f}}, {0.430f, 0.430f},+ {-0.104f, 0.638f}, 0.070f, {{0}}, {{0}},+ {{-1.713f, 0.111f}, {-1.600f, 0.631f}, {-1.283f, 0.936f}, {-0.756f, 1.009f}, {-0.229f, 1.082f}, {0.297f, 1.154f}, {0.805f, 1.099f}, {1.280f, 0.861f}, {1.741f, 0.609f}, {1.757f, 0.084f}, {1.341f, -0.148f}, {0.810f, -0.175f}, {0.278f, -0.180f}, {-0.253f, -0.180f}, {-0.785f, -0.175f}, {-1.316f, -0.138f}}}, /* Hill Climber */+ {IMG_CH_BIKE, IMG_WHEEL_BIKE, 2, 1, 2, 0, 15,+ {{-0.925f, 0.000f}, {0.925f, 0.000f}}, {0.440f, 0.440f},+ {-0.273f, 0.904f}, -0.279f, {{-0.021f, 0.231f, 0.000f, 5922406.0f, 0.090f}, {0.484f, 1.009f, 1.000f, 3159098.0f, 0.070f}}, {{0}},+ {{-1.366f, 0.978f}, {-0.970f, 1.054f}, {-0.573f, 1.129f}, {-0.176f, 1.205f}, {0.221f, 1.281f}, {0.593f, 1.190f}, {0.933f, 0.973f}, {1.260f, 0.737f}, {1.017f, 0.517f}, {0.662f, 0.325f}, {0.307f, 0.132f}, {-0.075f, 0.038f}, {-0.422f, 0.224f}, {-0.740f, 0.474f}, {-1.057f, 0.724f}}}, /* Motocross Bike */+ {IMG_CH_MONSTER, IMG_WHEEL_MONSTER, 2, 0, 0, 0, 16,+ {{-1.275f, 0.000f}, {1.275f, 0.000f}}, {0.620f, 0.620f},+ {-0.159f, 0.685f}, 0.070f, {{0}}, {{0}},+ {{-2.024f, 0.717f}, {-1.502f, 0.832f}, {-0.970f, 0.919f}, {-0.436f, 0.987f}, {0.100f, 1.037f}, {0.630f, 1.017f}, {1.146f, 0.862f}, {1.657f, 0.693f}, {1.846f, 0.289f}, {1.381f, 0.018f}, {0.864f, -0.122f}, {0.331f, -0.175f}, {-0.208f, -0.175f}, {-0.744f, -0.152f}, {-1.271f, -0.040f}, {-1.662f, 0.323f}}}, /* Monster Truck */+ {IMG_CH_QUAD, IMG_WHEEL_QUAD, 2, 1, 0, 0, 15,+ {{-0.875f, 0.000f}, {0.875f, 0.000f}}, {0.500f, 0.500f},+ {-0.152f, 0.863f}, -0.209f, {{0}}, {{0}},+ {{-1.400f, 0.863f}, {-0.992f, 0.942f}, {-0.584f, 1.021f}, {-0.176f, 1.100f}, {0.232f, 1.178f}, {0.630f, 1.094f}, {1.017f, 0.944f}, {1.325f, 0.718f}, {1.159f, 0.416f}, {0.766f, 0.282f}, {0.373f, 0.149f}, {-0.030f, 0.070f}, {-0.416f, 0.205f}, {-0.792f, 0.382f}, {-1.168f, 0.558f}}}, /* Quad Bike */+ {IMG_CH_RACE, IMG_WHEEL_RACE, 2, 0, 0, 0, 16,+ {{-1.225f, 0.000f}, {1.225f, 0.000f}}, {0.400f, 0.400f},+ {-0.121f, 0.311f}, 0.384f, {{0}}, {{0}},+ {{-2.260f, 1.225f}, {-1.715f, 1.212f}, {-1.183f, 1.066f}, {-0.653f, 0.908f}, {-0.124f, 0.749f}, {0.406f, 0.591f}, {0.928f, 0.409f}, {1.447f, 0.219f}, {1.502f, -0.072f}, {0.949f, -0.090f}, {0.396f, -0.104f}, {-0.157f, -0.104f}, {-0.707f, -0.083f}, {-1.236f, 0.078f}, {-1.701f, 0.363f}, {-2.121f, 0.722f}}}, /* Race Car */+ {IMG_CH_RALLY, IMG_WHEEL_RALLY, 2, 0, 0, 0, 16,+ {{-1.175f, 0.000f}, {1.175f, 0.000f}}, {0.420f, 0.420f},+ {-0.030f, 0.446f}, 0.105f, {{0}}, {{0}},+ {{-1.934f, 1.324f}, {-1.377f, 1.297f}, {-0.827f, 1.193f}, {-0.277f, 1.089f}, {0.270f, 0.974f}, {0.795f, 0.783f}, {1.321f, 0.592f}, {1.685f, 0.230f}, {1.410f, -0.048f}, {0.851f, -0.055f}, {0.291f, -0.059f}, {-0.268f, -0.059f}, {-0.827f, -0.041f}, {-1.384f, 0.017f}, {-1.857f, 0.209f}, {-1.917f, 0.765f}}}, /* Rally Car */+ {IMG_CH_BUGGY, IMG_WHEEL_BUGGY, 2, 0, 0, 0, 16,+ {{-1.150f, 0.000f}, {1.150f, 0.058f}}, {0.520f, 0.400f},+ {-0.597f, 0.320f}, 0.175f, {{0}}, {{0}},+ {{-1.674f, 0.611f}, {-1.281f, 0.763f}, {-0.865f, 0.884f}, {-0.438f, 0.853f}, {-0.010f, 0.788f}, {0.416f, 0.714f}, {0.823f, 0.565f}, {1.229f, 0.416f}, {1.344f, 0.030f}, {0.977f, -0.072f}, {0.544f, -0.066f}, {0.111f, -0.061f}, {-0.322f, -0.055f}, {-0.755f, -0.050f}, {-1.188f, -0.044f}, {-1.516f, 0.213f}}}, /* Dune Buggy */+ {IMG_CH_TANK, IMG_WHEEL_TANK, 5, 0, 0, 2, 16,+ {{-1.600f, 0.000f}, {-0.800f, -0.109f}, {0.000f, -0.109f}, {0.800f, -0.109f}, {1.600f, 0.000f}}, {0.300f, 0.300f, 0.300f, 0.300f, 0.300f},+ {0.036f, 0.945f}, 0.000f, {{0}}, {{IMG_LAYER_CAR_TANK_BG, -2.073f, 1.418f, 0}, {IMG_LAYER_CAR_TANK_CANNON, 0.218f, 2.218f, 1}},+ {{-2.309f, 1.036f}, {-1.819f, 1.316f}, {-1.218f, 1.494f}, {-0.608f, 1.622f}, {0.019f, 1.635f}, {0.627f, 1.533f}, {1.211f, 1.303f}, {1.795f, 1.074f}, {2.186f, 0.627f}, {1.800f, 0.430f}, {1.174f, 0.400f}, {0.546f, 0.400f}, {-0.081f, 0.400f}, {-0.709f, 0.400f}, {-1.336f, 0.400f}, {-1.937f, 0.561f}}}, /* Tank */+};+#endifdiff --git a/games/hillclimb/src/car.c b/games/hillclimb/src/car.cnew file mode 100644index 00000000..240282e7--- /dev/null+++ b/games/hillclimb/src/car.c@@ -0,0 +1,437 @@+/* A vehicle's physics (car.h). */+#include <math.h>+#include <string.h>+#include "art.h"+#include "car.h"+#include "stage.h"+#include "vehicle.h"++#define SUB 4 /* steps a frame */+#define DT (1.0f / (CAR_HZ * SUB))+#define ITER 10+#define BETA 0.2f /* how much of an overlap is pushed out each step */+#define SLOP 0.004f+#define MAXC 64+#define SEG 0.2f /* the ground is straight between points this far apart */+#define HULL_R 0.05f++typedef struct {+ Body *b;+ float rx, ry, nx, ny, depth, mu, mn, mt, jn, jt, bias;+ int tree; /* a tree's index, or -1 */+ int wheel; /* the wheel's index, or -1 */+} Contact;++static Contact con[MAXC];+static int ncon;++static float cross(float ax, float ay, float bx, float by) { return ax * by - ay * bx; }+static void rot(float a, float x, float y, float *ox, float *oy) {+ float c = cosf(a), s = sinf(a);+ *ox = c * x - s * y, *oy = s * x + c * y;+}++float car_fuel_seconds(int veh, const uint8_t lv[4]) {+ const VehDef *d = &vehicles[veh];+ float f = d->fuel;+ for (int u = 0; u < 4; u++)+ if (d->up[u] == UP_FUEL) f *= 1 + 1.6f * (float)(lv[u] - 1) / (float)(d->max[u] - 1);+ return f;+}++void car_init(Car *c, int veh, const uint8_t lv[4], float x) {+ const VehDef *d = &vehicles[veh];+ const VehArt *a = &veh_art[veh];+ memset(c, 0, sizeof *c);+ c->veh = veh, c->nw = a->naxles, c->tree_broken = -1;+ float eng = 0, sus = 0, tir = 0, awd = d->awd, air = d->air, down = 0;+ for (int u = 0; u < 4; u++) {+ float f = (float)(lv[u] - 1) / (float)(d->max[u] - 1);+ switch (d->up[u]) {+ case UP_ENGINE: eng = f; break;+ case UP_SUSPENSION: sus = f; break;+ case UP_TIRES: case UP_TRACKS: tir = f; break;+ case UP_AWD: awd = f; break;+ case UP_AIR: air *= 1 + 2.4f * f; break;+ case UP_DOWNFORCE: down = d->downforce * f; break;+ }+ }+ c->torque = d->torque * (1 + 1.5f * eng);+ c->wmax = d->speed * (1 + 0.6f * eng) / a->wheel_r[0];+ c->brake = d->torque * 1.6f;+ c->grip = d->grip * (1 + 0.55f * tir);+ c->air = air, c->down = down;+ c->com[0] = d->com[0], c->com[1] = d->com[1] - 0.07f * sus;+ /* bodies */+ c->ch.im = 1 / d->mass;+ c->ch.ii = 1 / (d->mass * d->radius * d->radius);+ float wsum = 0;+ for (int i = 0; i < c->nw; i++) {+ float r = a->wheel_r[i];+ c->wr[i] = r;+ c->wh[i].im = 1 / d->wmass;+ c->wh[i].ii = 1 / (0.6f * d->wmass * r * r);+ /* the rear wheel always driven; the others by the 4WD's share */+ c->drive[i] = i == 0 ? 1 : awd;+ wsum += c->drive[i];+ }+ for (int i = 0; i < c->nw; i++) c->drive[i] *= (float)c->nw / (wsum > 0 ? wsum : 1) * 0.5f;+ if (c->nw > 2) /* (the tank's five wheels share the engine) */+ for (int i = 0; i < c->nw; i++) c->drive[i] = 2.0f / (float)c->nw;+ /* springs: settled at `sag` under the chassis' share of the weight */+ float load = d->mass / (float)c->nw;+ float sag = d->sag * (1 - 0.25f * sus);+ c->k = load * 9.8f / sag;+ c->c = 2 * (d->zeta * (1 + 0.6f * sus)) * sqrtf(c->k * load);+ c->s0 = 2 * sag;+ c->smax = 2 * sag + d->droop;+ for (int i = 0; i < c->nw; i++) {+ c->anc[i][0] = a->axle[i][0] - c->com[0];+ c->anc[i][1] = a->axle[i][1] + sag - c->com[1];+ }+ c->nhull = a->nhull;+ for (int i = 0; i < a->nhull; i++) c->hull[i][0] = a->hull[i][0] - c->com[0], c->hull[i][1] = a->hull[i][1] - c->com[1];+ /* Bill's head over his hips, leaning */+ float nx, ny, hx, hy;+ rot(a->lean, BILL_NECK_X, BILL_NECK_Y, &nx, &ny);+ rot(a->lean, BILL_HEAD_X, BILL_HEAD_Y, &hx, &hy);+ c->head[0] = a->hips[0] + nx + hx - c->com[0];+ c->head[1] = a->hips[1] + ny + hy - c->com[1];+ /* on the ground at x, level */+ float gy = stage_floor(x);+ float lowest = 0;+ for (int i = 0; i < c->nw; i++)+ if (a->axle[i][1] - a->wheel_r[i] < lowest) lowest = a->axle[i][1] - a->wheel_r[i];+ c->ch.x = x + c->com[0], c->ch.y = gy - lowest + c->com[1] + 0.02f;+ for (int i = 0; i < c->nw; i++) {+ c->wh[i].x = c->ch.x + c->anc[i][0];+ c->wh[i].y = c->ch.y + c->anc[i][1] - sag;+ }+}++/* ------------------------------------------------------------------ the ground's contacts */+static Contact *new_contact(Body *b, float px, float py, float nx, float ny, float depth, float mu, int wheel) {+ if (ncon >= MAXC) return NULL;+ Contact *k = &con[ncon++];+ k->b = b, k->rx = px - b->x, k->ry = py - b->y, k->nx = nx, k->ny = ny, k->depth = depth, k->mu = mu;+ k->jn = k->jt = 0, k->tree = -1, k->wheel = wheel;+ return k;+}++/* a circle against a line through points of f, all of them above (floor) or below (ceiling) it: its deepest touch */+static bool circle_line(float cx, float cy, float r, bool ceiling, float *px, float *py, float *nx, float *ny, float *depth) {+ float best = 1e9f, bx = 0, by = 0;+ int i0 = (int)floorf((cx - r) / SEG) - 1, i1 = (int)ceilf((cx + r) / SEG) + 1;+ float ya = 0, yb;+ for (int i = i0; i <= i1; i++) {+ float xb = (float)i * SEG;+ if (ceiling) {+ if (!stage_ceiling(xb, &yb)) {+ if (i == i0) ya = 1e9f;+ else ya = 1e9f;+ continue;+ }+ } else {+ yb = stage_floor(xb);+ }+ if (i > i0 && ya < 1e8f) {+ float xa = xb - SEG, dx = SEG, dy = yb - ya;+ float t = ((cx - xa) * dx + (cy - ya) * dy) / (dx * dx + dy * dy);+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ float qx = xa + t * dx, qy = ya + t * dy;+ float ex = cx - qx, ey = cy - qy, d = sqrtf(ex * ex + ey * ey);+ /* inside the ground: the distance counts as negative */+ float side = cross(dx, dy, cx - xa, cy - ya);+ if (ceiling ? side > 0 : side < 0) d = -d;+ if (d < best) best = d, bx = qx, by = qy;+ }+ ya = yb;+ }+ if (best >= r) return false;+ *px = bx, *py = by;+ float ex = cx - bx, ey = cy - by, l = sqrtf(ex * ex + ey * ey);+ if (l > 1e-5f && best > 0) {+ *nx = ex / l, *ny = ey / l;+ } else { /* deep inside: straight out of the ground's slope */+ float x0 = cx - 0.1f, x1 = cx + 0.1f, y0, y1;+ if (ceiling) {+ stage_ceiling(x0, &y0), stage_ceiling(x1, &y1);+ } else {+ y0 = stage_floor(x0), y1 = stage_floor(x1);+ }+ float tx = x1 - x0, ty = y1 - y0, tl = sqrtf(tx * tx + ty * ty);+ *nx = -ty / tl, *ny = tx / tl;+ if (ceiling) *nx = -*nx, *ny = -*ny;+ }+ *depth = r - best;+ return true;+}++static void touch_circle(Body *b, float cx, float cy, float r, float mu, int wheel) {+ float px, py, nx, ny, d;+ if (circle_line(cx, cy, r, false, &px, &py, &nx, &ny, &d)) new_contact(b, cx - nx * r, cy - ny * r, nx, ny, d, mu, wheel);+ if (stage->ceiling && circle_line(cx, cy, r, true, &px, &py, &nx, &ny, &d))+ new_contact(b, cx - nx * r, cy - ny * r, nx, ny, d, mu, wheel);+ if (cx - r < STAGE_WALL) new_contact(b, cx - r, cy, 1, 0, STAGE_WALL - (cx - r), mu * 0.3f, wheel);+ if (stage->feature == FEAT_TREES) {+ for (int k = stage_tree_first(cx - 4);; k++) {+ float tx;+ if (!stage_tree(k, &tx)) {+ if (k % 6 == 0) break;+ continue;+ }+ if (tx > cx + 4) break;+ if (!stage_tree_standing(k) || tx < cx - 4) continue;+ float ty0 = stage_floor(tx), ty1 = ty0 + TREE_H;+ float qy = cy < ty0 ? ty0 : cy > ty1 ? ty1 : cy, ex = cx - tx, ey = cy - qy, l = sqrtf(ex * ex + ey * ey);+ if (l >= r + TREE_R || l < 1e-5f) continue;+ Contact *k2 = new_contact(b, cx - ex / l * r, cy - ey / l * r, ex / l, ey / l, r + TREE_R - l, 0.3f, wheel);+ if (k2) k2->tree = k;+ }+ }+}++static void find_contacts(Car *c) {+ ncon = 0;+ float mu = c->grip * stage->friction;+ for (int i = 0; i < c->nw; i++) {+ int before = ncon;+ touch_circle(&c->wh[i], c->wh[i].x, c->wh[i].y, c->wr[i], mu, i);+ c->ground[i] = c->ground[i] || ncon > before;+ }+ int before = ncon;+ float ca = cosf(c->ch.a), sa = sinf(c->ch.a);+ for (int i = 0; i < c->nhull; i++) {+ float px = c->ch.x + ca * c->hull[i][0] - sa * c->hull[i][1];+ float py = c->ch.y + sa * c->hull[i][0] + ca * c->hull[i][1];+ touch_circle(&c->ch, px, py, HULL_R, 0.6f * stage->friction, -1);+ }+ if (c->head_hit) { /* (Bill down: his head lies on the ground too) */+ float hx = c->ch.x + ca * c->head[0] - sa * c->head[1], hy = c->ch.y + sa * c->head[0] + ca * c->head[1];+ touch_circle(&c->ch, hx, hy, BILL_HEAD_R, 0.6f, -1);+ }+ c->touch = c->touch || ncon > before;+}++/* ------------------------------------------------------------------ solving */+static void push(Body *b, float px, float py, float rx, float ry) {+ b->vx += b->im * px, b->vy += b->im * py;+ b->w += b->ii * cross(rx, ry, px, py);+}++static void prepare_contacts(void) {+ for (int i = 0; i < ncon; i++) {+ Contact *k = &con[i];+ float rn = cross(k->rx, k->ry, k->nx, k->ny), rt = cross(k->rx, k->ry, -k->ny, k->nx);+ k->mn = 1 / (k->b->im + k->b->ii * rn * rn);+ k->mt = 1 / (k->b->im + k->b->ii * rt * rt);+ float pen = k->depth - SLOP;+ k->bias = pen > 0 ? BETA / DT * pen : 0;+ if (k->bias > 4) k->bias = 4;+ }+}++static void solve_contacts(void) {+ for (int i = 0; i < ncon; i++) {+ Contact *k = &con[i];+ Body *b = k->b;+ float vx = b->vx - b->w * k->ry, vy = b->vy + b->w * k->rx;+ /* along the normal: no going in */+ float vn = vx * k->nx + vy * k->ny;+ float j = k->mn * (k->bias - vn), old = k->jn;+ k->jn = old + j > 0 ? old + j : 0;+ j = k->jn - old;+ push(b, j * k->nx, j * k->ny, k->rx, k->ry);+ /* friction along the ground, up to mu times the push */+ vx = b->vx - b->w * k->ry, vy = b->vy + b->w * k->rx;+ float tx = -k->ny, ty = k->nx, vt = vx * tx + vy * ty;+ float jt = -k->mt * vt, lim = k->mu * k->jn;+ old = k->jt;+ k->jt = old + jt;+ if (k->jt > lim) k->jt = lim;+ if (k->jt < -lim) k->jt = -lim;+ jt = k->jt - old;+ push(b, jt * tx, jt * ty, k->rx, k->ry);+ }+}++/* the wheel joints: across the axis held, along it the bump stops; and the engine */+typedef struct {+ float px, py, sAy, my, bias; /* across the axis, and the error there pushed out */+ float dx, dy, sAx, mx, s; /* along it (down the chassis) */+ float jlo, jm, mmax, speed; /* the stops' and the engine's impulses; the engine's most, its target */+} Joint;+static Joint jo[CAR_MAXW];++static void prepare_joints(Car *c, float gas, float brake, bool fuel) {+ Body *A = &c->ch;+ float ca = cosf(A->a), sa = sinf(A->a);+ /* the engine: forward is the wheels turning clockwise */+ float spin = 0;+ for (int i = 0; i < c->nw; i++) spin += c->wh[i].w - A->w;+ spin /= (float)c->nw;+ float speed = 0, tmax = 0;+ bool shared = true;+ if (gas > 0 && fuel) {+ speed = -c->wmax, tmax = c->torque * gas;+ } else if (brake > 0) {+ if (spin < -1.5f || !fuel) speed = 0, tmax = c->brake * brake, shared = false; /* rolling forward: brake */+ else speed = c->wmax * 0.45f, tmax = c->torque * 0.7f * brake; /* stopped: reverse */+ } else {+ speed = 0, tmax = c->torque * 0.015f, shared = false; /* coasting: the engine's own drag */+ }+ c->rpm = 0;+ for (int i = 0; i < c->nw; i++) {+ Joint *J = &jo[i];+ Body *B = &c->wh[i];+ float rax = ca * c->anc[i][0] - sa * c->anc[i][1], ray = sa * c->anc[i][0] + ca * c->anc[i][1];+ float dx = B->x - (A->x + rax), dy = B->y - (A->y + ray);+ J->dx = sa, J->dy = -ca; /* down the chassis */+ J->px = ca, J->py = sa; /* across */+ J->s = dx * J->dx + dy * J->dy;+ J->bias = -BETA / DT * (dx * J->px + dy * J->py);+ J->sAy = cross(dx + rax, dy + ray, J->px, J->py);+ J->sAx = cross(dx + rax, dy + ray, J->dx, J->dy);+ J->my = 1 / (A->im + B->im + A->ii * J->sAy * J->sAy);+ J->mx = 1 / (A->im + B->im + A->ii * J->sAx * J->sAx);+ J->jlo = J->jm = 0;+ J->speed = speed;+ J->mmax = (shared ? tmax * c->drive[i] : tmax) * DT;+ /* the spring and damper: once a step, as an impulse */+ float vs = (B->vx - A->vx) * J->dx + (B->vy - A->vy) * J->dy - J->sAx * A->w;+ float f = c->k * (c->s0 - J->s) - c->c * vs;+ c->wheel_load[i] = f > 0 ? f : 0;+ float j = f * DT;+ B->vx += B->im * j * J->dx, B->vy += B->im * j * J->dy;+ A->vx -= A->im * j * J->dx, A->vy -= A->im * j * J->dy, A->w -= A->ii * j * J->sAx;+ float r = -(B->w - A->w) / c->wmax;+ if (r > c->rpm) c->rpm = r;+ }+ if (c->rpm > 1) c->rpm = 1;+}++static void solve_joints(Car *c) {+ Body *A = &c->ch;+ for (int i = 0; i < c->nw; i++) {+ Joint *J = &jo[i];+ Body *B = &c->wh[i];+ /* the engine (or brake) between chassis and wheel */+ if (J->mmax > 0) {+ float rel = B->w - A->w - J->speed;+ float j = -rel / (A->ii + B->ii), old = J->jm;+ J->jm = old + j;+ if (J->jm > J->mmax) J->jm = J->mmax;+ if (J->jm < -J->mmax) J->jm = -J->mmax;+ j = J->jm - old;+ A->w -= A->ii * j, B->w += B->ii * j;+ }+ /* across the axis: the wheel stays on it */+ float v = (B->vx - A->vx) * J->px + (B->vy - A->vy) * J->py - J->sAy * A->w;+ float j = J->my * (J->bias - v);+ B->vx += B->im * j * J->px, B->vy += B->im * j * J->py;+ A->vx -= A->im * j * J->px, A->vy -= A->im * j * J->py, A->w -= A->ii * j * J->sAy;+ /* along it: the bump stop (s >= 0) and the end of its travel (s <= smax) */+ float vs = (B->vx - A->vx) * J->dx + (B->vy - A->vy) * J->dy - J->sAx * A->w;+ if (J->s < 0.02f) {+ float bias = J->s < 0 ? -BETA / DT * J->s : 0;+ float jl = J->mx * (bias - vs), old = J->jlo;+ J->jlo = old + jl > 0 ? old + jl : 0;+ jl = J->jlo - old;+ B->vx += B->im * jl * J->dx, B->vy += B->im * jl * J->dy;+ A->vx -= A->im * jl * J->dx, A->vy -= A->im * jl * J->dy, A->w -= A->ii * jl * J->sAx;+ } else if (J->s > c->smax - 0.02f) {+ float bias = J->s > c->smax ? -BETA / DT * (J->s - c->smax) : 0;+ float jl = J->mx * (bias - vs), old = J->jlo;+ J->jlo = old + jl < 0 ? old + jl : 0;+ jl = J->jlo - old;+ B->vx += B->im * jl * J->dx, B->vy += B->im * jl * J->dy;+ A->vx -= A->im * jl * J->dx, A->vy -= A->im * jl * J->dy, A->w -= A->ii * jl * J->sAx;+ }+ }+}++static void integrate(Body *b) {+ b->x += b->vx * DT, b->y += b->vy * DT, b->a += b->w * DT;+}++void car_step(Car *c, float gas, float brake, bool fuel) {+ float g = stage->gravity;+ for (int i = 0; i < c->nw; i++) c->ground[i] = false;+ c->touch = false;+ c->tree_broken = -1;+ c->last_vx = c->ch.vx, c->last_vy = c->ch.vy;+ for (int sub = 0; sub < SUB; sub++) {+ /* forces: gravity, downforce, turning in the air */+ c->ch.vy -= g * DT;+ for (int i = 0; i < c->nw; i++) c->wh[i].vy -= g * DT;+ bool air = true;+ for (int i = 0; i < c->nw; i++) air = air && !c->ground[i];+ if (c->down > 0) {+ float v2 = c->ch.vx * c->ch.vx + c->ch.vy * c->ch.vy, f = c->down * v2 * c->ch.im * DT;+ if (f > g * 1.2f * DT) f = g * 1.2f * DT;+ c->ch.vx += sinf(c->ch.a) * f, c->ch.vy -= cosf(c->ch.a) * f;+ }+ if (air && !c->touch && !c->head_hit) c->ch.w += c->air * (gas - brake) * c->ch.ii * DT;+ /* a little air: nothing spins forever */+ c->ch.w *= 1 - 0.15f * DT;+ find_contacts(c);+ prepare_contacts();+ prepare_joints(c, gas, brake, fuel);+ for (int it = 0; it < ITER; it++) {+ solve_joints(c);+ solve_contacts();+ }+ /* trees that took too hard a knock fall */+ for (int i = 0; i < ncon; i++)+ if (con[i].tree >= 0 && con[i].jn > 55.0f) {+ stage_tree_fall(con[i].tree);+ c->tree_broken = con[i].tree;+ }+ integrate(&c->ch);+ for (int i = 0; i < c->nw; i++) {+ integrate(&c->wh[i]);+ c->spin[i] += c->wh[i].w * DT;+ }+ }+ /* Bill's head: does it touch the ground (or a cave's roof)? */+ if (!c->head_hit) {+ float hx, hy, px, py, nx, ny, d;+ float ca = cosf(c->ch.a), sa = sinf(c->ch.a);+ hx = c->ch.x + ca * c->head[0] - sa * c->head[1], hy = c->ch.y + sa * c->head[0] + ca * c->head[1];+ if (circle_line(hx, hy, BILL_HEAD_R * 0.92f, false, &px, &py, &nx, &ny, &d) ||+ (stage->ceiling && circle_line(hx, hy, BILL_HEAD_R * 0.92f, true, &px, &py, &nx, &ny, &d)))+ c->head_hit = true;+ }+ /* his head nods on its neck: a spring pulled by how the chassis speeds up */+ float ax = (c->ch.vx - c->last_vx) * CAR_HZ, ay = (c->ch.vy - c->last_vy) * CAR_HZ + g;+ float ca = cosf(-c->ch.a), sa = sinf(-c->ch.a), lx = ca * ax - sa * ay, ly = sa * ax + ca * ay;+ for (int k = 0; k < 2; k++) {+ float f = -160 * c->wob[k] - 14 * c->wobv[k] - (k ? ly - g : lx) * 0.6f;+ c->wobv[k] += f / CAR_HZ;+ c->wob[k] += c->wobv[k] / CAR_HZ;+ if (c->wob[k] > 0.12f) c->wob[k] = 0.12f, c->wobv[k] = 0;+ if (c->wob[k] < -0.12f) c->wob[k] = -0.12f, c->wobv[k] = 0;+ }+}++void car_origin(const Car *c, float *x, float *y) { car_point(c, 0, 0, x, y); }++void car_point(const Car *c, float lx, float ly, float *wx, float *wy) {+ float ox, oy;+ rot(c->ch.a, lx - c->com[0], ly - c->com[1], &ox, &oy);+ *wx = c->ch.x + ox, *wy = c->ch.y + oy;+}++void car_head(const Car *c, float *x, float *y) {+ float ox, oy;+ rot(c->ch.a, c->head[0] + c->wob[0], c->head[1] + c->wob[1], &ox, &oy);+ *x = c->ch.x + ox, *y = c->ch.y + oy;+}++float car_speed(const Car *c) { return sqrtf(c->ch.vx * c->ch.vx + c->ch.vy * c->ch.vy); }++bool car_airborne(const Car *c) {+ for (int i = 0; i < c->nw; i++)+ if (c->ground[i]) return false;+ return !c->touch;+}diff --git a/games/hillclimb/src/car.h b/games/hillclimb/src/car.hnew file mode 100644index 00000000..e81fa4f0--- /dev/null+++ b/games/hillclimb/src/car.h@@ -0,0 +1,51 @@+/* Hill Climb Racing: a vehicle's physics.+ *+ * The chassis (with Bill) and each wheel are rigid bodies in the plane. A wheel hangs from the chassis on a+ * spring and damper along the chassis' own up and down, held there by a joint; the engine turns the driven wheels+ * against the chassis, so it rears up when you floor it and turns in the air. The ground pushes on the wheels,+ * on the chassis' outline and, at the end, on Bill's head. Impulses are solved in turn (sequential impulses) at+ * 240 steps a second. Meters, seconds, kilograms; y up. */+#ifndef HC_CAR_H+#define HC_CAR_H+#include <stdbool.h>+#include <stdint.h>++#define CAR_MAXW 6+#define CAR_HZ 60 /* car_step's rate */++typedef struct { float x, y, a, vx, vy, w, im, ii; } Body; /* centre of mass, angle; inverse mass and inertia */++typedef struct {+ int veh, nw;+ Body ch, wh[CAR_MAXW];+ float wr[CAR_MAXW], spin[CAR_MAXW];+ float anc[CAR_MAXW][2]; /* the tops of the springs, from the centre of mass (chassis frame) */+ float s0, smax; /* the springs' length at rest unloaded, the most they let a wheel hang */+ float k, c; /* stiffness, damping */+ float torque, wmax, brake, drive[CAR_MAXW];+ float grip, air, down;+ float com[2]; /* the centre of mass from the picture's origin */+ float hull[16][2];+ int nhull;+ float head[2]; /* Bill's head's centre, from the centre of mass */+ bool ground[CAR_MAXW], touch, head_hit;+ float wheel_load[CAR_MAXW];+ float rpm; /* 0 to 1, for the meter */+ float wob[2], wobv[2]; /* Bill's head nodding on its neck (chassis frame) */+ float last_vx, last_vy;+ int tree_broken; /* a tree knocked down this step, or -1 */+} Car;++/* levels: the vehicle's four upgrades (1 and up) */+void car_init(Car *c, int veh, const uint8_t levels[4], float x);+/* one 1/60 s: gas and brake from 0 to 1; no fuel left: the engine is off */+void car_step(Car *c, float gas, float brake, bool fuel);+/* the picture's origin and angle: where to draw it */+void car_origin(const Car *c, float *x, float *y);+/* a point of the picture's frame (meters, y up) in the world */+void car_point(const Car *c, float lx, float ly, float *wx, float *wy);+void car_head(const Car *c, float *x, float *y); /* Bill's head's centre in the world (nodding) */+float car_speed(const Car *c); /* along the ground, m/s */+bool car_airborne(const Car *c);+float car_fuel_seconds(int veh, const uint8_t levels[4]);+#endifdiff --git a/games/hillclimb/src/data.S b/games/hillclimb/src/data.Snew file mode 100644index 00000000..6fc5327a--- /dev/null+++ b/games/hillclimb/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 _hc_data+_hc_data:+ .incbin DATA_BIN+ .p2align 2+#else+ .section .rodata.hc_data,"a"+ .balign 4+ .global hc_data+hc_data:+ .incbin DATA_BIN+ .balign 4+#endif+#ifdef __ELF__+ .section .note.GNU-stack,"",%progbits+#endifdiff --git a/games/hillclimb/src/data.bin b/games/hillclimb/src/data.binnew file mode 100644index 00000000..4b3f39b0Binary files /dev/null and b/games/hillclimb/src/data.bin differdiff --git a/games/hillclimb/src/data.h b/games/hillclimb/src/data.hnew file mode 100644index 00000000..6ef6c6e8--- /dev/null+++ b/games/hillclimb/src/data.h@@ -0,0 +1,119 @@+/* Generated by tools/pack.py: what src/data.bin holds. */+#ifndef HC_DATA_H+#define HC_DATA_H+#include <stdint.h>++enum {+ IMG_COIN5,+ IMG_COIN25,+ IMG_COIN100,+ IMG_COIN500,+ IMG_FUELCAN,+ IMG_CLOUD,+ IMG_TREE_TRUNK,+ IMG_TREE_TOP,+ IMG_PLANK,+ IMG_FLAG,+ IMG_ROCKS,+ IMG_ROCKS_MARS,+ IMG_ICICLE,+ IMG_SMOKE,+ IMG_DIRT,+ IMG_SNOW,+ IMG_GRASS,+ IMG_SLIME,+ IMG_SKY,+ IMG_SKY_CAVE,+ IMG_SKY_FOREST,+ IMG_SKY_MARS,+ IMG_SKY_ARCTIC_CAVE,+ IMG_SKY_HIGHWAY,+ IMG_SKY_MOON,+ IMG_SURF_COUNTRY,+ IMG_GROUND_COUNTRY,+ IMG_SURF_DESERT,+ IMG_GROUND_DESERT,+ IMG_SURF_ARCTIC,+ IMG_GROUND_ARCTIC,+ IMG_SURF_HIGHWAY,+ IMG_GROUND_HIGHWAY,+ IMG_SURF_CAVE,+ IMG_SURF_MOON,+ IMG_GROUND_MOON,+ IMG_SURF_MARS,+ IMG_GROUND_MARS,+ IMG_SURF_ALIEN,+ IMG_GROUND_ALIEN,+ IMG_SURF_FOREST,+ IMG_GROUND_FOREST,+ IMG_STAGE_COUNTRY,+ IMG_STAGE_DESERT,+ IMG_STAGE_ARCTIC,+ IMG_STAGE_HIGHWAY,+ IMG_STAGE_CAVE,+ IMG_STAGE_MOON,+ IMG_STAGE_MARS,+ IMG_STAGE_ALIEN,+ IMG_STAGE_ARCTIC_CAVE,+ IMG_STAGE_FOREST,+ IMG_STAGE_LOCKED,+ IMG_ICON_JEEP,+ IMG_ICON_BIKE,+ IMG_ICON_MONSTER,+ IMG_ICON_QUAD,+ IMG_ICON_RACE,+ IMG_ICON_RALLY,+ IMG_ICON_BUGGY,+ IMG_ICON_TANK,+ IMG_UP_ENGINE,+ IMG_UP_SUSPENSION,+ IMG_UP_TIRES,+ IMG_UP_AWD,+ IMG_UP_AIR,+ IMG_UP_DOWNFORCE,+ IMG_UP_FUEL,+ IMG_PEDAL_GAS,+ IMG_PEDAL_GAS_DOWN,+ IMG_PEDAL_BRAKE,+ IMG_PEDAL_BRAKE_DOWN,+ IMG_METER_RPM,+ IMG_METER_BOOST,+ IMG_NEEDLE,+ IMG_FUEL_ICON,+ IMG_FUEL_LOW,+ IMG_COIN_ICON,+ IMG_MENU_BG,+ IMG_LOGO,+ IMG_LOCK,+ IMG_START,+ IMG_BILL_BODY,+ IMG_BILL_HEAD,+ IMG_BILL_LEG,+ IMG_CH_JEEP,+ IMG_WHEEL_JEEP,+ IMG_CH_BIKE,+ IMG_WHEEL_BIKE,+ IMG_CH_MONSTER,+ IMG_WHEEL_MONSTER,+ IMG_CH_QUAD,+ IMG_WHEEL_QUAD,+ IMG_CH_RACE,+ IMG_WHEEL_RACE,+ IMG_CH_RALLY,+ IMG_WHEEL_RALLY,+ IMG_CH_BUGGY,+ IMG_WHEEL_BUGGY,+ IMG_CH_TANK,+ IMG_WHEEL_TANK,+ IMG_LAYER_CAR_TANK_BG,+ IMG_LAYER_CAR_TANK_CANNON,+ IMG_COUNT+};+enum {+ FONT_S,+ FONT_M,+ FONT_L,+ FONT_XL,+ FONT_COUNT+};+#endifdiff --git a/games/hillclimb/src/game.c b/games/hillclimb/src/game.cnew file mode 100644index 00000000..0b024de3--- /dev/null+++ b/games/hillclimb/src/game.c@@ -0,0 +1,152 @@+/* The game's screens: which one is up, the pause menu and the end of a run (the menus are in menu.c). */+#include <stdio.h>+#include <string.h>+#include "game.h"+#include "gfx.h"++int g_mode;+bool g_running = true;+uint32_t g_frame;+static uint32_t held;+static int pause_sel, pause_ask, end_t;++void game_init(void) {+ save_restore_copy();+ save_load();+ menu_enter(MODE_TITLE);+}++void game_quit(void) {+ if (g_mode == MODE_RUN || g_mode == MODE_PAUSE) run_finish(); /* (a run left halfway: its coins are kept) */+ else save_write();+ g_running = false;+}++static void start_run(void) {+ run_start(sv.vehicle, sv.stage);+ g_mode = MODE_RUN;+}++/* ------------------------------------------------------------------ pause */+static const char *const pause_items[] = {"RESUME", "RESTART", "GARAGE", "QUIT GAME"};++static void pause_frame(uint32_t pressed) {+ if (pause_ask) {+ if (pressed & K_OK) game_quit();+ else if (pressed & K_BACK) pause_ask = 0;+ return;+ }+ if (pressed & K_UP) pause_sel = (pause_sel + 3) % 4;+ if (pressed & K_DOWN) pause_sel = (pause_sel + 1) % 4;+ if (pressed & K_BACK) g_mode = MODE_RUN;+ if (pressed & K_OK) {+ switch (pause_sel) {+ case 0: g_mode = MODE_RUN; break;+ case 1: run_finish(), start_run(); break;+ case 2: run_finish(), menu_enter(MODE_GARAGE); break;+ case 3: pause_ask = 1; break;+ }+ }+}++static void pause_draw(void) {+ run_draw(true);+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, C_BLACK, 130);+ gfx_rrect(90, 44, 140, 156, 10, rgb565(0x2A2D33), 240);+ gfx_rrect(90, 44, 140, 30, 10, rgb565(0x4A4F57), 255);+ gfx_fill(90, 64, 140, 10, rgb565(0x4A4F57), 255);+ gfx_text(FONT_L, 160, 67, "PAUSED", C_WHITE, C_BLACK, 1);+ if (pause_ask) {+ gfx_text(FONT_M, 160, 110, "Quit the game?", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_S, 160, 130, "Your coins are kept.", rgb565(0xC8CDD4), C_BLACK, 1);+ gfx_rrect(104, 150, 54, 26, 6, rgb565(0x3DAA3D), 255);+ gfx_rrect(162, 150, 54, 26, 6, rgb565(0x8A2E2E), 255);+ gfx_text(FONT_M, 131, 169, "OK", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_M, 189, 169, "BACK", C_WHITE, C_BLACK, 1);+ return;+ }+ for (int i = 0; i < 4; i++) {+ int y = 84 + i * 28;+ bool on = i == pause_sel;+ gfx_rrect(102, y, 116, 24, 6, on ? rgb565(0xF2B531) : rgb565(0x40444B), 255);+ gfx_text(FONT_M, 160, y + 17, pause_items[i], on ? C_BLACK : C_WHITE, on ? rgb565(0xF2B531) : C_BLACK, 1);+ }+}++/* ------------------------------------------------------------------ the end of a run */+static void end_frame(uint32_t pressed) {+ end_t++;+ if (end_t < 20) return;+ if (pressed & K_OK) start_run();+ else if (pressed & K_BACK) menu_enter(MODE_GARAGE);+}++static void end_draw(void) {+ run_draw(false);+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, C_BLACK, 110);+ const char *title = run.end == END_DRIVER_DOWN ? "DRIVER DOWN" : "OUT OF FUEL";+ int a = end_t * 24 > 255 ? 255 : end_t * 24;+ gfx_text(FONT_XL, 160, 58, title, run.end == END_DRIVER_DOWN ? rgb565(0xFF5A3C) : rgb565(0xFFC21A), C_BLACK, 1);+ (void)a;+ char t[48], n[20];+ gfx_rrect(64, 74, 192, 112, 10, rgb565(0x2A2D33), 235);+ snprintf(t, sizeof t, "%dm", (int)run.dist);+ gfx_text(FONT_L, 160, 102, t, C_WHITE, C_BLACK, 1);+ if (run.new_best && (end_t / 15) % 2 == 0) gfx_text(FONT_M, 160, 120, "NEW RECORD!", rgb565(0xFFE14A), C_BLACK, 1);+ else {+ snprintf(t, sizeof t, "Best %dm", (int)sv.best[run.stage][run.vehicle]);+ gfx_text(FONT_M, 160, 120, t, rgb565(0xC8CDD4), C_BLACK, 1);+ }+ format_number(n, run.coins);+ gfx_text(FONT_S, 80, 140, "Coins", rgb565(0xC8CDD4), C_BLACK, 0);+ gfx_text(FONT_S, 240, 140, n, C_WHITE, C_BLACK, 2);+ format_number(n, run.bonus);+ gfx_text(FONT_S, 80, 154, "Tricks and levels", rgb565(0xC8CDD4), C_BLACK, 0);+ gfx_text(FONT_S, 240, 154, n, C_WHITE, C_BLACK, 2);+ gfx_fill(80, 160, 160, 1, rgb565(0x6A6F77), 255);+ gfx_text(FONT_M, 80, 176, "Total", C_WHITE, C_BLACK, 0);+ draw_coins_counter(240, 176, run_total(), 2);+ gfx_rrect(64, 196, 92, 28, 7, rgb565(0x3DAA3D), 255);+ gfx_rrect(164, 196, 92, 28, 7, rgb565(0x4A4F57), 255);+ gfx_text(FONT_M, 110, 216, "OK: RETRY", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_M, 210, 216, "BACK: GARAGE", C_WHITE, C_BLACK, 1);+ draw_coins_counter(312, 20, sv.coins, 2);+}++/* ------------------------------------------------------------------ the frame */+void game_frame(uint32_t keys) {+ uint32_t pressed = keys & ~held;+ held = keys;+ g_frame++;+ if (keys & K_HOME) {+ game_quit();+ return;+ }+ switch (g_mode) {+ case MODE_RUN:+ if (pressed & K_BACK && !run.over) {+ g_mode = MODE_PAUSE, pause_sel = 0, pause_ask = 0;+ break;+ }+ run_frame(keys);+ if (run.over && run.over_t > 75) {+ run_finish();+ g_mode = MODE_END, end_t = 0;+ }+ break;+ case MODE_PAUSE: pause_frame(pressed); break;+ case MODE_END: end_frame(pressed); break;+ default: menu_frame(keys, pressed); break;+ }+}++void game_draw(void) {+ gfx_begin();+ switch (g_mode) {+ case MODE_RUN: run_draw(true); break;+ case MODE_PAUSE: pause_draw(); break;+ case MODE_END: end_draw(); break;+ default: menu_draw(); break;+ }+ gfx_end();+}diff --git a/games/hillclimb/src/game.h b/games/hillclimb/src/game.hnew file mode 100644index 00000000..6d384534--- /dev/null+++ b/games/hillclimb/src/game.h@@ -0,0 +1,96 @@+/* Hill Climb Racing: the game's screens and the run being driven. */+#ifndef HC_GAME_H+#define HC_GAME_H+#include <stdbool.h>+#include <stdint.h>+#include "car.h"+#include "stage.h"+#include "vehicle.h"++enum { MODE_TITLE, MODE_HELP, MODE_GARAGE, MODE_STAGES, MODE_RUN, MODE_PAUSE, MODE_END };++/* what is kept (save.c) */+typedef struct {+ uint32_t coins;+ uint16_t vehicles, stages; /* bits: owned */+ uint8_t level[NVEHICLES][4]; /* each upgrade's level (1 and up) */+ uint16_t best[NSTAGES][NVEHICLES]; /* meters */+ uint8_t vehicle, stage, seen_help, pad;+ uint32_t runs, meters, flips, best_air_ms, coins_earned;+} Save;+extern Save sv;++enum { END_DRIVER_DOWN, END_OUT_OF_FUEL, END_QUIT };++typedef struct {+ char text[24];+ uint32_t value;+ uint16_t t; /* frames shown so far */+ uint8_t big;+} Popup;++typedef struct {+ float x, y, vx, vy, life, size;+ uint8_t kind; /* 0 the stage's dirt, 1 smoke, 2 a coin's sparkle */+} Particle;++#define NPOPUPS 4+#define NPARTICLES 40++typedef struct {+ Car car;+ int vehicle, stage;+ float fuel, fuel_max; /* seconds */+ uint32_t coins, bonus; /* collected, and from tricks and levels */+ float start_x, dist, best; /* meters: the farthest reached this run, the best before it */+ int level; /* levels done */+ float air_t, air_rot; /* in the air: for how long, turned how far (radians) */+ int air_flips, neck_ready;+ uint32_t air_value; /* what the air time is worth so far */+ bool over;+ int end; /* END_* */+ int over_t; /* frames since */+ int empty_t; /* frames stopped without fuel */+ bool new_best;+ float cam_x, cam_y, cam_s;+ uint32_t frame;+ float gas, brake; /* the pedals, eased */+ uint16_t got[COIN_GROUPS]; /* coins taken: a bit each */+ uint8_t fuel_got[512]; /* fuel cans taken */+ Popup pop[NPOPUPS];+ Particle part[NPARTICLES];+ int npart;+ uint32_t flips;+ uint32_t air_best_ms;+} Run;+extern Run run;++extern int g_mode;+extern bool g_running;+extern uint32_t g_frame;++void game_init(void);+void game_frame(uint32_t keys);+void game_draw(void);+void game_quit(void); /* Home or On/Off: save and stop */++void run_start(int vehicle, int stg);+void run_frame(uint32_t keys);+void run_draw(bool hud);+void run_finish(void); /* bank the run's coins and best */+uint32_t run_total(void); /* coins collected and earned */++/* menus (menu.c) */+void menu_frame(uint32_t keys, uint32_t pressed);+void menu_draw(void);+void menu_enter(int mode);++/* saves (save.c) */+void save_load(void);+bool save_write(void);+void save_restore_copy(void);++/* drawing helpers shared by the screens */+void draw_coins_counter(int x, int y, uint32_t n, int align);+void format_number(char *out, uint32_t n); /* 1,234,567 */+#endifdiff --git a/games/hillclimb/src/gfx.c b/games/hillclimb/src/gfx.cnew file mode 100644index 00000000..f06e8ec0--- /dev/null+++ b/games/hillclimb/src/gfx.c@@ -0,0 +1,481 @@+/* Drawing (gfx.h): the frame's commands, then each band of rows painted with every command that reaches it. */+#include <math.h>+#include <string.h>+#include "gfx.h"++enum { C_FILL, C_RRECT, C_VGRAD, C_ROWS, C_IMAGE, C_BLIT, C_TEXT, C_CIRCLE, C_RING, C_TUBE, C_GROUND };++typedef struct {+ uint8_t type, alpha;+ int16_t x0, y0, x1, y1; /* the pixels it may touch: [x0, x1) x [y0, y1) */+ union {+ struct { uint16_t c; } fill;+ struct { float x, y, w, h; uint16_t c; int16_t r; } rr;+ struct { uint32_t top, bottom; int16_t y, h; } grad;+ struct { const uint16_t *rows; } rows;+ struct { const Img *im; int32_t ua, ub, va, vb, u0, v0; } image; /* u = u0 + ua x + ub y (16.16) */+ struct { const Img *im; int16_t x, y; } blit; /* unscaled, its top-left */+ struct { const char *s; uint8_t font; uint16_t c, oc; int16_t x, y; } text;+ struct { float x, y, r, t; uint16_t c; } circle;+ struct { float ax, ay, bx, by, r; uint16_t c; } tube;+ };+} Cmd;++static Cmd cmds[GFX_MAX_CMDS];+static int ncmds;+static char pool[GFX_TEXT_POOL];+static int npool;+static uint16_t *band;+static int by0, by1; /* the band being painted */+Ground gfx_ground;++void gfx_init(uint16_t *b) { band = b; }+void gfx_begin(void) { ncmds = npool = 0; }++static Cmd *add(int type, int x0, int y0, int x1, int y1, int alpha) {+ if (ncmds >= GFX_MAX_CMDS || alpha <= 0) return NULL;+ if (x0 < 0) x0 = 0;+ if (y0 < 0) y0 = 0;+ if (x1 > SCREEN_W) x1 = SCREEN_W;+ if (y1 > SCREEN_H) y1 = SCREEN_H;+ if (x0 >= x1 || y0 >= y1) return NULL;+ Cmd *c = &cmds[ncmds++];+ c->type = (uint8_t)type, c->alpha = (uint8_t)(alpha > 255 ? 255 : alpha);+ c->x0 = (int16_t)x0, c->y0 = (int16_t)y0, c->x1 = (int16_t)x1, c->y1 = (int16_t)y1;+ return c;+}++/* ------------------------------------------------------------------ pixels */+static inline uint16_t pack(uint32_t r, uint32_t g, uint32_t b) {+ return (uint16_t)((r >> 3) << 11 | (g >> 2) << 5 | b >> 3);+}+/* premultiplied (r, g, b) with coverage a (0-255) over the pixel */+static inline void over(uint16_t *p, uint32_t r, uint32_t g, uint32_t b, uint32_t a) {+ if (a >= 252) {+ *p = pack(r, g, b);+ return;+ }+ uint32_t d = *p, k = 256 - a;+ uint32_t dr = (d >> 11) << 3 | d >> 13, dg = ((d >> 5) & 63) << 2 | ((d >> 9) & 3), db = (d & 31) << 3 | ((d >> 2) & 7);+ r += dr * k >> 8, g += dg * k >> 8, b += db * k >> 8;+ *p = pack(r > 255 ? 255 : r, g > 255 ? 255 : g, b > 255 ? 255 : b);+}+/* colour c at coverage a (0-255) over the pixel */+static inline void blend(uint16_t *p, uint16_t c, uint32_t a) {+ if (a >= 252) {+ *p = c;+ return;+ }+ uint32_t x = (c | (uint32_t)c << 16) & 0x07E0F81Fu, y = (*p | (uint32_t)*p << 16) & 0x07E0F81Fu;+ y = (y + ((x - y) * (a >> 3) >> 5)) & 0x07E0F81Fu;+ *p = (uint16_t)(y | y >> 16);+}++/* ------------------------------------------------------------------ commands */+void gfx_fill(int x, int y, int w, int h, uint16_t c, int alpha) {+ Cmd *k = add(C_FILL, x, y, x + w, y + h, alpha);+ if (k) k->fill.c = c;+}++void gfx_rrect(int x, int y, int w, int h, int r, uint16_t c, int alpha) {+ Cmd *k = add(C_RRECT, x, y, x + w, y + h, alpha);+ if (!k) return;+ /* (the corners are measured from the rectangle itself, not its clipped part) */+ k->rr.x = (float)x, k->rr.y = (float)y, k->rr.w = (float)w, k->rr.h = (float)h, k->rr.c = c, k->rr.r = (int16_t)r;+}++void gfx_vgrad(int x, int y, int w, int h, uint32_t top, uint32_t bottom) {+ Cmd *k = add(C_VGRAD, x, y, x + w, y + h, 255);+ if (!k) return;+ k->grad.top = top, k->grad.bottom = bottom, k->grad.y = (int16_t)y, k->grad.h = (int16_t)h;+}++void gfx_rows(const uint16_t *rows, int y0, int y1) {+ Cmd *k = add(C_ROWS, 0, y0, SCREEN_W, y1, 255);+ if (k) k->rows.rows = rows - y0;+}++static void corners(float x, float y, float scale, float ca, float sa, float u, float v, float *sx, float *sy) {+ *sx = x + scale * (ca * u + sa * v);+ *sy = y + scale * (-sa * u + ca * v);+}++void gfx_image_point(int id, float x, float y, float scale, float angle, float u, float v, float *sx, float *sy) {+ const Img *im = img(id);+ corners(x, y, scale, cosf(angle), sinf(angle), u - im->px4 / 4.0f, v - im->py4 / 4.0f, sx, sy);+}++/* a picture at its own size, its top-left on a pixel: copied, not filtered */+static void blit(const Img *im, int x, int y, int alpha) {+ Cmd *k = add(C_BLIT, x, y, x + im->w, y + im->h, alpha);+ if (k) k->blit.im = im, k->blit.x = (int16_t)x, k->blit.y = (int16_t)y;+}++void gfx_image(int id, float x, float y, float scale, float angle, int alpha) {+ const Img *im = img(id);+ if (scale <= 0.01f) return;+ if (angle == 0 && scale > 0.999f && scale < 1.001f) {+ blit(im, (int)floorf(x - im->px4 / 4.0f + 0.5f), (int)floorf(y - im->py4 / 4.0f + 0.5f), alpha);+ return;+ }+ float ca = cosf(angle), sa = sinf(angle), px = im->px4 / 4.0f, py = im->py4 / 4.0f;+ float xs[4], ys[4];+ corners(x, y, scale, ca, sa, -px, -py, &xs[0], &ys[0]);+ corners(x, y, scale, ca, sa, im->w - px, -py, &xs[1], &ys[1]);+ corners(x, y, scale, ca, sa, -px, im->h - py, &xs[2], &ys[2]);+ corners(x, y, scale, ca, sa, im->w - px, im->h - py, &xs[3], &ys[3]);+ float mx0 = xs[0], mx1 = xs[0], my0 = ys[0], my1 = ys[0];+ for (int i = 1; i < 4; i++) {+ if (xs[i] < mx0) mx0 = xs[i];+ if (xs[i] > mx1) mx1 = xs[i];+ if (ys[i] < my0) my0 = ys[i];+ if (ys[i] > my1) my1 = ys[i];+ }+ if (mx1 < 0 || my1 < 0 || mx0 > SCREEN_W || my0 > SCREEN_H) return;+ Cmd *k = add(C_IMAGE, (int)floorf(mx0) - 1, (int)floorf(my0) - 1, (int)ceilf(mx1) + 1, (int)ceilf(my1) + 1, alpha);+ if (!k) return;+ float is = 1.0f / scale;+ float ua = ca * is, ub = -sa * is, va = sa * is, vb = ca * is;+ /* the texel coordinates of pixel (0, 0)'s centre, half a texel back for the filter */+ float u0 = px - 0.5f + ua * (0.5f - x) + ub * (0.5f - y);+ float v0 = py - 0.5f + va * (0.5f - x) + vb * (0.5f - y);+ k->image.im = im;+ k->image.ua = (int32_t)(ua * 65536), k->image.ub = (int32_t)(ub * 65536);+ k->image.va = (int32_t)(va * 65536), k->image.vb = (int32_t)(vb * 65536);+ k->image.u0 = (int32_t)(u0 * 65536), k->image.v0 = (int32_t)(v0 * 65536);+}++void gfx_image_box(int id, int x, int y, int w, int h, int alpha) {+ const Img *im = img(id);+ if (w <= 0 || h <= 0) return;+ if (w == im->w && h == im->h) {+ blit(im, x, y, alpha);+ return;+ }+ Cmd *k = add(C_IMAGE, x, y, x + w, y + h, alpha);+ if (!k) return;+ float sx = (float)im->w / w, sy = (float)im->h / h;+ k->image.im = im;+ k->image.ua = (int32_t)(sx * 65536), k->image.ub = 0, k->image.va = 0, k->image.vb = (int32_t)(sy * 65536);+ k->image.u0 = (int32_t)((sx * (0.5f - x) - 0.5f) * 65536);+ k->image.v0 = (int32_t)((sy * (0.5f - y) - 0.5f) * 65536);+}++int gfx_text_width(int fid, const char *s) {+ const Font *f = font(fid);+ const Glyph *g = font_glyphs(f);+ int w = 0;+ for (; *s; s++) {+ int c = (uint8_t)*s - f->first;+ if (c >= 0 && c < f->count) w += g[c].adv;+ }+ return w;+}++int gfx_text(int fid, int x, int y, const char *s, uint16_t color, uint16_t outline, int align) {+ const Font *f = font(fid);+ int n = (int)strlen(s), w = gfx_text_width(fid, s);+ if (align == 1) x -= w / 2;+ else if (align == 2) x -= w;+ if (npool + n + 1 > GFX_TEXT_POOL) return w;+ Cmd *k = add(C_TEXT, x - 4, y - f->ascent - 4, x + w + 6, y + f->height - f->ascent + 4, 255);+ if (!k) return w;+ memcpy(pool + npool, s, (size_t)n + 1);+ k->text.s = pool + npool;+ npool += n + 1;+ k->text.font = (uint8_t)fid, k->text.c = color, k->text.oc = outline, k->text.x = (int16_t)x, k->text.y = (int16_t)y;+ return w;+}++void gfx_circle(float x, float y, float r, uint16_t c, int alpha) {+ Cmd *k = add(C_CIRCLE, (int)(x - r) - 1, (int)(y - r) - 1, (int)(x + r) + 2, (int)(y + r) + 2, alpha);+ if (k) k->circle.x = x, k->circle.y = y, k->circle.r = r, k->circle.c = c;+}++void gfx_ring(float x, float y, float r, float t, uint16_t c, int alpha) {+ Cmd *k = add(C_RING, (int)(x - r) - 1, (int)(y - r) - 1, (int)(x + r) + 2, (int)(y + r) + 2, alpha);+ if (k) k->circle.x = x, k->circle.y = y, k->circle.r = r, k->circle.t = t, k->circle.c = c;+}++void gfx_tube(float x0, float y0, float x1, float y1, float r, uint16_t c, int alpha) {+ float lx = x0 < x1 ? x0 : x1, hx = x0 < x1 ? x1 : x0, ly = y0 < y1 ? y0 : y1, hy = y0 < y1 ? y1 : y0;+ Cmd *k = add(C_TUBE, (int)(lx - r) - 1, (int)(ly - r) - 1, (int)(hx + r) + 2, (int)(hy + r) + 2, alpha);+ if (k) k->tube.ax = x0, k->tube.ay = y0, k->tube.bx = x1, k->tube.by = y1, k->tube.r = r, k->tube.c = c;+}++void gfx_ground_draw(void) { add(C_GROUND, 0, 0, SCREEN_W, SCREEN_H, 255); }++/* ------------------------------------------------------------------ painting a band */+__attribute__((noinline)) static void paint_fill(const Cmd *k, int y0, int y1) {+ for (int y = y0; y < y1; y++) {+ uint16_t *p = band + (y - by0) * SCREEN_W;+ if (k->alpha >= 252)+ for (int x = k->x0; x < k->x1; x++) p[x] = k->fill.c;+ else+ for (int x = k->x0; x < k->x1; x++) blend(p + x, k->fill.c, k->alpha);+ }+}++__attribute__((noinline)) static void paint_rrect(const Cmd *k, int y0, int y1) {+ float rx = k->rr.x, ry = k->rr.y, rw = k->rr.w, rh = k->rr.h, r = k->rr.r;+ for (int y = y0; y < y1; y++) {+ uint16_t *p = band + (y - by0) * SCREEN_W;+ float cy = y + 0.5f, dy = 0;+ if (cy < ry + r) dy = ry + r - cy;+ else if (cy > ry + rh - r) dy = cy - (ry + rh - r);+ for (int x = k->x0; x < k->x1; x++) {+ float cx = x + 0.5f, dx = 0;+ if (cx < rx + r) dx = rx + r - cx;+ else if (cx > rx + rw - r) dx = cx - (rx + rw - r);+ int a = k->alpha;+ if (dx > 0 && dy > 0) {+ float d = sqrtf(dx * dx + dy * dy), cov = r + 0.5f - d;+ if (cov <= 0) continue;+ if (cov < 1) a = (int)(a * cov);+ }+ blend(p + x, k->rr.c, (uint32_t)a);+ }+ }+}++static uint32_t lerp888(uint32_t a, uint32_t b, int t, int n) {+ uint32_t r = ((a >> 16 & 255) * (n - t) + (b >> 16 & 255) * t) / n;+ uint32_t g = ((a >> 8 & 255) * (n - t) + (b >> 8 & 255) * t) / n;+ uint32_t bl = ((a & 255) * (n - t) + (b & 255) * t) / n;+ return r << 16 | g << 8 | bl;+}++__attribute__((noinline)) static void paint_vgrad(const Cmd *k, int y0, int y1) {+ int top = k->grad.y, h = k->grad.h;+ for (int y = y0; y < y1; y++) {+ uint16_t c = rgb565(lerp888(k->grad.top, k->grad.bottom, y - top, h > 1 ? h - 1 : 1));+ uint16_t *p = band + (y - by0) * SCREEN_W;+ for (int x = k->x0; x < k->x1; x++) p[x] = c;+ }+}++__attribute__((noinline)) static void paint_rows(const Cmd *k, int y0, int y1) {+ for (int y = y0; y < y1; y++) {+ uint16_t c = k->rows.rows[y], *p = band + (y - by0) * SCREEN_W;+ for (int x = 0; x < SCREEN_W; x++) p[x] = c;+ }+}++/* the pixels [*x0, *x1) of a row where t = t0 + dt x stays in [lo, hi] */+static void span(int32_t t0, int32_t dt, int32_t lo, int32_t hi, int *x0, int *x1) {+ if (dt == 0) {+ if (t0 < lo || t0 > hi) *x1 = *x0;+ return;+ }+ /* x where t crosses lo and hi */+ float a = (float)(lo - t0) / dt, b = (float)(hi - t0) / dt;+ if (a > b) {+ float s = a;+ a = b, b = s;+ }+ int lo_x = (int)ceilf(a), hi_x = (int)floorf(b) + 1;+ if (lo_x > *x0) *x0 = lo_x;+ if (hi_x < *x1) *x1 = hi_x;+}++__attribute__((noinline)) static void paint_image(const Cmd *k, int y0, int y1) {+ const Img *im = k->image.im;+ const uint32_t *pal = img_pal(im);+ const uint8_t *px = img_px(im);+ int w = im->w, h = im->h;+ int32_t umax = (w - 1) << 16, vmax = (h - 1) << 16;+ uint32_t ga = k->alpha;+ for (int y = y0; y < y1; y++) {+ int32_t ur = k->image.u0 + k->image.ub * y, vr = k->image.v0 + k->image.vb * y;+ int x0 = k->x0, x1 = k->x1;+ span(ur, k->image.ua, 0, umax, &x0, &x1);+ span(vr, k->image.va, 0, vmax, &x0, &x1);+ if (x0 >= x1) continue;+ int32_t u = ur + k->image.ua * x0, v = vr + k->image.va * x0;+ uint16_t *p = band + (y - by0) * SCREEN_W + x0;+ for (int x = x0; x < x1; x++, p++, u += k->image.ua, v += k->image.va) {+ int iu = u >> 16, iv = v >> 16;+ if ((unsigned)iu > (unsigned)(w - 1) || (unsigned)iv > (unsigned)(h - 1)) continue; /* (rounding at the ends) */+ int iu1 = iu < w - 1 ? iu + 1 : iu, iv1 = iv < h - 1 ? w : 0;+ const uint8_t *r0 = px + iv * w;+ uint32_t c00 = pal[r0[iu]], c01 = pal[r0[iu1]], c10 = pal[r0[iu + iv1]], c11 = pal[r0[iu1 + iv1]];+ if (!((c00 | c01 | c10 | c11) >> 24)) continue; /* (all four see-through) */+ uint32_t fu = (u >> 12) & 15, fv = (v >> 12) & 15;+ uint32_t w11 = fu * fv, w01 = fu * (16 - fv), w10 = (16 - fu) * fv, w00 = 256 - w11 - w01 - w10;+ uint32_t rb = ((c00 & 0xFF00FF) * w00 + (c01 & 0xFF00FF) * w01 + (c10 & 0xFF00FF) * w10 + (c11 & 0xFF00FF) * w11) >> 8;+ uint32_t ag = (((c00 >> 8) & 0xFF00FF) * w00 + ((c01 >> 8) & 0xFF00FF) * w01 + ((c10 >> 8) & 0xFF00FF) * w10 ++ ((c11 >> 8) & 0xFF00FF) * w11) >> 8;+ if (ga < 255) rb = (rb & 0xFF00FF) * ga >> 8, ag = (ag & 0xFF00FF) * ga >> 8;+ uint32_t a = (ag >> 16) & 255;+ if (a < 3) continue;+ over(p, rb & 255, ag & 255, (rb >> 16) & 255, a);+ }+ }+}++__attribute__((noinline)) static void paint_blit(const Cmd *k, int y0, int y1) {+ const Img *im = k->blit.im;+ const uint32_t *pal = img_pal(im);+ const uint8_t *px = img_px(im);+ uint32_t ga = k->alpha;+ int x0 = k->x0, x1 = k->x1;+ bool solid = im->flags & IMG_OPAQUE && ga == 255;+ const uint16_t *pal565 = solid ? img_pal565(im) : NULL;+ for (int y = y0; y < y1; y++) {+ const uint8_t *src = px + (y - k->blit.y) * im->w - k->blit.x;+ uint16_t *p = band + (y - by0) * SCREEN_W;+ if (solid) {+ for (int x = x0; x < x1; x++) p[x] = pal565[src[x]];+ continue;+ }+ for (int x = x0; x < x1; x++) {+ uint32_t c = pal[src[x]], a = c >> 24;+ if (!a) continue;+ if (ga < 255) {+ uint32_t rb = (c & 0xFF00FF) * ga >> 8, g = ((c >> 8) & 0xFF00FF) * ga >> 8;+ c = (rb & 0xFF00FF) | (g & 0xFF00FF) << 8, a = c >> 24;+ }+ over(p + x, c & 255, (c >> 8) & 255, (c >> 16) & 255, a);+ }+ }+}++__attribute__((noinline)) static void paint_text(const Cmd *k, int y0, int y1) {+ const Font *f = font(k->text.font);+ const Glyph *gl = font_glyphs(f);+ const uint8_t *bits = font_bits(f);+ int pen = k->text.x;+ for (const char *s = k->text.s; *s; s++) {+ int c = (uint8_t)*s - f->first;+ if (c < 0 || c >= f->count) continue;+ const Glyph *g = &gl[c];+ int gx = pen + g->x, gy = k->text.y + g->y;+ pen += g->adv;+ int ya = gy > y0 ? gy : y0, yb = gy + g->h < y1 ? gy + g->h : y1;+ for (int y = ya; y < yb; y++) {+ const uint8_t *row = bits + g->off + (y - gy) * g->w;+ uint16_t *p = band + (y - by0) * SCREEN_W;+ for (int i = 0; i < g->w; i++) {+ int x = gx + i;+ if ((unsigned)x >= SCREEN_W) continue;+ uint8_t b = row[i];+ if (!b) continue;+ if (b & 15) blend(p + x, k->text.oc, (b & 15) * 17u);+ if (b >> 4) blend(p + x, k->text.c, (b >> 4) * 17u);+ }+ }+ }+}++__attribute__((noinline)) static void paint_circle(const Cmd *k, int y0, int y1, bool ring) {+ float cx = k->circle.x, cy = k->circle.y, r = k->circle.r, t = k->circle.t;+ for (int y = y0; y < y1; y++) {+ uint16_t *p = band + (y - by0) * SCREEN_W;+ float dy = y + 0.5f - cy;+ for (int x = k->x0; x < k->x1; x++) {+ float dx = x + 0.5f - cx, d = sqrtf(dx * dx + dy * dy), cov = r + 0.5f - d;+ if (cov <= 0) continue;+ if (ring) {+ float in = d - (r - t) + 0.5f;+ if (in <= 0) continue;+ if (in < cov) cov = in;+ }+ blend(p + x, k->circle.c, (uint32_t)(k->alpha * (cov > 1 ? 1 : cov)));+ }+ }+}++__attribute__((noinline)) static void paint_tube(const Cmd *k, int y0, int y1) {+ float ax = k->tube.ax, ay = k->tube.ay, dx = k->tube.bx - ax, dy = k->tube.by - ay, r = k->tube.r;+ float l = dx * dx + dy * dy, inv = l > 0 ? 1 / l : 0;+ for (int y = y0; y < y1; y++) {+ uint16_t *p = band + (y - by0) * SCREEN_W;+ float qy = y + 0.5f - ay;+ for (int x = k->x0; x < k->x1; x++) {+ float qx = x + 0.5f - ax, t = (qx * dx + qy * dy) * inv;+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ float ex = qx - t * dx, ey = qy - t * dy, d = ex * ex + ey * ey, e = r + 0.5f;+ if (d >= e * e) continue;+ float cov = e - sqrtf(d);+ blend(p + x, k->tube.c, (uint32_t)(k->alpha * (cov > 1 ? 1 : cov)));+ }+ }+}++/* The ground: rock or soil under the surface line (and over the ceiling's), then the surface strip along it. */+__attribute__((noinline)) static void paint_ground(int y0, int y1) {+ const Ground *g = &gfx_ground;+ const Img *gi = img(g->ground), *ci = img(g->cground);+ const uint16_t *gpal = img_pal565(gi), *cpal = img_pal565(ci);+ const uint8_t *gpx = img_px(gi), *cpx = img_px(ci);+ /* each row's line of the ground's picture, then column by column only the rows under the line (over the+ * ceiling's) */+ const uint8_t *grow[GFX_BAND], *crow[GFX_BAND];+ for (int y = y0; y < y1; y++) {+ int32_t v = g->gv0 + g->gdv * y;+ grow[y - y0] = gpx + ((v >> 16) & 127) * 128, crow[y - y0] = cpx + ((v >> 16) & 127) * 128;+ }+ for (int x = 0; x < SCREEN_W; x++) {+ int u = g->gu[x];+ int ys = (g->floor[x] + 3) >> 3; /* the first row whose centre is under the line */+ if (ys < y0) ys = y0;+ uint16_t *p = band + (ys - by0) * SCREEN_W + x;+ for (int y = ys; y < y1; y++, p += SCREEN_W) *p = gpal[grow[y - y0][u]];+ if (g->ceiling) {+ int ye = ((g->ceil[x] - 4) >> 3) + 1; /* past the last row whose centre is over the ceiling's line */+ if (ye > y1) ye = y1;+ p = band + (y0 - by0) * SCREEN_W + x;+ for (int y = y0; y < ye; y++, p += SCREEN_W) *p = cpal[crow[y - y0][u]];+ }+ }+ /* the strips: 16 rows of picture over above + below rows of the screen */+ const Img *si = img(g->surf), *cs = img(g->csurf);+ const uint32_t *spal = img_pal(si), *cspal = img_pal(cs);+ const uint8_t *spx = img_px(si), *cspx = img_px(cs);+ int span8 = (g->above + g->below) * 8, sh = si->h;+ if (span8 <= 0) return;+ for (int x = 0; x < SCREEN_W; x++) {+ for (int pass = 0; pass < 1 + g->ceiling; pass++) {+ int line = pass ? g->ceil[x] : g->floor[x];+ int top8 = pass ? line - g->below * 8 : line - g->above * 8; /* (the ceiling's strip hangs flipped) */+ int ya = (top8 >> 3) - 1, yb = ((top8 + span8) >> 3) + 1;+ if (ya < y0) ya = y0;+ if (yb > y1) yb = y1;+ for (int y = ya; y < yb; y++) {+ int t = (y * 8 + 4 - top8) * sh * 16 / span8; /* 1/16 of a strip row */+ if (t < 0 || t >= sh << 4) continue;+ int row = t >> 4;+ if (pass) row = sh - 1 - row;+ uint32_t c = pass ? cspal[cspx[row * cs->w + g->su[x]]] : spal[spx[row * si->w + g->su[x]]];+ uint32_t a = c >> 24;+ if (a < 3) continue;+ over(band + (y - by0) * SCREEN_W + x, c & 255, (c >> 8) & 255, (c >> 16) & 255, a);+ }+ }+ }+}++void gfx_end(void) {+ for (by0 = 0; by0 < SCREEN_H; by0 = by1) {+ by1 = by0 + GFX_BAND < SCREEN_H ? by0 + GFX_BAND : SCREEN_H;+ for (int i = 0; i < ncmds; i++) {+ const Cmd *k = &cmds[i];+ int y0 = k->y0 > by0 ? k->y0 : by0, y1 = k->y1 < by1 ? k->y1 : by1;+ if (y0 >= y1) continue;+ switch (k->type) {+ case C_FILL: paint_fill(k, y0, y1); break;+ case C_RRECT: paint_rrect(k, y0, y1); break;+ case C_VGRAD: paint_vgrad(k, y0, y1); break;+ case C_ROWS: paint_rows(k, y0, y1); break;+ case C_IMAGE: paint_image(k, y0, y1); break;+ case C_BLIT: paint_blit(k, y0, y1); break;+ case C_TEXT: paint_text(k, y0, y1); break;+ case C_CIRCLE: paint_circle(k, y0, y1, false); break;+ case C_RING: paint_circle(k, y0, y1, true); break;+ case C_TUBE: paint_tube(k, y0, y1); break;+ case C_GROUND: paint_ground(y0, y1); break;+ }+ }+ plat_push(0, by0, SCREEN_W, by1 - by0, band);+ }+}diff --git a/games/hillclimb/src/gfx.h b/games/hillclimb/src/gfx.hnew file mode 100644index 00000000..2dbb927a--- /dev/null+++ b/games/hillclimb/src/gfx.h@@ -0,0 +1,64 @@+/* Hill Climb Racing: drawing.+ *+ * A frame is a list of commands, rasterised a band of rows at a time (the calculator has no frame buffer for the+ * whole screen) and pushed. Commands are in screen pixels and painted in the order given. Pictures turn and scale+ * around their pivot and are sampled with bilinear filtering, so the vehicles roll and tilt smoothly. */+#ifndef HC_GFX_H+#define HC_GFX_H+#include <stdbool.h>+#include <stdint.h>+#include "plat.h"+#include "res.h"++static inline uint16_t rgb565(uint32_t rgb) { /* 0xRRGGBB */+ return (uint16_t)(((rgb >> 8) & 0xF800) | ((rgb >> 5) & 0x07E0) | ((rgb >> 3) & 0x001F));+}+#define C_BLACK 0x0000+#define C_WHITE 0xFFFF++#define GFX_BAND 24 /* rows rasterised at a time */+#define GFX_MAX_CMDS 360+#define GFX_TEXT_POOL 1024++/* the band: SCREEN_W * GFX_BAND pixels */+void gfx_init(uint16_t *band);+void gfx_begin(void);+void gfx_end(void);++/* alpha: 0 (none) to 255 */+void gfx_fill(int x, int y, int w, int h, uint16_t c, int alpha);+void gfx_rrect(int x, int y, int w, int h, int r, uint16_t c, int alpha); /* rounded corners */+void gfx_vgrad(int x, int y, int w, int h, uint32_t top, uint32_t bottom); /* 0xRRGGBB, top to bottom */+/* each row of the screen its colour (the sky), from rows[0] at y0 */+void gfx_rows(const uint16_t *rows, int y0, int y1);+/* picture id, its pivot at (x, y), `scale` screen pixels for one of its own, turned by `angle` radians+ * (counterclockwise on the screen) */+void gfx_image(int id, float x, float y, float scale, float angle, int alpha);+/* the same, its top-left at (x, y), w x h screen pixels */+void gfx_image_box(int id, int x, int y, int w, int h, int alpha);+/* text with a dark outline: y is the baseline; align 0 left, 1 centred, 2 right of x; its width */+int gfx_text(int font, int x, int y, const char *s, uint16_t color, uint16_t outline, int align);+int gfx_text_width(int font, const char *s);+void gfx_circle(float x, float y, float r, uint16_t c, int alpha);+void gfx_ring(float x, float y, float r, float t, uint16_t c, int alpha); /* a circle's edge t wide */+/* a tube from (x0, y0) to (x1, y1), r thick each side, round ends */+void gfx_tube(float x0, float y0, float x1, float y1, float r, uint16_t c, int alpha);++/* The ground of the frame, filled column by column by the game (see game.c) before gfx_ground_draw() */+typedef struct {+ int16_t floor[SCREEN_W]; /* the surface's line, screen rows x 8; past the bottom: none */+ int16_t ceil[SCREEN_W]; /* the ceiling's line x 8; above the top: none */+ uint8_t su[SCREEN_W]; /* the surface strip's column (0-255) */+ uint8_t gu[SCREEN_W]; /* the ground's column (0-127) */+ int32_t gv0, gdv; /* the ground's row at the screen's top and down each row (16.16) */+ int16_t above, below; /* rows of the surface strip above and below its line */+ uint8_t surf, ground, csurf, cground; /* pictures: the strip and the ground, under it and over the ceiling */+ bool ceiling;+ uint16_t shade; /* the ground darkens towards this colour, deeper (0: not) */+} Ground;+extern Ground gfx_ground;+void gfx_ground_draw(void);++/* screen points from a picture's own: where its pixel (u, v) lands */+void gfx_image_point(int id, float x, float y, float scale, float angle, float u, float v, float *sx, float *sy);+#endifdiff --git a/games/hillclimb/src/icon.png b/games/hillclimb/src/icon.pngnew file mode 100644index 00000000..63363fc4Binary files /dev/null and b/games/hillclimb/src/icon.png differdiff --git a/games/hillclimb/src/main.c b/games/hillclimb/src/main.cnew file mode 100644index 00000000..33dddda8--- /dev/null+++ b/games/hillclimb/src/main.c@@ -0,0 +1,45 @@+/* Hill Climb Racing for the NumWorks calculator.+ *+ * Inspired by Hill Climb Racing by Fingersoft, not affiliated with them.+ * Made by Mason Chen as part of NumPlay. */+#include "game.h"+#include "gfx.h"+#include "plat.h"++#ifndef HOST+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Hill Climb";+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;++uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */+uint32_t perf_max __attribute__((used));+static uint16_t band[SCREEN_W * GFX_BAND];++int main(void) {+ gfx_init(band);+ plat_begin();+ game_init();+ /* the game's frames at 60 a second; drawn when caught up (at most 3 updates a drawing) */+ uint32_t next = plat_millis() * 3; /* in thirds of a millisecond: 50 a frame */+ while (g_running) {+ int n = 0;+ uint32_t now = plat_millis() * 3;+ while ((int32_t)(now - next) >= 0 && n < 3 && g_running) {+ game_frame(plat_keys());+ next += 50;+ n++;+ }+ if (!g_running) break;+ if ((int32_t)(now - next) > 300) next = now; /* far behind: do not rush */+ if (n) {+ uint32_t t0 = plat_millis();+ game_draw();+ uint32_t dt = plat_millis() - t0;+ if (dt > perf_max && perf_frames > 30) perf_max = dt;+ perf_frames++;+ } else {+ plat_sleep(1);+ }+ }+ return plat_end();+}+#endifdiff --git a/games/hillclimb/src/menu.c b/games/hillclimb/src/menu.cnew file mode 100644index 00000000..9c6665ba--- /dev/null+++ b/games/hillclimb/src/menu.c@@ -0,0 +1,277 @@+/* The menus: the title, how to drive, the garage (vehicles and their upgrades) and the stages. */+#include <stdio.h>+#include <string.h>+#include "game.h"+#include "gfx.h"++static int row; /* the garage: 0 the vehicle, 1 its upgrades */+static int up_sel; /* the upgrade chosen */+static int ask; /* buying: 0 not asked, 1 the vehicle, 2 the stage */+static int shown; /* the vehicle or stage on show (it may not be owned) */+static int flash; /* frames left of a "not enough coins" */+static int bought; /* frames left of the sparkle of something bought */+static int t; /* frames on this screen */++void menu_enter(int mode) {+ g_mode = mode, ask = 0, t = 0, flash = 0;+ if (mode == MODE_GARAGE) shown = sv.vehicle, row = 0;+ if (mode == MODE_STAGES) shown = sv.stage;+}++static void begin(void) {+ if (!sv.seen_help) {+ menu_enter(MODE_HELP);+ return;+ }+ run_start(sv.vehicle, sv.stage);+ g_mode = MODE_RUN;+}++static bool pay(uint32_t price) {+ if (sv.coins < price) {+ flash = 40;+ return false;+ }+ sv.coins -= price;+ bought = 30;+ save_write();+ return true;+}++void menu_frame(uint32_t keys, uint32_t pressed) {+ (void)keys;+ t++;+ if (flash) flash--;+ if (bought) bought--;+ if (ask) {+ if (pressed & K_OK) {+ if (ask == 1 && pay(vehicles[shown].price)) sv.vehicles |= (uint16_t)(1 << shown), sv.vehicle = (uint8_t)shown;+ if (ask == 2 && pay(stages[shown].price)) sv.stages |= (uint16_t)(1 << shown), sv.stage = (uint8_t)shown;+ save_write();+ ask = 0;+ } else if (pressed & K_BACK) {+ ask = 0;+ }+ return;+ }+ switch (g_mode) {+ case MODE_TITLE:+ if (pressed & K_OK && t > 10) menu_enter(MODE_GARAGE);+ else if (pressed & K_UP) menu_enter(MODE_HELP);+ else if (pressed & K_BACK && t > 10) game_quit();+ break;+ case MODE_HELP:+ if (pressed & (K_OK | K_BACK) && t > 15) {+ bool first = !sv.seen_help;+ sv.seen_help = 1;+ save_write();+ if (first && pressed & K_OK) begin();+ else menu_enter(MODE_TITLE);+ }+ break;+ case MODE_GARAGE: {+ bool owned = sv.vehicles >> shown & 1;+ if (row == 0) {+ if (pressed & K_LEFT) shown = (shown + NVEHICLES - 1) % NVEHICLES, t = 0;+ if (pressed & K_RIGHT) shown = (shown + 1) % NVEHICLES, t = 0;+ owned = sv.vehicles >> shown & 1;+ if (owned) sv.vehicle = (uint8_t)shown;+ if (pressed & K_DOWN && owned) row = 1;+ if (pressed & K_OK) {+ if (owned) menu_enter(MODE_STAGES);+ else if (sv.coins >= vehicles[shown].price) ask = 1;+ else flash = 40;+ }+ if (pressed & K_BACK) {+ if (!owned) shown = sv.vehicle;+ menu_enter(MODE_TITLE);+ }+ } else {+ if (pressed & K_LEFT) up_sel = (up_sel + 3) % 4;+ if (pressed & K_RIGHT) up_sel = (up_sel + 1) % 4;+ if (pressed & (K_UP | K_BACK)) row = 0;+ if (pressed & K_OK) {+ uint8_t *lv = &sv.level[shown][up_sel];+ if (*lv < vehicles[shown].max[up_sel] && pay(upgrade_cost(shown, up_sel, *lv + 1))) {+ (*lv)++;+ save_write();+ }+ }+ }+ break;+ }+ case MODE_STAGES: {+ if (pressed & K_LEFT) shown = (shown + NSTAGES - 1) % NSTAGES, t = 0;+ if (pressed & K_RIGHT) shown = (shown + 1) % NSTAGES, t = 0;+ bool owned = sv.stages >> shown & 1;+ if (owned) sv.stage = (uint8_t)shown;+ if (pressed & K_OK) {+ if (owned) begin();+ else if (sv.coins >= stages[shown].price) ask = 2;+ else flash = 40;+ }+ if (pressed & K_BACK) {+ shown = sv.stage;+ menu_enter(MODE_GARAGE);+ }+ break;+ }+ }+}++/* ------------------------------------------------------------------ drawing */+static void backdrop(const char *title) {+ gfx_image_box(IMG_MENU_BG, 0, 0, SCREEN_W, SCREEN_H, 255);+ if (title) {+ gfx_fill(0, 0, SCREEN_W, 30, rgb565(0x2B2E33), 235);+ gfx_fill(0, 30, SCREEN_W, 2, rgb565(0x15171A), 255);+ gfx_text(FONT_L, 10, 24, title, C_WHITE, C_BLACK, 0);+ }+ draw_coins_counter(312, 22, sv.coins, 2);+}++static void arrows(int y) {+ int dx = (t / 8) % 2;+ gfx_text(FONT_XL, 14 - dx, y, "<", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_XL, 306 + dx, y, ">", C_WHITE, C_BLACK, 1);+}++static void price_tag(int x, int y, uint32_t price, bool can) {+ char n[20];+ format_number(n, price);+ int w = gfx_text_width(FONT_M, n) + 22;+ gfx_image(IMG_COIN_ICON, (float)(x - w / 2 + 8), (float)(y - 5), 1, 0, 255);+ gfx_text(FONT_M, x - w / 2 + 20, y, n, can ? rgb565(0xFFE14A) : rgb565(0xFF5A4A), C_BLACK, 0);+}++static void ask_box(const char *what, uint32_t price) {+ char t2[48], n[20];+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, C_BLACK, 140);+ gfx_rrect(56, 70, 208, 104, 10, rgb565(0x2A2D33), 245);+ snprintf(t2, sizeof t2, "Buy %s?", what);+ gfx_text(FONT_L, 160, 100, t2, C_WHITE, C_BLACK, 1);+ format_number(n, price);+ price_tag(160, 126, price, true);+ (void)n;+ gfx_rrect(76, 138, 80, 26, 6, rgb565(0x3DAA3D), 255);+ gfx_rrect(164, 138, 80, 26, 6, rgb565(0x8A2E2E), 255);+ gfx_text(FONT_M, 116, 157, "OK: BUY", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_M, 204, 157, "BACK", C_WHITE, C_BLACK, 1);+}++static void title_draw(void) {+ gfx_image_box(IMG_MENU_BG, 0, 0, SCREEN_W, SCREEN_H, 255);+ gfx_image(IMG_LOGO, 160, 62, 1, 0, 255);+ gfx_image(IMG_ICON_JEEP, 160, 146, 1.1f, 0, 255);+ if ((t / 25) % 2 == 0) gfx_text(FONT_L, 160, 212, "PRESS OK TO PLAY", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_S, 6, 234, "Up: how to drive", rgb565(0xB8C0C8), C_BLACK, 0);+ gfx_text(FONT_S, 314, 234, "Back: quit", rgb565(0xB8C0C8), C_BLACK, 2);+ draw_coins_counter(312, 20, sv.coins, 2);+}++static void help_draw(void) {+ backdrop("HOW TO DRIVE");+ gfx_rrect(10, 40, 300, 192, 10, rgb565(0x23262B), 225);+ gfx_image(IMG_PEDAL_BRAKE, 48, 86, 1, 0, 255);+ gfx_image(IMG_PEDAL_GAS, 272, 86, 1, 0, 255);+ gfx_text(FONT_M, 48, 132, "Left or 4", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_S, 48, 146, "brake, reverse", rgb565(0xC8CDD4), C_BLACK, 1);+ gfx_text(FONT_M, 272, 132, "Right, OK or 6", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_S, 272, 146, "gas", rgb565(0xC8CDD4), C_BLACK, 1);+ gfx_text(FONT_M, 160, 70, "In the air:", rgb565(0xFFE14A), C_BLACK, 1);+ gfx_text(FONT_S, 160, 86, "gas tilts you back,", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_S, 160, 100, "brake tilts you forward", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_S, 160, 172, "Pick up fuel cans before the tank runs dry.", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_S, 160, 186, "Bill's neck can't take a landing on his head!", C_WHITE, C_BLACK, 1);+ gfx_text(FONT_S, 160, 200, "Air time and flips earn coins. Back: pause.", C_WHITE, C_BLACK, 1);+ if ((t / 25) % 2 == 0) gfx_text(FONT_M, 160, 224, sv.seen_help ? "OK" : "OK: DRIVE!", rgb565(0xFFE14A), C_BLACK, 1);+}++static void level_bar(int x, int y, int w, int level, int max) {+ gfx_rrect(x, y, w, 7, 3, C_BLACK, 200);+ int f = (w - 2) * (level - 1) / (max - 1 > 0 ? max - 1 : 1);+ if (f > 0) gfx_rrect(x + 1, y + 1, f, 5, 2, rgb565(0x7FD63A), 255);+}++static void garage_draw(void) {+ backdrop("VEHICLE");+ const VehDef *v = &vehicles[shown];+ bool owned = sv.vehicles >> shown & 1;+ /* the vehicle, on a turntable of light */+ gfx_circle(160, 118, 66, rgb565(0x5A6F80), 60);+ gfx_image(v->icon, 160, 92 + (row == 0 && !(t & 32) ? 0 : 0), owned ? 1.15f : 1.0f, 0, owned ? 255 : 150);+ if (!owned) gfx_image(IMG_LOCK, 160, 92, 1, 0, 255);+ if (row == 0) arrows(108);+ gfx_text(FONT_L, 160, 154, v->name, row == 0 ? rgb565(0xFFE14A) : C_WHITE, C_BLACK, 1);+ char tx[48];+ if (!owned) {+ price_tag(160, 176, v->price, sv.coins >= v->price);+ gfx_text(FONT_S, 160, 196, v->about, rgb565(0xC8CDD4), C_BLACK, 1);+ gfx_text(FONT_S, 160, 230, sv.coins >= v->price ? "OK: buy" : "Not enough coins yet", flash ? rgb565(0xFF5A4A) : C_WHITE,+ C_BLACK, 1);+ return;+ }+ /* its four upgrades */+ for (int u = 0; u < 4; u++) {+ int x = 6 + u * 78, y = 164;+ bool on = row == 1 && u == up_sel;+ int lv = sv.level[shown][u], max = v->max[u];+ gfx_rrect(x, y, 74, 70, 7, on ? rgb565(0xF2B531) : rgb565(0x2A2D33), on ? 255 : 220);+ gfx_image(upgrade_icons[v->up[u]], (float)x + 20, (float)y + 21, 0.85f, 0, 255);+ snprintf(tx, sizeof tx, "%d/%d", lv, max);+ gfx_text(FONT_S, x + 70, y + 14, tx, on ? C_BLACK : C_WHITE, on ? rgb565(0xF2B531) : C_BLACK, 2);+ gfx_text(FONT_S, x + 37, y + 49, upgrade_names[v->up[u]], on ? C_BLACK : C_WHITE, on ? rgb565(0xF2B531) : C_BLACK, 1);+ level_bar(x + 6, y + 52, 62, lv, max);+ if (lv >= max) gfx_text(FONT_S, x + 37, y + 68, "MAX", rgb565(0x7FD63A), C_BLACK, 1);+ else {+ char n[20];+ format_number(n, upgrade_cost(shown, u, lv + 1));+ gfx_text(FONT_S, x + 37, y + 68, n, sv.coins >= upgrade_cost(shown, u, lv + 1) ? rgb565(0xFFE14A) : rgb565(0xFF7A6A),+ C_BLACK, 1);+ }+ }+ if (row == 0) gfx_text(FONT_S, 160, 236 - 74, "", C_WHITE, C_BLACK, 1);+ const char *hint = row == 0 ? "OK: choose a stage Down: upgrades" : flash ? "Not enough coins!" : "OK: upgrade Up: back";+ gfx_text(FONT_S, 312, 44, hint, flash ? rgb565(0xFF5A4A) : rgb565(0xC8CDD4), C_BLACK, 2);+}++static void stages_draw(void) {+ backdrop("STAGE");+ const Stage *s = &stages[shown];+ bool owned = sv.stages >> shown & 1;+ gfx_rrect(42, 46, 236, 122, 10, C_BLACK, 160);+ gfx_image_box(s->icon, 46, 50, 228, 114, 255);+ if (!owned) gfx_image_box(IMG_STAGE_LOCKED, 46, 50, 228, 114, 210);+ arrows(118);+ gfx_text(FONT_L, 160, 192, s->name, rgb565(0xFFE14A), C_BLACK, 1);+ char tx[48];+ if (owned) {+ snprintf(tx, sizeof tx, "Best with the %s: %dm", vehicles[sv.vehicle].name, sv.best[shown][sv.vehicle]);+ gfx_text(FONT_S, 160, 210, tx, rgb565(0xC8CDD4), C_BLACK, 1);+ if ((t / 25) % 2 == 0) gfx_text(FONT_M, 160, 232, "OK: START", C_WHITE, C_BLACK, 1);+ } else {+ price_tag(160, 212, s->price, sv.coins >= s->price);+ gfx_text(FONT_S, 160, 232, sv.coins >= s->price ? "OK: buy" : "Not enough coins yet", flash ? rgb565(0xFF5A4A) : C_WHITE,+ C_BLACK, 1);+ }+ /* where this stage is in the list */+ for (int i = 0; i < NSTAGES; i++)+ gfx_circle(160 - (NSTAGES - 1) * 5 + i * 10.0f, 40, i == shown ? 3 : 2, i == shown ? C_WHITE : rgb565(0x7A828C), 255);+}++void menu_draw(void) {+ switch (g_mode) {+ case MODE_TITLE: title_draw(); break;+ case MODE_HELP: help_draw(); break;+ case MODE_GARAGE: garage_draw(); break;+ case MODE_STAGES: stages_draw(); break;+ }+ if (ask == 1) ask_box(vehicles[shown].name, vehicles[shown].price);+ if (ask == 2) ask_box(stages[shown].name, stages[shown].price);+ if (bought) {+ for (int i = 0; i < 12; i++) {+ float a = (float)i * 0.52f + (float)bought * 0.1f, r = (float)(30 - bought) * 3;+ gfx_circle(160 + r * __builtin_cosf(a), 110 + r * __builtin_sinf(a), 3, rgb565(0xFFE14A), bought * 8);+ }+ }+}diff --git a/games/hillclimb/src/plat.h b/games/hillclimb/src/plat.hnew file mode 100644index 00000000..aa7795ce--- /dev/null+++ b/games/hillclimb/src/plat.h@@ -0,0 +1,40 @@+/* Hill Climb Racing: the platform (the calculator, or a computer for tests).+ *+ * plat_eadk.c: the calculator's EADK display, keyboard, time and files.+ * plat_host.c: a frame buffer that tests save as images, scripted keys and+ * simulated time (tests/play.c). */+#ifndef HC_PLAT_H+#define HC_PLAT_H+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++#define SCREEN_W 320+#define SCREEN_H 240++/* keys held now, as bits */+enum {+ K_LEFT = 1 << 0, /* Left, 4: brake and reverse */+ K_RIGHT = 1 << 1, /* Right, 6: gas */+ K_UP = 1 << 2, /* Up, 8 */+ K_DOWN = 1 << 3, /* Down, 2 */+ K_OK = 1 << 4, /* OK, EXE, 5: gas in a run, choose in menus */+ K_BACK = 1 << 5, /* Back: pause, back a screen */+ K_HOME = 1 << 6, /* Home, On/Off: save and quit */+ K_ANY = 1 << 7+};+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);+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 (the calculator's storage is RAM): 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) */+#endifdiff --git a/games/hillclimb/src/plat_eadk.c b/games/hillclimb/src/plat_eadk.cnew file mode 100644index 00000000..c0c5e6aa--- /dev/null+++ b/games/hillclimb/src/plat_eadk.c@@ -0,0 +1,38 @@+/* The calculator: EADK display, keyboard, time and files. */+#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) | KEY(eadk_key_exe) | KEY(eadk_key_five))) r |= K_OK;+ if (k & KEY(eadk_key_back)) r |= K_BACK;+ 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);+}+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/hillclimb/src/plat_host.c b/games/hillclimb/src/plat_host.cnew file mode 100644index 00000000..91a01972--- /dev/null+++ b/games/hillclimb/src/plat_host.c@@ -0,0 +1,70 @@+/* 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];+}++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];+uint8_t *plat_reserve(const char *name, uint32_t len) {+ (void)name;+ return len <= sizeof reserved ? 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/hillclimb/src/res.c b/games/hillclimb/src/res.cnew file mode 100644index 00000000..2538cecb--- /dev/null+++ b/games/hillclimb/src/res.c@@ -0,0 +1,13 @@+/* The pictures and fonts in data.bin: "HCRD", their counts, then where each one starts. */+#include "res.h"++static uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }++const Img *img(int id) {+ return (const Img *)(const void *)(hc_data + rd32(hc_data + 16 + 4 * id));+}++const Font *font(int id) {+ uint32_t nimg = rd32(hc_data + 4);+ return (const Font *)(const void *)(hc_data + rd32(hc_data + 16 + 4 * (nimg + (uint32_t)id)));+}diff --git a/games/hillclimb/src/res.h b/games/hillclimb/src/res.hnew file mode 100644index 00000000..a2cd91f4--- /dev/null+++ b/games/hillclimb/src/res.h@@ -0,0 +1,35 @@+/* Hill Climb Racing: the pictures and fonts in data.bin (tools/pack.py). */+#ifndef HC_RES_H+#define HC_RES_H+#include <stdint.h>+#include "data.h"++typedef struct {+ uint16_t w, h, ncolors, flags; /* flags 1: opaque */+ uint16_t ppm4; /* its pixels a meter x 4 (0: a picture of the menus) */+ int16_t px4, py4; /* its pivot x 4 */+ uint16_t pad;+} Img;+enum { IMG_OPAQUE = 1 };++typedef struct {+ uint8_t w, h;+ int8_t x, y; /* the bitmap's top-left from the pen, y from the baseline */+ uint8_t adv, pad[3];+ uint32_t off;+} Glyph;+typedef struct {+ uint8_t first, count, height, ascent;+} Font;++extern const uint8_t hc_data[];+const Img *img(int id);+static inline const uint32_t *img_pal(const Img *i) { return (const uint32_t *)(const void *)(i + 1); }+static inline const uint16_t *img_pal565(const Img *i) { return (const uint16_t *)(const void *)(img_pal(i) + i->ncolors); }+static inline const uint8_t *img_px(const Img *i) {+ return (const uint8_t *)(img_pal(i) + i->ncolors) + (i->flags & IMG_OPAQUE ? 2 * i->ncolors : 0);+}+const Font *font(int id);+static inline const Glyph *font_glyphs(const Font *f) { return (const Glyph *)(const void *)(f + 1); }+static inline const uint8_t *font_bits(const Font *f) { return (const uint8_t *)(font_glyphs(f) + f->count); }+#endifdiff --git a/games/hillclimb/src/run.c b/games/hillclimb/src/run.cnew file mode 100644index 00000000..31cb069c--- /dev/null+++ b/games/hillclimb/src/run.c@@ -0,0 +1,608 @@+/* The run being driven: pedals, fuel, coins, tricks, levels, the end; the camera and the picture of it all. */+#include <math.h>+#include <stdio.h>+#include <string.h>+#include "art.h"+#include "game.h"+#include "gfx.h"++Run run;++#define SX 118 /* where the camera's point is on the screen */+#define SY 138+#define PI 3.14159265f+#define FLIP_TURN (1.5f * PI) /* a flip counts once upside down and the other wheel on top: 270 degrees */++static const uint32_t air_values[] = {25, 50, 75, 100, 200, 300, 400, 500};++/* ------------------------------------------------------------------ popups and particles */+static void popup(const char *text, uint32_t value, int big) {+ int slot = 0;+ for (int i = 0; i < NPOPUPS; i++)+ if (run.pop[i].t > run.pop[slot].t) slot = i;+ for (int i = 0; i < NPOPUPS; i++)+ if (!run.pop[i].text[0]) {+ slot = i;+ break;+ }+ Popup *p = &run.pop[slot];+ snprintf(p->text, sizeof p->text, "%s", text);+ p->value = value, p->t = 0, p->big = (uint8_t)big;+}++static void particle(float x, float y, float vx, float vy, float life, float size, int kind) {+ Particle *p;+ if (run.npart < NPARTICLES) p = &run.part[run.npart++];+ else p = &run.part[run.frame % NPARTICLES];+ p->x = x, p->y = y, p->vx = vx, p->vy = vy, p->life = life, p->size = size, p->kind = (uint8_t)kind;+}++static uint32_t rnd_state = 1;+static float rndf(void) {+ rnd_state = rnd_state * 1664525u + 1013904223u;+ return (float)(rnd_state >> 8) * (1.0f / 16777216.0f);+}++/* ------------------------------------------------------------------ the run */+void run_start(int vehicle, int stg) {+ memset(&run, 0, sizeof run);+ stage_set(stg);+ stage_trees_reset();+ run.vehicle = vehicle, run.stage = stg;+ car_init(&run.car, vehicle, sv.level[vehicle], 0);+ run.fuel = run.fuel_max = car_fuel_seconds(vehicle, sv.level[vehicle]);+ run.start_x = run.car.ch.x;+ run.best = sv.best[stg][vehicle];+ run.cam_x = run.car.ch.x, run.cam_y = run.car.ch.y + 0.4f, run.cam_s = 30;+ rnd_state = 12345u + (uint32_t)stg;+}++uint32_t run_total(void) { return run.coins + run.bonus; }++static void end_run(int why) {+ if (run.over) return;+ run.over = true, run.end = why, run.over_t = 0;+}++void run_finish(void) {+ if (run.dist > (float)sv.best[run.stage][run.vehicle]) {+ sv.best[run.stage][run.vehicle] = (uint16_t)(run.dist < 65535 ? run.dist : 65535);+ run.new_best = true;+ }+ uint32_t t = run_total();+ sv.coins = sv.coins + t < sv.coins ? 0xFFFFFFFFu : sv.coins + t;+ sv.coins_earned += t;+ sv.runs++;+ sv.meters += (uint32_t)run.dist;+ sv.flips += run.flips;+ if (run.air_best_ms > sv.best_air_ms) sv.best_air_ms = run.air_best_ms;+ save_write();+}++/* the air time's worth after t seconds in the air: from a second on, a step every quarter second */+static uint32_t air_worth(float t) {+ if (t < 1.0f) return 0;+ int n = (int)((t - 1.0f) / 0.25f);+ if (n < 8) return air_values[n];+ uint32_t v = 1000 + 500 * (uint32_t)(n - 8);+ return v > 25000 ? 25000 : v;+}++static void tricks(void) {+ Car *c = &run.car;+ bool air = car_airborne(c) && !c->head_hit;+ static float last_a;+ float da = c->ch.a - last_a;+ last_a = c->ch.a;+ if (air) {+ run.air_t += 1.0f / CAR_HZ;+ run.air_rot += da;+ run.air_value = air_worth(run.air_t);+ /* a flip each time it has turned 270 degrees more (and 360 for each next one) */+ float turn = fabsf(run.air_rot) - FLIP_TURN - 2 * PI * (float)run.air_flips;+ if (turn >= 0) {+ run.air_flips++;+ run.flips++;+ run.bonus += 1000;+ popup(run.air_rot > 0 ? "BACK FLIP" : "FLIP", 1000, 1);+ }+ } else if (run.air_t > 0) {+ if (!c->head_hit && run.air_value) {+ run.bonus += run.air_value;+ popup(run.air_value >= 1000 ? "INSANE AIR TIME" : run.air_value >= 200 ? "BIG AIR TIME" : "AIR TIME",+ run.air_value, run.air_value >= 1000);+ uint32_t ms = (uint32_t)(run.air_t * 1000);+ if (ms > run.air_best_ms) run.air_best_ms = ms;+ }+ run.air_t = 0, run.air_rot = 0, run.air_flips = 0, run.air_value = 0;+ }+}++static void pickups(void) {+ Car *c = &run.car;+ /* the points of the vehicle that take things: its middle, wheels and Bill */+ float px[CAR_MAXW + 2], py[CAR_MAXW + 2];+ int n = 0;+ px[n] = c->ch.x, py[n] = c->ch.y, n++;+ car_head(c, &px[n], &py[n]), n++;+ for (int i = 0; i < c->nw; i++) px[n] = c->wh[i].x, py[n] = c->wh[i].y, n++;+ float xmin = c->ch.x - 3, xmax = c->ch.x + 3;+ /* coins */+ int k0 = (int)((xmin - 8) / COIN_SPACING), k1 = (int)((xmax + 8) / COIN_SPACING) + 1;+ for (int k = k0 < 1 ? 1 : k0; k <= k1 && k < COIN_GROUPS; k++) {+ float cx[14], cy[14];+ int val[14];+ int m = stage_coin_group(k, cx, cy, val);+ for (int i = 0; i < m; i++) {+ if (run.got[k] >> i & 1) continue;+ for (int j = 0; j < n; j++) {+ float dx = cx[i] - px[j], dy = cy[i] - py[j], r = j >= 2 ? c->wr[j - 2] + 0.35f : 1.1f;+ if (dx * dx + dy * dy < r * r) {+ run.got[k] |= (uint16_t)(1 << i);+ run.coins += (uint32_t)val[i];+ for (int s = 0; s < 3; s++) particle(cx[i], cy[i], rndf() * 2 - 1, rndf() * 2 + 1, 0.4f, 0.3f, 2);+ break;+ }+ }+ }+ }+ /* fuel */+ for (int k = 0; k < 4096; k++) {+ float fx;+ if (!stage_fuel(k, &fx) || fx > xmax + 2) break;+ if (fx < xmin - 2 || (k < 4096 && run.fuel_got[k >> 3] >> (k & 7) & 1)) continue;+ float fy = stage_floor(fx) + 0.45f;+ for (int j = 0; j < n; j++) {+ float dx = fx - px[j], dy = fy - py[j], r = j >= 2 ? c->wr[j - 2] + 0.45f : 1.2f;+ if (dx * dx + dy * dy < r * r) {+ run.fuel_got[k >> 3] |= (uint8_t)(1 << (k & 7));+ run.fuel = run.fuel_max;+ popup("FUEL", 0, 0);+ break;+ }+ }+ }+}++void run_frame(uint32_t keys) {+ Car *c = &run.car;+ run.frame++;+ bool gas = !run.over && (keys & (K_RIGHT | K_OK)), brake = !run.over && (keys & K_LEFT);+ /* the pedals go down quickly and come up a little slower, as feet do */+ run.gas += ((gas ? 1.0f : 0.0f) - run.gas) * (gas ? 0.5f : 0.35f);+ run.brake += ((brake ? 1.0f : 0.0f) - run.brake) * (brake ? 0.5f : 0.35f);+ if (run.over) run.gas = run.brake = 0;+ bool fuel = run.fuel > 0;+ /* the bridge under the vehicle sags with its weight */+ stage_bridge_load(c->ch.x, 0.35f * (vehicles[run.vehicle].mass / 300.0f));+ car_step(c, run.gas, run.brake, fuel && !c->head_hit);+ if (c->tree_broken >= 0) {+ float tx;+ if (stage_tree(c->tree_broken, &tx))+ for (int s = 0; s < 6; s++)+ particle(tx, stage_floor(tx) + 0.6f + rndf() * 1.4f, rndf() * 3, rndf() * 2, 0.7f, 0.35f, 0);+ }+ /* fuel burns while the run goes on */+ if (!run.over && run.fuel > 0) {+ run.fuel -= 1.0f / CAR_HZ;+ if (run.fuel < 0) run.fuel = 0;+ }+ /* distance and levels */+ float d = c->ch.x - run.start_x;+ if (d > run.dist) run.dist = d;+ if (!run.over)+ while (run.dist >= stage_level_end(run.level + 1)) {+ run.level++;+ uint32_t r = stage_level_reward(run.level);+ run.bonus += r;+ char t[24];+ snprintf(t, sizeof t, "LEVEL %d", run.level);+ popup(t, r, 1);+ }+ if (!run.over) {+ tricks();+ pickups();+ }+ /* Bill's neck */+ if (c->head_hit && !run.over) {+ if (fabsf(run.air_rot) >= PI * 0.75f || run.air_flips) {+ run.bonus += 2500;+ popup("NECK FLIP", 2500, 1);+ }+ end_run(END_DRIVER_DOWN);+ }+ /* out of fuel: when the vehicle has stopped */+ if (!run.over && run.fuel <= 0) {+ if (car_speed(c) < 0.6f) run.empty_t++;+ else run.empty_t = 0;+ if (run.empty_t > 90) end_run(END_OUT_OF_FUEL);+ }+ if (run.over) run.over_t++;+ /* dust from the wheels that spin on the ground, smoke from the exhaust */+ for (int i = 0; i < c->nw; i++) {+ float slip = fabsf(c->wh[i].w * c->wr[i] - (c->wh[i].vx)), sp = fabsf(c->wh[i].vx);+ if (c->ground[i] && (slip > 2.5f || sp > 6) && (run.frame + (uint32_t)i) % 3 == 0)+ particle(c->wh[i].x - c->wr[i] * 0.6f, c->wh[i].y - c->wr[i] * 0.8f, -c->wh[i].vx * 0.2f - rndf() * 2,+ 1 + rndf() * 2, 0.5f, 0.22f + rndf() * 0.12f, 0);+ }+ if (run.gas > 0.5f && fuel && run.frame % 6 == 0) {+ float ex, ey;+ car_point(c, -1.4f, 0.2f, &ex, &ey);+ particle(ex, ey, -1.2f + c->ch.vx * 0.3f, 0.6f, 0.9f, 0.25f, 1);+ }+ for (int i = 0; i < run.npart; i++) {+ Particle *p = &run.part[i];+ if (p->life <= 0) continue;+ p->life -= 1.0f / CAR_HZ;+ p->x += p->vx / CAR_HZ, p->y += p->vy / CAR_HZ;+ if (p->kind == 0) p->vy -= 6.0f / CAR_HZ;+ else if (p->kind == 1) p->size += 0.5f / CAR_HZ;+ }+ for (int i = 0; i < NPOPUPS; i++)+ if (run.pop[i].text[0] && ++run.pop[i].t > 110) run.pop[i].text[0] = 0;+ /* the camera: ahead of the vehicle as it goes, zooming out with speed */+ float sp = car_speed(c), lead = c->ch.vx * 0.13f;+ if (lead > 2.6f) lead = 2.6f;+ if (lead < -1.5f) lead = -1.5f;+ float tx = c->ch.x + lead, ty = c->ch.y + 0.4f;+ run.cam_x += (tx - run.cam_x) * 0.12f;+ run.cam_y += (ty - run.cam_y) * 0.12f;+ float ts = 30 - (sp > 22 ? 22 : sp) * 0.42f;+ run.cam_s += (ts - run.cam_s) * 0.03f;+}++/* ------------------------------------------------------------------ drawing */+static float scr_x(float wx) { return SX + (wx - run.cam_x) * run.cam_s; }+static float scr_y(float wy) { return SY - (wy - run.cam_y) * run.cam_s; }+static float wld_x(float sx) { return run.cam_x + (sx - SX) / run.cam_s; }++static uint16_t sky_rows[SCREEN_H];+static int sky_of = -1;++static void make_sky(void) {+ const Img *im = img(stage->sky);+ const uint32_t *pal = img_pal(im);+ const uint8_t *px = img_px(im);+ for (int y = 0; y < SCREEN_H; y++) {+ float t = (float)y * (float)(im->h - 1) / (SCREEN_H - 1);+ int i = (int)t;+ float f = t - (float)i;+ uint32_t a = pal[px[i]], b = pal[px[i + 1 < im->h ? i + 1 : i]];+ int r = (int)((a & 255) * (1 - f) + (b & 255) * f), g = (int)((a >> 8 & 255) * (1 - f) + (b >> 8 & 255) * f),+ bl = (int)((a >> 16 & 255) * (1 - f) + (b >> 16 & 255) * f);+ sky_rows[y] = rgb565((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)bl);+ }+ sky_of = run.stage;+}++static uint32_t hash2(uint32_t a) {+ a ^= a >> 16;+ a *= 0x7FEB352Du;+ a ^= a >> 15;+ a *= 0x846CA68Bu;+ a ^= a >> 16;+ return a;+}++static void draw_sky(void) {+ if (sky_of != run.stage) make_sky();+ gfx_rows(sky_rows, 0, SCREEN_H);+ if (stage->stars) { /* the Moon's and the alien planet's night: stars, and the Earth or a planet */+ for (uint32_t i = 0; i < 46; i++) {+ uint32_t h = hash2(i * 77 + (uint32_t)run.stage);+ float x = (float)(h % 340) - fmodf(run.cam_x * 0.6f, 340.0f), y = (float)(h >> 9 & 127);+ if (x < -10) x += 340;+ gfx_fill((int)x, (int)y, 1 + (h >> 20 & 1), 1 + (h >> 20 & 1), C_WHITE, 120 + (int)(h >> 24 & 127));+ }+ float ex = 250 - fmodf(run.cam_x * 0.05f, 400.0f);+ if (ex < -40) ex += 400;+ if (run.stage == ST_MOON) {+ gfx_circle(ex, 44, 17, rgb565(0x2F6FD6), 255);+ gfx_circle(ex - 5, 40, 7, rgb565(0x3FA34D), 255);+ gfx_circle(ex + 6, 50, 5, rgb565(0x3FA34D), 255);+ gfx_circle(ex + 3, 35, 4, rgb565(0xEAF2FF), 200);+ } else {+ gfx_circle(ex, 48, 22, rgb565(0xD8C96A), 255);+ gfx_circle(ex + 7, 42, 22, rgb565(0x2B3A2A), 230);+ }+ }+ if (stage->clouds) {+ for (int i = -1; i < 4; i++) {+ float base = run.cam_x * 0.12f;+ int k = (int)floorf(base / 130.0f) + i;+ uint32_t h = hash2((uint32_t)k * 31u + 7u);+ float x = (float)k * 130.0f - base + (float)(h % 60) + 20;+ float y = 18 + (float)(h >> 8 & 31) - (run.cam_y - 2) * 0.6f;+ gfx_image(IMG_CLOUD, x, y, 1, 0, 255);+ }+ }+}++static void draw_ground(void) {+ Ground *g = &gfx_ground;+ float s = run.cam_s;+ g->surf = stage->surf, g->ground = stage->ground, g->csurf = stage->csurf, g->cground = stage->ground;+ g->ceiling = stage->ceiling != 0;+ /* one sample every 2 columns, in between halfway */+ float fl[SCREEN_W / 2 + 2], ce[SCREEN_W / 2 + 2];+ for (int i = 0; i <= SCREEN_W / 2 + 1; i++) {+ float wx = wld_x((float)(i * 2));+ fl[i] = scr_y(stage_ground(wx));+ float c;+ ce[i] = g->ceiling && stage_ceiling(wx, &c) ? scr_y(c) : -4000;+ }+ for (int x = 0; x < SCREEN_W; x++) {+ int i = x >> 1;+ float f = (x & 1) ? (fl[i] + fl[i + 1]) * 0.5f : fl[i], c = (x & 1) ? (ce[i] + ce[i + 1]) * 0.5f : ce[i];+ if (ce[i] < -3000 || ce[i + 1] < -3000) c = ce[i];+ g->floor[x] = (int16_t)(f > 4000 ? 32000 : f < -4000 ? -32000 : f * 8);+ g->ceil[x] = (int16_t)(c > 4000 ? 32000 : c < -4000 ? -32000 : c * 8);+ float wx = wld_x((float)x + 0.5f);+ int32_t u = (int32_t)floorf(wx * 32.0f);+ g->su[x] = (uint8_t)(u & 255), g->gu[x] = (uint8_t)(u & 127);+ }+ float top = run.cam_y + SY / s; /* the world's height at the screen's top */+ g->gv0 = (int32_t)(-top * 32.0f * 65536.0f);+ g->gdv = (int32_t)(32.0f / s * 65536.0f);+ g->above = (int16_t)(0.26f * s + 0.5f), g->below = (int16_t)(0.26f * s + 0.5f);+ gfx_ground_draw();+}++static void draw_bridges(void) {+ if (stage->feature != FEAT_BRIDGES) return;+ float x0w = wld_x(-20), x1w = wld_x(SCREEN_W + 20);+ for (float x = x0w; x < x1w;) {+ float b0, b1;+ if (!stage_bridge(x, &b0, &b1)) {+ x += 2;+ continue;+ }+ float s = run.cam_s;+ /* the posts at each end, the ropes over the planks */+ for (int e = 0; e < 2; e++) {+ float px = e ? b1 : b0, py = stage_floor(px);+ gfx_tube(scr_x(px), scr_y(py - 0.3f), scr_x(px), scr_y(py + 1.3f), 0.12f * s, rgb565(0x6B4423), 255);+ }+ int n = (int)((b1 - b0) / 0.55f);+ float lx = 0, ly = 0;+ for (int i = 0; i <= n; i++) {+ float px = b0 + (b1 - b0) * (float)i / (float)n, py = stage_floor(px);+ float a = atan2f(stage_floor(px + 0.1f) - stage_floor(px - 0.1f), 0.2f);+ float sx = scr_x(px), sy = scr_y(py - 0.14f);+ gfx_image(IMG_PLANK, sx, sy, s / img(IMG_PLANK)->ppm4 * 4.0f * 0.5f, a, 255);+ float rx = scr_x(px), ry = scr_y(py + 1.0f);+ if (i) gfx_tube(lx, ly, rx, ry, 0.035f * s, rgb565(0x8A6A3A), 255);+ lx = rx, ly = ry;+ }+ x = b1 + 1;+ }+}++static void draw_trees(void) {+ if (stage->feature != FEAT_TREES) return;+ float x0w = wld_x(-40), x1w = wld_x(SCREEN_W + 40), s = run.cam_s;+ for (int k = stage_tree_first(x0w);; k++) {+ float tx;+ if (!stage_tree(k, &tx)) {+ if (k % 6 == 0 && k > stage_tree_first(x1w) + 6) break;+ continue;+ }+ if (tx > x1w) break;+ float ty = stage_floor(tx), sc = s / (img(IMG_TREE_TOP)->ppm4 / 4.0f);+ if (stage_tree_standing(k)) {+ gfx_image(IMG_TREE_TRUNK, scr_x(tx), scr_y(ty) + 2, sc, 0, 255);+ float th = img(IMG_TREE_TRUNK)->h * sc * 0.8f;+ gfx_image(IMG_TREE_TOP, scr_x(tx), scr_y(ty) - th + 4, sc, 0, 255);+ } else { /* knocked down: lying ahead */+ gfx_image(IMG_TREE_TRUNK, scr_x(tx + 0.4f), scr_y(ty + 0.2f), sc, -1.35f, 255);+ gfx_image(IMG_TREE_TOP, scr_x(tx + 1.5f), scr_y(ty + 0.25f), sc, -1.45f, 255);+ }+ }+}++static void draw_icicles(void) {+ if (stage->feature != FEAT_ICICLES) return;+ float s = run.cam_s, x0 = floorf(wld_x(-20) / 3.0f) * 3.0f, x1 = wld_x(SCREEN_W + 20);+ for (float x = x0; x < x1; x += 3.0f) {+ uint32_t h = hash2((uint32_t)(int32_t)(x * 10) + 99u);+ if (h % 3 == 0) continue;+ float px = x + (float)(h >> 8 & 255) / 256.0f * 2.5f, c;+ if (!stage_ceiling(px, &c)) continue;+ gfx_image(IMG_ICICLE, scr_x(px), scr_y(c) - 2, s / (img(IMG_ICICLE)->ppm4 / 4.0f) * (0.6f + (float)(h >> 16 & 7) * 0.06f),+ 0, 255);+ }+}++static void draw_things(void) {+ float s = run.cam_s, x0 = wld_x(-30), x1 = wld_x(SCREEN_W + 30);+ /* the flag at the best distance */+ if (run.best > 1) {+ float fx = run.start_x + run.best, fy = stage_floor(fx);+ if (fx > x0 && fx < x1) {+ gfx_tube(scr_x(fx), scr_y(fy), scr_x(fx), scr_y(fy + 2.4f), 0.05f * s, rgb565(0x3A3A3A), 255);+ gfx_image(IMG_FLAG, scr_x(fx), scr_y(fy + 2.4f), s / (img(IMG_FLAG)->ppm4 / 4.0f), 0, 255);+ }+ }+ /* fuel cans */+ for (int k = 0; k < 4096; k++) {+ float fx;+ if (!stage_fuel(k, &fx) || fx > x1) break;+ if (fx < x0 || run.fuel_got[k >> 3] >> (k & 7) & 1) continue;+ float bob = sinf((float)run.frame * 0.08f + fx) * 0.06f;+ gfx_image(IMG_FUELCAN, scr_x(fx), scr_y(stage_floor(fx) + bob), s / (img(IMG_FUELCAN)->ppm4 / 4.0f), 0, 255);+ }+ /* coins */+ int k0 = (int)((x0 - 8) / COIN_SPACING), k1 = (int)((x1 + 8) / COIN_SPACING) + 1;+ for (int k = k0 < 1 ? 1 : k0; k <= k1 && k < COIN_GROUPS; k++) {+ float cx[14], cy[14];+ int val[14];+ int m = stage_coin_group(k, cx, cy, val);+ for (int i = 0; i < m; i++) {+ if (run.got[k] >> i & 1) continue;+ int id = val[i] == 5 ? IMG_COIN5 : val[i] == 25 ? IMG_COIN25 : val[i] == 100 ? IMG_COIN100 : IMG_COIN500;+ gfx_image(id, scr_x(cx[i]), scr_y(cy[i]), s / (img(id)->ppm4 / 4.0f), 0, 255);+ }+ }+}++/* a picture at a point of the vehicle's frame, turned with it */+static void car_image(int id, float lx, float ly, float extra) {+ const Car *c = &run.car;+ float wx, wy;+ car_point(c, lx, ly, &wx, &wy);+ gfx_image(id, scr_x(wx), scr_y(wy), run.cam_s / (img(id)->ppm4 / 4.0f), c->ch.a + extra, 255);+}++static void draw_bill(const VehArt *a) {+ const Car *c = &run.car;+ if (a->legs) car_image(IMG_BILL_LEG, a->hips[0] + 0.05f, a->hips[1] + 0.02f, a->lean * 0.3f);+ car_image(IMG_BILL_BODY, a->hips[0], a->hips[1], a->lean);+ /* the head on the neck, nodding; dropped to the side once Bill is down */+ float nx = BILL_NECK_X, ny = BILL_NECK_Y, ca = cosf(a->lean), sa = sinf(a->lean);+ float lx = a->hips[0] + ca * nx - sa * ny + c->wob[0], ly = a->hips[1] + sa * nx + ca * ny + c->wob[1];+ float tilt = c->head_hit ? -0.9f : -c->wob[0] * 2.0f;+ car_image(IMG_BILL_HEAD, lx, ly, a->lean + tilt);+}++static void draw_car(void) {+ const Car *c = &run.car;+ const VehArt *a = &veh_art[run.vehicle];+ float s = run.cam_s;+ bool rider = a->legs;+ /* behind: the tank's tracks, and the bikes' swingarm */+ for (int i = 0; i < a->nlayers; i++)+ if (!a->layer[i][3]) car_image((int)a->layer[i][0], a->layer[i][1], a->layer[i][2], 0);+ if (run.vehicle == V_TANK) { /* the track around the wheels */+ float x0 = scr_x(c->wh[0].x), y0 = scr_y(c->wh[0].y), x1 = scr_x(c->wh[c->nw - 1].x), y1 = scr_y(c->wh[c->nw - 1].y);+ gfx_tube(x0, y0, x1, y1, (c->wr[0] + 0.07f) * s, rgb565(0x2A2A2A), 255);+ gfx_tube(x0, y0, x1, y1, (c->wr[0] - 0.02f) * s, rgb565(0x4A4A4A), 255);+ }+ if (a->ntubes) {+ int i = 0;+ float tx, ty;+ car_point(c, a->tube[i][0], a->tube[i][1], &tx, &ty);+ int w = (int)a->tube[i][2];+ gfx_tube(scr_x(tx), scr_y(ty), scr_x(c->wh[w].x), scr_y(c->wh[w].y), a->tube[i][4] * s,+ rgb565((uint32_t)a->tube[i][3]), 255);+ }+ if (!rider) draw_bill(a);+ car_image(a->chassis, 0, 0, 0);+ if (rider) draw_bill(a);+ for (int i = 0; i < c->nw; i++)+ gfx_image(a->wheel, scr_x(c->wh[i].x), scr_y(c->wh[i].y), s / (img(a->wheel)->ppm4 / 4.0f) * c->wr[i] / a->wheel_r[0],+ c->spin[i], 255);+ for (int i = 1; i < a->ntubes; i++) {+ float tx, ty;+ car_point(c, a->tube[i][0], a->tube[i][1], &tx, &ty);+ int w = (int)a->tube[i][2];+ gfx_tube(scr_x(tx), scr_y(ty), scr_x(c->wh[w].x), scr_y(c->wh[w].y), a->tube[i][4] * s,+ rgb565((uint32_t)a->tube[i][3]), 255);+ }+ for (int i = 0; i < a->nlayers; i++)+ if (a->layer[i][3]) car_image((int)a->layer[i][0], a->layer[i][1], a->layer[i][2], 0);+}++static void draw_particles(void) {+ float s = run.cam_s;+ for (int i = 0; i < run.npart; i++) {+ const Particle *p = &run.part[i];+ if (p->life <= 0) continue;+ int a = (int)(p->life * 400);+ if (a > 255) a = 255;+ int id = p->kind == 1 ? IMG_SMOKE : p->kind == 2 ? IMG_COIN_ICON : stage->particle;+ const Img *im = img(id);+ gfx_image(id, scr_x(p->x), scr_y(p->y), p->size * s / (float)im->w * 2.0f, p->x * 3, p->kind == 1 ? a / 2 : a);+ }+}++/* ------------------------------------------------------------------ the dashboard */+void format_number(char *out, uint32_t n) {+ char t[16];+ int k = snprintf(t, sizeof t, "%lu", (unsigned long)n), j = 0;+ for (int i = 0; i < k; i++) {+ out[j++] = t[i];+ if ((k - 1 - i) % 3 == 0 && i < k - 1) out[j++] = ',';+ }+ out[j] = 0;+}++void draw_coins_counter(int x, int y, uint32_t n, int align) {+ char t[20];+ format_number(t, n);+ int w = gfx_text_width(FONT_M, t) + 22;+ int x0 = align == 2 ? x - w : align == 1 ? x - w / 2 : x;+ gfx_image(IMG_COIN_ICON, (float)x0 + 8, (float)y - 5, 1, 0, 255);+ gfx_text(FONT_M, x0 + 20, y, t, rgb565(0xFFE14A), C_BLACK, 0);+}++static void draw_hud(void) {+ const Car *c = &run.car;+ char t[40];+ /* fuel: the can, then the gauge */+ float f = run.fuel / run.fuel_max;+ gfx_image(IMG_FUEL_ICON, 14, 13, 1, 0, 255);+ gfx_rrect(26, 7, 64, 12, 3, C_BLACK, 200);+ uint32_t col = f > 0.5f ? 0x5BE33A : f > 0.25f ? 0xF2C230 : 0xE8392E;+ int fw = (int)(60 * f + 0.5f);+ if (fw > 0) gfx_rrect(28, 9, fw, 8, 2, rgb565(col), 255);+ if (f < 0.25f && !run.over && (run.frame / 20) % 2) gfx_image(IMG_FUEL_LOW, 160, 96, 1, 0, 230);+ draw_coins_counter(8, 38, run_total(), 0);+ /* distance and the level */+ snprintf(t, sizeof t, "%dm", (int)run.dist);+ gfx_text(FONT_L, 160, 24, t, C_WHITE, C_BLACK, 1);+ float l0 = stage_level_end(run.level), l1 = stage_level_end(run.level + 1);+ float p = (run.dist - l0) / (l1 - l0);+ gfx_rrect(122, 30, 76, 6, 3, C_BLACK, 170);+ if (p > 0) gfx_rrect(123, 31, (int)(74 * (p > 1 ? 1 : p)), 4, 2, rgb565(0xFFC21A), 255);+ snprintf(t, sizeof t, "LEVEL %d", run.level + 1);+ gfx_text(FONT_S, 160, 46, t, C_WHITE, C_BLACK, 1);+ if (run.best > 1) {+ snprintf(t, sizeof t, "BEST %dm", (int)run.best);+ gfx_text(FONT_S, 312, 14, t, rgb565(0xDDE6EE), C_BLACK, 2);+ }+ /* the meters and the pedals */+ int pb = run.brake > 0.5f ? IMG_PEDAL_BRAKE_DOWN : IMG_PEDAL_BRAKE, pg = run.gas > 0.5f ? IMG_PEDAL_GAS_DOWN : IMG_PEDAL_GAS;+ gfx_image(pb, 23, 218, 1, 0, 255);+ gfx_image(pg, 297, 218, 1, 0, 255);+ float rpm = c->rpm * (run.fuel > 0 ? 1 : 0.1f), boost = car_speed(c) / (vehicles[run.vehicle].speed * 1.6f);+ if (boost > 1) boost = 1;+ for (int m = 0; m < 2; m++) {+ float mx = m ? 186 : 134, my = 216, v = m ? rpm : boost;+ gfx_image(m ? IMG_METER_RPM : IMG_METER_BOOST, mx, my, 1, 0, 255);+ gfx_image(IMG_NEEDLE, mx, my, 1, 2.2f - v * 4.4f, 255);+ }+ /* what was just earned */+ int row = 0;+ for (int i = 0; i < NPOPUPS; i++) {+ const Popup *q = &run.pop[i];+ if (!q->text[0]) continue;+ int a = q->t < 80 ? 255 : 255 - (q->t - 80) * 8;+ if (a <= 0) continue;+ char v[16];+ if (q->value) {+ format_number(v, q->value);+ snprintf(t, sizeof t, "%s +%s", q->text, v);+ } else {+ snprintf(t, sizeof t, "%s", q->text);+ }+ int y = 74 + row * 18 - (q->t < 8 ? 8 - q->t : 0);+ gfx_text(q->big ? FONT_L : FONT_M, 160, y, t, q->big ? rgb565(0xFFE14A) : C_WHITE, C_BLACK, 1);+ row++;+ }+ if (run.air_value && !run.over) {+ snprintf(t, sizeof t, "AIR TIME +%lu", (unsigned long)run.air_value);+ gfx_text(FONT_M, 160, 74 + row * 18, t, rgb565(0xBFF0FF), C_BLACK, 1);+ }+}++void run_draw(bool hud) {+ draw_sky();+ draw_ground();+ draw_icicles();+ draw_bridges();+ draw_trees();+ draw_things();+ draw_car();+ draw_particles();+ if (hud) draw_hud();+}diff --git a/games/hillclimb/src/save.c b/games/hillclimb/src/save.cnew file mode 100644index 00000000..21849fe8--- /dev/null+++ b/games/hillclimb/src/save.c@@ -0,0 +1,131 @@+/* Saves: hillclimb.sav (coins, vehicles, stages, upgrades, bests), and a copy of it in a Python script:+ * installing apps from the NumWorks website keeps only Python scripts, so the save comes back from it when the+ * file itself is gone. The copy is a comment line "#>name:base64" (the way NumPlay and its big games keep theirs). */+#include <string.h>+#include "game.h"+#include "plat.h"++#define SAVE_NAME "hillclimb.sav"+#define COPY_NAME "hillclimb_saves.py"+#define MAGIC 0x31524348u /* "HCR1" */++Save sv;++typedef struct {+ uint32_t magic, size;+ Save s;+} SaveFile;++static const char copy_head[] =+ "# Hill Climb Racing keeps a copy of your progress here, so\n"+ "# that reinstalling it doesn't erase it. If you delete this\n"+ "# file, the game writes it again: your progress stays.\n";+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++static void copy_write(void) {+ uint32_t len;+ const uint8_t *d = plat_load(SAVE_NAME, &len);+ if (!d || !len) return;+ uint32_t nl = (uint32_t)strlen(SAVE_NAME), total = 1 + (sizeof copy_head - 1) + 2 + nl + 1 + (len + 2) / 3 * 4 + 2;+ plat_remove(COPY_NAME);+ uint8_t *o = plat_reserve(COPY_NAME, total), *p = o;+ if (!o) return;+ d = plat_load(SAVE_NAME, &len); /* (making the copy may have moved the file) */+ if (!d) return;+ *p++ = 0; /* (the script's status byte: not imported) */+ memcpy(p, copy_head, sizeof copy_head - 1), p += sizeof copy_head - 1;+ *p++ = '#', *p++ = '>';+ memcpy(p, SAVE_NAME, nl), p += nl;+ *p++ = ':';+ for (uint32_t i = 0; i < len; i += 3, p += 4) {+ /* (written out: GCC 15.2 for the calculator got a loop over the four wrong, see NumPlay's+ * launcher/src/storage.c) */+ uint32_t left = len - i, v = (uint32_t)d[i] << 16 | (left > 1 ? d[i + 1] << 8 : 0) | (left > 2 ? d[i + 2] : 0);+ p[0] = (uint8_t)b64[v >> 18 & 63];+ p[1] = (uint8_t)b64[v >> 12 & 63];+ p[2] = left > 1 ? (uint8_t)b64[v >> 6 & 63] : '=';+ p[3] = left > 2 ? (uint8_t)b64[v & 63] : '=';+ }+ *p++ = '\n';+ *p++ = 0;+ plat_reserved(COPY_NAME, (uint32_t)(p - o));+}++static int b64_value(uint8_t c) {+ for (int i = 0; i < 64; i++)+ if ((uint8_t)b64[i] == c) return i;+ return -1;+}++static const uint8_t *copy_line(uint32_t *len) {+ uint32_t n, nl = (uint32_t)strlen(SAVE_NAME);+ const uint8_t *c = plat_load(COPY_NAME, &n);+ if (!c) return NULL;+ for (uint32_t i = 0; i + nl + 3 <= n; i++)+ if (c[i] == '#' && c[i + 1] == '>' && !memcmp(c + i + 2, SAVE_NAME, nl) && c[i + 2 + nl] == ':') {+ const uint8_t *l = c + i + 3 + nl;+ uint32_t m = 0;+ while (l + m < c + n && l[m] != '\n' && l[m]) m++;+ *len = m;+ return l;+ }+ return NULL;+}++void save_restore_copy(void) {+ uint32_t have, len;+ if (plat_load(SAVE_NAME, &have)) return;+ const uint8_t *l = copy_line(&len);+ if (!l || !len || len % 4) return;+ uint32_t size = len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=');+ uint8_t *out = plat_reserve(SAVE_NAME, size);+ if (!out) return;+ l = copy_line(&len);+ bool ok = l != NULL && len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=') == size;+ uint32_t o = 0;+ for (uint32_t i = 0; ok && i < len; i += 4) {+ int v0 = l[i] == '=' ? 0 : b64_value(l[i]), v1 = l[i + 1] == '=' ? 0 : b64_value(l[i + 1]);+ int v2 = l[i + 2] == '=' ? 0 : b64_value(l[i + 2]), v3 = l[i + 3] == '=' ? 0 : b64_value(l[i + 3]);+ if (v0 < 0 || v1 < 0 || v2 < 0 || v3 < 0) ok = false;+ uint32_t wd = (uint32_t)(v0 << 18 | v1 << 12 | v2 << 6 | v3);+ if (o < size) out[o++] = (uint8_t)(wd >> 16);+ if (o < size) out[o++] = (uint8_t)(wd >> 8);+ if (o < size) out[o++] = (uint8_t)wd;+ }+ if (ok && o == size) plat_reserved(SAVE_NAME, size);+ else plat_remove(SAVE_NAME);+}++static void defaults(void) {+ memset(&sv, 0, sizeof sv);+ sv.vehicles = 1, sv.stages = 1;+ for (int v = 0; v < NVEHICLES; v++)+ for (int u = 0; u < 4; u++) sv.level[v][u] = 1;+}++void save_load(void) {+ defaults();+ uint32_t len;+ const uint8_t *d = plat_load(SAVE_NAME, &len);+ if (!d || len != sizeof(SaveFile)) return;+ SaveFile f;+ memcpy(&f, d, sizeof f);+ if (f.magic != MAGIC || f.size != sizeof(Save)) return;+ sv = f.s;+ /* (whatever the file says, the first vehicle and stage are owned and levels stay in range) */+ sv.vehicles |= 1, sv.stages |= 1;+ if (sv.vehicle >= NVEHICLES || !(sv.vehicles >> sv.vehicle & 1)) sv.vehicle = 0;+ if (sv.stage >= NSTAGES || !(sv.stages >> sv.stage & 1)) sv.stage = 0;+ for (int v = 0; v < NVEHICLES; v++)+ for (int u = 0; u < 4; u++)+ if (sv.level[v][u] < 1 || sv.level[v][u] > vehicles[v].max[u]) sv.level[v][u] = 1;+}++bool save_write(void) {+ SaveFile f;+ memset(&f, 0, sizeof f);+ f.magic = MAGIC, f.size = sizeof(Save), f.s = sv;+ bool ok = plat_save(SAVE_NAME, &f, sizeof f);+ copy_write();+ return ok;+}diff --git a/games/hillclimb/src/stage.c b/games/hillclimb/src/stage.cnew file mode 100644index 00000000..3ed5a932--- /dev/null+++ b/games/hillclimb/src/stage.c@@ -0,0 +1,250 @@+/* The stages (stage.h): their ground, ceilings, bridges, trees, coins, fuel and levels. */+#include <math.h>+#include "data.h"+#include "stage.h"++/* name, price, gravity, friction; sky, surface, ground, ceiling's surface, icon, particle; ceiling, feature, clouds,+ * stars; seed; the four noises; a cave's height; fuel; coins; levels; the surface's colour. The prices, the+ * levels' lengths and rewards, fuel spacing and where the big coins start are the game's (Hill Climb Racing Wiki). */+const Stage stages[NSTAGES] = {+ {"Countryside", 0, 9.8f, 1.0f, IMG_SKY, IMG_SURF_COUNTRY, IMG_GROUND_COUNTRY, IMG_SURF_CAVE, IMG_STAGE_COUNTRY,+ IMG_GRASS, 0, FEAT_NONE, 1, 0, 11,+ {64, 24, 8.5f, 2.6f}, {4.5f, 1.8f, 0.35f, 0}, {5, 3, 1.1f, 0.22f}, {12, 6, 2.2f, 0.42f}, 0, 0,+ 90, 90, 0, 90, 100, 200, 422, 5613, 200, 200, 5000, 3000, 0x7CC62B},+ {"Desert", 35000, 9.8f, 0.9f, IMG_SKY, IMG_SURF_DESERT, IMG_GROUND_DESERT, IMG_SURF_CAVE, IMG_STAGE_DESERT,+ IMG_DIRT, 0, FEAT_BRIDGES, 1, 0, 23,+ {70, 26, 9, 3.2f}, {3, 1.4f, 0.2f, 0}, {5, 3.2f, 0.8f, 0.12f}, {13, 7, 1.8f, 0.3f}, 0, 0,+ 90, 90, 0, 90, 100, 220, 480, 6695, 200, 0, 3000, 2000, 0xE8D99A},+ {"Arctic", 75000, 9.8f, 0.42f, IMG_SKY, IMG_SURF_ARCTIC, IMG_GROUND_ARCTIC, IMG_SURF_CAVE, IMG_STAGE_ARCTIC,+ IMG_SNOW, 0, FEAT_NONE, 1, 0, 11,+ {64, 24, 8.5f, 2.6f}, {4.5f, 1.8f, 0.35f, 0}, {5, 3, 1.1f, 0.22f}, {12, 6, 2.2f, 0.42f}, 0, 0,+ 90, 90, 4, 200, 90, 160, 270, 3604, 200, 0, 6000, 2000, 0xF2F6FA},+ {"Highway", 125000, 9.8f, 1.1f, IMG_SKY_HIGHWAY, IMG_SURF_HIGHWAY, IMG_GROUND_HIGHWAY, IMG_SURF_CAVE,+ IMG_STAGE_HIGHWAY, IMG_SMOKE, 0, FEAT_NONE, 1, 0, 37,+ {110, 40, 12, 3}, {0.4f, 0.2f, 0, 0}, {3.2f, 2, 0.35f, 0.05f}, {16, 8, 1.4f, 0.16f}, 0, 0,+ 150, 160, 18, 650, 120, 260, 600, 6090, 600, 300, 17000, 7500, 0x6E6E6E},+ {"Cave", 150000, 9.8f, 1.0f, IMG_SKY_CAVE, IMG_SURF_CAVE, IMG_GROUND_COUNTRY, IMG_SURF_CAVE, IMG_STAGE_CAVE,+ IMG_ROCKS, 1, FEAT_NONE, 0, 0, 41,+ {48, 18, 7, 2.4f}, {1.8f, 0.8f, 0.25f, 0.05f}, {3, 2.4f, 1, 0.2f}, {7, 4.4f, 1.8f, 0.4f}, 4.3f, 2.2f,+ 150, 120, 0, 150, 90, 180, 300, 4143, 300, 0, 11000, 9000, 0xB7B2A8},+ {"Moon", 175000, 2.6f, 0.9f, IMG_SKY_MOON, IMG_SURF_MOON, IMG_GROUND_MOON, IMG_SURF_CAVE, IMG_STAGE_MOON,+ IMG_SMOKE, 0, FEAT_NONE, 0, 1, 53,+ {56, 20, 7, 2.2f}, {3, 1.4f, 0.4f, 0.04f}, {4.5f, 3, 1.2f, 0.25f}, {12, 6.5f, 2.4f, 0.5f}, 0, 0,+ 90, 90, 0, 90, 80, 160, 272, 4500, 200, 300, 10000, 12000, 0xB9BAD8},+ {"Mars", 250000, 4.6f, 0.95f, IMG_SKY_MARS, IMG_SURF_MARS, IMG_GROUND_MARS, IMG_SURF_MARS, IMG_STAGE_MARS,+ IMG_ROCKS_MARS, 2, FEAT_NONE, 0, 0, 67,+ {60, 22, 8, 2.6f}, {2.4f, 1.2f, 0.3f, 0.04f}, {4, 2.6f, 1, 0.2f}, {10, 5.5f, 2, 0.42f}, 4.8f, 2.4f,+ 150, 150, 10, 420, 90, 180, 302, 4800, 200, 300, 10000, 12000, 0xC77B5A},+ {"Alien Planet", 750000, 9.8f, 0.85f, IMG_SKY_FOREST, IMG_SURF_ALIEN, IMG_GROUND_ALIEN, IMG_SURF_ALIEN,+ IMG_STAGE_ALIEN, IMG_SLIME, 0, FEAT_NONE, 0, 1, 71,+ {44, 19, 7, 2.2f}, {4, 1.8f, 0.4f, 0.05f}, {6, 3.5f, 1.3f, 0.25f}, {13, 7, 2.6f, 0.5f}, 0, 0,+ 120, 120, 8, 320, 90, 180, 300, 4000, 300, 0, 15000, 12000, 0x6FA34A},+ {"Arctic Cave", 800000, 9.8f, 0.45f, IMG_SKY_ARCTIC_CAVE, IMG_SURF_ARCTIC, IMG_GROUND_ARCTIC, IMG_SURF_ARCTIC,+ IMG_STAGE_ARCTIC_CAVE, IMG_SNOW, 1, FEAT_ICICLES, 0, 0, 83,+ {50, 19, 7, 2.4f}, {1.8f, 0.8f, 0.25f, 0.05f}, {3, 2.4f, 1, 0.2f}, {7, 4.4f, 1.8f, 0.4f}, 4.6f, 2.2f,+ 120, 120, 5, 260, 90, 180, 300, 4000, 300, 0, 15000, 12000, 0xEAF3F8},+ {"Forest", 850000, 9.8f, 1.0f, IMG_SKY_FOREST, IMG_SURF_FOREST, IMG_GROUND_FOREST, IMG_SURF_CAVE,+ IMG_STAGE_FOREST, IMG_GRASS, 0, FEAT_TREES, 1, 0, 97,+ {52, 20, 7.5f, 2.6f}, {3, 1.5f, 0.3f, 0.02f}, {5, 3, 1.1f, 0.22f}, {12, 6.5f, 2.2f, 0.42f}, 0, 0,+ 90, 90, 0, 90, 90, 180, 300, 4500, 200, 250, 10000, 10000, 0x4E9A2E},+};++const Stage *stage = &stages[0];+static int stage_id;+void stage_set(int s) { stage = &stages[s], stage_id = s; }++/* ------------------------------------------------------------------ noise */+static uint32_t hash(uint32_t a, uint32_t b) {+ uint32_t h = a * 0x9E3779B1u ^ (b + 0x7F4A7C15u) * 0x85EBCA77u;+ h ^= h >> 15;+ h *= 0x2C1B3C6Du;+ h ^= h >> 12;+ h *= 0x297A2D39u;+ h ^= h >> 15;+ return h;+}+static float rnd(uint32_t a, uint32_t b) { return (float)(hash(a, b) >> 8) * (1.0f / 8388608.0f) - 1.0f; } /* -1..1 */+static float frnd(uint32_t a, uint32_t b) { return (float)(hash(a, b) >> 8) * (1.0f / 16777216.0f); } /* 0..1 */++/* a smooth curve through a hashed height at every whole t (Catmull-Rom) */+static float noise(uint32_t seed, float t) {+ float f = floorf(t);+ int32_t i = (int32_t)f;+ float u = t - f;+ float p0 = rnd(seed, (uint32_t)(i - 1)), p1 = rnd(seed, (uint32_t)i), p2 = rnd(seed, (uint32_t)(i + 1)),+ p3 = rnd(seed, (uint32_t)(i + 2));+ return p1 + 0.5f * u * (p2 - p0 + u * (2 * p0 - 5 * p1 + 4 * p2 - p3 + u * (3 * (p1 - p2) + p3 - p0)));+}++static float smoothstep(float a, float b, float x) {+ float t = (x - a) / (b - a);+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ return t * t * (3 - 2 * t);+}++/* the hills: the noises, growing with the distance, after a flat start; `from` leaves out the large ones */+static float hills(float x, int from, int to) {+ if (x <= 12) return 0;+ float km = x * 0.001f, h = 0;+ for (int o = from; o < to; o++) {+ float a = stage->amp0[o] + stage->grow[o] * km;+ if (a > stage->amax[o]) a = stage->amax[o];+ if (a > 0) h += a * noise(stage->seed * 4 + (uint32_t)o, x / stage->len[o]);+ }+ return h * smoothstep(12, 70, x);+}++/* Highway: the road starts flat and only now and then a hill */+static float road(float x) {+ float h = hills(x, 0, 4);+ return x < 600 ? h * smoothstep(0, 600, x) * 0.7f : h;+}++/* ------------------------------------------------------------------ bridges */+static float load_x = -1e9f, load_d;+void stage_bridge_load(float x, float depth) { load_x = x, load_d = depth; }++/* bridge k: from x0 to x1 (k from 0) */+static void bridge_k(int k, float *x0, float *x1) {+ *x0 = 340.0f + (float)k * 300.0f + frnd(stage->seed, 9000u + (uint32_t)k) * 120.0f;+ *x1 = *x0 + 14.0f + frnd(stage->seed, 9500u + (uint32_t)k) * 10.0f;+}++bool stage_bridge(float x, float *x0, float *x1) {+ if (stage->feature != FEAT_BRIDGES || x < 300) return false;+ int k = (int)((x - 340.0f) / 300.0f);+ for (int j = k - 1; j <= k; j++) {+ if (j < 0) continue;+ bridge_k(j, x0, x1);+ if (x >= *x0 && x <= *x1) return true;+ }+ return false;+}++static float base_floor(float x) { return stage_id == ST_HIGHWAY ? road(x) : hills(x, 0, 4); }++/* the bridge's planks: a rope's sag between its ends, and a dip under the vehicle */+static float bridge_y(float x, float x0, float x1) {+ float t = (x - x0) / (x1 - x0), y0 = base_floor(x0), y1 = base_floor(x1);+ float sag = (x1 - x0) * 0.045f * sinf(3.14159265f * t);+ float d = (x - load_x) / 2.5f;+ float dip = d > -3 && d < 3 ? load_d * expf(-d * d) * sinf(3.14159265f * t) : 0;+ return y0 + (y1 - y0) * t - sag - dip;+}++float stage_floor(float x) {+ float x0, x1;+ if (stage_bridge(x, &x0, &x1)) return bridge_y(x, x0, x1);+ return base_floor(x);+}++float stage_ground(float x) {+ float x0, x1, h = base_floor(x);+ if (!stage_bridge(x, &x0, &x1)) return h;+ float t = (x - x0) / (x1 - x0), b = bridge_y(x, x0, x1) - 0.4f;+ if (h > b) h = b;+ return h - 9.0f * powf(sinf(3.14159265f * t), 0.35f);+}++/* ------------------------------------------------------------------ ceilings */+#define TUNNEL_START 260.0f+#define TUNNEL_EVERY 520.0f+#define TUNNEL_LEN 170.0f++bool stage_ceiling(float x, float *y) {+ if (!stage->ceiling) return false;+ float lift = 0;+ if (stage->ceiling == 2) { /* Mars: tunnels now and then, their roof coming down over 30 m at each end */+ float p = x - TUNNEL_START;+ if (p < -30) return false;+ p = fmodf(p + 30, TUNNEL_EVERY) - 30;+ if (p > TUNNEL_LEN + 30) return false;+ float in = p < 0 ? (p + 30) / 30 : p > TUNNEL_LEN ? (TUNNEL_LEN + 30 - p) / 30 : 1;+ lift = (1 - smoothstep(0, 1, in)) * 40;+ } else if (x < 8) {+ lift = (8 - x) * 0.4f; /* (the cave's mouth over the start) */+ }+ /* over the large hills (the small bumps come closer to it), with its own unevenness */+ float c = hills(x, 0, 2) + stage->clear + stage->clear_var * (0.5f + 0.5f * noise(stage->seed * 7 + 1, x / 13.0f)) ++ 0.35f * noise(stage->seed * 7 + 2, x / 3.1f);+ float f = hills(x, 0, 4) + 2.7f; /* never lower than a vehicle needs */+ *y = (c > f ? c : f) + lift;+ return true;+}++/* ------------------------------------------------------------------ trees: in bunches */+#define TREE_BUNCH 70.0f+bool stage_tree(int k, float *x) {+ if (stage->feature != FEAT_TREES || k < 0) return false;+ int b = k / 6, i = k % 6;+ int n = 2 + (int)(frnd(stage->seed, 7000u + (uint32_t)b) * 5); /* 2 to 6 trees in a bunch */+ if (i >= n) return false;+ *x = 120.0f + (float)b * TREE_BUNCH + frnd(stage->seed, 7500u + (uint32_t)b) * 20.0f + (float)i * 2.2f;+ return true;+}+static uint8_t fallen[TREES_MAX / 8];+void stage_trees_reset(void) {+ for (unsigned i = 0; i < sizeof fallen; i++) fallen[i] = 0;+}+bool stage_tree_standing(int k) { return k < 0 || k >= TREES_MAX || !(fallen[k >> 3] >> (k & 7) & 1); }+void stage_tree_fall(int k) {+ if (k >= 0 && k < TREES_MAX) fallen[k >> 3] |= (uint8_t)(1 << (k & 7));+}+int stage_tree_first(float x) {+ int b = (int)((x - 120.0f - 30.0f) / TREE_BUNCH);+ return b < 0 ? 0 : b * 6;+}++/* ------------------------------------------------------------------ coins */+int stage_coin_group(int k, float *xs, float *ys, int *vals) {+ if (k < 1 || k >= COIN_GROUPS) return 0;+ float x = (float)k * COIN_SPACING + 8.0f, d = x;+ int n = 4 + (k > 48 ? 4 : k / 12);+ uint32_t h = hash(stage->seed + 3u, (uint32_t)k);+ int value = d < stage->coin25 ? 5 : d < stage->coin100 ? 25 : d < stage->coin500 ? 100 : 500;+ if (value == 500 && d < stage->all500) {+ float share = (d - stage->coin500) / (stage->all500 - stage->coin500);+ if ((float)(h & 1023) / 1024.0f > share * 0.9f + 0.06f) value = 100;+ }+ int rows = (h >> 12) % 5 == 0 && k > 10 ? 2 : 1;+ if (n > 7 && rows == 2) n = 7;+ float cx = x - (n - 1) * 0.42f;+ int m = 0;+ for (int r = 0; r < rows; r++)+ for (int i = 0; i < n; i++) {+ float px = cx + (float)i * 0.84f;+ float g = stage_floor(px), cy = 1.05f + (float)r * 0.84f;+ float top;+ if (stage_ceiling(px, &top) && g + cy > top - 0.5f) cy = (top - g) * 0.5f;+ xs[m] = px, ys[m] = g + cy, vals[m] = value, m++;+ }+ return m;+}++/* ------------------------------------------------------------------ fuel */+bool stage_fuel(int k, float *x) {+ if (k < 0 || k > 4000) return false;+ if (stage_id == ST_CAVE) { /* 150 m, 120 m, 90 m, again */+ static const float gaps[3] = {150, 120, 90};+ float p = 0;+ for (int i = 0; i <= k; i++) p += gaps[i % 3];+ *x = p;+ return true;+ }+ /* the gaps grow by fuel_grow a can, up to fuel_max: a sum in closed form */+ float g0 = stage->fuel_gap, dg = stage->fuel_grow, gmax = stage->fuel_max;+ int ramp = dg > 0 ? (int)((gmax - g0) / dg) : 0;+ if (ramp < 0) ramp = 0;+ float p;+ if (k <= ramp) p = (float)k * g0 + dg * (float)k * (float)(k + 1) * 0.5f;+ else p = (float)ramp * g0 + dg * (float)ramp * (float)(ramp + 1) * 0.5f + (float)(k - ramp) * gmax;+ *x = stage->fuel_first + p;+ return true;+}++/* ------------------------------------------------------------------ levels */+float stage_level_end(int n) {+ /* each one lvl_inc longer than the last */+ return (float)n * stage->lvl_len + stage->lvl_inc * (float)n * (float)(n - 1) * 0.5f;+}+uint32_t stage_level_reward(int n) { return stage->lvl_reward + stage->lvl_reward_inc * (uint32_t)(n - 1); }diff --git a/games/hillclimb/src/stage.h b/games/hillclimb/src/stage.hnew file mode 100644index 00000000..538a25ac--- /dev/null+++ b/games/hillclimb/src/stage.h@@ -0,0 +1,70 @@+/* Hill Climb Racing: the stages, their ground and what lies along it.+ *+ * A stage's ground is the same on every run: a sum of smooth noises (each a Catmull-Rom curve through hashed+ * heights) whose size grows with the distance, so the hills get steeper and bumpier the further you go. Caves+ * have a ceiling; the Desert has rope bridges over canyons, the Forest trees to break through. Coins come every+ * 30 m, fuel cans at the stage's own spacing, and each stretch of the road is a level with its reward. */+#ifndef HC_STAGE_H+#define HC_STAGE_H+#include <stdbool.h>+#include <stdint.h>++enum { ST_COUNTRYSIDE, ST_DESERT, ST_ARCTIC, ST_HIGHWAY, ST_CAVE, ST_MOON, ST_MARS, ST_ALIEN, ST_ARCTIC_CAVE,+ ST_FOREST, NSTAGES };+enum { FEAT_NONE, FEAT_BRIDGES, FEAT_TREES, FEAT_ICICLES };++typedef struct {+ const char *name;+ uint32_t price;+ float gravity, friction;+ uint8_t sky, surf, ground, csurf, icon, particle;+ uint8_t ceiling; /* 0 none, 1 all along (a cave), 2 tunnels now and then */+ uint8_t feature, clouds, stars;+ uint32_t seed;+ float len[4], amp0[4], grow[4], amax[4]; /* the noises: wavelength, size at the start, + per km, at most */+ float clear, clear_var; /* a cave's height over its floor */+ float fuel_first, fuel_gap, fuel_grow, fuel_max; /* the first can, the gap, its growth per can, at most */+ float coin25, coin100, coin500, all500; /* where coins of each value start */+ float lvl_len, lvl_inc; /* a level's length and how much longer each next one is */+ uint32_t lvl_reward, lvl_reward_inc;+ uint32_t surf_color; /* the surface's colour (particles, the map) */+} Stage;++extern const Stage stages[NSTAGES];+extern const Stage *stage; /* the stage being driven */+void stage_set(int s);++/* the ground under x (meters), what wheels drive on: bridges count */+float stage_floor(float x);+/* the ground drawn under x: below a bridge, the canyon's floor */+float stage_ground(float x);+/* the ceiling over x, if there is one there */+bool stage_ceiling(float x, float *y);+/* the start: a wall behind it */+#define STAGE_WALL -6.0f++/* bridges: the one over x (its ends), or false */+bool stage_bridge(float x, float *x0, float *x1);+/* how the bridge under the vehicle gives way: its weight at x (set each frame) */+void stage_bridge_load(float x, float depth);++/* trees: the k-th tree's place (false past the stage's end); broken ones are kept in a bit set */+bool stage_tree(int k, float *x);+int stage_tree_first(float x); /* the first tree at or after x */+#define TREES_MAX 4800+void stage_trees_reset(void); /* all standing again (a new run) */+bool stage_tree_standing(int k);+void stage_tree_fall(int k);+#define TREE_H 2.4f+#define TREE_R 0.16f++/* coins: group k's coins (at most 14); value of a coin; positions */+#define COIN_GROUPS 2048+#define COIN_SPACING 30.0f+int stage_coin_group(int k, float *x, float *y, int *value); /* how many, their places and values */+/* fuel cans: the k-th one's x, k from 0; false past the last */+bool stage_fuel(int k, float *x);+/* levels: where level n (1, 2...) ends and its reward */+float stage_level_end(int n);+uint32_t stage_level_reward(int n);+#endifdiff --git a/games/hillclimb/src/vehicle.c b/games/hillclimb/src/vehicle.cnew file mode 100644index 00000000..d5a42fef--- /dev/null+++ b/games/hillclimb/src/vehicle.c@@ -0,0 +1,43 @@+/* The vehicles (vehicle.h). Their prices, upgrades, the upgrades' last levels and prices are the game's (Hill+ * Climb Racing Wiki); how they drive is tuned to match it: the Hill Climber light and tippy, rear-wheel driven+ * until its 4WD is upgraded; the bike quick to flip; the Monster Truck's big soft wheels; the Race Car fast and low;+ * the Tank slow, heavy and gripping everything. */+#include "data.h"+#include "vehicle.h"++const char *const upgrade_names[NUPKINDS] = {"Engine", "Suspension", "Tires", "4WD", "Air Control", "Downforce",+ "Fuel", "Tracks"};+const uint8_t upgrade_icons[NUPKINDS] = {IMG_UP_ENGINE, IMG_UP_SUSPENSION, IMG_UP_TIRES, IMG_UP_AWD, IMG_UP_AIR,+ IMG_UP_DOWNFORCE, IMG_UP_FUEL, IMG_UP_TIRES};++const VehDef vehicles[NVEHICLES] = {+ {"Hill Climber", "Bill's trusty jeep. Upgrade its 4WD to climb anything.", 0, IMG_ICON_JEEP,+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AWD}, {13, 14, 16, 10}, {1000, 1000, 1000, 1000},+ 300, 24, {0.02f, 0.38f}, 0.95f, 0.14f, 0.16f, 0.55f, 640, 13.5f, 0, 0.95f, 1150, 40, 0},+ {"Motocross Bike", "Race the hills with this impressive turboed motocross bike.", 75000, IMG_ICON_BIKE,+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AIR}, {12, 14, 16, 10}, {1500, 1000, 1000, 3000},+ 150, 14, {-0.05f, 0.55f}, 0.62f, 0.13f, 0.18f, 0.5f, 330, 15.5f, 0, 1.0f, 420, 40, 0},+ {"Monster Truck", "With large wheels and a supercharged engine this car really gives a new experience for Hill "+ "Climbing!", 100000, IMG_ICON_MONSTER,+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AWD}, {13, 14, 15, 10}, {1500, 1200, 1200, 1500},+ 340, 48, {0.0f, 0.45f}, 1.05f, 0.26f, 0.3f, 0.45f, 1250, 14.5f, 0, 1.0f, 1500, 40, 0},+ {"Quad Bike", "4x4 quad bike with almost the same agility as the bike offers you a different ride.", 175000,+ IMG_ICON_QUAD, {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AIR}, {13, 14, 16, 10}, {1500, 1200, 1200, 2500},+ 190, 20, {0.0f, 0.5f}, 0.7f, 0.18f, 0.22f, 0.5f, 420, 15, 1.0f, 1.0f, 520, 40, 0},+ {"Race Car", "High power and aerodynamic ultimate hill climbing vehicle. Upgrade downforce to make this car "+ "follow the road like a magnet.", 250000, IMG_ICON_RACE,+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_DOWNFORCE}, {12, 14, 16, 12}, {1500, 1500, 1500, 2500},+ 270, 18, {0.05f, 0.18f}, 1.05f, 0.06f, 0.08f, 0.6f, 620, 21, 0, 1.05f, 900, 40, 9.0f},+ {"Rally Car", "Powerful engine and downforce upgraded provide the most ultimate combination for hill climbing.",+ 750000, IMG_ICON_RALLY, {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_DOWNFORCE}, {14, 14, 17, 10},+ {2000, 2000, 2000, 3000},+ 320, 22, {0.05f, 0.3f}, 1.0f, 0.11f, 0.13f, 0.6f, 820, 20, 0.6f, 1.05f, 1000, 40, 8.0f},+ {"Dune Buggy", "Quick, good traction and handy hill climbing vehicle!", 800000, IMG_ICON_BUGGY,+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_FUEL}, {15, 15, 15, 20}, {3000, 3000, 3000, 3000},+ 260, 22, {0.1f, 0.32f}, 0.95f, 0.17f, 0.22f, 0.5f, 760, 18, 0.8f, 1.15f, 900, 52, 0},+ {"Tank", "It's a tank!", 1000000, IMG_ICON_TANK,+ {UP_ENGINE, UP_SUSPENSION, UP_TRACKS, UP_FUEL}, {15, 15, 15, 20}, {3000, 3000, 3000, 3000},+ 900, 30, {0.0f, 0.42f}, 1.15f, 0.08f, 0.1f, 0.7f, 520, 9.5f, 1.0f, 1.45f, 2600, 40, 0},+};++uint32_t upgrade_cost(int v, int u, int level) { return (uint32_t)vehicles[v].cost[u] * (uint32_t)(level * level); }diff --git a/games/hillclimb/src/vehicle.h b/games/hillclimb/src/vehicle.hnew file mode 100644index 00000000..c13f54ab--- /dev/null+++ b/games/hillclimb/src/vehicle.h@@ -0,0 +1,30 @@+/* Hill Climb Racing: the vehicles, their upgrades and how they drive (car.c). */+#ifndef HC_VEHICLE_H+#define HC_VEHICLE_H+#include <stdbool.h>+#include <stdint.h>++enum { V_JEEP, V_BIKE, V_MONSTER, V_QUAD, V_RACE, V_RALLY, V_BUGGY, V_TANK, NVEHICLES };+enum { UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AWD, UP_AIR, UP_DOWNFORCE, UP_FUEL, UP_TRACKS, NUPKINDS };++typedef struct {+ const char *name, *about;+ uint32_t price;+ uint8_t icon;+ uint8_t up[4], max[4]; /* its four upgrades and their last levels */+ uint16_t cost[4]; /* level L costs cost x L x L coins */+ float mass, wmass; /* the chassis with Bill, each wheel (kg) */+ float com[2]; /* the centre of mass, from the picture's origin (meters) */+ float radius; /* the chassis' radius of gyration (meters) */+ float sag, droop, zeta; /* the springs: how far they settle, how far wheels hang, damping ratio */+ float torque, speed; /* the engine at level 1: the most torque on a wheel (N m), top speed (m/s) */+ float awd; /* torque on the other wheels than the rear (0 to 1) at level 1 */+ float grip, air, fuel; /* tyre grip; turning in the air (N m); seconds of fuel */+ float downforce; /* with the upgrade at its last level: N for 1 (m/s)^2 */+} VehDef;++extern const VehDef vehicles[NVEHICLES];+extern const char *const upgrade_names[NUPKINDS];+extern const uint8_t upgrade_icons[NUPKINDS];+uint32_t upgrade_cost(int v, int u, int level); /* the price of reaching `level` (2 and up) */+#endifdiff --git a/games/hillclimb/tests/play.c b/games/hillclimb/tests/play.cnew file mode 100644index 00000000..ca6ab905--- /dev/null+++ b/games/hillclimb/tests/play.c@@ -0,0 +1,130 @@+/* Plays Hill Climb Racing on a computer, with scripted keys, and saves frames.+ *+ * play [--frames N] [--keys "10-40:right,50:ok,..."] [--shots 30,60|every:N] [--out DIR] [--saves DIR]+ * [--run STAGE,VEHICLE] [--levels E,S,T,A] [--coins N] [--auto] [--trace N]+ *+ * Keys: left right up down ok back home. "a-b:key" holds the key from frame a to b, "a:key" for one frame.+ * --run starts a run on that stage with that vehicle, past the menus; --auto then drives it like a player would+ * (gas, and the pedals to land on the wheels). Screenshots are DIR/shot_<frame>.ppm.+ * At the end it prints the state: END mode M dist D coins C total T over O end E level L flips F. */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include "../src/game.h"+#include "../src/gfx.h"++extern uint32_t host_keys, host_time;+void host_shot(const char *path);+void host_save_dir(const char *d);++typedef struct { int a, b; uint32_t k; } Hold;+static Hold holds[4096];+static int nholds;+static int shots[4096], nshots, every;++static uint32_t key_of(const char *s) {+ static const char *const names[] = {"left", "right", "up", "down", "ok", "back", "home"};+ static const uint32_t bits[] = {K_LEFT, K_RIGHT, K_UP, K_DOWN, K_OK, K_BACK, K_HOME};+ for (int i = 0; i < 7; i++)+ if (!strcmp(s, names[i])) return bits[i];+ fprintf(stderr, "unknown key %s\n", s);+ exit(2);+}++static void parse_keys(const char *spec) {+ char buf[65536];+ snprintf(buf, sizeof buf, "%s", spec);+ for (char *tok = strtok(buf, ","); tok; tok = strtok(NULL, ",")) {+ int a, b;+ char k[16];+ if (sscanf(tok, "%d-%d:%15s", &a, &b, k) == 3) holds[nholds++] = (Hold){a, b, key_of(k)};+ else if (sscanf(tok, "%d:%15s", &a, k) == 2) holds[nholds++] = (Hold){a, a, key_of(k)};+ }+}++/* a driver: gas, and in the air the pedals to land level with the ground ahead */+static uint32_t autopilot(void) {+ const Car *c = &run.car;+ if (run.over) return 0;+ float x = c->ch.x, slope = atan2f(stage_floor(x + 1.5f) - stage_floor(x - 1.5f), 3.0f);+ float a = c->ch.a;+ while (a > 3.14159f) a -= 6.28318f;+ while (a < -3.14159f) a += 6.28318f;+ float d = a - slope;+ if (car_airborne(c)) {+ if (d > 0.25f) return K_LEFT;+ if (d < -0.35f) return K_RIGHT;+ return 0;+ }+ if (d > 0.75f) return 0; /* rearing up: ease off */+ if (car_speed(c) < 0.3f && run.fuel <= 0) return 0;+ return K_RIGHT;+}++int main(int argc, char **argv) {+ int frames = 600, run_stage = -1, run_vehicle = 0, trace = 0;+ bool autop = false;+ const char *out = "build/shots";+ int levels[4] = {1, 1, 1, 1};+ long coins = -1;+ for (int i = 1; i < argc; i++) {+ if (!strcmp(argv[i], "--frames")) frames = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--keys")) parse_keys(argv[++i]);+ else if (!strcmp(argv[i], "--shots")) {+ const char *s = argv[++i];+ if (!strncmp(s, "every:", 6)) every = atoi(s + 6);+ else+ for (const char *p = s; *p;) {+ shots[nshots++] = atoi(p);+ while (*p && *p != ',') p++;+ if (*p) p++;+ }+ } else if (!strcmp(argv[i], "--out")) out = argv[++i];+ else if (!strcmp(argv[i], "--saves")) host_save_dir(argv[++i]);+ else if (!strcmp(argv[i], "--run")) sscanf(argv[++i], "%d,%d", &run_stage, &run_vehicle);+ else if (!strcmp(argv[i], "--levels")) sscanf(argv[++i], "%d,%d,%d,%d", &levels[0], &levels[1], &levels[2], &levels[3]);+ else if (!strcmp(argv[i], "--coins")) coins = atol(argv[++i]);+ else if (!strcmp(argv[i], "--auto")) autop = true;+ else if (!strcmp(argv[i], "--trace")) trace = atoi(argv[++i]);+ }+ mkdir("build", 0755);+ mkdir(out, 0755);+ static uint16_t band[SCREEN_W * GFX_BAND];+ gfx_init(band);+ game_init();+ if (coins >= 0) sv.coins = (uint32_t)coins;+ if (run_stage >= 0) {+ sv.vehicles |= (uint16_t)(1 << run_vehicle), sv.stages |= (uint16_t)(1 << run_stage);+ for (int u = 0; u < 4; u++) sv.level[run_vehicle][u] = (uint8_t)levels[u];+ sv.vehicle = (uint8_t)run_vehicle, sv.stage = (uint8_t)run_stage, sv.seen_help = 1;+ run_start(run_vehicle, run_stage);+ g_mode = MODE_RUN;+ }+ for (int f = 0; f < frames && g_running; f++) {+ uint32_t k = 0;+ for (int i = 0; i < nholds; i++)+ if (f >= holds[i].a && f <= holds[i].b) k |= holds[i].k;+ if (autop && g_mode == MODE_RUN) k |= autopilot();+ host_keys = k;+ game_frame(k);+ host_time += 17;+ bool shot = every ? f % every == 0 : false;+ for (int i = 0; i < nshots; i++) shot |= shots[i] == f;+ if (shot) {+ game_draw();+ char p[512];+ snprintf(p, sizeof p, "%s/shot_%06d.ppm", out, f);+ host_shot(p);+ }+ if (trace && f % trace == 0 && (g_mode == MODE_RUN || g_mode == MODE_END))+ printf("f %d x %.1f y %.1f a %.2f v %.1f fuel %.1f air %d head %d dist %.0f coins %u\n", f, run.car.ch.x,+ run.car.ch.y, run.car.ch.a, car_speed(&run.car), run.fuel, car_airborne(&run.car), run.car.head_hit,+ run.dist, (unsigned)run_total());+ }+ printf("END mode %d dist %d coins %u total %u over %d end %d level %d flips %u saved %u running %d\n", g_mode,+ (int)run.dist, (unsigned)run.coins, (unsigned)run_total(), run.over, run.end, run.level, (unsigned)run.flips,+ (unsigned)sv.coins, g_running);+ return 0;+}diff --git a/games/hillclimb/tests/shots.py b/games/hillclimb/tests/shots.pynew file mode 100644index 00000000..deaca2dd--- /dev/null+++ b/games/hillclimb/tests/shots.py@@ -0,0 +1,14 @@+#!/usr/bin/env python3+"""Puts the host's screenshots (PPM) side by side in one PNG, 2x: shots.py OUT.png a.ppm b.ppm ..."""+import sys++from PIL import Image++out, files = sys.argv[1], sys.argv[2:]+ims = [Image.open(f).convert("RGB") for f in files]+cols = 2 if len(ims) > 1 else 1+rows = (len(ims) + cols - 1) // cols+sheet = Image.new("RGB", (320 * 2 * cols + 8 * (cols - 1), 240 * 2 * rows + 8 * (rows - 1)), (255, 255, 255))+for i, im in enumerate(ims):+ sheet.paste(im.resize((640, 480), Image.NEAREST), ((i % cols) * 648, (i // cols) * 488))+sheet.save(out)diff --git a/games/hillclimb/tools/art.py b/games/hillclimb/tools/art.pynew file mode 100644index 00000000..47291bbe--- /dev/null+++ b/games/hillclimb/tools/art.py@@ -0,0 +1,47 @@+"""Where everything sits: the vehicles' pictures over their bodies, and how big every picture is kept.++Vehicles are measured in the pixels of their chassis picture (x right, y down), as the wiki keeps it; meters come+from the distance between their first and last axles (`wheelbase`). tools/pack.py turns this into src/art.h, and+tools/preview.py draws each vehicle put together, to check the numbers."""++# Each vehicle: its chassis picture; its axles (the wheels' centres at rest, in the chassis' pixels); the wheel's+# picture, the radius of its tyre in that picture and in meters (one per axle when they differ); the distance+# between the first and last axles in meters; where Bill's hips go (chassis pixels), how he leans (degrees, back)+VEHICLES = [+ dict(id="jeep", name="Hill Climber", chassis="Chassis-hillclimber-red.png",+ axles=[(50, 108), (205, 108)], wheelbase=2.15, wheel="Common_Wheel_-_Type_1.png", wheel_px=31,+ wheel_m=[0.43, 0.43], driver=dict(hips=(120, 62), lean=4)),+ dict(id="bike", name="Motocross Bike", chassis="Bike-motocross.png",+ axles=[(42, 126), (218, 126)], wheelbase=1.85, wheel="Bike-motocross-tire.png", wheel_px=31,+ wheel_m=[0.44, 0.44], driver=dict(hips=(104, 40), lean=-16, legs=True),+ # the swingarm (engine -> rear axle) and fork (handlebar -> front axle), drawn as tubes+ tubes=[((128, 104), 0, 0x5A5E66, 0.09), ((176, 30), 1, 0x30343A, 0.07)]),+ dict(id="monster", name="Monster Truck", chassis="Car-monster.png",+ axles=[(50, 99), (210, 99)], wheelbase=2.55, wheel="Car-monster-tire.png", wheel_px=31,+ wheel_m=[0.62, 0.62], driver=dict(hips=(120, 56), lean=4)),+ dict(id="quad", name="Quad Bike", chassis="Car-quadbike.png",+ axles=[(54, 106), (204, 106)], wheelbase=1.75, wheel="Common_Wheel_-_Type_4.png", wheel_px=62,+ wheel_m=[0.5, 0.5], driver=dict(hips=(116, 32), lean=-12, legs=True)),+ dict(id="race", name="Race Car", chassis="Car-racecar.png",+ axles=[(62, 86), (204, 86)], wheelbase=2.45, wheel="Common_Wheel_-_Type_2.png", wheel_px=31,+ wheel_m=[0.4, 0.4], driver=dict(hips=(126, 68), lean=22)),+ dict(id="rally", name="Rally Car", chassis="Car-rallycar.png",+ axles=[(53, 92), (211, 92)], wheelbase=2.35, wheel="Common_Wheel_-_Type_8.png", wheel_px=31,+ wheel_m=[0.42, 0.42], driver=dict(hips=(130, 62), lean=6)),+ dict(id="buggy", name="Dune Buggy", chassis="Dune_Buggy_Chassis_(Sprite).png",+ axles=[(48, 88), (206, 84)], wheelbase=2.3, wheel="buggy-tire", wheel_px=39,+ wheel_m=[0.52, 0.4], driver=dict(hips=(86, 66), lean=10)),+ dict(id="tank", name="Tank", chassis="Car-tank-fg.png",+ axles=[(40, 96), (84, 102), (128, 102), (172, 102), (216, 96)], wheelbase=3.2, wheel="Car-tank-tire.png",+ wheel_px=31, wheel_m=[0.3] * 5, driver=dict(hips=(130, 44), lean=0),+ # the tracks' base under the hull and the cannon over it: (picture, its pixel on the chassis' (0, 0),+ # its scale to the chassis, in front)+ layers=[("Car-tank-bg.png", (14, 18), 0.92, False), ("Car-tank-cannon.png", (140, -26), 0.42, True)]),+]++# Bill: his head and body pictures and where they join (picture pixels): the base of the neck on the body, the+# neck under the chin on the head, his hips at the bottom of the body; how big they are (meters, the pictures'+# heights); his legs on bikes (the leg picture, its hip and its size)+BILL = dict(head="Driver-head.png", body="Driver-body.png", head_neck=(52, 104), body_neck=(34, 10),+ body_hips=(36, 110), body_m=0.98, head_m=0.84, leg="Bike-driver-leg-full.png", leg_hip=(12, 28),+ leg_m=0.78)diff --git a/games/hillclimb/tools/fetch.py b/games/hillclimb/tools/fetch.pynew file mode 100644index 00000000..cf625b15--- /dev/null+++ b/games/hillclimb/tools/fetch.py@@ -0,0 +1,106 @@+#!/usr/bin/env python3+"""Gathers the public material the pack is made from, into REF (not committed):++ python3 -I tools/fetch.py REF++- REF/wiki/*.png: the game's own pictures, as the Hill Climb Racing Wiki (hillclimbracing.fandom.com) keeps them:+ the vehicles' chassis and wheels, Bill, the coins and fuel, the stages' sky, surface and ground, their icons,+ the vehicles' and upgrades' icons, the pedals, the meters and the menus+- REF/fonts/Teko.ttf: Teko (SIL Open Font License), the closest free font to the game's own++Files already there are kept: run it again to fetch only what is missing."""+import hashlib+import json+import os+import sys+import time+import urllib.parse+import urllib.request++API = "https://hillclimbracing.fandom.com/api.php"+UA = {"User-Agent": "NumPlay-HillClimb/1.0 (fan port for the NumWorks calculator; one-time asset fetch)"}+FONT = ("Teko.ttf", "https://raw.githubusercontent.com/google/fonts/main/ofl/teko/Teko%5Bwght%5D.ttf")++FILES = [+ # the vehicles: chassis, wheels, parts+ "Chassis-hillclimber-red.png", "Common_Wheel_-_Type_1.png",+ "Bike-motocross.png", "Bike-motocross-tire.png", "Bike-driver-leg-full.png",+ "Car-monster.png", "Car-monster-tire.png",+ "Car-quadbike.png", "Common_Wheel_-_Type_4.png",+ "Car-racecar.png", "Common_Wheel_-_Type_2.png",+ "Car-rallycar.png", "Common_Wheel_-_Type_8.png",+ "Dune_Buggy_Chassis_(Sprite).png", "Dune_Buggy_(Sprite).png",+ "Car-tank-bg.png", "Car-tank-fg.png", "Car-tank-cannon.png", "Car-tank-tire.png", "Chaintrack.png",+ # Bill+ "Driver-head.png", "Driver-body.png",+ # on the way+ "Coin5.png", "Coin25.png", "Coin100.png", "Coin500.png", "Fuel-canister.png", "Sky-cloud.png",+ "Lowres-tree-part1.png", "Lowres-tree-part2.png", "BridgeWoodBlock.png", "Flag.png", "Rocks.png", "Rocks-mars.png",+ "Iceshard.png", "Smoke.png", "Dirt.png", "Snow.png", "Countryside_Particle.png", "Alien-slime.png",+ # the stages: sky, surface, ground, icon+ "Sky-bg.png", "Sky-bg-cave.png", "Sky-bg-forest.png", "Sky-bg-mars.png", "Sky-bg-arctic-cave.png",+ "Highway-sky-bg.png", "Moon-bg.png",+ "Lowres-terrain-surface.png", "Lowres-terrain-ground.png", "Lowres-desert-surface.png",+ "Lowres-desert-ground.png", "Lowres-arctic-surface.png", "Lowres-arctic-ground.png",+ "Lowres-highway-surface.png", "Lowres-highway-ground.png", "Lowres-terrain-cave-surface.png",+ "Lowres-moon-surface.png", "Lowres-moon-ground.png", "Lowres-terrain-mars-surface.png", "Lowres-mars-ground.png",+ "Lowres-terrain-alien-surface.png", "Lowres-terrain-alien.png", "Lowres-terrain-forest-surface.png",+ "Lowres-terrain-forest-ground.png",+ "Stage-icon-countryside.png", "Stage-icon-desert.png", "Stage-icon-arctic.png", "Stage-icon-highway.png",+ "Stage-icon-cave.png", "Stage-icon-moon.png", "Stage-icon-mars.png", "Stage-icon-alienplanet.png",+ "Stage-icon-arctic-cave.png", "Stage-icon-forest.png", "Stage-icon-locked.png",+ # the menus+ "Mission-vehicle-jeep.png", "Mission-vehicle-bike.png", "Mission-vehicle-monster.png",+ "Mission-vehicle-quadbike.png", "Mission-vehicle-racecar.png", "Mission-vehicle-rallycar.png",+ "Mission-vehicle-dunebuggy.png", "Mission-vehicle-tank.png",+ "MainMenuUpgradeEngine.png", "MainMenuUpgradeSuspension.png", "MainMenuUpgradeTires.png",+ "MainMenuUpgradeAWD.png", "MainMenuUpgradeBikeRotation.png", "MainMenuUpgradeDownforce.png",+ "MainMenuUpgradeFuel.png",+ "Pedal-gas-normal.png", "Pedal-gas-pressed.png", "Pedal-brake-normal.png", "Pedal-brake-pressed.png",+ "Meter-rpm.png", "Meter-boost.png", "Meter-needle.png", "Fuel-icon.png", "Fuel-warning.png", "Coin-icon.png",+ "Menu-bg.png", "Game-logo.png", "Lock.png", "Icon-start.png", "Distance-icon.png",+]+++def get(url):+ for attempt in range(4):+ try:+ return urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=60).read()+ except Exception:+ if attempt == 3:+ raise+ time.sleep(2 ** attempt)+++def main():+ ref = sys.argv[1]+ wiki = os.path.join(ref, "wiki")+ os.makedirs(wiki, exist_ok=True)+ todo = [n for n in FILES if not os.path.exists(os.path.join(wiki, n))]+ for i in range(0, len(todo), 40):+ chunk = todo[i:i + 40]+ q = urllib.parse.urlencode({"action": "query", "titles": "|".join("File:" + n for n in chunk),+ "prop": "imageinfo", "iiprop": "url|sha1", "format": "json"})+ pages = json.loads(get(API + "?" + q))["query"]["pages"].values()+ for p in pages:+ info = p.get("imageinfo")+ if not info:+ raise SystemExit(f"fetch: the wiki has no {p['title']}")+ name = p["title"][5:].replace(" ", "_")+ url = info[0]["url"]+ data = get(url + ("&" if "?" in url else "?") + "format=original") # (not the WebP the CDN serves)+ if hashlib.sha1(data).hexdigest() != info[0]["sha1"]:+ print(f"fetch: {name} differs from the wiki's checksum (kept anyway)")+ with open(os.path.join(wiki, name), "wb") as f:+ f.write(data)+ print("wiki", name)+ fonts = os.path.join(ref, "fonts")+ os.makedirs(fonts, exist_ok=True)+ if not os.path.exists(os.path.join(fonts, FONT[0])):+ with open(os.path.join(fonts, FONT[0]), "wb") as f:+ f.write(get(FONT[1]))+ print("font", FONT[0])+++if __name__ == "__main__":+ main()diff --git a/games/hillclimb/tools/pack.py b/games/hillclimb/tools/pack.pynew file mode 100644index 00000000..4a9f7b76--- /dev/null+++ b/games/hillclimb/tools/pack.py@@ -0,0 +1,468 @@+#!/usr/bin/env python3+"""Hill Climb Racing's pictures and fonts -> src/data.bin, src/data.h and src/art.h.++ python3 -I tools/pack.py REF (REF: the folder tools/fetch.py filled)++data.bin: "HCRD", the number of pictures and fonts, then a table of their offsets (u32), then each one:+- a picture: w, h, colours, flags (u16 each; flags 1: opaque), its pixels a meter x 4 (0: a picture of the menus),+ its pivot x 4 (s16, s16), 0; its colours as premultiplied R, G, B, A bytes; for an opaque one also as RGB565;+ then w x h colour indices, row by row+- a font: first character, count, line height, ascent (u8 each); then a glyph each (w, h, x and y of its top-left+ from the pen, advance, 3 bytes of 0, offset of its bitmap: u8 u8 s8 s8 u8, u32) and the bitmaps, a byte a pixel: the+ letter's coverage in the high 4 bits, its dark outline's in the low 4++data.h names them (IMG_*, FONT_*); art.h is tools/art.py's vehicles in meters, for src/vehicle.c."""+import math+import os+import struct+import subprocess+import sys+import tempfile++import numpy as np+from PIL import Image, ImageDraw, ImageFont++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import art # noqa: E402++SRC = os.path.join(HERE, "..", "src")+VPPM = 44 # pixels a meter the vehicles, Bill and the things on the way are kept at (the game draws them at 30 or less)++# name, wiki file, crop box or None, how it is sized: ("ppm", source pixels a meter) keeps VPPM pixels a meter;+# ("w", width) or ("h", height) or ("size", w, h) for the menus; pivot ("c": centre, or (x, y) source pixels)+PICTURES = [+ ("COIN5", "Coin5.png", None, ("ppm", 64 / 0.72), "c"),+ ("COIN25", "Coin25.png", None, ("ppm", 64 / 0.72), "c"),+ ("COIN100", "Coin100.png", None, ("ppm", 64 / 0.72), "c"),+ ("COIN500", "Coin500.png", None, ("ppm", 64 / 0.72), "c"),+ ("FUELCAN", "Fuel-canister.png", None, ("ppm", 64 / 0.95), (32, 60)),+ ("CLOUD", "Sky-cloud.png", None, ("w", 76), "c"),+ ("TREE_TRUNK", "Lowres-tree-part1.png", None, ("ppm", 64 / 1.3), (32, 31)),+ ("TREE_TOP", "Lowres-tree-part2.png", None, ("ppm", 64 / 1.9), (32, 31)),+ ("PLANK", "BridgeWoodBlock.png", None, ("ppm", 64 / 1.1), "c"),+ ("FLAG", "Flag.png", None, ("ppm", 128 / 1.6), (4, 62)),+ ("ROCKS", "Rocks.png", None, ("ppm", 64 / 1.2), "c"),+ ("ROCKS_MARS", "Rocks-mars.png", None, ("ppm", 64 / 1.2), "c"),+ ("ICICLE", "Iceshard.png", None, ("ppm", 64 / 1.4), (32, 2)),+ ("SMOKE", "Smoke.png", None, ("w", 20), "c"),+ ("DIRT", "Dirt.png", None, ("w", 20), "c"),+ ("SNOW", "Snow.png", None, ("w", 20), "c"),+ ("GRASS", "Countryside_Particle.png", None, ("w", 20), "c"),+ ("SLIME", "Alien-slime.png", None, ("w", 20), "c"),+ # skies (a column of colours from top to bottom) and the stages' ground+ ("SKY", "Sky-bg.png", None, ("size", 1, 32), "c"),+ ("SKY_CAVE", "Sky-bg-cave.png", None, ("size", 1, 32), "c"),+ ("SKY_FOREST", "Sky-bg-forest.png", None, ("size", 1, 32), "c"),+ ("SKY_MARS", "Sky-bg-mars.png", None, ("size", 1, 32), "c"),+ ("SKY_ARCTIC_CAVE", "Sky-bg-arctic-cave.png", None, ("size", 1, 32), "c"),+ ("SKY_HIGHWAY", "Highway-sky-bg.png", None, ("size", 1, 32), "c"),+ ("SKY_MOON", "Moon-bg.png", None, ("size", 1, 64), "c"),+ ("SURF_COUNTRY", "Lowres-terrain-surface.png", None, ("size", 256, 16), "c"),+ ("GROUND_COUNTRY", "Lowres-terrain-ground.png", None, ("size", 128, 128), "c"),+ ("SURF_DESERT", "Lowres-desert-surface.png", None, ("size", 256, 16), "c"),+ ("GROUND_DESERT", "Lowres-desert-ground.png", None, ("size", 128, 128), "c"),+ ("SURF_ARCTIC", "Lowres-arctic-surface.png", None, ("size", 256, 16), "c"),+ ("GROUND_ARCTIC", "Lowres-arctic-ground.png", None, ("size", 128, 128), "c"),+ ("SURF_HIGHWAY", "Lowres-highway-surface.png", None, ("size", 256, 16), "c"),+ ("GROUND_HIGHWAY", "Lowres-highway-ground.png", None, ("size", 128, 128), "c"),+ ("SURF_CAVE", "Lowres-terrain-cave-surface.png", None, ("size", 256, 16), "c"),+ ("SURF_MOON", "Lowres-moon-surface.png", None, ("size", 256, 16), "c"),+ ("GROUND_MOON", "Lowres-moon-ground.png", None, ("size", 128, 128), "c"),+ ("SURF_MARS", "Lowres-terrain-mars-surface.png", None, ("size", 256, 16), "c"),+ ("GROUND_MARS", "Lowres-mars-ground.png", None, ("size", 128, 128), "c"),+ ("SURF_ALIEN", "Lowres-terrain-alien-surface.png", None, ("size", 256, 16), "c"),+ ("GROUND_ALIEN", "Lowres-terrain-alien.png", None, ("size", 128, 128), "c"),+ ("SURF_FOREST", "Lowres-terrain-forest-surface.png", None, ("size", 256, 16), "c"),+ ("GROUND_FOREST", "Lowres-terrain-forest-ground.png", None, ("size", 128, 128), "c"),+ # the menus+ ("STAGE_COUNTRY", "Stage-icon-countryside.png", None, ("size", 144, 72), "c"),+ ("STAGE_DESERT", "Stage-icon-desert.png", None, ("size", 144, 72), "c"),+ ("STAGE_ARCTIC", "Stage-icon-arctic.png", None, ("size", 144, 72), "c"),+ ("STAGE_HIGHWAY", "Stage-icon-highway.png", None, ("size", 144, 72), "c"),+ ("STAGE_CAVE", "Stage-icon-cave.png", None, ("size", 144, 72), "c"),+ ("STAGE_MOON", "Stage-icon-moon.png", None, ("size", 144, 72), "c"),+ ("STAGE_MARS", "Stage-icon-mars.png", None, ("size", 144, 72), "c"),+ ("STAGE_ALIEN", "Stage-icon-alienplanet.png", None, ("size", 144, 72), "c"),+ ("STAGE_ARCTIC_CAVE", "Stage-icon-arctic-cave.png", None, ("size", 144, 72), "c"),+ ("STAGE_FOREST", "Stage-icon-forest.png", None, ("size", 144, 72), "c"),+ ("STAGE_LOCKED", "Stage-icon-locked.png", None, ("size", 144, 72), "c"),+ ("ICON_JEEP", "Mission-vehicle-jeep.png", None, ("w", 112), "c"),+ ("ICON_BIKE", "Mission-vehicle-bike.png", None, ("w", 112), "c"),+ ("ICON_MONSTER", "Mission-vehicle-monster.png", None, ("w", 112), "c"),+ ("ICON_QUAD", "Mission-vehicle-quadbike.png", None, ("w", 112), "c"),+ ("ICON_RACE", "Mission-vehicle-racecar.png", None, ("w", 112), "c"),+ ("ICON_RALLY", "Mission-vehicle-rallycar.png", None, ("w", 112), "c"),+ ("ICON_BUGGY", "Mission-vehicle-dunebuggy.png", None, ("w", 112), "c"),+ ("ICON_TANK", "Mission-vehicle-tank.png", None, ("w", 112), "c"),+ ("UP_ENGINE", "MainMenuUpgradeEngine.png", None, ("w", 40), "c"),+ ("UP_SUSPENSION", "MainMenuUpgradeSuspension.png", None, ("w", 40), "c"),+ ("UP_TIRES", "MainMenuUpgradeTires.png", None, ("w", 40), "c"),+ ("UP_AWD", "MainMenuUpgradeAWD.png", None, ("w", 40), "c"),+ ("UP_AIR", "MainMenuUpgradeBikeRotation.png", None, ("w", 40), "c"),+ ("UP_DOWNFORCE", "MainMenuUpgradeDownforce.png", None, ("w", 40), "c"),+ ("UP_FUEL", "MainMenuUpgradeFuel.png", None, ("w", 40), "c"),+ ("PEDAL_GAS", "Pedal-gas-normal.png", "trim", ("h", 43), "c"),+ ("PEDAL_GAS_DOWN", "Pedal-gas-pressed.png", "trim", ("h", 43), "c"),+ ("PEDAL_BRAKE", "Pedal-brake-normal.png", "trim", ("h", 43), "c"),+ ("PEDAL_BRAKE_DOWN", "Pedal-brake-pressed.png", "trim", ("h", 43), "c"),+ ("METER_RPM", "Meter-rpm.png", None, ("w", 50), "c"),+ ("METER_BOOST", "Meter-boost.png", None, ("w", 50), "c"),+ ("NEEDLE", "Meter-needle.png", None, ("h", 27), (16, 100)),+ ("FUEL_ICON", "Fuel-icon.png", None, ("w", 20), "c"),+ ("FUEL_LOW", "Fuel-warning.png", None, ("w", 70), "c"),+ ("COIN_ICON", "Coin-icon.png", None, ("w", 18), "c"),+ ("MENU_BG", "Menu-bg.png", None, ("size", 320, 240), "c"),+ ("LOGO", "Game-logo.png", "trim", ("w", 200), "c"),+ ("LOCK", "Lock.png", None, ("w", 28), "c"),+ ("START", "Icon-start.png", None, ("w", 30), "c"),+]++# the fonts, from Teko: name, the height of its capitals in pixels, weight, outline width+FONTS = [("FONT_S", 9, 560, 1), ("FONT_M", 13, 600, 1.5), ("FONT_L", 20, 620, 2), ("FONT_XL", 34, 640, 3)]+++def ref_path(ref, name):+ return os.path.join(ref, "wiki", name)+++def load(ref, name):+ if name == "buggy-tire": # the Dune Buggy's tyre, from the picture of the whole buggy+ return Image.open(ref_path(ref, "Dune_Buggy_(Sprite).png")).convert("RGBA").crop((6, 133, 86, 213))+ return Image.open(ref_path(ref, name)).convert("RGBA")+++def premul_resize(im, w, h):+ """Resized without the dark fringes straight alpha gives: in premultiplied colours."""+ a = np.asarray(im).astype(np.float32) / 255+ p = a.copy()+ p[..., :3] *= p[..., 3:4]+ planes = [Image.fromarray(p[..., i]).resize((w, h), Image.LANCZOS) for i in range(4)]+ q = np.stack([np.asarray(x) for x in planes], -1)+ q = np.clip(q, 0, 1)+ al = q[..., 3:4]+ rgb = np.where(al > 1e-4, q[..., :3] / np.maximum(al, 1e-4), 0)+ out = np.concatenate([np.clip(rgb, 0, 1), al], -1)+ return Image.fromarray((out * 255 + 0.5).astype(np.uint8), "RGBA")+++def quantize(im, colors=256):+ """Palette and indices from pngquant (keeps the alpha's smooth edges)."""+ with tempfile.TemporaryDirectory() as d:+ src, dst = os.path.join(d, "in.png"), os.path.join(d, "out.png")+ im.save(src)+ subprocess.run(["pngquant", "--force", "--speed", "1", "--nofs", str(colors), "--output", dst, src],+ check=True)+ q = Image.open(dst)+ q.load()+ if q.mode != "P":+ q = im.convert("P", palette=Image.ADAPTIVE, colors=colors)+ pal = q.getpalette()[:768]+ trns = q.info.get("transparency", b"")+ n = len(pal) // 3+ alpha = [255] * n+ if isinstance(trns, bytes):+ for i, a in enumerate(trns):+ alpha[i] = a+ elif isinstance(trns, int):+ alpha[trns] = 0+ idx = np.asarray(q, dtype=np.uint8)+ used = int(idx.max()) + 1+ cols = [(pal[3 * i], pal[3 * i + 1], pal[3 * i + 2], alpha[i]) for i in range(used)]+ return cols, idx+++def rgb565(r, g, b):+ return (r >> 3) << 11 | (g >> 2) << 5 | b >> 3+++def picture(im, ppm, pivot, opaque=False):+ cols, idx = quantize(im)+ h, w = idx.shape+ flags = 1 if opaque else 0+ out = bytearray(struct.pack("<HHHHHhhH", w, h, len(cols), flags, int(round(ppm * 4)),+ int(round(pivot[0] * 4)), int(round(pivot[1] * 4)), 0))+ for r, g, b, a in cols:+ if opaque:+ a = 255+ out += bytes([r * a // 255, g * a // 255, b * a // 255, a])+ if opaque:+ for r, g, b, a in cols:+ out += struct.pack("<H", rgb565(r, g, b))+ out += idx.tobytes()+ while len(out) % 4:+ out.append(0)+ return out+++def sized(im, how, crop):+ if crop == "trim":+ im = im.crop(im.getbbox())+ elif crop:+ im = im.crop(crop)+ kind = how[0]+ if kind == "ppm":+ k = min(1.0, VPPM / how[1])+ return premul_resize(im, max(1, round(im.width * k)), max(1, round(im.height * k))), k, VPPM if k < 1 else how[1]+ if kind == "w":+ k = how[1] / im.width+ elif kind == "h":+ k = how[1] / im.height+ else:+ w, h = how[1], how[2]+ if w == 1: # a sky: the middle column+ col = im.crop((im.width // 2, 0, im.width // 2 + 1, im.height))+ return col.resize((1, h), Image.BILINEAR), 1, 0+ return premul_resize(im, w, h), w / im.width, 0+ return premul_resize(im, max(1, round(im.width * k)), max(1, round(im.height * k))), k, 0+++def vehicle_pictures(ref):+ """The vehicles' pictures, kept at VPPM pixels a meter, and art.h's tables."""+ pics = []+ lines = ["/* Generated by tools/pack.py from tools/art.py: the vehicles put together, in meters. */",+ "#ifndef HC_ART_H", "#define HC_ART_H", '#include "data.h"', ""]+ B = art.BILL+ body, head, leg = load(ref, B["body"]), load(ref, B["head"]), load(ref, B["leg"])+ bppm, hppm, lppm = body.height / B["body_m"], head.height / B["head_m"], leg.height / B["leg_m"]+ for name, im, ppm, piv in (("BILL_BODY", body, bppm, B["body_hips"]), ("BILL_HEAD", head, hppm, B["head_neck"]),+ ("BILL_LEG", leg, lppm, B["leg_hip"])):+ k = VPPM / ppm+ pics.append((name, premul_resize(im, round(im.width * k), round(im.height * k)), VPPM,+ (piv[0] * k, piv[1] * k), False))+ # the neck from the hips (meters, Bill upright, y up); the head's circle from the neck+ neck = ((B["body_neck"][0] - B["body_hips"][0]) / bppm, -(B["body_neck"][1] - B["body_hips"][1]) / bppm)+ hb = np.asarray(head)[..., 3] > 128+ ys, xs = np.nonzero(hb)+ hcx, hcy = (xs.min() + xs.max()) / 2, (ys.min() + ys.max()) / 2+ hr = min(xs.max() - xs.min(), ys.max() - ys.min()) / 2 * 0.86 / hppm+ lines.append(f"#define BILL_NECK_X {neck[0]:.3f}f")+ lines.append(f"#define BILL_NECK_Y {neck[1]:.3f}f")+ lines.append(f"#define BILL_HEAD_X {(hcx - B['head_neck'][0]) / hppm:.3f}f /* the head's centre from the neck */")+ lines.append(f"#define BILL_HEAD_Y {-(hcy - B['head_neck'][1]) / hppm:.3f}f")+ lines.append(f"#define BILL_HEAD_R {hr:.3f}f")+ lines.append("")+ lines.append("typedef struct {")+ lines.append(" uint8_t chassis, wheel, naxles, legs, ntubes, nlayers, nhull;")+ lines.append(" float axle[6][2], wheel_r[6]; /* from the chassis' origin: halfway between the first and last axles */")+ lines.append(" float hips[2], lean; /* Bill's hips, and how far he leans back (radians) */")+ lines.append(" float tube[2][5]; /* from (x, y) to axle (index), colour 0xRRGGBB, radius */")+ lines.append(" float layer[2][4]; /* picture, its pivot's place (x, y), in front (1) or behind */")+ lines.append(" float hull[16][2]; /* the chassis' outline, for the ground to push on */")+ lines.append("} VehArt;")+ lines.append(f"#define NVEH {len(art.VEHICLES)}")+ lines.append("static const VehArt veh_art[NVEH] = {")+ for v in art.VEHICLES:+ ch = load(ref, v["chassis"])+ ax = v["axles"]+ cppm = (ax[-1][0] - ax[0][0]) / v["wheelbase"]+ ox, oy = (ax[0][0] + ax[-1][0]) / 2, ax[0][1]+ k = VPPM / cppm+ cname = "CH_" + v["id"].upper()+ pics.append((cname, premul_resize(ch, round(ch.width * k), round(ch.height * k)), VPPM, (ox * k, oy * k), False))+ m = lambda p: ((p[0] - ox) / cppm, -(p[1] - oy) / cppm) # noqa: E731+ wname = "WHEEL_" + v["id"].upper()+ wim = load(ref, v["wheel"])+ wppm = v["wheel_px"] / max(v["wheel_m"])+ wk = VPPM / wppm+ pics.append((wname, premul_resize(wim, round(wim.width * wk), round(wim.height * wk)), VPPM,+ (wim.width * wk / 2, wim.height * wk / 2), False))+ # the outline: the convex hull of the chassis' opaque pixels, points along it every 0.35 m+ a = np.asarray(ch)[..., 3] > 140+ pts = np.argwhere(a)[:, ::-1].astype(float)+ hull = convex_hull(pts)+ ring = resample_ring([m(p) for p in hull], 0.4, 16)+ layers = []+ for (lpic, at, scale, front) in v.get("layers", []):+ lim = load(ref, lpic)+ lk = k * scale+ lname = "LAYER_" + lpic.split(".")[0].upper().replace("-", "_")+ pics.append((lname, premul_resize(lim, round(lim.width * lk), round(lim.height * lk)), VPPM, (0, 0), False))+ layers.append((lname, m(at), front))+ tubes = []+ for (frm, axi, col, r) in v.get("tubes", []):+ p = m(frm)+ tubes.append((p[0], p[1], axi, col, r))+ d = v["driver"]+ hips = m(d["hips"])+ f = lambda x: f"{x:.3f}f" # noqa: E731+ axs = ", ".join("{" + f(m(p)[0]) + ", " + f(m(p)[1]) + "}" for p in ax)+ rs = ", ".join(f(r) for r in v["wheel_m"])+ tb = ", ".join("{" + ", ".join([f(t[0]), f(t[1]), f(t[2]), f"{float(t[3])}f", f(t[4])]) + "}" for t in tubes) or "{0}"+ ly = ", ".join("{IMG_" + n + ", " + f(p[0]) + ", " + f(p[1]) + ", " + ("1" if fr else "0") + "}"+ for n, p, fr in layers) or "{0}"+ hl = ", ".join("{" + f(x) + ", " + f(y) + "}" for x, y in ring)+ lines.append(f" {{IMG_{cname}, IMG_{wname}, {len(ax)}, {1 if d.get('legs') else 0}, {len(tubes)}, "+ f"{len(layers)}, {len(ring)},")+ lines.append(f" {{{axs}}}, {{{rs}}},")+ lines.append(f" {{{f(hips[0])}, {f(hips[1])}}}, {f(math.radians(d['lean']))}, {{{tb}}}, {{{ly}}},")+ lines.append(f" {{{hl}}}}}, /* {v['name']} */")+ lines.append("};")+ lines.append("#endif")+ return pics, lines+++def convex_hull(pts):+ pts = sorted(set(map(tuple, pts)))+ if len(pts) < 3:+ return pts++ def cross(o, a, b):+ return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])+ lower, upper = [], []+ for p in pts:+ while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:+ lower.pop()+ lower.append(p)+ for p in reversed(pts):+ while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:+ upper.pop()+ upper.append(p)+ return lower[:-1] + upper[:-1]+++def resample_ring(ring, step, most):+ """Points along a closed outline about `step` apart, at most `most`, the corners kept first."""+ n = len(ring)+ per = sum(math.dist(ring[i], ring[(i + 1) % n]) for i in range(n))+ count = max(6, min(most, int(per / step)))+ out = []+ for j in range(count):+ t = per * j / count+ for i in range(n):+ seg = math.dist(ring[i], ring[(i + 1) % n])+ if t <= seg:+ a, b = ring[i], ring[(i + 1) % n]+ u = t / seg if seg else 0+ out.append((a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u))+ break+ t -= seg+ return out+++def font_data(ttf, cap, weight, outline):+ up = 4+ for size in range(6, 400):+ f = ImageFont.truetype(ttf, size * up)+ try:+ f.set_variation_by_axes([weight])+ except Exception:+ pass+ bb = f.getbbox("H", anchor="ls")+ if -bb[1] >= cap * up:+ break+ o = int(round(outline * up))+ glyphs, data = [], bytearray()+ asc = desc = 0+ for c in range(32, 127):+ ch = chr(c)+ adv = round(f.getlength(ch) / up + outline)+ bb = f.getbbox(ch, anchor="ls")+ if bb[2] <= bb[0]:+ glyphs.append((0, 0, 0, 0, adv, len(data)))+ continue+ pad = o + 2 * up+ x0, y0 = pad - bb[0], pad - bb[1]+ x0 += (-x0) % up+ y0 += (-y0) % up+ w, h = x0 + bb[2] + pad, y0 + bb[3] + pad+ w += (-w) % up+ h += (-h) % up+ fill = Image.new("L", (w, h))+ ImageDraw.Draw(fill).text((x0, y0), ch, font=f, fill=255, anchor="ls")+ line = Image.new("L", (w, h))+ ImageDraw.Draw(line).text((x0, y0), ch, font=f, fill=255, anchor="ls", stroke_width=o)+ fa = np.asarray(fill, np.float32).reshape(h // up, up, w // up, up).mean(axis=(1, 3)) / 255+ la = np.asarray(line, np.float32).reshape(h // up, up, w // up, up).mean(axis=(1, 3)) / 255+ fq = np.clip(np.round(fa * 15), 0, 15).astype(np.uint8)+ lq = np.clip(np.round(la * 15), 0, 15).astype(np.uint8)+ ys, xs = np.nonzero(lq)+ if not len(ys):+ glyphs.append((0, 0, 0, 0, adv, len(data)))+ continue+ y_a, y_b, x_a, x_b = ys.min(), ys.max() + 1, xs.min(), xs.max() + 1+ fq, lq = fq[y_a:y_b, x_a:x_b], lq[y_a:y_b, x_a:x_b]+ gw, gh = x_b - x_a, y_b - y_a+ ox, oy = x_a - x0 // up, y_a - y0 // up+ if c < 127:+ asc, desc = max(asc, -oy), max(desc, gh + oy)+ glyphs.append((gw, gh, ox, oy, adv, len(data)))+ data += (fq << 4 | lq).astype(np.uint8).tobytes()+ out = bytearray(struct.pack("<BBBB", 32, len(glyphs), asc + desc, asc))+ for gw, gh, ox, oy, adv, off in glyphs:+ out += struct.pack("<BBbbBxxxI", gw, gh, ox, oy, adv, off)+ out += data+ while len(out) % 4:+ out.append(0)+ return out+++def icon(ref):+ """The app's icon (55 x 56): the Hill Climber on a hill under the game's sky, in a rounded square."""+ k = 4+ W, H = 55 * k, 56 * k+ sky = load(ref, "Sky-bg.png").convert("RGB").resize((1, 32))+ im = Image.new("RGBA", (W, H))+ for y in range(H):+ im.paste(sky.getpixel((0, y * 32 // H)) + (255,), (0, y, W, y + 1))+ d = ImageDraw.Draw(im)+ pts = [(x, int(H * 0.74 - 18 * k * math.sin(x / W * 2.6 + 0.4))) for x in range(0, W + 1, 4)]+ d.polygon(pts + [(W, H), (0, H)], fill=(84, 52, 28, 255))+ d.line(pts, fill=(126, 198, 43, 255), width=5 * k)+ car = load(ref, "Mission-vehicle-jeep.png").crop((0, 0, 206, 145))+ car = car.resize((52 * k, round(52 * k * car.height / car.width)), Image.LANCZOS).rotate(8, Image.BICUBIC, expand=True)+ im.alpha_composite(car, ((W - car.width) // 2, H - car.height - 6 * k))+ head = load(ref, "Driver-head.png")+ head = head.resize((19 * k, 19 * k), Image.LANCZOS)+ im.alpha_composite(head, (W // 2 - 11 * k, 8 * k))+ mask = Image.new("L", (W, H))+ ImageDraw.Draw(mask).rounded_rectangle((0, 0, W - 1, H - 1), radius=12 * k, fill=255)+ im.putalpha(Image.fromarray(np.minimum(np.asarray(im)[..., 3], np.asarray(mask))))+ im.resize((55, 56), Image.LANCZOS).save(os.path.join(SRC, "icon.png"))+++def main():+ ref = sys.argv[1]+ icon(ref)+ pics = []+ for name, file, crop, how, pivot in PICTURES:+ im, k, ppm = sized(load(ref, file), how, crop)+ if pivot == "c":+ pv = (im.width / 2, im.height / 2)+ else:+ pv = (pivot[0] * k, pivot[1] * k)+ opaque = name.startswith(("GROUND_", "SKY", "MENU_BG", "STAGE_"))+ pics.append((name, im, ppm, pv, opaque))+ vp, art_lines = vehicle_pictures(ref)+ pics += vp+ blobs = [picture(im, ppm, pv, opaque) for _, im, ppm, pv, opaque in pics]+ ttf = os.path.join(ref, "fonts", "Teko.ttf")+ fonts = [font_data(ttf, cap, wt, ol) for _, cap, wt, ol in FONTS]+ head = 16 + 4 * (len(blobs) + len(fonts))+ offs, at = [], head+ for b in blobs + fonts:+ offs.append(at)+ at += len(b)+ out = bytearray(b"HCRD" + struct.pack("<III", len(blobs), len(fonts), 0))+ out += b"".join(struct.pack("<I", o) for o in offs)+ for b in blobs + fonts:+ out += b+ with open(os.path.join(SRC, "data.bin"), "wb") as f:+ f.write(out)+ h = ["/* Generated by tools/pack.py: what src/data.bin holds. */", "#ifndef HC_DATA_H", "#define HC_DATA_H",+ "#include <stdint.h>", "", "enum {"]+ h += [f" IMG_{name}," for name, *_ in pics]+ h += [" IMG_COUNT", "};", "enum {"]+ h += [f" {name}," for name, *_ in FONTS]+ h += [" FONT_COUNT", "};", "#endif", ""]+ with open(os.path.join(SRC, "data.h"), "w") as f:+ f.write("\n".join(h))+ with open(os.path.join(SRC, "art.h"), "w") as f:+ f.write("\n".join(art_lines) + "\n")+ print(f"data.bin: {len(out)} bytes, {len(blobs)} pictures, {len(fonts)} fonts")+ for (name, im, *_), b in sorted(zip(pics, blobs), key=lambda x: -len(x[1]))[:8]:+ print(f" {name}: {im.width}x{im.height}, {len(b)} bytes")+++if __name__ == "__main__":+ main()diff --git a/games/hillclimb/tools/preview.py b/games/hillclimb/tools/preview.pynew file mode 100644index 00000000..b4b1d1e2--- /dev/null+++ b/games/hillclimb/tools/preview.py@@ -0,0 +1,96 @@+#!/usr/bin/env python3+"""Draws each vehicle put together from tools/art.py, big, with its axles marked: a check of the numbers.++ python3 -I tools/preview.py REF OUT.png"""+import math+import os+import sys++from PIL import Image, ImageDraw++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import art # noqa: E402++PPM = 70 # the preview's pixels per meter+++def load(ref, name):+ if name == "buggy-tire":+ return Image.open(os.path.join(ref, "wiki", "Dune_Buggy_(Sprite).png")).convert("RGBA").crop((6, 133, 86, 213))+ return Image.open(os.path.join(ref, "wiki", name)).convert("RGBA")+++def paste(canvas, im, scale, anchor_src, anchor_dst, angle=0):+ """im scaled, turned by angle degrees (counterclockwise) around anchor_src, which lands on anchor_dst."""+ w, h = max(1, round(im.width * scale)), max(1, round(im.height * scale))+ s = im.resize((w, h), Image.LANCZOS)+ ax, ay = anchor_src[0] * scale, anchor_src[1] * scale+ if angle:+ big = Image.new("RGBA", (w * 3, h * 3))+ big.alpha_composite(s, (w, h))+ big = big.rotate(angle, resample=Image.BICUBIC, center=(w + ax, h + ay))+ s, ax, ay = big, w + ax, h + ay+ canvas.alpha_composite(s, (round(anchor_dst[0] - ax), round(anchor_dst[1] - ay)))+++def bill(canvas, ref, v, at_px, k):+ """Bill seated, his hips at at_px (canvas pixels), k canvas pixels a meter."""+ d = v["driver"]+ B = art.BILL+ body = load(ref, B["body"])+ head = load(ref, B["head"])+ bs = B["body_m"] * d["size"] * k / body.height+ paste(canvas, body, bs, B["body_hips"], at_px, d["lean"])+ a = math.radians(d["lean"])+ nx = (B["body_neck"][0] - B["body_hips"][0]) * bs+ ny = (B["body_neck"][1] - B["body_hips"][1]) * bs+ neck = (at_px[0] + nx * math.cos(a) + ny * math.sin(a), at_px[1] - nx * math.sin(a) + ny * math.cos(a))+ hs = B["head_m"] * d["size"] * k / head.height+ paste(canvas, head, hs, B["head_neck"], neck)+++def main():+ ref, out = sys.argv[1], sys.argv[2]+ tiles = []+ for v in art.VEHICLES:+ ch = load(ref, v["chassis"])+ ax = v["axles"]+ cppm = (ax[-1][0] - ax[0][0]) / v["wheelbase"] # the chassis picture's pixels a meter+ k = PPM / cppm # chassis pixels -> preview pixels+ W, H = int(ch.width * k) + 120, int(ch.height * k) + 160+ c = Image.new("RGBA", (W, H), (150, 200, 235, 255))+ ox, oy = 60, 110+ to = lambda p: (ox + p[0] * k, oy + p[1] * k) # noqa: E731+ if v["id"] == "tank":+ paste(c, load(ref, "Car-tank-bg.png"), k, (0, 0), to((0, 0)))+ bill(c, ref, v, to(v["driver"]["hips"]), PPM)+ paste(c, ch, k, (0, 0), to((0, 0)))+ wheel = load(ref, v["wheel"])+ ws = v["wheel_m"] * PPM / v["wheel_px"]+ for p in ax:+ paste(c, wheel, ws, (wheel.width / 2, wheel.height / 2), to(p))+ dr = ImageDraw.Draw(c)+ for p in ax:+ x, y = to(p)+ r = v["wheel_m"] * PPM+ dr.ellipse((x - r, y - r, x + r, y + r), outline=(255, 0, 255, 255))+ dr.line((x - 4, y, x + 4, y), fill=(255, 0, 255, 255))+ dr.text((4, 4), v["name"], fill=(0, 0, 0, 255))+ tiles.append(c)+ W = max(t.width for t in tiles) * 2+ rows = [tiles[i:i + 2] for i in range(0, len(tiles), 2)]+ H = sum(max(t.height for t in r) for r in rows)+ sheet = Image.new("RGBA", (W, H), (255, 255, 255, 255))+ y = 0+ for r in rows:+ x = 0+ for t in r:+ sheet.alpha_composite(t, (x, y))+ x += W // 2+ y += max(t.height for t in r)+ sheet.convert("RGB").save(out)+++if __name__ == "__main__":+ main()