Skip to content

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

Hill Climb Racing: the Tractor, Tourist Bus, Super Diesel 4x4, Snow Mobile and Truck, and the Mountain, Mudpool and Volcano

Mason363dc1a85259b50
diff --git a/Makefile b/Makefile
index 36062e12..709c6340 100644
--- a/Makefile
+++ b/Makefile
@@ -36,6 +36,8 @@ APP_SPACE = 2031616
# external flash (0x90800000), over the second copy of the calculator's software: a NumPlay of the big
# games (games.json "xl", made with the customizer website from `make kit`) is for that
XL_APP_SPACE = 6291456
+# big games that must install on their own without Enlarged Extra Apps: make check holds them to APP_SPACE
+APP_SPACE_APPS = HillClimbRacing
# Upsilon, the N0110 and N0115's custom software, gives .nwa apps less RAM: NumPlay-Upsilon.nwa has
# the games that fit it (NumPlay draws their text there: see launcher/src/compat.c)
UPSILON_RAM = 107674
@@ -218,6 +220,9 @@ check: nwa apps
@for a in $(BIG_APPS); do $(NWLINK) nwa-bin --ram-length $(CUSTOM_RAM) $(B)/apps/$$a.nwa $(B)/apps/$$a.bin >/dev/null || \
{ echo "$$a.nwa needs more RAM than custom builds of 25.2 give apps ($(CUSTOM_RAM) bytes)"; exit 1; }; done; \
echo "NumPlay's games and $(BIG_APPS) fit in $(CUSTOM_RAM) bytes of RAM"
+ @for a in $(APP_SPACE_APPS); do n=$$(wc -c < $(B)/apps/$$a.bin); \
+ [ $$n -le $(APP_SPACE) ] || { echo "$$a.nwa is bigger than the calculator's app space ($(APP_SPACE) bytes)"; exit 1; }; \
+ echo "$$a.nwa installs as $$n bytes ($$(( $(APP_SPACE) - n )) to spare)"; done
@for a in $(foreach g,$(OPTIONAL_GAMES),$(if $(NWA_$(g)),$(basename $(NWA_$(g))))); do \
$(NWLINK) nwa-bin --ram-length $(CUSTOM_RAM) $(B)/apps/$$a.nwa $(B)/apps/$$a.bin >/dev/null || \
{ echo "$$a.nwa needs more RAM than custom builds of 25.2 give apps ($(CUSTOM_RAM) bytes)"; exit 1; }; \
diff --git a/games/hillclimb/Makefile b/games/hillclimb/Makefile
index b1b63bd0..c3053e6c 100644
--- a/games/hillclimb/Makefile
+++ b/games/hillclimb/Makefile
@@ -41,10 +41,15 @@ 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)
+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones); installed on its
+# own, the app must fit the calculator's space for apps (0x90200000 to 0x903F0000 in its flash)
+RAM_LENGTH = 133652
+APP_SPACE = 2031616
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"
+ $(Q) $(NWLINK) nwa-bin --ram-length $(RAM_LENGTH) $< $(BUILD_DIR)/hillclimb.bin
+ @n=$$(wc -c < $(BUILD_DIR)/hillclimb.bin); \
+ echo "BIN $(BUILD_DIR)/hillclimb.bin: $$n bytes, $$(( $(APP_SPACE) - n )) to spare of the app space"; \
+ [ $$n -le $(APP_SPACE) ] || { echo "hillclimb.nwa is bigger than the calculator's app space ($(APP_SPACE) bytes)"; exit 1; }
$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)
$(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@
diff --git a/games/hillclimb/README.md b/games/hillclimb/README.md
index c9c34053..4c3a7179 100644
--- a/games/hillclimb/README.md
+++ b/games/hillclimb/README.md
@@ -8,7 +8,7 @@
<p align="center">
<b>Newton Bill's ride up the hills, on the NumWorks calculator.</b><br>
- Ten stages, eight vehicles and every one of their upgrades: drive as far as your fuel and Bill's neck allow.
+ Thirteen stages, thirteen vehicles and every one of their upgrades: drive as far as your fuel and Bill's neck allow.
</p>
<p align="center">
@@ -22,11 +22,11 @@
## Highlights
-* **The game's own physics:** it runs on Box2D 2.2.1, the physics engine the game itself uses, 60 steps a second, with the game's own numbers read from its Android package: each vehicle's chassis, wheels, springs, engine, turbo, brakes, air control and downforce, each stage's gravity and grip, and the ground in pieces of half a meter. The wheels hang on springs and the engine turns them against the chassis, so the nose rises when you floor it and you can flip over backwards on a steep hill. In the air, gas tilts you back and brake tilts you forward.
-* **Bill's neck:** when his head touches the ground or a cave's roof, it's *Driver down*, and the run ends 4 seconds later. A tank lasts 40 seconds (the Dune Buggy and the Tank burn theirs at their own rate, which their Fuel upgrade lowers), each fuel can fills it up, and the cans come at the stage's own spacing. When it runs dry you roll on for 4 more seconds.
+* **The game's own physics:** it runs on Box2D 2.2.1, the physics engine the game itself uses, 60 steps a second, with the game's own numbers read from its Android package: each vehicle's chassis, wheels, springs, engine, turbo, brakes, air control and downforce, each stage's gravity and grip, and the ground in pieces of half a meter. The Tractor's back wheel is a soft tire of 16 balls on springs, the Tourist Bus carries three passengers who go limp when they hit the ground, and the Snow Mobile rides on a ski and a track. The wheels hang on springs and the engine turns them against the chassis, so the nose rises when you floor it and you can flip over backwards on a steep hill. In the air, gas tilts you back and brake tilts you forward.
+* **Bill's neck:** when his head touches the ground or a cave's roof, it's *Driver down*, and the run ends 4 seconds later. A tank lasts 40 seconds (vehicles with a Fuel upgrade burn theirs at their own rate, which the upgrade lowers), each fuel can fills it up, and the cans come at the stage's own spacing. When it runs dry you roll on for 4 more seconds.
* **Coins of 5, 25, 100 and 500**, bigger the further you go, in rows along the road. **Air time** pays from 0.75 s in the air, every 0.2 s: 25 for the first four steps, then *Big air time* 100 each, then *Insane air time* 500 each. Every **flip** and **back flip** pays 1,000, and a **neck flip** (going down in the middle of one) 2,500.
* **Levels, as in the game:** each stage has its own, kept from run to run. Reach the goal (200 m on the Countryside, then 400 m, 600 m...) and its bonus is paid; the next one waits for you, on this run or the next.
-* **Ten stages**, each with its own ground, sky, grip, gravity and spacing of fuel, with the game's prices:
+* **Thirteen stages**, each with its own ground, sky, grip, gravity and spacing of fuel, with the game's prices:
| Stage | Price | |
| --- | --- | --- |
@@ -40,22 +40,30 @@
| Alien Planet | 750,000 | A slimy, slippery, sloped world under a green night |
| Arctic Cave | 800,000 | A cave of ice, slippery, with icicles hanging from its roof |
| Forest | 850,000 | Bunches of pine trees in the way: ram them or push them over |
+ | Mountain | 850,000 | Very bumpy and uphill nearly all the way, with rope bridges |
+ | Mudpool | 1,000,000 | Pools of mud in its dips: you sink in and slow down, and push through with the gas |
+ | Volcano | 1,000,000 | Ash and pools of lava: whatever touches the lava catches fire, and fire burns fuel fast |
-* **Eight vehicles** that each drive their own way, with the game's prices and their four upgrades, each in the game's number of levels and at its prices:
+* **Thirteen vehicles** that each drive their own way, in the game's order, with its prices and their four upgrades, each in the game's number of levels and at its prices:
| Vehicle | Price | Upgrades |
| --- | --- | --- |
| Hill Climber | free | Engine, Suspension, Tires, 4WD |
| Motocross Bike | 75,000 | Engine, Suspension, Tires, Air Control |
| Monster Truck | 100,000 | Engine, Suspension, Tires, 4WD |
+ | Tractor | 100,000 | Engine, Tires, Fuel, Stability |
| Quad Bike | 175,000 | Engine, Suspension, Tires, 4WD |
+ | Tourist Bus | 200,000 | Engine, Suspension, Tires, Fuel |
| Race Car | 250,000 | Engine, Suspension, Tires, Downforce |
+ | Super Diesel 4x4 | 500,000 | Engine, Suspension, Tires, Fuel |
| Rally Car | 750,000 | Engine, Suspension, Tires, Downforce |
- | Dune Buggy | 800,000 | Engine, Suspension, Tires, Fuel |
| Tank | 1,000,000 | Engine, Suspension, Tracks, Fuel |
+ | Snow Mobile | 1,000,000 | Engine, Suspension, Tracks, Fuel |
+ | Truck | 1,000,000 | Engine, Suspension, Tires, Fuel |
+ | Dune Buggy | 800,000 | Engine, Suspension, Tires, Fuel |
* **The game's own look:** its vehicles, wheels and Bill, its coins and fuel cans, each stage's sky, surface and ground, the pedals and the RPM and boost meters on the dashboard, the garage and the stage cards, all from the game itself.
-* **Saved as you go:** coins, what you own and its upgrades, and your best distance on each stage with each vehicle. A run left halfway keeps its coins. The save is also copied into `hillclimb_saves.py`, so installing the app again doesn't erase it.
+* **Saved as you go:** coins, what you own and its upgrades, and your best distance on each stage with each vehicle. A run left halfway keeps its coins. The save is also copied into `hillclimb_saves.py`, so installing the app again doesn't erase it. Saves from earlier versions load with their coins and progress.
<table>
<tr>
@@ -66,7 +74,17 @@
<tr>
<td align="center"><img src="docs/cave.png" width="100%" alt="The Hill Climber in the Cave, under its rocky ceiling"><br>The Cave</td>
<td align="center"><img src="docs/forest.png" width="100%" alt="The Hill Climber ramming the Forest's pine trees"><br>The Forest's trees</td>
- <td align="center"><img src="docs/garage.png" width="100%" alt="The garage: the Hill Climber and its four upgrades"><br>The garage</td>
+ <td align="center"><img src="docs/mountain.png" width="100%" alt="The Tourist Bus and its passengers on a rope bridge on the Mountain"><br>The Tourist Bus on the Mountain</td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/mudpool.png" width="100%" alt="The Truck sunk to its cab in a pool of mud"><br>The Truck in the Mudpool</td>
+ <td align="center"><img src="docs/volcano.png" width="100%" alt="The Tractor on fire in a pool of lava"><br>The Tractor in the Volcano's lava</td>
+ <td align="center"><img src="docs/snowmobile.png" width="100%" alt="The Snow Mobile on the Arctic, coins ahead"><br>The Snow Mobile on the Arctic</td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/garage.png" width="100%" alt="The garage: the Tractor and its four upgrades, the vehicles in a strip at the top"><br>The garage</td>
+ <td align="center"><img src="docs/stages.png" width="100%" alt="The stages: the Volcano, the stages in a strip at the top"><br>The stages</td>
+ <td></td>
</tr>
</table>
@@ -78,14 +96,21 @@
| **Left** (or 4) | Brake, then reverse; in the air, tilt forward |
| **Back** | Pause: Resume, Restart, Garage, Quit game (it asks first) |
| **Home** or **On/Off** | Keep the run's coins and quit |
-| In the menus | **Left**, **Right** to choose a vehicle or a stage, **Down** to the upgrades, **OK** to buy or go, **Back** to go back |
+| In the menus | **Left**, **Right** to choose a vehicle or a stage (the strip at the top shows them all, the chosen one framed), **Down** to the upgrades, **OK** to buy or go, **Back** to go back. The line at the bottom says what each key does |
+
+## Good to know
+
+* **13 vehicles and 13 stages, as in version 1.10.2.** The game kept growing after that, to 44 vehicles and about as many stages. Those are left out: their code is only in builds without symbols, so how they drive can't be read from it, and the wiki has their prices and upgrades but not their physics. The Moonlander and the Onewheeler are in 1.10.2's code, but weren't on sale yet, so they're left out too.
+* **Upgrades as in the game.** The Monster Truck, Quad Bike, Race Car, Rally Car, Dune Buggy and Tank now have the game's last levels and prices. An old save with an upgrade past its new last level is lowered to it, and the coins paid for the levels taken off come back.
+* **The Tractor's soft tire** is the game's 16 balls on springs, but it is drawn as a round tire that grows and shrinks with them rather than bending.
+* **Lava only burns fuel.** As in the game, mud and lava never count as touching Bill's head: only the ground under them does.
## Credits
-**Hill Climb Racing** is [Fingersoft](https://fingersoft.com)'s game (2012), with Newton Bill at the wheel. This version is written in C and C++ for NumPlay. How it plays is the game's own: the vehicles, the stages' ground, gravity and grip, the bridges and trees, the coins, fuel, levels, prices and bonuses follow the numbers and rules read from the game's Android package (versions 1.0 to 1.70, mostly 1.10 and 1.16), and were checked against videos of the game. Its pictures (the vehicles, Bill, the coins, the stages' grounds and skies, the pedals, meters, icons and the logo) are the game's own, as the [Hill Climb Racing Wiki](https://hillclimbracing.fandom.com) keeps them. Its text is set in **Teko** (SIL Open Font License, [license](../../LICENSES/OFL-1.1-Teko.txt)). It is an unofficial fan game, not affiliated with Fingersoft.
+**Hill Climb Racing** is [Fingersoft](https://fingersoft.com)'s game (2012), with Newton Bill at the wheel. This version is written in C and C++ for NumPlay. How it plays is the game's own: the vehicles, the stages' ground, gravity and grip, the bridges, pits and trees, the coins, fuel, levels, prices and bonuses follow the numbers and rules read from the game's Android package (versions 1.0 to 1.70, mostly 1.10 and 1.16; the five vehicles and three stages added here from 1.10.2), and were checked against videos of the game. Its pictures (the vehicles, Bill, the coins, the stages' grounds and skies, the pedals, meters, icons and the logo) are the game's own, as the [Hill Climb Racing Wiki](https://hillclimbracing.fandom.com) keeps them, or taken from the game's 1.10.2 Android package where the wiki has no copy (the Tractor, the Tourist Bus and its passengers, the Super Diesel 4x4, the Truck, and the Mountain's, Mudpool's and Volcano's grounds, skies, mud, lava and fire). Its text is set in **Teko** (SIL Open Font License, [license](../../LICENSES/OFL-1.1-Teko.txt)). It is an unofficial fan game, not affiliated with Fingersoft.
The physics is **Box2D 2.2.1** by Erin Catto (zlib license, [src/box2d/License.txt](src/box2d/License.txt)), the version the game is built with, cut down to the parts the game uses. The files changed to fit the calculator say so at their top.
-`tools/fetch.py` gathers the wiki's pictures and the font, and `tools/pack.py` turns them into `src/data.bin` (committed, so building needs no network).
+`tools/fetch.py` gathers the wiki's pictures, the game's 1.10.2 Android package for the pictures the wiki lacks, and the font, and `tools/pack.py` turns them into `src/data.bin` (committed, so building needs no network).
Build: `make` (needs `arm-none-eabi-gcc` and `arm-none-eabi-g++`, and Node.js for nwlink). `make test` plays it on a computer with the sanitizers (tests/check.py).
diff --git a/games/hillclimb/docs/garage.png b/games/hillclimb/docs/garage.png
index 52434b95..89b7a246 100644
Binary files a/games/hillclimb/docs/garage.png and b/games/hillclimb/docs/garage.png differ
diff --git a/games/hillclimb/docs/mountain.png b/games/hillclimb/docs/mountain.png
new file mode 100644
index 00000000..4dbf0e86
Binary files /dev/null and b/games/hillclimb/docs/mountain.png differ
diff --git a/games/hillclimb/docs/mudpool.png b/games/hillclimb/docs/mudpool.png
new file mode 100644
index 00000000..bb1c7389
Binary files /dev/null and b/games/hillclimb/docs/mudpool.png differ
diff --git a/games/hillclimb/docs/snowmobile.png b/games/hillclimb/docs/snowmobile.png
new file mode 100644
index 00000000..4776ee92
Binary files /dev/null and b/games/hillclimb/docs/snowmobile.png differ
diff --git a/games/hillclimb/docs/stages.png b/games/hillclimb/docs/stages.png
new file mode 100644
index 00000000..b5afda12
Binary files /dev/null and b/games/hillclimb/docs/stages.png differ
diff --git a/games/hillclimb/docs/volcano.png b/games/hillclimb/docs/volcano.png
new file mode 100644
index 00000000..955f636c
Binary files /dev/null and b/games/hillclimb/docs/volcano.png differ
diff --git a/games/hillclimb/src/art.h b/games/hillclimb/src/art.h
index ce02d2ba..6f7f94fd 100644
--- a/games/hillclimb/src/art.h
+++ b/games/hillclimb/src/art.h
@@ -12,7 +12,7 @@ typedef struct {
float tube[2][5]; /* from (x, y) to axle (index), colour 0xRRGGBB, radius */
float layer[2][4]; /* picture, its centre (x, y), in front (1) or behind */
} VehArt;
-#define NVEH 8
+#define NVEH 13
static const VehArt veh_art[NVEH] = {
{IMG_CH_JEEP, IMG_WHEEL_JEEP, 0, 0, 0, 0.400f, {{0}}, {{0}}}, /* Hill Climber */
{IMG_CH_BIKE, IMG_WHEEL_BIKE, 1, 2, 0, 0.500f, {{0.000f, -0.500f, 0.000f, 5922406.0f, 0.090f}, {0.600f, 0.425f, 1.000f, 3159098.0f, 0.070f}}, {{0}}}, /* Motocross Bike */
@@ -22,5 +22,10 @@ static const VehArt veh_art[NVEH] = {
{IMG_CH_RALLY, IMG_WHEEL_RALLY, 0, 0, 0, 0.500f, {{0}}, {{0}}}, /* Rally Car */
{IMG_CH_BUGGY, IMG_WHEEL_BUGGY, 0, 0, 0, 0.500f, {{0}}, {{0}}}, /* Dune Buggy */
{IMG_CH_TANK, IMG_WHEEL_TANK, 0, 0, 2, 0.350f, {{0}}, {{IMG_LAYER_CAR_TANK_BG, 0.000f, 0.000f, 0}, {IMG_LAYER_CAR_TANK_CANNON, 1.600f, 0.800f, 1}}}, /* Tank */
+ {IMG_CH_TRACTOR, IMG_WHEEL_TRACTOR, 0, 0, 0, 1.090f, {{0}}, {{0}}}, /* Tractor */
+ {IMG_CH_BUS, IMG_WHEEL_MONSTER, 0, 0, 0, 0.700f, {{0}}, {{0}}}, /* Tourist Bus */
+ {IMG_CH_DIESEL, IMG_WHEEL_MONSTER, 0, 0, 0, 0.700f, {{0}}, {{0}}}, /* Super Diesel 4x4 */
+ {IMG_CH_SNOWMOBILE, IMG_WHEEL_TANK, 1, 0, 0, 0.462f, {{0}}, {{0}}}, /* Snow Mobile */
+ {IMG_CH_TRUCK, IMG_WHEEL_MONSTER, 0, 0, 0, 0.700f, {{0}}, {{0}}}, /* Truck */
};
#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2Settings.cpp b/games/hillclimb/src/box2d/Box2D/Common/b2Settings.cpp
index 01b3d5ad..33b9829a 100644
--- a/games/hillclimb/src/box2d/Box2D/Common/b2Settings.cpp
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2Settings.cpp
@@ -1,4 +1,5 @@
-/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): b2Log prints nothing */
+/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): b2Log prints nothing; on a computer (tests) the
+ * memory in use is counted */
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
@@ -24,6 +25,27 @@
b2Version b2_version = {2, 2, 1};
// Memory allocators. Modify these to use your own allocator.
+#ifdef HOST
+/* (tests: Box2D's memory in use and the most it has used, a word before each block keeping its size) */
+extern "C" { long b2_heap_now, b2_heap_peak; }
+void* b2Alloc(int32 size)
+{
+ long *p = (long *)malloc(size + sizeof(long) * 2);
+ if (!p) return NULL;
+ p[0] = size;
+ b2_heap_now += size;
+ if (b2_heap_now > b2_heap_peak) b2_heap_peak = b2_heap_now;
+ return p + 2;
+}
+
+void b2Free(void* mem)
+{
+ if (!mem) return;
+ long *p = (long *)mem - 2;
+ b2_heap_now -= p[0];
+ free(p);
+}
+#else
void* b2Alloc(int32 size)
{
return malloc(size);
@@ -33,6 +55,7 @@ void b2Free(void* mem)
{
free(mem);
}
+#endif
// You can modify this to use your logging facility.
void b2Log(const char* string, ...)
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp
index 557af7f0..6ee200ff 100644
--- a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp
@@ -1,3 +1,5 @@
+/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): sensors call PreSolve while they overlap, as in the
+ * game's own Box2D (its pits of mud and lava are sensors) */
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
@@ -233,7 +235,7 @@ void b2Contact::Update(b2ContactListener* listener)
listener->EndContact(this);
}
- if (sensor == false && touching && listener)
+ if (touching && listener)
{
listener->PreSolve(this, &oldManifold);
}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2Joint.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2Joint.cpp
index 6ad78b0f..1625996c 100644
--- a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2Joint.cpp
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2Joint.cpp
@@ -1,4 +1,5 @@
-/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): only the distance, revolute and wheel joints are made */
+/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): only the distance, revolute, prismatic and wheel joints
+ * are made */
/*
* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org
*
@@ -21,6 +22,7 @@
#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>
#include <Box2D/Dynamics/Joints/b2WheelJoint.h>
#include <Box2D/Dynamics/Joints/b2RevoluteJoint.h>
+#include <Box2D/Dynamics/Joints/b2PrismaticJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2World.h>
#include <Box2D/Common/b2BlockAllocator.h>
@@ -54,6 +56,13 @@ b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator)
}
break;
+ case e_prismaticJoint:
+ {
+ void* mem = allocator->Allocate(sizeof(b2PrismaticJoint));
+ joint = new (mem) b2PrismaticJoint((b2PrismaticJointDef*)def);
+ }
+ break;
+
default:
b2Assert(false);
break;
@@ -78,6 +87,10 @@ void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator)
case e_wheelJoint:
allocator->Free(joint, sizeof(b2WheelJoint));
break;
+
+ case e_prismaticJoint:
+ allocator->Free(joint, sizeof(b2PrismaticJoint));
+ break;
default:
b2Assert(false);
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp
new file mode 100644
index 00000000..88a38807
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp
@@ -0,0 +1,637 @@
+/*
+* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
+*
+* This software is provided 'as-is', without any express or implied
+* warranty. In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include <Box2D/Dynamics/Joints/b2PrismaticJoint.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+
+// Linear constraint (point-to-line)
+// d = p2 - p1 = x2 + r2 - x1 - r1
+// C = dot(perp, d)
+// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1))
+// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2)
+// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)]
+//
+// Angular constraint
+// C = a2 - a1 + a_initial
+// Cdot = w2 - w1
+// J = [0 0 -1 0 0 1]
+//
+// K = J * invM * JT
+//
+// J = [-a -s1 a s2]
+// [0 -1 0 1]
+// a = perp
+// s1 = cross(d + r1, a) = cross(p2 - x1, a)
+// s2 = cross(r2, a) = cross(p2 - x2, a)
+
+
+// Motor/Limit linear constraint
+// C = dot(ax1, d)
+// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2)
+// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)]
+
+// Block Solver
+// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even
+// when the mass has poor distribution (leading to large torques about the joint anchor points).
+//
+// The Jacobian has 3 rows:
+// J = [-uT -s1 uT s2] // linear
+// [0 -1 0 1] // angular
+// [-vT -a1 vT a2] // limit
+//
+// u = perp
+// v = axis
+// s1 = cross(d + r1, u), s2 = cross(r2, u)
+// a1 = cross(d + r1, v), a2 = cross(r2, v)
+
+// M * (v2 - v1) = JT * df
+// J * v2 = bias
+//
+// v2 = v1 + invM * JT * df
+// J * (v1 + invM * JT * df) = bias
+// K * df = bias - J * v1 = -Cdot
+// K = J * invM * JT
+// Cdot = J * v1 - bias
+//
+// Now solve for f2.
+// df = f2 - f1
+// K * (f2 - f1) = -Cdot
+// f2 = invK * (-Cdot) + f1
+//
+// Clamp accumulated limit impulse.
+// lower: f2(3) = max(f2(3), 0)
+// upper: f2(3) = min(f2(3), 0)
+//
+// Solve for correct f2(1:2)
+// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1
+// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3)
+// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2)
+// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
+//
+// Now compute impulse to be applied:
+// df = f2 - f1
+
+void b2PrismaticJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis)
+{
+ bodyA = bA;
+ bodyB = bB;
+ localAnchorA = bodyA->GetLocalPoint(anchor);
+ localAnchorB = bodyB->GetLocalPoint(anchor);
+ localAxisA = bodyA->GetLocalVector(axis);
+ referenceAngle = bodyB->GetAngle() - bodyA->GetAngle();
+}
+
+b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def)
+: b2Joint(def)
+{
+ m_localAnchorA = def->localAnchorA;
+ m_localAnchorB = def->localAnchorB;
+ m_localXAxisA = def->localAxisA;
+ m_localXAxisA.Normalize();
+ m_localYAxisA = b2Cross(1.0f, m_localXAxisA);
+ m_referenceAngle = def->referenceAngle;
+
+ m_impulse.SetZero();
+ m_motorMass = 0.0;
+ m_motorImpulse = 0.0f;
+
+ m_lowerTranslation = def->lowerTranslation;
+ m_upperTranslation = def->upperTranslation;
+ m_maxMotorForce = def->maxMotorForce;
+ m_motorSpeed = def->motorSpeed;
+ m_enableLimit = def->enableLimit;
+ m_enableMotor = def->enableMotor;
+ m_limitState = e_inactiveLimit;
+
+ m_axis.SetZero();
+ m_perp.SetZero();
+}
+
+void b2PrismaticJoint::InitVelocityConstraints(const b2SolverData& data)
+{
+ m_indexA = m_bodyA->m_islandIndex;
+ m_indexB = m_bodyB->m_islandIndex;
+ m_localCenterA = m_bodyA->m_sweep.localCenter;
+ m_localCenterB = m_bodyB->m_sweep.localCenter;
+ m_invMassA = m_bodyA->m_invMass;
+ m_invMassB = m_bodyB->m_invMass;
+ m_invIA = m_bodyA->m_invI;
+ m_invIB = m_bodyB->m_invI;
+
+ b2Vec2 cA = data.positions[m_indexA].c;
+ float32 aA = data.positions[m_indexA].a;
+ b2Vec2 vA = data.velocities[m_indexA].v;
+ float32 wA = data.velocities[m_indexA].w;
+
+ b2Vec2 cB = data.positions[m_indexB].c;
+ float32 aB = data.positions[m_indexB].a;
+ b2Vec2 vB = data.velocities[m_indexB].v;
+ float32 wB = data.velocities[m_indexB].w;
+
+ b2Rot qA(aA), qB(aB);
+
+ // Compute the effective masses.
+ b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
+ b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
+ b2Vec2 d = (cB - cA) + rB - rA;
+
+ float32 mA = m_invMassA, mB = m_invMassB;
+ float32 iA = m_invIA, iB = m_invIB;
+
+ // Compute motor Jacobian and effective mass.
+ {
+ m_axis = b2Mul(qA, m_localXAxisA);
+ m_a1 = b2Cross(d + rA, m_axis);
+ m_a2 = b2Cross(rB, m_axis);
+
+ m_motorMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2;
+ if (m_motorMass > 0.0f)
+ {
+ m_motorMass = 1.0f / m_motorMass;
+ }
+ }
+
+ // Prismatic constraint.
+ {
+ m_perp = b2Mul(qA, m_localYAxisA);
+
+ m_s1 = b2Cross(d + rA, m_perp);
+ m_s2 = b2Cross(rB, m_perp);
+
+ float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2;
+ float32 k12 = iA * m_s1 + iB * m_s2;
+ float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2;
+ float32 k22 = iA + iB;
+ if (k22 == 0.0f)
+ {
+ // For bodies with fixed rotation.
+ k22 = 1.0f;
+ }
+ float32 k23 = iA * m_a1 + iB * m_a2;
+ float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2;
+
+ m_K.ex.Set(k11, k12, k13);
+ m_K.ey.Set(k12, k22, k23);
+ m_K.ez.Set(k13, k23, k33);
+ }
+
+ // Compute motor and limit terms.
+ if (m_enableLimit)
+ {
+ float32 jointTranslation = b2Dot(m_axis, d);
+ if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop)
+ {
+ m_limitState = e_equalLimits;
+ }
+ else if (jointTranslation <= m_lowerTranslation)
+ {
+ if (m_limitState != e_atLowerLimit)
+ {
+ m_limitState = e_atLowerLimit;
+ m_impulse.z = 0.0f;
+ }
+ }
+ else if (jointTranslation >= m_upperTranslation)
+ {
+ if (m_limitState != e_atUpperLimit)
+ {
+ m_limitState = e_atUpperLimit;
+ m_impulse.z = 0.0f;
+ }
+ }
+ else
+ {
+ m_limitState = e_inactiveLimit;
+ m_impulse.z = 0.0f;
+ }
+ }
+ else
+ {
+ m_limitState = e_inactiveLimit;
+ m_impulse.z = 0.0f;
+ }
+
+ if (m_enableMotor == false)
+ {
+ m_motorImpulse = 0.0f;
+ }
+
+ if (data.step.warmStarting)
+ {
+ // Account for variable time step.
+ m_impulse *= data.step.dtRatio;
+ m_motorImpulse *= data.step.dtRatio;
+
+ b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis;
+ float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1;
+ float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2;
+
+ vA -= mA * P;
+ wA -= iA * LA;
+
+ vB += mB * P;
+ wB += iB * LB;
+ }
+ else
+ {
+ m_impulse.SetZero();
+ m_motorImpulse = 0.0f;
+ }
+
+ data.velocities[m_indexA].v = vA;
+ data.velocities[m_indexA].w = wA;
+ data.velocities[m_indexB].v = vB;
+ data.velocities[m_indexB].w = wB;
+}
+
+void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data)
+{
+ b2Vec2 vA = data.velocities[m_indexA].v;
+ float32 wA = data.velocities[m_indexA].w;
+ b2Vec2 vB = data.velocities[m_indexB].v;
+ float32 wB = data.velocities[m_indexB].w;
+
+ float32 mA = m_invMassA, mB = m_invMassB;
+ float32 iA = m_invIA, iB = m_invIB;
+
+ // Solve linear motor constraint.
+ if (m_enableMotor && m_limitState != e_equalLimits)
+ {
+ float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA;
+ float32 impulse = m_motorMass * (m_motorSpeed - Cdot);
+ float32 oldImpulse = m_motorImpulse;
+ float32 maxImpulse = data.step.dt * m_maxMotorForce;
+ m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
+ impulse = m_motorImpulse - oldImpulse;
+
+ b2Vec2 P = impulse * m_axis;
+ float32 LA = impulse * m_a1;
+ float32 LB = impulse * m_a2;
+
+ vA -= mA * P;
+ wA -= iA * LA;
+
+ vB += mB * P;
+ wB += iB * LB;
+ }
+
+ b2Vec2 Cdot1;
+ Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA;
+ Cdot1.y = wB - wA;
+
+ if (m_enableLimit && m_limitState != e_inactiveLimit)
+ {
+ // Solve prismatic and limit constraint in block form.
+ float32 Cdot2;
+ Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA;
+ b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2);
+
+ b2Vec3 f1 = m_impulse;
+ b2Vec3 df = m_K.Solve33(-Cdot);
+ m_impulse += df;
+
+ if (m_limitState == e_atLowerLimit)
+ {
+ m_impulse.z = b2Max(m_impulse.z, 0.0f);
+ }
+ else if (m_limitState == e_atUpperLimit)
+ {
+ m_impulse.z = b2Min(m_impulse.z, 0.0f);
+ }
+
+ // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
+ b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y);
+ b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y);
+ m_impulse.x = f2r.x;
+ m_impulse.y = f2r.y;
+
+ df = m_impulse - f1;
+
+ b2Vec2 P = df.x * m_perp + df.z * m_axis;
+ float32 LA = df.x * m_s1 + df.y + df.z * m_a1;
+ float32 LB = df.x * m_s2 + df.y + df.z * m_a2;
+
+ vA -= mA * P;
+ wA -= iA * LA;
+
+ vB += mB * P;
+ wB += iB * LB;
+ }
+ else
+ {
+ // Limit is inactive, just solve the prismatic constraint in block form.
+ b2Vec2 df = m_K.Solve22(-Cdot1);
+ m_impulse.x += df.x;
+ m_impulse.y += df.y;
+
+ b2Vec2 P = df.x * m_perp;
+ float32 LA = df.x * m_s1 + df.y;
+ float32 LB = df.x * m_s2 + df.y;
+
+ vA -= mA * P;
+ wA -= iA * LA;
+
+ vB += mB * P;
+ wB += iB * LB;
+
+ b2Vec2 Cdot10 = Cdot1;
+
+ Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA;
+ Cdot1.y = wB - wA;
+
+ if (b2Abs(Cdot1.x) > 0.01f || b2Abs(Cdot1.y) > 0.01f)
+ {
+ b2Vec2 test = b2Mul22(m_K, df);
+ Cdot1.x += 0.0f;
+ }
+ }
+
+ data.velocities[m_indexA].v = vA;
+ data.velocities[m_indexA].w = wA;
+ data.velocities[m_indexB].v = vB;
+ data.velocities[m_indexB].w = wB;
+}
+
+bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data)
+{
+ b2Vec2 cA = data.positions[m_indexA].c;
+ float32 aA = data.positions[m_indexA].a;
+ b2Vec2 cB = data.positions[m_indexB].c;
+ float32 aB = data.positions[m_indexB].a;
+
+ b2Rot qA(aA), qB(aB);
+
+ float32 mA = m_invMassA, mB = m_invMassB;
+ float32 iA = m_invIA, iB = m_invIB;
+
+ // Compute fresh Jacobians
+ b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
+ b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
+ b2Vec2 d = cB + rB - cA - rA;
+
+ b2Vec2 axis = b2Mul(qA, m_localXAxisA);
+ float32 a1 = b2Cross(d + rA, axis);
+ float32 a2 = b2Cross(rB, axis);
+ b2Vec2 perp = b2Mul(qA, m_localYAxisA);
+
+ float32 s1 = b2Cross(d + rA, perp);
+ float32 s2 = b2Cross(rB, perp);
+
+ b2Vec3 impulse;
+ b2Vec2 C1;
+ C1.x = b2Dot(perp, d);
+ C1.y = aB - aA - m_referenceAngle;
+
+ float32 linearError = b2Abs(C1.x);
+ float32 angularError = b2Abs(C1.y);
+
+ bool active = false;
+ float32 C2 = 0.0f;
+ if (m_enableLimit)
+ {
+ float32 translation = b2Dot(axis, d);
+ if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop)
+ {
+ // Prevent large angular corrections
+ C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection);
+ linearError = b2Max(linearError, b2Abs(translation));
+ active = true;
+ }
+ else if (translation <= m_lowerTranslation)
+ {
+ // Prevent large linear corrections and allow some slop.
+ C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f);
+ linearError = b2Max(linearError, m_lowerTranslation - translation);
+ active = true;
+ }
+ else if (translation >= m_upperTranslation)
+ {
+ // Prevent large linear corrections and allow some slop.
+ C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection);
+ linearError = b2Max(linearError, translation - m_upperTranslation);
+ active = true;
+ }
+ }
+
+ if (active)
+ {
+ float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
+ float32 k12 = iA * s1 + iB * s2;
+ float32 k13 = iA * s1 * a1 + iB * s2 * a2;
+ float32 k22 = iA + iB;
+ if (k22 == 0.0f)
+ {
+ // For fixed rotation
+ k22 = 1.0f;
+ }
+ float32 k23 = iA * a1 + iB * a2;
+ float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2;
+
+ b2Mat33 K;
+ K.ex.Set(k11, k12, k13);
+ K.ey.Set(k12, k22, k23);
+ K.ez.Set(k13, k23, k33);
+
+ b2Vec3 C;
+ C.x = C1.x;
+ C.y = C1.y;
+ C.z = C2;
+
+ impulse = K.Solve33(-C);
+ }
+ else
+ {
+ float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
+ float32 k12 = iA * s1 + iB * s2;
+ float32 k22 = iA + iB;
+ if (k22 == 0.0f)
+ {
+ k22 = 1.0f;
+ }
+
+ b2Mat22 K;
+ K.ex.Set(k11, k12);
+ K.ey.Set(k12, k22);
+
+ b2Vec2 impulse1 = K.Solve(-C1);
+ impulse.x = impulse1.x;
+ impulse.y = impulse1.y;
+ impulse.z = 0.0f;
+ }
+
+ b2Vec2 P = impulse.x * perp + impulse.z * axis;
+ float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1;
+ float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2;
+
+ cA -= mA * P;
+ aA -= iA * LA;
+ cB += mB * P;
+ aB += iB * LB;
+
+ data.positions[m_indexA].c = cA;
+ data.positions[m_indexA].a = aA;
+ data.positions[m_indexB].c = cB;
+ data.positions[m_indexB].a = aB;
+
+ return linearError <= b2_linearSlop && angularError <= b2_angularSlop;
+}
+
+b2Vec2 b2PrismaticJoint::GetAnchorA() const
+{
+ return m_bodyA->GetWorldPoint(m_localAnchorA);
+}
+
+b2Vec2 b2PrismaticJoint::GetAnchorB() const
+{
+ return m_bodyB->GetWorldPoint(m_localAnchorB);
+}
+
+b2Vec2 b2PrismaticJoint::GetReactionForce(float32 inv_dt) const
+{
+ return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis);
+}
+
+float32 b2PrismaticJoint::GetReactionTorque(float32 inv_dt) const
+{
+ return inv_dt * m_impulse.y;
+}
+
+float32 b2PrismaticJoint::GetJointTranslation() const
+{
+ b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA);
+ b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB);
+ b2Vec2 d = pB - pA;
+ b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA);
+
+ float32 translation = b2Dot(d, axis);
+ return translation;
+}
+
+float32 b2PrismaticJoint::GetJointSpeed() const
+{
+ b2Body* bA = m_bodyA;
+ b2Body* bB = m_bodyB;
+
+ b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter);
+ b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter);
+ b2Vec2 p1 = bA->m_sweep.c + rA;
+ b2Vec2 p2 = bB->m_sweep.c + rB;
+ b2Vec2 d = p2 - p1;
+ b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA);
+
+ b2Vec2 vA = bA->m_linearVelocity;
+ b2Vec2 vB = bB->m_linearVelocity;
+ float32 wA = bA->m_angularVelocity;
+ float32 wB = bB->m_angularVelocity;
+
+ float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA));
+ return speed;
+}
+
+bool b2PrismaticJoint::IsLimitEnabled() const
+{
+ return m_enableLimit;
+}
+
+void b2PrismaticJoint::EnableLimit(bool flag)
+{
+ if (flag != m_enableLimit)
+ {
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_enableLimit = flag;
+ m_impulse.z = 0.0f;
+ }
+}
+
+float32 b2PrismaticJoint::GetLowerLimit() const
+{
+ return m_lowerTranslation;
+}
+
+float32 b2PrismaticJoint::GetUpperLimit() const
+{
+ return m_upperTranslation;
+}
+
+void b2PrismaticJoint::SetLimits(float32 lower, float32 upper)
+{
+ b2Assert(lower <= upper);
+ if (lower != m_lowerTranslation || upper != m_upperTranslation)
+ {
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_lowerTranslation = lower;
+ m_upperTranslation = upper;
+ m_impulse.z = 0.0f;
+ }
+}
+
+bool b2PrismaticJoint::IsMotorEnabled() const
+{
+ return m_enableMotor;
+}
+
+void b2PrismaticJoint::EnableMotor(bool flag)
+{
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_enableMotor = flag;
+}
+
+void b2PrismaticJoint::SetMotorSpeed(float32 speed)
+{
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_motorSpeed = speed;
+}
+
+void b2PrismaticJoint::SetMaxMotorForce(float32 force)
+{
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_maxMotorForce = force;
+}
+
+float32 b2PrismaticJoint::GetMotorForce(float32 inv_dt) const
+{
+ return inv_dt * m_motorImpulse;
+}
+
+void b2PrismaticJoint::Dump()
+{
+ int32 indexA = m_bodyA->m_islandIndex;
+ int32 indexB = m_bodyB->m_islandIndex;
+
+ b2Log(" b2PrismaticJointDef jd;\n");
+ b2Log(" jd.bodyA = bodies[%d];\n", indexA);
+ b2Log(" jd.bodyB = bodies[%d];\n", indexB);
+ b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
+ b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y);
+ b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y);
+ b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y);
+ b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle);
+ b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit);
+ b2Log(" jd.lowerTranslation = %.15lef;\n", m_lowerTranslation);
+ b2Log(" jd.upperTranslation = %.15lef;\n", m_upperTranslation);
+ b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor);
+ b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed);
+ b2Log(" jd.maxMotorForce = %.15lef;\n", m_maxMotorForce);
+ b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h
new file mode 100644
index 00000000..8d0f3422
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2PrismaticJoint.h
@@ -0,0 +1,196 @@
+/*
+* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
+*
+* This software is provided 'as-is', without any express or implied
+* warranty. In no event will the authors be held liable for any damages
+* arising from the use of this software.
+* Permission is granted to anyone to use this software for any purpose,
+* including commercial applications, and to alter it and redistribute it
+* freely, subject to the following restrictions:
+* 1. The origin of this software must not be misrepresented; you must not
+* claim that you wrote the original software. If you use this software
+* in a product, an acknowledgment in the product documentation would be
+* appreciated but is not required.
+* 2. Altered source versions must be plainly marked as such, and must not be
+* misrepresented as being the original software.
+* 3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef B2_PRISMATIC_JOINT_H
+#define B2_PRISMATIC_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Prismatic joint definition. This requires defining a line of
+/// motion using an axis and an anchor point. The definition uses local
+/// anchor points and a local axis so that the initial configuration
+/// can violate the constraint slightly. The joint translation is zero
+/// when the local anchor points coincide in world space. Using local
+/// anchors and a local axis helps when saving and loading a game.
+struct b2PrismaticJointDef : public b2JointDef
+{
+ b2PrismaticJointDef()
+ {
+ type = e_prismaticJoint;
+ localAnchorA.SetZero();
+ localAnchorB.SetZero();
+ localAxisA.Set(1.0f, 0.0f);
+ referenceAngle = 0.0f;
+ enableLimit = false;
+ lowerTranslation = 0.0f;
+ upperTranslation = 0.0f;
+ enableMotor = false;
+ maxMotorForce = 0.0f;
+ motorSpeed = 0.0f;
+ }
+
+ /// Initialize the bodies, anchors, axis, and reference angle using the world
+ /// anchor and unit world axis.
+ void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis);
+
+ /// The local anchor point relative to bodyA's origin.
+ b2Vec2 localAnchorA;
+
+ /// The local anchor point relative to bodyB's origin.
+ b2Vec2 localAnchorB;
+
+ /// The local translation unit axis in bodyA.
+ b2Vec2 localAxisA;
+
+ /// The constrained angle between the bodies: bodyB_angle - bodyA_angle.
+ float32 referenceAngle;
+
+ /// Enable/disable the joint limit.
+ bool enableLimit;
+
+ /// The lower translation limit, usually in meters.
+ float32 lowerTranslation;
+
+ /// The upper translation limit, usually in meters.
+ float32 upperTranslation;
+
+ /// Enable/disable the joint motor.
+ bool enableMotor;
+
+ /// The maximum motor torque, usually in N-m.
+ float32 maxMotorForce;
+
+ /// The desired motor speed in radians per second.
+ float32 motorSpeed;
+};
+
+/// A prismatic joint. This joint provides one degree of freedom: translation
+/// along an axis fixed in bodyA. Relative rotation is prevented. You can
+/// use a joint limit to restrict the range of motion and a joint motor to
+/// drive the motion or to model joint friction.
+class b2PrismaticJoint : public b2Joint
+{
+public:
+ b2Vec2 GetAnchorA() const;
+ b2Vec2 GetAnchorB() const;
+
+ b2Vec2 GetReactionForce(float32 inv_dt) const;
+ float32 GetReactionTorque(float32 inv_dt) const;
+
+ /// The local anchor point relative to bodyA's origin.
+ const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
+
+ /// The local anchor point relative to bodyB's origin.
+ const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
+
+ /// The local joint axis relative to bodyA.
+ const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; }
+
+ /// Get the reference angle.
+ float32 GetReferenceAngle() const { return m_referenceAngle; }
+
+ /// Get the current joint translation, usually in meters.
+ float32 GetJointTranslation() const;
+
+ /// Get the current joint translation speed, usually in meters per second.
+ float32 GetJointSpeed() const;
+
+ /// Is the joint limit enabled?
+ bool IsLimitEnabled() const;
+
+ /// Enable/disable the joint limit.
+ void EnableLimit(bool flag);
+
+ /// Get the lower joint limit, usually in meters.
+ float32 GetLowerLimit() const;
+
+ /// Get the upper joint limit, usually in meters.
+ float32 GetUpperLimit() const;
+
+ /// Set the joint limits, usually in meters.
+ void SetLimits(float32 lower, float32 upper);
+
+ /// Is the joint motor enabled?
+ bool IsMotorEnabled() const;
+
+ /// Enable/disable the joint motor.
+ void EnableMotor(bool flag);
+
+ /// Set the motor speed, usually in meters per second.
+ void SetMotorSpeed(float32 speed);
+
+ /// Get the motor speed, usually in meters per second.
+ float32 GetMotorSpeed() const;
+
+ /// Set the maximum motor force, usually in N.
+ void SetMaxMotorForce(float32 force);
+ float32 GetMaxMotorForce() const { return m_maxMotorForce; }
+
+ /// Get the current motor force given the inverse time step, usually in N.
+ float32 GetMotorForce(float32 inv_dt) const;
+
+ /// Dump to b2Log
+ void Dump();
+
+protected:
+ friend class b2Joint;
+ friend class b2GearJoint;
+ b2PrismaticJoint(const b2PrismaticJointDef* def);
+
+ void InitVelocityConstraints(const b2SolverData& data);
+ void SolveVelocityConstraints(const b2SolverData& data);
+ bool SolvePositionConstraints(const b2SolverData& data);
+
+ // Solver shared
+ b2Vec2 m_localAnchorA;
+ b2Vec2 m_localAnchorB;
+ b2Vec2 m_localXAxisA;
+ b2Vec2 m_localYAxisA;
+ float32 m_referenceAngle;
+ b2Vec3 m_impulse;
+ float32 m_motorImpulse;
+ float32 m_lowerTranslation;
+ float32 m_upperTranslation;
+ float32 m_maxMotorForce;
+ float32 m_motorSpeed;
+ bool m_enableLimit;
+ bool m_enableMotor;
+ b2LimitState m_limitState;
+
+ // Solver temp
+ int32 m_indexA;
+ int32 m_indexB;
+ b2Vec2 m_localCenterA;
+ b2Vec2 m_localCenterB;
+ float32 m_invMassA;
+ float32 m_invMassB;
+ float32 m_invIA;
+ float32 m_invIB;
+ b2Vec2 m_axis, m_perp;
+ float32 m_s1, m_s2;
+ float32 m_a1, m_a2;
+ b2Mat33 m_K;
+ float32 m_motorMass;
+};
+
+inline float32 b2PrismaticJoint::GetMotorSpeed() const
+{
+ return m_motorSpeed;
+}
+
+#endif
diff --git a/games/hillclimb/src/car.cpp b/games/hillclimb/src/car.cpp
index c38b0404..20907aa5 100644
--- a/games/hillclimb/src/car.cpp
+++ b/games/hillclimb/src/car.cpp
@@ -1,6 +1,6 @@
/* A vehicle and its world (car.h), as the game builds them: its PlayerCar classes' bodies, fixtures, joints and
- * driving, its terrain's edges, rope bridges and trees, on Box2D 2.2.1 like the game. The numbers come from the
- * game's own code (Android libgame.so; see the README's credits). */
+ * driving, its terrain's edges, rope bridges, pits and trees, on Box2D 2.2.1 like the game. The numbers come from
+ * the game's own code (Android libgame.so; see the README's credits). */
#include <math.h>
#include <new>
#include <string.h>
@@ -10,6 +10,7 @@
#include <Box2D/Collision/b2Collision.h>
#include <Box2D/Dynamics/Contacts/b2Contact.h>
#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>
+#include <Box2D/Dynamics/Joints/b2PrismaticJoint.h>
#include <Box2D/Dynamics/Joints/b2RevoluteJoint.h>
#include <Box2D/Dynamics/Joints/b2WheelJoint.h>
#include <Box2D/Dynamics/b2Body.h>
@@ -34,10 +35,11 @@ namespace {
const float DT = 1.0f / CAR_HZ;
/* the game's object types (PhysicsObject::Type): what a body is, as the contacts tell */
-enum { T_COIN = 2, T_FUEL = 4, T_CAR = 8, T_DRIVER = 32, T_GROUND = 64, T_BRIDGE = 128, T_TREE = 256, T_ICE = 512 };
+enum { T_COIN = 2, T_FUEL = 4, T_CAR = 8, T_DRIVER = 32, T_GROUND = 64, T_BRIDGE = 128, T_TREE = 256, T_MUD = 512,
+ T_LAVA = 1024 };
/* collision filters: category, mask */
-const uint16 CAR_MASK = 0x7C6, DRIVER_MASK = 0x1C6, GROUND_MASK = 296, BRIDGE_MASK = 40, TREE_MASK = 120;
-const uint16 NONLETHAL = 0x300; /* touching these with the head is fine (trees, ice) */
+const uint16 CAR_MASK = 0x7C6, DRIVER_MASK = 0x1C6, GROUND_MASK = 296, BRIDGE_MASK = 40, TREE_MASK = 120, PIT_MASK = 40;
+const uint16 NONLETHAL = 0x300; /* touching these with the head is fine (PlayerCar::getNonLethalObjectTypes: trees, mud) */
/* ------------------------------------------------------------------ the vehicles' numbers (PlayerCar*) */
struct Spec {
@@ -62,8 +64,8 @@ struct Spec {
float down0, down_k; /* downforce coefficient down0 + down_k x L (0, 0: none) */
};
-/* indexes match vehicle.h (V_JEEP...) */
-const Spec SPECS[NVEHICLES] = {
+/* indexes match vehicle.h (V_JEEP...V_TANK: the first eight; the others are built by their own code below) */
+const Spec SPECS[V_TANK + 1] = {
/* Hill Climber */
{3, 0.2f, 1.11f, 14, 28, 1.05f, 1, 0.5f, 1.15f, 1.0f, 10, 0.5f, 1.115f, 0, 0, 0.4f, 0.4f, 1.15f, 1, 0.2f, 0.5f, 0.045f,
1, false, {-0.1f, 0.8f}, 0.3f, 0.5f, 20, 6, {{-1, -0.5f}, {1, -0.5f}, {1.5f, 0}, {0, 0.5f}, {-1.15f, 0.5f}, {-1.5f, 0.2f}},
@@ -104,6 +106,58 @@ const float TANK_WHEELS[6][6] = {
{0.5f, -1.5e-17f, 0, 1, -1.5f, 1}, {1.5f, 0.1f, 0, 1, -1, 1}, {2.2f, 1.0f, -0.8f, 0.2f, 10.1f, 1},
};
+/* The five vehicles of 1.10.2 the port had not had: their own classes' numbers (PlayerCarTractor, PlayerCarTouristbus,
+ * PlayerCarDieselTruck, PlayerCarSnowMobile, PlayerCarTruck). Each one's bodies are made in create_new below. */
+struct NewSpec {
+ int nv;
+ float poly[7][2]; /* the chassis */
+ float cdens, com_k; /* its density; the centre of mass lowered by com_k a level of upgrade com_up */
+ int com_up;
+ float hz, damp0, damp_k; /* the wheels' springs: frequency, damping damp0 x damp_k^L(suspension) */
+ float speed0, speed_k, speed_m; /* top wheel speed (rad/s) */
+ float cap0, cap_k; /* the turbo's cap cap0 x cap_k^L */
+ float rate0; /* its build rate rate0 x 1.1^(L - rate_l) */
+ int rate_l;
+ float torque, awd, tire0, tire_k;
+ float gas_r, gas_f, gas_k; /* gas: a wheel's torque share T f (gas + gas_k turbo), rear and front */
+ int reverse; /* 0: share T f^4.05 (0.5 + 0.5 t); 1: the bus' (rear f (0.3 + 0.7 t)); 2: the
+ tractor's share T f (1 + t) / 2 */
+ float brake, brake_air; /* the brake's torque, on the ground and after 5 steps in the air */
+ float decay0, decay1; /* the turbo off gas: t -= dt (decay0 + decay1 t) */
+ float air; /* the air control's torque */
+ float seat[2];
+ float weight; /* getObstacleWeightMultiplier */
+ float mud_damp;
+};
+const NewSpec NSPECS[NVEHICLES - V_TRACTOR] = {
+ /* Tractor */
+ {7, {{1.5725f, -0.1895f}, {2.1215f, -0.0065f}, {2.213f, 0.5425f}, {2.1215f, 1.0915f}, {1.0235f, 1.22875f},
+ {-2.0875f, 1.04575f}, {-2.22475f, 0.22225f}},
+ 0.65f, 0.035f, 3, 5, 1.35f, 1, 15, 1.05f, 1, 0.5f, 1.15f, 0.3f, 0, 20, 0.5f, 0.8f, 1.15f, 1, 1, 1, 2, 25, 1.25f,
+ 0.05f, 1.45f, 30, {-1.17578f, 2.013f}, 0.75f, 4},
+ /* Tourist Bus */
+ {4, {{-3.285f, 1}, {-3.285f, -0.5f}, {3.385f, -0.5f}, {3.785f, 1.5f}}, 0.55f, 0.045f, 1, 5, 0.2f, 1.11f, 15, 1.05f, 1,
+ 0.5f, 1.15f, 0.3f, 1, 10, 0.5f, 0.75f, 1.115f, 0.25f, 0.5f, 2, 1, 20, 1, 0.05f, 1.45f, 90, {2.55f, 2.55f}, 0.35f, 4},
+ /* Super Diesel 4x4 */
+ {5, {{-2.25f, 0.2f}, {-2.125f, -0.5f}, {2.1875f, -0.5f}, {2.3125f, 0.2f}, {1.25f, 0.8f}}, 0.775f, 0.045f, 1, 3, 0.2f,
+ 1.11f, 17, 1.05f, 1, 0.5f, 1.15f, 0.5f, 1, 20, 0.5f, 0.95f, 1.115f, 0.5f, 0.5f, 1.35f, 0, 20, 1, 0.01f, 0.75f, 45,
+ {0.1f, 1.25f}, 0.65f, 3.2f},
+ /* Snow Mobile (its pedals are the Tank's, over its five track wheels) */
+ {6, {{-1.275f, -0.4f}, {2.21f, -0.6f}, {2.465f, -0.2f}, {0.68f, 1.1f}, {-2.04f, 0.25f}, {-2.04f, 0}}, 0.5f,
+ 0.0707142857f, 1, 3, 0, 0, 45.9f, 1.048f, 0.55f, 0.87f, 1.14f, 3.33f, 1, 6, 0.5f, 0.5f, 1.1612f, 0, 0, 0, 0, 20, 1,
+ 1, 4, 3.5f, {-0.2f, 1.4f}, 2, 4},
+ /* Truck */
+ {5, {{-2.875f, 0.2f}, {-2.875f, -0.5f}, {2.875f, -0.5f}, {2.9325f, 0.2f}, {1.15f, 1.1f}}, 0.95f, 0.045f, 1, 4, 0.2f,
+ 1.11f, 15, 1.05f, 1, 0.5f, 1.15f, 0.3f, 1, 10, 0.5f, 0.75f, 1.115f, 0.25f, 0.5f, 2, 1, 20, 1, 0.01f, 0.45f, 90,
+ {0.85f, 1.65f}, 0.35f, 4},
+};
+/* the Snow Mobile's track wheels, from the spawn point: x, y, y's share of the suspension's damping (0.3), spring
+ * frequency (or x the base's for negative), and the friction share it loses toward the front */
+const float SNOW_TRACK[5][4] = {
+ {-0.9f, 0.8f, 0, 10.1f}, {-2.1f, 0.1f, 0.3f, -2.5f}, {-0.5f, -0.2f, 0.3f, -1.47f}, {0.5f, 0.1f, 0.3f, -2.2f},
+ {1.3f, 0.9f, 0, 30},
+};
+
float powi(float b, int n) {
float r = 1;
for (int i = 0; i < n; i++) r *= b;
@@ -119,29 +173,54 @@ b2Body *ground;
/* what a body is: its type, and which part of the car */
struct Tag {
int type;
- int part; /* 0 chassis, 1.. wheels (index + 1), -1 torso, -2 head, -3 none */
+ int part; /* 0 chassis, 1.. wheels (index + 1), -1 torso, -2 head, -3 none, -4 the exhaust, -5 a soft tire's ball,
+ -10 - 2 p a passenger's torso, -11 - 2 p their head */
};
-Tag tag_ground = {T_GROUND, -3}, tag_bridge = {T_BRIDGE, -3}, tag_tree = {T_TREE, -3};
-Tag tag_car[CAR_MAXW + 1], tag_torso = {T_CAR, -1}, tag_head = {T_CAR, -2};
+Tag tag_ground = {T_GROUND, -3}, tag_bridge = {T_BRIDGE, -3}, tag_tree = {T_TREE, -3}, tag_mud = {T_MUD, -3},
+ tag_lava = {T_LAVA, -3};
+Tag tag_car[CAR_MAXW + 1], tag_torso = {T_CAR, -1}, tag_head = {T_CAR, -2}, tag_exhaust = {T_CAR, -4},
+ tag_seg = {T_CAR, -5}, tag_pass[CAR_PASS * 2];
/* ------------------------------------------------------------------ the vehicle (PlayerCar) */
+/* a rider (Bill or a bus passenger): torso, head, the neck's joint and the two springs */
+struct Rider {
+ b2Body *torso, *head;
+ b2RevoluteJoint *neck;
+ b2Joint *spring[2];
+};
+
struct Vehicle {
- const Spec *s;
- int veh, nw;
+ const Spec *s; /* (the first eight) */
+ const NewSpec *n; /* (the new five) */
+ int veh, nw, ndriven;
b2Body *chassis, *wheel[CAR_MAXW], *torso, *head;
- b2WheelJoint *joint[CAR_MAXW];
+ b2Joint *joint[CAR_MAXW];
+ bool rev_joint[CAR_MAXW]; /* a revolute joint (the tractor's soft tire) rather than a wheel joint */
b2RevoluteJoint *neck; /* torso to head */
b2DistanceJoint *spring[2]; /* chassis to torso, torso to head */
- float wr[CAR_MAXW], share[CAR_MAXW];
+ float wr[CAR_MAXW], share[CAR_MAXW], gas[CAR_MAXW], wspeed[CAR_MAXW];
float hz, damp, speed, turbo_cap, rate, tires, awd, air, down;
float turbo, rev;
int air_frames;
- unsigned touch_chassis, touch_wheel[CAR_MAXW];
+ unsigned touch_chassis, touch_wheel[CAR_MAXW], touch_exhaust;
bool decel_air;
bool dead, head_hit;
int flips_k; /* the turn handleFlips counts from */
bool alive_at_turn;
bool accelerating;
+ /* the new vehicles' parts */
+ int level_com; /* (the tractor's stability) */
+ int mud_a, mud_b; /* the wheels whose touches PlayerCar::baseUpdate takes (its "chassis", "wheels") */
+ Rider pass[CAR_PASS];
+ int npass;
+ bool pass_hit[CAR_PASS];
+ b2Body *seg[CAR_SEGS]; /* the tractor's soft tire */
+ int nseg;
+ b2Body *exhaust;
+ b2RevoluteJoint *exhaust_joint;
+ /* mud and lava (PlayerCar::baseUpdate) */
+ int mud_frames_a, mud_frames_b; /* steps the "chassis", anything, has been in mud */
+ int burn[5];
} V;
/* the level of the vehicle's upgrade of a kind, or -1 */
@@ -173,17 +252,17 @@ void add_fixture(b2Body *b, const b2Shape *sh, float friction, float density, ui
b->CreateFixture(&fd);
}
-/* PlayerCar::createDriver: a torso and a head, each on a revolute joint and a spring */
-void create_driver(float x, float y) {
- const Spec *s = V.s;
+/* PlayerCar::createDriver: a torso and a head, each on a revolute joint and a spring (bus passengers alike) */
+Rider create_rider(float x, float y, float limit, float friction, Tag *torso_tag, Tag *head_tag) {
+ Rider r;
b2Body *prev = V.chassis;
for (int i = 0; i < 2; i++) {
b2PolygonShape box;
box.SetAsBox(0.3f, 0.3f);
b2CircleShape circle;
circle.m_radius = 0.33f;
- b2Body *b = make_body(x, y + 0.3f + 0.6f * (float)i, 3.14159f, false, i ? &tag_head : &tag_torso);
- add_fixture(b, i ? (b2Shape *)&circle : (b2Shape *)&box, s->driver_fric, 0.01f, T_DRIVER, DRIVER_MASK, 0);
+ b2Body *b = make_body(x, y + 0.3f + 0.6f * (float)i, 3.14159f, false, i ? head_tag : torso_tag);
+ add_fixture(b, i ? (b2Shape *)&circle : (b2Shape *)&box, friction, 0.01f, T_DRIVER, DRIVER_MASK, 0);
b2RevoluteJointDef rj;
rj.bodyA = prev;
rj.bodyB = b;
@@ -191,10 +270,10 @@ void create_driver(float x, float y) {
rj.localAnchorB.Set(-0.0f, 0.3f);
rj.referenceAngle = i ? 0 : 3.14159265f;
rj.enableLimit = true;
- rj.lowerAngle = -s->neck_limit;
- rj.upperAngle = s->neck_limit;
+ rj.lowerAngle = -limit;
+ rj.upperAngle = limit;
b2RevoluteJoint *rev = (b2RevoluteJoint *)W->CreateJoint(&rj);
- if (i) V.neck = rev;
+ if (i) r.neck = rev;
/* a zero-length spring beside the joint keeps him upright */
b2DistanceJointDef dj;
dj.bodyA = prev;
@@ -206,11 +285,18 @@ void create_driver(float x, float y) {
float k = 1 + 0.25f * (float)i;
dj.frequencyHz = 10.1f / k;
dj.dampingRatio = 10.0f / k;
- V.spring[i] = (b2DistanceJoint *)W->CreateJoint(&dj);
- if (i) V.head = b;
- else V.torso = b;
+ r.spring[i] = W->CreateJoint(&dj);
+ if (i) r.head = b;
+ else r.torso = b;
prev = b;
}
+ return r;
+}
+
+void create_driver(float x, float y, float limit, float friction) {
+ Rider r = create_rider(x, y, limit, friction, &tag_torso, &tag_head);
+ V.torso = r.torso, V.head = r.head, V.neck = r.neck;
+ V.spring[0] = (b2DistanceJoint *)r.spring[0], V.spring[1] = (b2DistanceJoint *)r.spring[1];
}
b2WheelJoint *wheel_joint(b2Body *wheel, b2Vec2 axis, float hz, float damp) {
@@ -224,11 +310,205 @@ b2WheelJoint *wheel_joint(b2Body *wheel, b2Vec2 axis, float hz, float damp) {
return (b2WheelJoint *)W->CreateJoint(&jd);
}
+/* a wheel's motor (b2WheelJoint or, for the soft tire's hub, b2RevoluteJoint) */
+void motor(int i, float torque, float speed) {
+ if (V.rev_joint[i]) {
+ ((b2RevoluteJoint *)V.joint[i])->SetMaxMotorTorque(torque);
+ ((b2RevoluteJoint *)V.joint[i])->SetMotorSpeed(speed);
+ } else {
+ ((b2WheelJoint *)V.joint[i])->SetMaxMotorTorque(torque);
+ ((b2WheelJoint *)V.joint[i])->SetMotorSpeed(speed);
+ }
+}
+void motor_torque(int i, float torque) {
+ if (V.rev_joint[i]) ((b2RevoluteJoint *)V.joint[i])->SetMaxMotorTorque(torque);
+ else ((b2WheelJoint *)V.joint[i])->SetMaxMotorTorque(torque);
+}
+
+/* a circle wheel: its body, fixture and the tag that says it is wheel i */
+b2Body *make_wheel(int i, float x, float y, float r, float friction, float density, int16 group) {
+ b2CircleShape c;
+ c.m_radius = V.wr[i] = r;
+ tag_car[i + 1] = {T_CAR, i + 1};
+ b2Body *b = make_body(x, y, 0, true, &tag_car[i + 1]);
+ add_fixture(b, &c, friction, density, T_CAR, CAR_MASK, group);
+ return V.wheel[i] = b;
+}
+
+/* the chassis: its polygon, at the spawn point + (0, 1); its centre of mass moved by (dx, dy) */
+void make_chassis(int nv, const float (*poly)[2], float density, int16 group, float x, float y, float dx, float dy) {
+ b2PolygonShape p;
+ b2Vec2 vs[8];
+ for (int i = 0; i < nv; i++) vs[i].Set(poly[i][0], poly[i][1]);
+ p.Set(vs, nv);
+ tag_car[0] = {T_CAR, 0};
+ V.chassis = make_body(x, y + 1, 0, true, &tag_car[0]);
+ add_fixture(V.chassis, &p, 0.2f, density, T_CAR, CAR_MASK, group);
+ b2MassData md;
+ V.chassis->GetMassData(&md);
+ md.center.x += dx;
+ md.center.y += dy;
+ V.chassis->SetMassData(&md);
+}
+
+/* SoftTire::SoftTire: n balls of r 0.135 R around a hub of r ratio R, each on a spring (hz, damping 0.5) and a radial
+ * slide that lets it in by ratio R; the hub turns on a revolute motor at the chassis */
+void make_soft_tire(float cx, float cy, float R, float ratio, float hz, float density, float friction, int n) {
+ float rb = R * 0.135f;
+ V.nseg = n;
+ for (int i = 0; i < n; i++) {
+ float a = (float)i * (6.283185307179586f / (float)n);
+ b2CircleShape c;
+ c.m_radius = rb;
+ V.seg[i] = make_body(cx + (R - rb) * cosf(a), cy + (R - rb) * sinf(a), 0, true, &tag_seg);
+ add_fixture(V.seg[i], &c, friction, density, T_CAR, CAR_MASK, 0);
+ }
+ b2CircleShape hub;
+ hub.m_radius = R * ratio;
+ tag_car[1] = {T_CAR, 1};
+ V.wheel[0] = make_body(cx, cy, 0, true, &tag_car[1]);
+ V.wr[0] = R;
+ add_fixture(V.wheel[0], &hub, friction, density, T_CAR, CAR_MASK, 0);
+ for (int i = 0; i < n; i++) {
+ float a = (float)i * (6.283185307179586f / (float)n);
+ b2Vec2 at = V.seg[i]->GetWorldCenter();
+ b2DistanceJointDef dj;
+ dj.Initialize(V.seg[i], V.wheel[0], at, b2Vec2(cx, cy));
+ dj.frequencyHz = hz;
+ dj.dampingRatio = 0.5f;
+ W->CreateJoint(&dj);
+ b2PrismaticJointDef pj;
+ pj.Initialize(V.seg[i], V.wheel[0], at, b2Vec2(-cosf(a), -sinf(a)));
+ pj.enableLimit = true;
+ pj.lowerTranslation = -(R * ratio);
+ pj.upperTranslation = 0;
+ W->CreateJoint(&pj);
+ }
+ b2RevoluteJointDef rj;
+ rj.Initialize(V.chassis, V.wheel[0], V.wheel[0]->GetPosition());
+ rj.enableMotor = true;
+ rj.maxMotorTorque = 500;
+ rj.motorSpeed = 0;
+ V.joint[0] = W->CreateJoint(&rj);
+ V.rev_joint[0] = true;
+}
+
+/* PlayerCarTractor::createExhaust: a pipe on a joint held straight; a knock bends it, a hard one breaks it off */
+void make_exhaust(void) {
+ b2Vec2 at = V.chassis->GetWorldPoint(b2Vec2(1.281f, 1.9215f));
+ V.exhaust = make_body(at.x, at.y, 0, true, &tag_exhaust);
+ b2PolygonShape box;
+ box.SetAsBox(0.0915f, 0.68625f, b2Vec2(0, 0), 0);
+ add_fixture(V.exhaust, &box, 0.2f, 0.65f, T_CAR, CAR_MASK, -1);
+ b2Vec2 c = V.exhaust->GetWorldCenter();
+ b2RevoluteJointDef rj;
+ rj.Initialize(V.chassis, V.exhaust, b2Vec2(c.x, c.y - 1));
+ rj.enableLimit = true;
+ rj.lowerAngle = 0;
+ rj.upperAngle = 0;
+ V.exhaust_joint = (b2RevoluteJoint *)W->CreateJoint(&rj);
+}
+
+/* the five new vehicles' bodies and numbers (their classes' create and constructor) */
+void create_new(int veh, const uint8_t lv[4], float x, float y) {
+ const NewSpec *n = V.n = &NSPECS[veh - V_TRACTOR];
+ int le = level_of(veh, lv, UP_ENGINE), ls = level_of(veh, lv, UP_SUSPENSION), lt = level_of(veh, lv, UP_TIRES);
+ if (lt < 0) lt = level_of(veh, lv, UP_TRACKS);
+ if (le < 1) le = 1;
+ if (lt < 1) lt = 1;
+ if (ls < 1) ls = 1;
+ V.level_com = lv[n->com_up] < 1 ? 1 : lv[n->com_up];
+ V.hz = n->hz;
+ V.damp = n->damp0 * powi(n->damp_k, ls);
+ V.speed = n->speed0 * powi(n->speed_k, le) * n->speed_m;
+ V.turbo_cap = n->cap0 * powi(n->cap_k, le);
+ V.rate = n->rate0 * powi(1.1f, le - n->rate_l);
+ V.tires = n->tire0 * powi(n->tire_k, lt);
+ V.awd = n->awd;
+ V.air = n->air;
+ float com = -(float)(V.level_com - 1) * n->com_k;
+ switch (veh) {
+ case V_TRACTOR:
+ make_chassis(n->nv, n->poly, n->cdens, 0, x, y, 0, com);
+ make_exhaust();
+ V.nw = 2, V.ndriven = 2;
+ make_soft_tire(x - 1.83f + 0.6039f, y + 0.251625f + 0.324825f, 1.09f, 0.6f, 6, 0.5f, V.tires, CAR_SEGS);
+ make_wheel(1, x + 1.83f, y + 0.251625f + 0.25f, 0.47f, V.tires, 0.5f, 0);
+ V.joint[1] = wheel_joint(V.wheel[1], b2Vec2(0, 1), V.hz, V.damp);
+ V.share[0] = 1 - V.awd, V.share[1] = V.awd;
+ V.gas[0] = n->gas_r, V.gas[1] = n->gas_f;
+ V.wspeed[0] = V.speed, V.wspeed[1] = V.speed * 2.319149f; /* (the front's radius is 0.47 / 1.09 the back's) */
+ V.mud_a = 1, V.mud_b = 0;
+ break;
+ case V_BUS:
+ case V_DIESEL:
+ case V_TRUCK: {
+ make_chassis(n->nv, n->poly, n->cdens, 0, x, y, 0, com);
+ /* wheels: x from the spawn point, rear ones first; the last one is the front */
+ static const float XS[3][3] = {{-2.15f, 2.95f, 0}, {-1.75f, 1.75f, 0}, {-1.4f, -2.65f, 2.8f}};
+ int row = veh == V_BUS ? 0 : veh == V_DIESEL ? 1 : 2;
+ float r = veh == V_DIESEL ? 0.65f : 0.55f;
+ V.nw = V.ndriven = veh == V_TRUCK ? 3 : 2;
+ for (int i = 0; i < V.nw; i++) {
+ bool front = i == V.nw - 1;
+ make_wheel(i, x + XS[row][i], y - 0.25f, r, V.tires, 0.2f, 0);
+ V.joint[i] = wheel_joint(V.wheel[i], b2Vec2(0, 1), V.hz, V.damp);
+ V.share[i] = front ? V.awd : 1 - V.awd;
+ V.gas[i] = front ? n->gas_f : n->gas_r;
+ V.wspeed[i] = V.speed;
+ }
+ V.mud_a = V.nw - 1, V.mud_b = 0;
+ break;
+ }
+ case V_SNOWMOBILE: {
+ /* the tank's sister: its centre of mass 1 m back, a ski in front (two wheels whose motors hold them still) and
+ * a track of five wheels */
+ bool snow = stage_id == ST_ARCTIC || stage_id == ST_ARCTIC_CAVE;
+ if (snow) V.tires *= 3;
+ if (stage_id == ST_ALIEN) V.tires *= 1.6f;
+ V.damp = 1 - powf(0.9f, (float)ls);
+ make_chassis(n->nv, n->poly, n->cdens, 1, x, y, -1, -0.07071428f * (float)(ls - 1));
+ V.nw = 7, V.ndriven = 5;
+ for (int i = 0; i < 2; i++) { /* (the ski first, as the game makes it; kept after the track's five) */
+ b2Vec2 at = V.chassis->GetWorldPoint(b2Vec2(1.5f + 1.1f * (float)i, -1.1f));
+ make_wheel(5 + i, at.x, at.y, 0.28f * (1 + 0.2f * (float)i), snow ? 1.0f : 3.0f, 0.12f, -1);
+ V.joint[5 + i] = wheel_joint(V.wheel[5 + i], b2Vec2(-0.1961161f, 0.9805807f), 6, 1);
+ }
+ for (int i = 0; i < 5; i++) {
+ const float *t = SNOW_TRACK[i];
+ make_wheel(i, x + t[0], y + t[1] + t[2] * V.damp, 0.28f * 1.2f,
+ V.tires - (float)(i + 1) / 5.0f * (V.tires * 0.25f), 0.3f, -1);
+ float hz = t[3] > 0 ? t[3] : -t[3] * V.hz;
+ V.joint[i] = wheel_joint(V.wheel[i], b2Vec2(0, 1), hz, 1);
+ V.share[i] = 1 - V.awd;
+ V.wspeed[i] = V.speed;
+ }
+ V.mud_a = 2, V.mud_b = 1;
+ break;
+ }
+ }
+ bool bike = veh == V_SNOWMOBILE;
+ create_driver(x + n->seat[0], y + n->seat[1], bike ? 0.4f : 0.3f, bike ? 0.75f : 0.5f);
+ if (veh == V_BUS) {
+ V.npass = CAR_PASS;
+ for (int p = 0; p < CAR_PASS; p++) {
+ tag_pass[2 * p] = {T_CAR, -10 - 2 * p}, tag_pass[2 * p + 1] = {T_CAR, -11 - 2 * p};
+ V.pass[p] = create_rider(x - 2.4f + 1.35f * (float)p, y + 2.35f, 0.3f, 0.5f, &tag_pass[2 * p], &tag_pass[2 * p + 1]);
+ }
+ }
+}
+
/* PlayerCar*::PlayerCar and ::create: at x (the ground's height there + 3) */
void create_vehicle(int veh, const uint8_t lv[4], float x, float y) {
- const Spec *s = &SPECS[veh];
memset(&V, 0, sizeof V);
- V.s = s, V.veh = veh;
+ V.veh = veh;
+ if (veh >= V_TRACTOR) {
+ create_new(veh, lv, x, y);
+ V.alive_at_turn = true;
+ return;
+ }
+ const Spec *s = &SPECS[veh];
+ V.s = s;
int le = level_of(veh, lv, UP_ENGINE), ls = level_of(veh, lv, UP_SUSPENSION), lt = level_of(veh, lv, UP_TIRES);
if (lt < 0) lt = level_of(veh, lv, UP_TRACKS);
int la = level_of(veh, lv, UP_AWD), lair = level_of(veh, lv, UP_AIR), ld = level_of(veh, lv, UP_DOWNFORCE);
@@ -261,39 +541,37 @@ void create_vehicle(int veh, const uint8_t lv[4], float x, float y) {
V.chassis->SetMassData(&md);
/* the wheels */
if (veh == V_TANK) {
- V.nw = 6;
+ V.nw = V.ndriven = 6;
for (int i = 0; i < 6; i++) {
const float *t = TANK_WHEELS[i];
- b2CircleShape c;
- c.m_radius = V.wr[i] = s->r;
- tag_car[i + 1] = {T_CAR, i + 1};
- V.wheel[i] = make_body(x + t[0], y + t[1], 0, true, &tag_car[i + 1]);
- add_fixture(V.wheel[i], &c, V.tires - (float)(i + 1) / 6.0f * (V.tires * 0.25f), s->wdens, T_CAR, CAR_MASK, -1);
+ make_wheel(i, x + t[0], y + t[1], s->r, V.tires - (float)(i + 1) / 6.0f * (V.tires * 0.25f), s->wdens, -1);
float hz = t[4] > 0 ? t[4] : -t[4] * V.hz, damp = t[4] > 0 ? t[5] : V.damp;
V.joint[i] = wheel_joint(V.wheel[i], b2Vec2(t[2], t[3]), hz, damp);
}
+ V.mud_a = 4, V.mud_b = 1;
} else {
- V.nw = 2;
+ V.nw = V.ndriven = 2;
for (int i = 0; i < 2; i++) {
- b2CircleShape c;
- c.m_radius = V.wr[i] = i ? s->r : s->rr;
- tag_car[i + 1] = {T_CAR, i + 1};
- V.wheel[i] = make_body(x + (i ? s->hwb : -s->hwb), y - s->wy, 0, true, &tag_car[i + 1]);
- add_fixture(V.wheel[i], &c, i ? V.tires * s->front_fric : V.tires, s->wdens, T_CAR, CAR_MASK, 0);
+ make_wheel(i, x + (i ? s->hwb : -s->hwb), y - s->wy, i ? s->r : s->rr, i ? V.tires * s->front_fric : V.tires,
+ s->wdens, 0);
b2Vec2 axis = i && s->fork ? b2Vec2(-0.410365f, 0.911922f) : b2Vec2(0, 1);
V.joint[i] = wheel_joint(V.wheel[i], axis, V.hz, V.damp);
}
V.share[0] = 1 - V.awd, V.share[1] = V.awd;
+ V.mud_a = 1, V.mud_b = 0;
}
- create_driver(x + s->seat[0], y + s->seat[1]);
+ create_driver(x + s->seat[0], y + s->seat[1], s->neck_limit, s->driver_fric);
V.alive_at_turn = true;
}
-/* PlayerCar::reportTouch: what touched which part */
+/* PlayerCar*::reportTouch: what touched which part */
void report_touch(int type, const Tag *part) {
if (part->part == 0) V.touch_chassis |= (unsigned)type;
else if (part->part > 0) V.touch_wheel[part->part - 1] |= (unsigned)type;
else if (part->part == -2 && !V.dead && !(type & NONLETHAL)) V.head_hit = true;
+ else if (part->part == -4) V.touch_exhaust |= (unsigned)type;
+ else if (part->part == -5) V.touch_wheel[0] |= (unsigned)type; /* (SoftTire::isSubBody: the rear wheel) */
+ else if (part->part <= -10) V.pass_hit[(-10 - part->part) / 2] = true; /* (a passenger touched something) */
}
struct Listener : b2ContactListener {
@@ -451,6 +729,55 @@ void update_bridges(float cx) {
}
}
+/* ------------------------------------------------------------------ pits (Pit::create) */
+/* a static sensor box len x depth under the pit's surface; the car's parts touching it are in mud or lava */
+struct PitBody {
+ int k; /* which pit, or -1 */
+ b2Body *b;
+} pits[2];
+
+void pit_make(PitBody *p, int k) {
+ float x0, len, y;
+ if (!stage_pit_k(k, &x0, &len, &y)) return;
+ float depth = stage_pit_depth();
+ b2BodyDef bd;
+ bd.position.Set(x0 + len * 0.5f + 0.5f, y - (depth + 0.5f) * 0.5f);
+ bd.userData = stage->pits == PIT_LAVA ? &tag_lava : &tag_mud;
+ p->b = W->CreateBody(&bd);
+ b2PolygonShape box;
+ box.SetAsBox(len * 0.5f, depth * 0.5f);
+ b2FixtureDef fd;
+ fd.shape = &box;
+ fd.friction = 0.2f;
+ fd.isSensor = true;
+ fd.filter.categoryBits = stage->pits == PIT_LAVA ? T_LAVA : T_MUD;
+ fd.filter.maskBits = PIT_MASK;
+ p->b->CreateFixture(&fd);
+ p->k = k;
+}
+
+void update_pits(float cx) {
+ if (!stage->pits) return;
+ int near = -1;
+ for (int k = stage_pit_first(cx - 40);; k++) {
+ float x0, len, y;
+ if (!stage_pit_k(k, &x0, &len, &y) || x0 > cx + 45) break;
+ if (x0 + len + 1 < cx - 30) continue;
+ near = k;
+ break;
+ }
+ for (int i = 0; i < 2; i++)
+ if (pits[i].k >= 0 && pits[i].k != near) W->DestroyBody(pits[i].b), pits[i].k = -1, pits[i].b = NULL;
+ if (near < 0) return;
+ for (int i = 0; i < 2; i++)
+ if (pits[i].k == near) return;
+ for (int i = 0; i < 2; i++)
+ if (pits[i].k < 0) {
+ pit_make(&pits[i], near);
+ return;
+ }
+}
+
/* ------------------------------------------------------------------ trees (the Forest's: Tree::create) */
const int MAXTREE = 10;
struct TreeBody {
@@ -495,7 +822,9 @@ void tree_make(TreeBody *t, int k, float weight) {
t->k = k, t->t = 0, t->held = 0;
}
-const float OBSTACLE_WEIGHT[NVEHICLES] = {0.85f, 1.2f, 0.45f, 1.0f, 1.0f, 1.0f, 0.95f, 0.6f};
+/* PlayerCar*::getObstacleWeightMultiplier */
+const float OBSTACLE_WEIGHT[V_TANK + 1] = {0.85f, 1.2f, 0.45f, 1.0f, 1.0f, 1.0f, 0.95f, 0.6f};
+float obstacle_weight(int veh) { return veh >= V_TRACTOR ? NSPECS[veh - V_TRACTOR].weight : OBSTACLE_WEIGHT[veh]; }
void update_trees(float cx) {
tree_broken = -1;
@@ -537,7 +866,7 @@ void update_trees(float cx) {
if (have) continue;
for (int i = 0; i < MAXTREE; i++)
if (trees[i].k < 0) {
- tree_make(&trees[i], k, OBSTACLE_WEIGHT[V.veh]);
+ tree_make(&trees[i], k, obstacle_weight(V.veh));
break;
}
}
@@ -545,13 +874,26 @@ void update_trees(float cx) {
/* ------------------------------------------------------------------ driving (accelerate, decelerate, idleEngine) */
float wheel_w(int i) { return V.wheel[i]->GetAngularVelocity(); }
+bool tracked(void) { return V.veh == V_TANK || V.veh == V_SNOWMOBILE; }
+
+/* PlayerCar::baseAccelerate, baseDeccelerate: in a Mudpool's mud the car swims ahead (or back) */
+void base_pedal(int pedal) {
+ if (stage->pits != PIT_MUD) return;
+ b2Body *ch = V.chassis;
+ for (int pass = 0; pass < 2; pass++) {
+ if (pass ? V.mud_frames_b <= 0 : V.mud_frames_a <= 0) continue;
+ float t = 0.2f * clampf(1 - ch->GetAngularVelocity(), 0, 1);
+ ch->ApplyForceToCenter(b2Vec2(5.0f * (float)pedal, 0));
+ ch->ApplyTorque(pedal > 0 ? t : -t);
+ }
+}
/* the air control: cars push while 5 steps in the air; the bikes ease in over 15 more, always */
void air_control(int pedal) {
b2Body *ch = V.chassis;
float w = ch->GetAngularVelocity();
bool bike = V.veh == V_BIKE || V.veh == V_QUAD;
- int reps = V.veh == V_TANK ? V.nw : 1; /* (the Tank pushes once a wheel) */
+ int reps = tracked() ? V.ndriven : 1; /* (the Tank and the Snow Mobile push once a track wheel) */
for (int r = 0; r < reps; r++) {
if (bike) {
float a = clampf((float)(V.air_frames - 5) / 15.0f, 0, 1) * V.air;
@@ -566,58 +908,75 @@ void air_control(int pedal) {
}
void idle_engine(void) {
- for (int i = 0; i < V.nw; i++) V.joint[i]->SetMaxMotorTorque(0);
+ for (int i = 0; i < V.ndriven; i++) motor_torque(i, 0);
V.accelerating = false;
}
void accelerate(void) {
+ base_pedal(1);
air_control(1);
- if (V.veh == V_TANK) {
- for (int i = 0; i < V.nw; i++) {
+ if (tracked()) {
+ for (int i = 0; i < V.ndriven; i++) {
float f = clampf(V.speed - fabsf(wheel_w(i)), 0, 1);
- float t = (float)(i + 1) / (float)V.nw * 2 + (V.turbo + 0.5f) * ((1 - V.awd) * V.s->torque * f);
+ float t = (float)(i + 1) / (float)V.ndriven * 2 + (V.turbo + 0.5f) * ((1 - V.awd) * (V.s ? V.s->torque : V.n->torque) * f);
if (V.air_frames > 0) t *= 0.25f;
- V.joint[i]->SetMaxMotorTorque(t);
- V.joint[i]->SetMotorSpeed(-V.speed);
+ motor(i, t, -V.speed);
+ }
+ } else if (V.n) { /* the new vehicles: each wheel its share, rear and front their own turbo boost */
+ for (int i = 0; i < V.ndriven; i++) {
+ float f = clampf(V.wspeed[i] - fabsf(wheel_w(i)), 0, 1);
+ float t = V.share[i] * V.n->torque * f * (V.gas[i] + V.n->gas_k * V.turbo);
+ if (V.air_frames > 0) t *= 0.25f;
+ motor(i, t, -V.wspeed[i]);
}
} else {
for (int i = 0; i < 2; i++) {
float f = clampf(V.speed - fabsf(wheel_w(i)), 0, 1);
float t = V.share[i] * V.s->torque * f * (0.5f + V.turbo);
if (V.air_frames > 0) t *= 0.25f;
- V.joint[i]->SetMaxMotorTorque(t);
- V.joint[i]->SetMotorSpeed(-V.speed);
+ motor(i, t, -V.speed);
}
}
V.accelerating = true;
}
void decelerate(void) {
+ base_pedal(-1);
V.decel_air = true;
air_control(-1);
- bool tank = V.veh == V_TANK;
+ bool tank = tracked();
if (V.chassis->GetLinearVelocity().x > 2.5f) { /* rolling forward: brake */
- for (int i = 0; i < V.nw; i++) {
- float t = V.air_frames > 5 ? 1.0f : 20.0f;
- if (tank) t = (t + (float)(i + 1) / (float)V.nw * 2) * 0.5f;
- V.joint[i]->SetMaxMotorTorque(t);
- V.joint[i]->SetMotorSpeed(0);
+ float b = V.n ? V.n->brake : 20, ba = V.n ? V.n->brake_air : 1;
+ for (int i = 0; i < V.ndriven; i++) {
+ float t = V.air_frames > 5 ? ba : b;
+ if (tank) t = (t + (float)(i + 1) / (float)V.ndriven * 2) * 0.5f;
+ motor(i, t, 0);
}
V.accelerating = false;
return;
}
- for (int i = 0; i < V.nw; i++) { /* else reverse */
- float f = powf(clampf(V.speed - fabsf(wheel_w(i)), 0, 1), 4.05f);
+ float torque = V.s ? V.s->torque : V.n->torque;
+ int mode = V.n ? V.n->reverse : 0;
+ for (int i = 0; i < V.ndriven; i++) { /* else reverse */
+ float f = clampf(V.wspeed[i] > 0 ? V.wspeed[i] - fabsf(wheel_w(i)) : V.speed - fabsf(wheel_w(i)), 0, 1);
+ bool front = V.n && i == V.ndriven - 1;
float t;
- if (tank) t = ((float)(i + 1) / (float)V.nw * 2 + (0.5f + 0.5f * V.turbo) * ((1 - V.awd) * V.s->torque * f)) * 0.5f;
- else t = V.share[i] * V.s->torque * f * (0.5f + 0.5f * V.turbo);
- V.joint[i]->SetMaxMotorTorque(t);
- V.joint[i]->SetMotorSpeed(V.speed);
+ if (tank) t = ((float)(i + 1) / (float)V.ndriven * 2 + (0.5f + 0.5f * V.turbo) * ((1 - V.awd) * torque * powf(f, 4.05f))) * 0.5f;
+ else if (mode == 1 && !front) t = V.share[i] * torque * f * (0.3f + 0.7f * V.turbo);
+ else if (mode == 2) t = V.share[i] * torque * f * (1 + V.turbo) * 0.5f;
+ else t = V.share[i] * torque * powf(f, 4.05f) * (0.5f + 0.5f * V.turbo);
+ motor(i, t, V.wspeed[i] > 0 ? V.wspeed[i] : V.speed);
}
V.accelerating = true;
}
/* ------------------------------------------------------------------ after each step (PlayerCar*::update) */
+void release_rider(Rider *r) {
+ for (int i = 0; i < 2; i++)
+ if (r->spring[i]) W->DestroyJoint(r->spring[i]), r->spring[i] = NULL;
+ if (r->neck) r->neck->SetLimits(-1.22173f, 1.047198f);
+}
+
void handle_head_hit(void) {
if (!V.head_hit) return;
V.head_hit = false;
@@ -656,20 +1015,101 @@ void downforce(void) {
ch->ApplyForceToCenter(b2Vec2(sinf(a) * f, -cosf(a) * f));
}
+/* a force toward the chassis' floor (the Tractor's stability, the Snow Mobile's weight) */
+void push_down(float f) {
+ float a = V.chassis->GetAngle() + 3.14159f;
+ V.chassis->ApplyForceToCenter(b2Vec2(-sinf(a) * f, cosf(a) * f));
+}
+
+/* PlayerCar::baseUpdate: mud (the Mudpool) and lava (the Volcano). a and b: the touches of the two parts the vehicle
+ * hands it (its front and back wheels for most: the game calls them the chassis and the wheels) */
+void base_update(unsigned a, unsigned b) {
+ const unsigned PITS = T_MUD | T_LAVA;
+ b2Body *ch = V.chassis;
+ if (stage->pits == PIT_MUD) {
+ float damp = V.n ? V.n->mud_damp : 4;
+ if (a & PITS) {
+ ch->SetLinearDamping(damp);
+ ch->SetAngularDamping(damp);
+ ch->ApplyForceToCenter(b2Vec2(0, 10));
+ V.mud_frames_a++, V.mud_frames_b++;
+ } else if (b & PITS) {
+ ch->SetLinearDamping(damp * 0.5f);
+ ch->ApplyForceToCenter(b2Vec2(0, 10 * 0.5f));
+ V.mud_frames_b++;
+ } else {
+ ch->SetLinearDamping(0);
+ ch->SetAngularDamping(0);
+ V.mud_frames_a = V.mud_frames_b = 0;
+ }
+ }
+ if (stage->pits == PIT_LAVA) {
+ int *c = V.burn;
+ bool on_a = a & T_LAVA, on_b = b & T_LAVA;
+ if (!on_a && !on_b) {
+ for (int i = 0; i < 5; i++)
+ if (c[i] > 0) c[i]--;
+ } else {
+ /* the fire spreads from what touches the lava: c4 the "chassis", c0 the "wheels", to c3, c1, then c2 */
+ int old4 = c[4];
+ if (c[4] > 10 || c[0] > 10) c[3]++;
+ if (c[3] > 10) c[1]++;
+ if (c[1] > 10) c[2]++;
+ if (on_a || c[2] > 10) c[4] = old4 + 1;
+ if (on_b || c[2] > 10) c[0]++;
+ }
+ }
+}
+
+/* PlayerCarTractor::handleExhaustBreak: touched, the pipe bends to where it is; past 0.3 rad it breaks off */
+void handle_exhaust(void) {
+ if (!V.exhaust_joint || !V.touch_exhaust) return;
+ float a = V.exhaust_joint->GetJointAngle();
+ if (a < -0.3f || a > 0.3f) {
+ W->DestroyJoint(V.exhaust_joint);
+ V.exhaust_joint = NULL;
+ return;
+ }
+ float lo = V.exhaust_joint->GetLowerLimit(), hi = V.exhaust_joint->GetUpperLimit();
+ if (a < 0) V.exhaust_joint->SetLimits(a <= lo ? a : lo, hi);
+ else V.exhaust_joint->SetLimits(lo, a >= hi ? a : hi);
+}
+
+/* PlayerCarTractor::update's stability: when only one end's wheel touches, a torque rights it; while one does, a
+ * force holds it to the ground */
+void tractor_stability(void) {
+ bool rear = V.touch_wheel[0] != 0, front = V.touch_wheel[1] != 0;
+ if (!rear && !front) return;
+ float t = (float)(V.level_com - 1) / 14.0f * 25;
+ if (front && !rear) V.chassis->ApplyTorque(t);
+ if (rear && !front) V.chassis->ApplyTorque(-t);
+ push_down((float)V.level_com / 14.0f * 6);
+}
+
int update(void) {
+ /* PlayerCar::baseUpdate first (it reads this step's touches) */
+ base_update(V.mud_a >= 0 ? V.touch_wheel[V.mud_a] : 0, V.mud_b >= 0 ? V.touch_wheel[V.mud_b] : 0);
/* the engine's revs (the meter): towards 1 + |rear wheel| / 5 with gas, 1 without */
- if (V.accelerating) V.rev += DT * 6 * (1 + fabsf(wheel_w(0)) / 5 - V.rev);
+ float wr = V.veh == V_SNOWMOBILE ? fabsf(wheel_w(1) + wheel_w(2)) * 0.5f / 3 : fabsf(wheel_w(0));
+ if (V.veh == V_BUS) wr *= 1 - V.awd;
+ if (V.accelerating) V.rev += DT * 6 * (1 + wr / 5 - V.rev);
else V.rev += DT * 3 * (1 - V.rev);
- unsigned any = V.touch_chassis;
+ unsigned any = V.touch_chassis | V.touch_exhaust;
for (int i = 0; i < V.nw; i++) any |= V.touch_wheel[i];
+ if (V.veh == V_TRACTOR) tractor_stability();
if (any) V.air_frames = 0, V.decel_air = false;
else V.air_frames++;
+ handle_exhaust();
handle_head_hit();
+ for (int p = 0; p < V.npass; p++) /* (a bus passenger who touched the ground goes limp) */
+ if (V.pass_hit[p]) release_rider(&V.pass[p]), V.pass_hit[p] = false;
int flip = handle_flips();
downforce();
+ if (V.veh == V_SNOWMOBILE) push_down(1.5f);
/* the turbo builds while the gas is down */
+ float d0 = V.n ? V.n->decay0 : 1, d1 = V.n ? V.n->decay1 : 4;
if (V.accelerating) V.turbo += (0.35f + 0.75f * V.turbo) * V.rate / 60.0f;
- else V.turbo -= DT * (1 + 4 * V.turbo);
+ else V.turbo -= DT * (d0 + d1 * V.turbo);
V.turbo = clampf(V.turbo, 0, V.turbo_cap);
return flip;
}
@@ -683,6 +1123,16 @@ void snapshot(Car *c, int flip) {
c->wh[i].a = V.wheel[i]->GetAngle();
c->ground[i] = V.touch_wheel[i] != 0;
}
+ for (int p = 0; p < V.npass; p++)
+ for (int k = 0; k < 2; k++) {
+ b2Body *pb = k ? V.pass[p].head : V.pass[p].torso;
+ c->pass[p][k].x = pb->GetPosition().x, c->pass[p][k].y = pb->GetPosition().y, c->pass[p][k].a = pb->GetAngle();
+ }
+ for (int i = 0; i < V.nseg; i++) c->seg[i][0] = V.seg[i]->GetPosition().x, c->seg[i][1] = V.seg[i]->GetPosition().y;
+ if (V.exhaust) {
+ c->has_exhaust = true;
+ c->exhaust.x = V.exhaust->GetPosition().x, c->exhaust.y = V.exhaust->GetPosition().y, c->exhaust.a = V.exhaust->GetAngle();
+ }
c->vx = V.chassis->GetLinearVelocity().x, c->vy = V.chassis->GetLinearVelocity().y;
c->w = V.chassis->GetAngularVelocity();
c->air = V.air_frames;
@@ -690,6 +1140,11 @@ void snapshot(Car *c, int flip) {
c->flip = flip;
c->rev = V.rev, c->turbo = V.turbo;
c->tree_broken = tree_broken;
+ c->burning = 0;
+ for (int i = 0; i < 5; i++) {
+ c->burn[i] = (uint8_t)(V.burn[i] > 255 ? 255 : V.burn[i]);
+ c->burning += V.burn[i] > 0;
+ }
}
} // namespace
@@ -706,7 +1161,7 @@ extern "C" void car_init(Car *c, int veh, const uint8_t levels[4]) {
memset(&ceil_ring, 0, sizeof ceil_ring);
ceil_ring.ceiling = true;
game_end = 0, wall = NULL, wall_x = -1e9f;
- for (int i = 0; i < 2; i++) bridges[i].k = -1, bridges[i].n = 0;
+ for (int i = 0; i < 2; i++) bridges[i].k = -1, bridges[i].n = 0, pits[i].k = -1, pits[i].b = NULL;
for (int i = 0; i < MAXTREE; i++) trees[i].k = -1, trees[i].b = NULL, trees[i].j = NULL;
/* GameContentLayer::init: the vehicle 3 m over the ground at 0 */
float y = stage_floor(0) + 3;
@@ -733,8 +1188,9 @@ extern "C" void car_step(Car *c, int pedal, bool engine) {
float cx = V.chassis->GetPosition().x;
update_ground(cx);
update_bridges(cx);
+ update_pits(cx);
update_trees(cx);
- V.touch_chassis = 0;
+ V.touch_chassis = V.touch_exhaust = 0;
for (int i = 0; i < V.nw; i++) V.touch_wheel[i] = 0;
W->Step(DT, 8, 3);
snapshot(c, update());
@@ -757,9 +1213,12 @@ extern "C" bool car_touches_box(const Car *c, float x, float y, float half) {
box.SetAsBox(half, half);
b2Transform bx;
bx.Set(b2Vec2(x, y), 0);
- b2Body *parts[CAR_MAXW + 3] = {V.chassis, V.torso, V.head};
+ b2Body *parts[3 + CAR_MAXW + 2 * CAR_PASS + CAR_SEGS + 1] = {V.chassis, V.torso, V.head};
int n = 3;
for (int i = 0; i < V.nw; i++) parts[n++] = V.wheel[i];
+ for (int p = 0; p < V.npass; p++) parts[n++] = V.pass[p].torso, parts[n++] = V.pass[p].head;
+ for (int i = 0; i < V.nseg; i++) parts[n++] = V.seg[i];
+ if (V.exhaust) parts[n++] = V.exhaust;
for (int i = 0; i < n; i++) {
b2Vec2 p = parts[i]->GetPosition();
if (fabsf(p.x - x) > half + 3 || fabsf(p.y - y) > half + 3) continue;
@@ -771,11 +1230,38 @@ extern "C" bool car_touches_box(const Car *c, float x, float y, float half) {
extern "C" float car_fuel_rate(int veh, const uint8_t levels[4]) {
int lf = level_of(veh, levels, UP_FUEL);
- if (veh == V_BUGGY) return 1.65f - 0.9f * (float)lf / 21.0f;
- if (veh == V_TANK) return 1.5f - 0.9f * (float)lf / 21.0f;
- return 1;
+ switch (veh) {
+ case V_BUGGY: return 1.65f - 0.9f * (float)lf / 21.0f;
+ case V_TANK: return 1.5f - 0.9f * (float)lf / 21.0f;
+ case V_TRACTOR: return 1.2f - 0.7f * (float)(lf - 1) / 19.0f;
+ case V_BUS: case V_TRUCK: return 1.5f - 1.1f * (float)lf / 26.0f;
+ case V_DIESEL: case V_SNOWMOBILE: return 1.5f - 0.9f * (float)lf / 21.0f;
+ default: return 1;
+ }
}
+extern "C" void car_meters(int veh, float *rev_k, float *rev_b, float *turbo_k) {
+ *rev_b = 0;
+ switch (veh) {
+ case V_MONSTER: *rev_k = 1.65f, *turbo_k = 0.87f; break;
+ case V_BUGGY: *rev_k = 1.09f, *turbo_k = 0.66f; break;
+ case V_TANK: *rev_k = 1, *turbo_k = 0.44f; break;
+ case V_TRACTOR: *rev_k = 1.6f, *turbo_k = 0.67f; break;
+ case V_BUS: case V_DIESEL: case V_TRUCK: *rev_k = 1.6f, *turbo_k = 0.755f; break;
+ case V_SNOWMOBILE: *rev_k = 4.125f * 0.55f, *rev_b = -1, *turbo_k = 0.5f * 0.43f; break;
+ default: *rev_k = 1, *turbo_k = 1; break;
+ }
+}
+
+#ifdef HOST
+/* (tests: the numbers a vehicle was built with) */
+extern "C" void car_numbers(float out[12]) {
+ out[0] = V.speed, out[1] = V.s ? V.s->torque : V.n->torque, out[2] = V.tires, out[3] = V.hz, out[4] = V.damp;
+ out[5] = V.turbo_cap, out[6] = V.rate, out[7] = V.awd, out[8] = V.air, out[9] = V.chassis->GetMass();
+ out[10] = (float)V.nw, out[11] = (float)V.nseg;
+}
+#endif
+
extern "C" int car_planks(CarBody *out, int most) {
int n = 0;
for (int i = 0; i < 2; i++)
diff --git a/games/hillclimb/src/car.h b/games/hillclimb/src/car.h
index 17c0fd6d..faaa81ab 100644
--- a/games/hillclimb/src/car.h
+++ b/games/hillclimb/src/car.h
@@ -3,8 +3,8 @@
* The game runs on Box2D 2.2.1, and so does this: the same bodies, fixtures and joints with the game's numbers
* (its PlayerCar classes, read from its Android package), stepped 60 times a second with 8 velocity and 3 position
* iterations. The chassis and the wheels hang on wheel joints whose motors drive them; Bill is a torso and a head
- * on revolute joints and springs; the ground is a chain of 0.5 m edges, rope bridges are planks on revolute joints.
- * Meters, seconds, radians; y up. car_step is one 1/60 s. */
+ * on revolute joints and springs; the ground is a chain of 0.5 m edges, rope bridges are planks on revolute joints,
+ * pits of mud and lava are sensors under their surface. Meters, seconds, radians; y up. car_step is one 1/60 s. */
#ifndef HC_CAR_H
#define HC_CAR_H
#include <stdbool.h>
@@ -13,8 +13,10 @@
extern "C" {
#endif
-#define CAR_MAXW 6
+#define CAR_MAXW 8
#define CAR_HZ 60 /* car_step's rate */
+#define CAR_SEGS 16 /* the tractor's soft tire: its balls */
+#define CAR_PASS 3 /* the tourist bus' passengers */
typedef struct { float x, y, a; } CarBody; /* a body's origin and angle */
@@ -31,6 +33,15 @@ typedef struct {
float rev, turbo; /* the engine's revs and the turbo's pressure, for the meters */
int tree_broken; /* a tree knocked over this step, or -1 */
bool ground[CAR_MAXW]; /* the wheel touched something this step */
+ /* the new vehicles' parts, for drawing */
+ CarBody pass[CAR_PASS][2]; /* the bus' passengers: torso, head */
+ float seg[CAR_SEGS][2]; /* the tractor's soft tire: its balls' centres */
+ CarBody exhaust; /* the tractor's exhaust pipe */
+ bool has_exhaust;
+ /* lava (the Volcano): each part's fire, 0 when it doesn't burn (the game's five counters: the wheels, the front,
+ * Bill, the middle, the body); each burning one takes 0.02 of fuel a step */
+ uint8_t burn[5];
+ int burning;
} Car;
/* a new world for the stage being driven (stage.h), and the vehicle in it at the start */
@@ -47,10 +58,17 @@ bool car_airborne(const Car *c);
bool car_touches_box(const Car *c, float x, float y, float half);
/* the fuel's use (1, or by the Fuel upgrade) */
float car_fuel_rate(int veh, const uint8_t levels[4]);
+/* the meters' scale of the revs and the turbo (PlayerCar*::getEngineRev, getTurboPressure): v x k + b */
+void car_meters(int veh, float *rev_k, float *rev_b, float *turbo_k);
/* a bridge's planks, for drawing: how many, and each one's centre and angle */
int car_planks(CarBody *out, int most);
/* the trees near the car (Forest): their feet and angles, and which trees they are */
int car_trees(CarBody *out, int *which, int most);
+#ifdef HOST
+/* (tests) speed, torque, tires, hz, damping, turbo cap, turbo rate, 4WD share, air control, chassis mass, wheels,
+ * soft tire balls */
+void car_numbers(float out[12]);
+#endif
#ifdef __cplusplus
}
diff --git a/games/hillclimb/src/data.bin b/games/hillclimb/src/data.bin
index 772ad8dc..264cc751 100644
Binary files a/games/hillclimb/src/data.bin and b/games/hillclimb/src/data.bin differ
diff --git a/games/hillclimb/src/data.h b/games/hillclimb/src/data.h
index 6ef6c6e8..01a4cbd7 100644
--- a/games/hillclimb/src/data.h
+++ b/games/hillclimb/src/data.h
@@ -22,6 +22,13 @@ enum {
IMG_SNOW,
IMG_GRASS,
IMG_SLIME,
+ IMG_DIRT_MUD,
+ IMG_FIRE,
+ IMG_EXHAUST,
+ IMG_SKI,
+ IMG_PASS1,
+ IMG_PASS2,
+ IMG_PASS3,
IMG_SKY,
IMG_SKY_CAVE,
IMG_SKY_FOREST,
@@ -29,6 +36,9 @@ enum {
IMG_SKY_ARCTIC_CAVE,
IMG_SKY_HIGHWAY,
IMG_SKY_MOON,
+ IMG_SKY_CLIFFS,
+ IMG_SKY_MUD,
+ IMG_SKY_VOLCANO,
IMG_SURF_COUNTRY,
IMG_GROUND_COUNTRY,
IMG_SURF_DESERT,
@@ -46,6 +56,13 @@ enum {
IMG_GROUND_ALIEN,
IMG_SURF_FOREST,
IMG_GROUND_FOREST,
+ IMG_GROUND_CLIFFS,
+ IMG_SURF_MUD,
+ IMG_GROUND_MUD,
+ IMG_SURF_VOLCANO,
+ IMG_GROUND_VOLCANO,
+ IMG_PIT_MUD,
+ IMG_PIT_LAVA,
IMG_STAGE_COUNTRY,
IMG_STAGE_DESERT,
IMG_STAGE_ARCTIC,
@@ -56,6 +73,9 @@ enum {
IMG_STAGE_ALIEN,
IMG_STAGE_ARCTIC_CAVE,
IMG_STAGE_FOREST,
+ IMG_STAGE_MOUNTAIN,
+ IMG_STAGE_MUDPOOL,
+ IMG_STAGE_VOLCANO,
IMG_STAGE_LOCKED,
IMG_ICON_JEEP,
IMG_ICON_BIKE,
@@ -65,6 +85,11 @@ enum {
IMG_ICON_RALLY,
IMG_ICON_BUGGY,
IMG_ICON_TANK,
+ IMG_ICON_TRACTOR,
+ IMG_ICON_BUS,
+ IMG_ICON_DIESEL,
+ IMG_ICON_SNOWMOBILE,
+ IMG_ICON_TRUCK,
IMG_UP_ENGINE,
IMG_UP_SUSPENSION,
IMG_UP_TIRES,
@@ -86,6 +111,32 @@ enum {
IMG_LOGO,
IMG_LOCK,
IMG_START,
+ IMG_THUMB_V0,
+ IMG_THUMB_V1,
+ IMG_THUMB_V2,
+ IMG_THUMB_V3,
+ IMG_THUMB_V4,
+ IMG_THUMB_V5,
+ IMG_THUMB_V6,
+ IMG_THUMB_V7,
+ IMG_THUMB_V8,
+ IMG_THUMB_V9,
+ IMG_THUMB_V10,
+ IMG_THUMB_V11,
+ IMG_THUMB_V12,
+ IMG_THUMB_S0,
+ IMG_THUMB_S1,
+ IMG_THUMB_S2,
+ IMG_THUMB_S3,
+ IMG_THUMB_S4,
+ IMG_THUMB_S5,
+ IMG_THUMB_S6,
+ IMG_THUMB_S7,
+ IMG_THUMB_S8,
+ IMG_THUMB_S9,
+ IMG_THUMB_S10,
+ IMG_THUMB_S11,
+ IMG_THUMB_S12,
IMG_BILL_BODY,
IMG_BILL_HEAD,
IMG_BILL_LEG,
@@ -107,6 +158,12 @@ enum {
IMG_WHEEL_TANK,
IMG_LAYER_CAR_TANK_BG,
IMG_LAYER_CAR_TANK_CANNON,
+ IMG_CH_TRACTOR,
+ IMG_WHEEL_TRACTOR,
+ IMG_CH_BUS,
+ IMG_CH_DIESEL,
+ IMG_CH_SNOWMOBILE,
+ IMG_CH_TRUCK,
IMG_COUNT
};
enum {
diff --git a/games/hillclimb/src/game.h b/games/hillclimb/src/game.h
index 99ddf483..93a9fa35 100644
--- a/games/hillclimb/src/game.h
+++ b/games/hillclimb/src/game.h
@@ -9,8 +9,11 @@
enum { MODE_TITLE, MODE_HELP, MODE_GARAGE, MODE_STAGES, MODE_RUN, MODE_PAUSE, MODE_END };
-/* what is kept (save.c) */
+/* what is kept (save.c): hillclimb.sav, version 3 (13 vehicles and 13 stages); versions 1 and 2 (8 vehicles, 10
+ * stages) are read and carried over */
+#define SAVE_VERSION 3
typedef struct {
+ uint16_t version, pad0;
uint32_t coins;
uint16_t vehicles, stages; /* bits: owned */
uint8_t level[NVEHICLES][4]; /* each upgrade's level (1 and up) */
@@ -18,9 +21,8 @@ typedef struct {
uint8_t vehicle, stage, seen_help, pad;
uint32_t runs, meters, flips, best_air_ms, coins_earned;
uint8_t stage_level[NSTAGES]; /* each stage's level, from 0 (the game keeps them from run to run) */
- uint8_t pad2[2];
+ uint8_t pad2[3];
} Save;
-#define SAVE_V1_SIZE 224 /* (saves from before the levels were kept) */
extern Save sv;
enum { END_DRIVER_DOWN, END_OUT_OF_FUEL, END_QUIT };
diff --git a/games/hillclimb/src/gfx.c b/games/hillclimb/src/gfx.c
index f06e8ec0..bcebabfe 100644
--- a/games/hillclimb/src/gfx.c
+++ b/games/hillclimb/src/gfx.c
@@ -3,7 +3,7 @@
#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 };
+enum { C_FILL, C_RRECT, C_VGRAD, C_ROWS, C_IMAGE, C_BLIT, C_TEXT, C_CIRCLE, C_RING, C_TUBE, C_GROUND, C_LIQUID };
typedef struct {
uint8_t type, alpha;
@@ -204,6 +204,7 @@ void gfx_tube(float x0, float y0, float x1, float y1, float r, uint16_t c, int a
}
void gfx_ground_draw(void) { add(C_GROUND, 0, 0, SCREEN_W, SCREEN_H, 255); }
+void gfx_liquid_draw(void) { add(C_LIQUID, 0, 0, SCREEN_W, SCREEN_H, 255); }
/* ------------------------------------------------------------------ painting a band */
__attribute__((noinline)) static void paint_fill(const Cmd *k, int y0, int y1) {
@@ -455,6 +456,29 @@ __attribute__((noinline)) static void paint_ground(int y0, int y1) {
}
}
+/* A pit's mud or lava: from its surface's line down to the ground's, the pit's picture's rows by the depth */
+__attribute__((noinline)) static void paint_liquid(int y0, int y1) {
+ const Ground *g = &gfx_ground;
+ const Img *li = img(g->lpic);
+ const uint16_t *pal = img_pal565(li);
+ const uint8_t *px = img_px(li);
+ int h = li->h, w = li->w;
+ for (int x = 0; x < SCREEN_W; x++) {
+ int top8 = g->liquid[x];
+ if (top8 >= g->floor[x]) continue;
+ int ya = (top8 + 3) >> 3, yb = (g->floor[x] + 3) >> 3;
+ if (ya < y0) ya = y0;
+ if (yb > y1) yb = y1;
+ int u = (g->gu[x] * w) >> 7;
+ for (int y = ya; y < yb; y++) {
+ int32_t v = (int32_t)((int64_t)(y * 8 + 4 - top8) * g->ldv >> 3) >> 16;
+ if (v >= h) v = h - 1;
+ if (v < 0) v = 0;
+ band[(y - by0) * SCREEN_W + x] = pal[px[v * w + u]];
+ }
+ }
+}
+
void gfx_end(void) {
for (by0 = 0; by0 < SCREEN_H; by0 = by1) {
by1 = by0 + GFX_BAND < SCREEN_H ? by0 + GFX_BAND : SCREEN_H;
@@ -474,6 +498,7 @@ void gfx_end(void) {
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;
+ case C_LIQUID: paint_liquid(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.h
index 2dbb927a..8f56797b 100644
--- a/games/hillclimb/src/gfx.h
+++ b/games/hillclimb/src/gfx.h
@@ -55,9 +55,13 @@ typedef struct {
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) */
+ int16_t liquid[SCREEN_W]; /* a pit's surface's line x 8 (32000: none), its picture, its rows down a screen row */
+ uint8_t lpic;
+ int32_t ldv; /* (16.16) */
} Ground;
extern Ground gfx_ground;
void gfx_ground_draw(void);
+void gfx_liquid_draw(void); /* the pits' mud or lava (after the vehicle), from gfx_ground's liquid and floor */
/* 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);
diff --git a/games/hillclimb/src/menu.c b/games/hillclimb/src/menu.c
index 548c2214..ef0158f4 100644
--- a/games/hillclimb/src/menu.c
+++ b/games/hillclimb/src/menu.c
@@ -12,6 +12,14 @@ 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 */
+/* the garage goes through the vehicles in the game's order */
+static int vehicle_index(int v) {
+ for (int i = 0; i < NVEHICLES; i++)
+ if (vehicle_order[i] == v) return i;
+ return 0;
+}
+static int vehicle_step(int v, int d) { return vehicle_order[(vehicle_index(v) + d + NVEHICLES) % NVEHICLES]; }
+
void menu_enter(int mode) {
g_mode = mode, ask = 0, t = 0, flash = 0;
if (mode == MODE_GARAGE) shown = sv.vehicle, row = 0;
@@ -45,8 +53,8 @@ void menu_frame(uint32_t keys, uint32_t pressed) {
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;
+ if (ask == 1 && pay(vehicles[shown].price)) sv.vehicles |= (uint16_t)(1u << shown), sv.vehicle = (uint8_t)shown;
+ if (ask == 2 && pay(stages[shown].price)) sv.stages |= (uint16_t)(1u << shown), sv.stage = (uint8_t)shown;
save_write();
ask = 0;
} else if (pressed & K_BACK) {
@@ -72,8 +80,8 @@ void menu_frame(uint32_t keys, uint32_t pressed) {
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;
+ if (pressed & K_LEFT) shown = vehicle_step(shown, -1), t = 0;
+ if (pressed & K_RIGHT) shown = vehicle_step(shown, 1), t = 0;
owned = sv.vehicles >> shown & 1;
if (owned) sv.vehicle = (uint8_t)shown;
if (pressed & K_DOWN && owned) row = 1;
@@ -130,6 +138,29 @@ static void backdrop(const char *title) {
draw_coins_counter(312, 22, sv.coins, 2);
}
+/* the strip over a picker: every vehicle or stage small, in order, the one on show in a bright frame, the ones not
+ * owned dimmed; n of them, thumbs from first_img, which id each slot is, the one on show, owned bits */
+static void strip(int n, int first_img, const uint8_t *ids, int on, uint32_t owned) {
+ int slot = 24, x0 = (SCREEN_W - n * slot) / 2, y = 43;
+ gfx_fill(0, 32, SCREEN_W, 22, C_BLACK, 120);
+ for (int i = 0; i < n; i++) {
+ int id = ids ? ids[i] : i, cx = x0 + i * slot + slot / 2;
+ bool sel = id == on, have = owned >> id & 1;
+ if (sel) {
+ gfx_rrect(cx - 14, y - 11, 28, 22, 5, rgb565(0xFFD21F), 255);
+ gfx_rrect(cx - 11, y - 8, 22, 16, 3, rgb565(0x23262B), 255);
+ }
+ const Img *im = img(first_img + id);
+ float k = 21.0f / (float)im->w < 1 ? 21.0f / (float)im->w : 1;
+ gfx_image(first_img + id, (float)cx, (float)y, k, 0, have || sel ? 255 : 80);
+ }
+}
+
+/* the key line at the bottom: plain words */
+static void keys(const char *s, bool warn) {
+ gfx_text(FONT_S, 160, 236, s, warn ? rgb565(0xFF5A4A) : rgb565(0xD8DEE6), C_BLACK, 1);
+}
+
static void arrows(int y) {
int dx = (t / 8) % 2;
gfx_text(FONT_XL, 14 - dx, y, "<", C_WHITE, C_BLACK, 1);
@@ -187,7 +218,7 @@ static void help_draw(void) {
if ((t / 25) % 2 == 0) gfx_text(FONT_M, 160, 224, sv.seen_help ? "OK" : "OK: DRIVE!", rgb565(0xFFE14A), C_BLACK, 1);
}
-/* a text in lines of at most width pixels, centred on cx, 13 pixels apart */
+/* a text in lines of at most width pixels, centred on cx, 12 pixels apart */
static void wrapped(int cx, int y, int width, const char *s) {
char line[96];
while (*s) {
@@ -205,7 +236,7 @@ static void wrapped(int cx, int y, int width, const char *s) {
gfx_text(FONT_S, cx, y, line, rgb565(0xC8CDD4), C_BLACK, 1);
s += fit;
while (*s == ' ') s++;
- y += 13;
+ y += 12;
}
}
@@ -219,67 +250,69 @@ 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);
+ strip(NVEHICLES, IMG_THUMB_V0, vehicle_order, shown, sv.vehicles);
char tx[48];
+ snprintf(tx, sizeof tx, "%d/%d", vehicle_index(shown) + 1, NVEHICLES);
+ gfx_text(FONT_S, 314, 68, tx, rgb565(0xB8C0C8), C_BLACK, 2);
+ /* the vehicle, on a turntable of light */
+ gfx_circle(160, 106, 58, rgb565(0x5A6F80), 60);
+ gfx_image(v->icon, 160, 99, owned ? 1.0f : 0.92f, 0, owned ? 255 : 150);
+ if (!owned) gfx_image(IMG_LOCK, 160, 99, 1, 0, 255);
+ if (row == 0) arrows(113);
+ gfx_text(FONT_L, 160, 156, v->name, row == 0 ? rgb565(0xFFE14A) : C_WHITE, C_BLACK, 1);
if (!owned) {
- price_tag(160, 176, v->price, sv.coins >= v->price);
- wrapped(160, 196, 296, v->about);
- gfx_text(FONT_S, 160, 230, sv.coins >= v->price ? "OK: buy" : "Not enough coins yet", flash ? rgb565(0xFF5A4A) : C_WHITE,
- C_BLACK, 1);
+ price_tag(160, 174, v->price, sv.coins >= v->price);
+ wrapped(160, 188, 308, v->about);
+ keys(flash ? "Not enough coins yet" : sv.coins >= v->price ? "OK: buy Left Right: choose Back: title"
+ : "Left Right: choose Back: title", flash);
return;
}
/* its four upgrades */
for (int u = 0; u < 4; u++) {
- int x = 6 + u * 78, y = 164;
+ int x = 6 + u * 78, y = 161;
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);
+ gfx_rrect(x, y, 74, 64, 7, on ? rgb565(0xF2B531) : rgb565(0x2A2D33), on ? 255 : 220);
+ gfx_image(upgrade_icons[v->up[u]], (float)x + 20, (float)y + 19, 0.8f, 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);
+ gfx_text(FONT_S, x + 70, y + 13, tx, on ? C_BLACK : C_WHITE, on ? rgb565(0xF2B531) : C_BLACK, 2);
+ gfx_text(FONT_S, x + 37, y + 44, upgrade_names[v->up[u]], on ? C_BLACK : C_WHITE, on ? rgb565(0xF2B531) : C_BLACK, 1);
+ level_bar(x + 6, y + 47, 62, lv, max);
+ if (lv >= max) gfx_text(FONT_S, x + 37, y + 62, "MAX", rgb565(0x7FD63A), C_BLACK, 1);
else {
char n[20];
format_number(n, upgrade_cost(shown, u, lv + 1));
bool can = sv.coins >= upgrade_cost(shown, u, lv + 1);
- gfx_text(FONT_S, x + 37, y + 68, n, on ? (can ? C_BLACK : rgb565(0xA01010)) : can ? rgb565(0xFFE14A) : rgb565(0xFF7A6A),
+ gfx_text(FONT_S, x + 37, y + 62, n, on ? (can ? C_BLACK : rgb565(0xA01010)) : can ? rgb565(0xFFE14A) : rgb565(0xFF7A6A),
on ? rgb565(0xF2B531) : 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);
+ if (row == 0) keys("OK: stages Down: upgrades Left Right: choose", false);
+ else keys(flash ? "Not enough coins!" : "OK: upgrade Left Right: choose Up: back", flash);
}
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);
+ strip(NSTAGES, IMG_THUMB_S0, NULL, shown, sv.stages);
char tx[48];
+ snprintf(tx, sizeof tx, "%d/%d", shown + 1, NSTAGES);
+ gfx_text(FONT_S, 314, 68, tx, rgb565(0xB8C0C8), C_BLACK, 2);
+ gfx_rrect(50, 58, 220, 112, 10, C_BLACK, 160);
+ gfx_image_box(s->icon, 54, 62, 212, 104, 255);
+ if (!owned) gfx_image_box(IMG_STAGE_LOCKED, 54, 62, 212, 104, 210);
+ arrows(126);
+ gfx_text(FONT_L, 160, 194, s->name, rgb565(0xFFE14A), C_BLACK, 1);
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);
+ gfx_text(FONT_S, 160, 213, tx, rgb565(0xC8CDD4), C_BLACK, 1);
+ keys("OK: drive Left Right: choose Back: vehicle", false);
} 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);
+ price_tag(160, 214, s->price, sv.coins >= s->price);
+ keys(flash ? "Not enough coins yet" : sv.coins >= s->price ? "OK: buy Left Right: choose Back: vehicle"
+ : "Left Right: choose Back: vehicle", flash);
}
- /* 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) {
diff --git a/games/hillclimb/src/run.c b/games/hillclimb/src/run.c
index b508f38e..5ae33b84 100644
--- a/games/hillclimb/src/run.c
+++ b/games/hillclimb/src/run.c
@@ -146,7 +146,10 @@ static void pickups(void) {
if (car_touches_box(c, cx[i], cy[i], half)) {
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.5f, 2);
+ for (int s = 0; s < 3; s++) {
+ float vx = rndf() * 2 - 1, vy = rndf() * 2 + 1; /* (one at a time: arguments have no order) */
+ particle(cx[i], cy[i], vx, vy, 0.4f, 0.5f, 2);
+ }
}
}
}
@@ -173,12 +176,15 @@ void run_frame(uint32_t keys) {
if (c->tree_broken >= 0) {
float tx, ty;
if (stage_tree(c->tree_broken, &tx, &ty))
- for (int s = 0; s < 14; s++)
- particle(tx, ty + 0.3f + rndf() * 2.0f, c->vx * 0.5f + rndf() * 4 - 1, rndf() * 4, 0.9f, 0.3f + rndf() * 0.2f, 0);
+ for (int s = 0; s < 14; s++) {
+ float py = ty + 0.3f + rndf() * 2.0f, vx = c->vx * 0.5f + rndf() * 4 - 1, vy = rndf() * 4, sz = 0.3f + rndf() * 0.2f;
+ particle(tx, py, vx, vy, 0.9f, sz, 0);
+ }
}
- /* fuel: 2.5 a second (and the vehicle's rate) out of 100; empty, the run ends 4 s later */
+ /* fuel: 2.5 a second (and the vehicle's rate) out of 100, and 0.02 a step for each part on fire (lava); empty,
+ * the run ends 4 s later */
if (run.fuel > 0) {
- run.fuel -= run.burn * DT;
+ run.fuel -= run.burn * DT + 0.02f * (float)c->burning;
if (run.fuel <= 0) run.fuel = 0;
run.empty_t = 0;
} else if (!run.over && (run.empty_t += DT) > 4) {
@@ -211,9 +217,10 @@ void run_frame(uint32_t keys) {
/* dust from the wheels that spin on the ground, smoke from the exhaust */
for (int i = 0; i < c->nw; i++) {
float sp = fabsf(c->vx);
- if (c->ground[i] && (sp > 4 || gas) && (run.frame + (uint32_t)i) % 5 == 0)
- particle(c->wh[i].x - c->wr[i] * 0.6f, c->wh[i].y - c->wr[i] * 0.8f, -c->vx * 0.2f - rndf() * 2,
- 1 + rndf() * 2, 0.5f, 0.22f + rndf() * 0.12f, 0);
+ if (c->ground[i] && (sp > 4 || gas) && (run.frame + (uint32_t)i) % 5 == 0) {
+ float vx = -c->vx * 0.2f - rndf() * 2, vy = 1 + rndf() * 2, sz = 0.22f + rndf() * 0.12f;
+ particle(c->wh[i].x - c->wr[i] * 0.6f, c->wh[i].y - c->wr[i] * 0.8f, vx, vy, 0.5f, sz, 0);
+ }
}
if (gas && run.fuel > 0 && !c->dead && run.frame % 9 == 0 && car_speed(c) < 6) {
float ex, ey;
@@ -479,6 +486,20 @@ static void draw_bill(const VehArt *a) {
body_image(IMG_BILL_HEAD, c->head.x, c->head.y, ha);
}
+/* a rider on two bodies: a torso picture from his hips, a head picture on his head (the bus' passengers) */
+static void draw_rider(const CarBody *torso, const CarBody *head, int head_id) {
+ float ta = torso->a - PI;
+ float hx = torso->x + sinf(ta) * 0.3f, hy = torso->y - cosf(ta) * 0.3f;
+ body_image(IMG_BILL_BODY, hx, hy, ta);
+ body_image(head_id, head->x, head->y, head->a - PI);
+}
+
+static void draw_wheel(const VehArt *a, int i, float size) {
+ const Car *c = &run.car;
+ gfx_image(a->wheel, scr_x(c->wh[i].x), scr_y(c->wh[i].y), run.cam_s / (img(a->wheel)->ppm4 / 4.0f) * size, c->wh[i].a,
+ 255);
+}
+
static void draw_car(void) {
const Car *c = &run.car;
const VehArt *a = &veh_art[run.vehicle];
@@ -486,10 +507,11 @@ static void draw_car(void) {
bool rider = a->legs;
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 */
+ if (run.vehicle == V_TANK || run.vehicle == V_SNOWMOBILE) { /* the track around the wheels */
+ int n = run.vehicle == V_TANK ? c->nw : 5;
for (int pass = 0; pass < 2; pass++)
- for (int i = 0; i < c->nw; i++) {
- int j = (i + 1) % c->nw;
+ for (int i = 0; i < n; i++) {
+ int j = (i + 1) % n;
gfx_tube(scr_x(c->wh[i].x), scr_y(c->wh[i].y), scr_x(c->wh[j].x), scr_y(c->wh[j].y),
(c->wr[0] + (pass ? -0.02f : 0.07f)) * s, rgb565(pass ? 0x4A4A4A : 0x2A2A2A), 255);
}
@@ -501,12 +523,27 @@ static void draw_car(void) {
gfx_tube(scr_x(tx), scr_y(ty), scr_x(c->wh[w].x), scr_y(c->wh[w].y), a->tube[0][4] * s,
rgb565((uint32_t)a->tube[0][3]), 255);
}
+ if (run.vehicle == V_TRACTOR && c->has_exhaust) body_image(IMG_EXHAUST, c->exhaust.x, c->exhaust.y, c->exhaust.a);
+ if (run.vehicle == V_BUS) /* the passengers on the upper deck, behind its side */
+ for (int p = 0; p < CAR_PASS; p++) draw_rider(&c->pass[p][0], &c->pass[p][1], IMG_PASS1 + p);
if (!rider) draw_bill(a);
- car_image(a->chassis, 0, 0, 0);
+ car_image(a->chassis, 0, 0, run.vehicle == V_TRUCK ? 0.025f : 0); /* (the truck's picture is turned a little) */
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,
- c->wh[i].a, 255);
+ if (run.vehicle == V_TRACTOR) {
+ /* the soft tire: its picture as round as its balls are far out (the balls are 0.135 R, R 1.09) */
+ float d = 0;
+ for (int i = 0; i < CAR_SEGS; i++) d += hypotf(c->seg[i][0] - c->wh[0].x, c->seg[i][1] - c->wh[0].y);
+ draw_wheel(a, 0, (d / CAR_SEGS + 1.09f * 0.135f) / a->wheel_r);
+ draw_wheel(a, 1, c->wr[1] / a->wheel_r);
+ } else if (run.vehicle == V_SNOWMOBILE) {
+ for (int i = 0; i < 5; i++) draw_wheel(a, i, c->wr[i] / a->wheel_r);
+ /* the ski across its two wheels (a multibody sprite), 0.1 ahead and 0.19 under their middle */
+ float dx = c->wh[6].x - c->wh[5].x, dy = c->wh[6].y - c->wh[5].y, an = atan2f(dy, dx), cs = cosf(an), sn = sinf(an);
+ float mx = (c->wh[5].x + c->wh[6].x) * 0.5f + 0.1f * cs + 0.19f * sn, my = (c->wh[5].y + c->wh[6].y) * 0.5f + 0.1f * sn - 0.19f * cs;
+ body_image(IMG_SKI, mx, my, an);
+ } else {
+ for (int i = 0; i < c->nw; i++) draw_wheel(a, i, c->wr[i] / a->wheel_r);
+ }
for (int i = 1; i < a->ntubes; i++) { /* the fork, in front */
float tx, ty;
car_point(c, a->tube[i][0], a->tube[i][1], &tx, &ty);
@@ -518,6 +555,28 @@ static void draw_car(void) {
if (a->layer[i][3]) car_image((int)a->layer[i][0], a->layer[i][1], a->layer[i][2], 0);
}
+/* lava: fire on the parts that burn (the game's five counters: the back wheel, the front, Bill, the middle, the body) */
+static void draw_fire(void) {
+ const Car *c = &run.car;
+ if (!c->burning) return;
+ float px[5], py[5];
+ px[0] = c->wh[0].x, py[0] = c->wh[0].y;
+ px[1] = c->wh[c->nw > 2 && run.vehicle != V_SNOWMOBILE ? c->nw - 1 : 1].x;
+ py[1] = c->wh[c->nw > 2 && run.vehicle != V_SNOWMOBILE ? c->nw - 1 : 1].y;
+ px[2] = c->torso.x, py[2] = c->torso.y;
+ car_point(c, 0.8f, 0.2f, &px[3], &py[3]);
+ px[4] = c->ch.x, py[4] = c->ch.y;
+ for (int k = 0; k < 5; k++) {
+ if (!c->burn[k]) continue;
+ float grow = c->burn[k] > 99 ? 1 : 0.4f + 0.6f * (float)c->burn[k] / 99.0f;
+ for (int f = 0; f < 3; f++) {
+ uint32_t h = hash2(run.frame * 3u + (uint32_t)(k * 7 + f));
+ float fx = px[k] + ((float)(h & 255) / 255.0f - 0.5f) * 0.8f, fy = py[k] + (float)(h >> 8 & 255) / 255.0f * 0.9f;
+ gfx_image(IMG_FIRE, scr_x(fx), scr_y(fy), run.cam_s / (float)img(IMG_FIRE)->w * 1.1f * grow, 0, 200);
+ }
+ }
+}
+
static void draw_particles(void) {
float s = run.cam_s;
for (int i = 0; i < run.npart; i++) {
@@ -586,9 +645,9 @@ static void draw_hud(void) {
gfx_image(pb, 23, 218, 1, 0, 255);
gfx_image(pg, 297, 218, 1, 0, 255);
/* (each vehicle's own scale: PlayerCar*::getEngineRev, getTurboPressure) */
- float rk = run.vehicle == V_MONSTER ? 1.65f : run.vehicle == V_BUGGY ? 1.09f : 1;
- float tk = run.vehicle == V_MONSTER ? 0.87f : run.vehicle == V_BUGGY ? 0.66f : run.vehicle == V_TANK ? 0.44f : 1;
- float rpm = run.fuel > 0 && !c->dead ? needle(c->rev * rk, 23) : needle(0, 23);
+ float rk, rb, tk;
+ car_meters(run.vehicle, &rk, &rb, &tk);
+ float rpm = run.fuel > 0 && !c->dead ? needle(c->rev * rk + rb, 23) : needle(0, 23);
float boost = needle(c->turbo * tk, 87);
for (int m = 0; m < 2; m++) {
float mx = m ? 186 : 134, my = 216;
@@ -622,6 +681,29 @@ static void draw_hud(void) {
else if (run.fuel <= 0 && !run.over) gfx_text(FONT_XL, 160, 150, "OUT OF FUEL", rgb565(0xFFC21A), C_BLACK, 1);
}
+/* the pits' mud or lava, over the car as in the game (Pit::draw comes after the car's pictures) */
+static void draw_pits(void) {
+ if (!stage->pits) return;
+ Ground *g = &gfx_ground;
+ float x0w = wld_x(0), x1w = wld_x(SCREEN_W);
+ bool any = false;
+ for (int x = 0; x < SCREEN_W; x++) g->liquid[x] = 32000;
+ for (int k = stage_pit_first(x0w);; k++) {
+ float p0, len, py;
+ if (!stage_pit_k(k, &p0, &len, &py) || p0 > x1w) break;
+ int a = (int)ceilf(scr_x(p0)), b = (int)floorf(scr_x(p0 + len));
+ if (a < 0) a = 0;
+ if (b > SCREEN_W) b = SCREEN_W;
+ float top = scr_y(py);
+ for (int x = a; x < b; x++) g->liquid[x] = (int16_t)(top > 4000 ? 32000 : top < -4000 ? -32000 : top * 8);
+ any = any || a < b;
+ }
+ if (!any) return;
+ g->lpic = stage->pits == PIT_LAVA ? IMG_PIT_LAVA : IMG_PIT_MUD;
+ g->ldv = (int32_t)((float)img(g->lpic)->h / (stage_pit_depth() * run.cam_s) * 65536.0f);
+ gfx_liquid_draw();
+}
+
void run_draw(bool hud) {
draw_sky();
draw_ground();
@@ -630,6 +712,8 @@ void run_draw(bool hud) {
draw_trees();
draw_things();
draw_car();
+ draw_pits();
+ draw_fire();
draw_particles();
if (hud) draw_hud();
}
diff --git a/games/hillclimb/src/save.c b/games/hillclimb/src/save.c
index 10400987..f739f62a 100644
--- a/games/hillclimb/src/save.c
+++ b/games/hillclimb/src/save.c
@@ -8,7 +8,7 @@
#define SAVE_NAME "hillclimb.sav"
#define COPY_NAME "hillclimb_saves.py"
-#define MAGIC 0x31524348u /* "HCR1" */
+#define MAGIC 0x31524348u /* "HCR1" (all versions; the size and the version tell them apart) */
Save sv;
@@ -16,7 +16,32 @@ typedef struct {
uint32_t magic, size;
Save s;
} SaveFile;
-_Static_assert(offsetof(Save, stage_level) == SAVE_V1_SIZE, "the old saves' part comes first");
+
+/* versions 1 and 2: 8 vehicles, 10 stages (version 1 without the stages' levels) */
+#define OLD_V 8
+#define OLD_S 10
+typedef struct {
+ uint32_t coins;
+ uint16_t vehicles, stages;
+ uint8_t level[OLD_V][4];
+ uint16_t best[OLD_S][OLD_V];
+ uint8_t vehicle, stage, seen_help, pad;
+ uint32_t runs, meters, flips, best_air_ms, coins_earned;
+ uint8_t stage_level[OLD_S];
+ uint8_t pad2[2];
+} SaveV2;
+#define SAVE_V1_SIZE 224
+_Static_assert(offsetof(SaveV2, stage_level) == SAVE_V1_SIZE, "version 1 is version 2 without the stages' levels");
+_Static_assert(sizeof(SaveV2) == 236, "version 2's size");
+/* (tests/check.py and NumPlay's tests/test_games.py read these) */
+_Static_assert(sizeof(Save) == 444 && offsetof(Save, best) == 64 && offsetof(Save, runs) == 408 &&
+ offsetof(Save, stage_level) == 428, "version 3's layout");
+/* the upgrades' last levels and prices before version 3 (they were not the game's: version 3 has the game's own) */
+static const uint8_t OLD_MAX[OLD_V][4] = {{13, 14, 16, 10}, {12, 14, 16, 10}, {13, 14, 15, 10}, {13, 14, 16, 10},
+ {12, 14, 16, 12}, {14, 14, 17, 10}, {15, 15, 15, 20}, {15, 15, 15, 20}};
+static const uint16_t OLD_COST[OLD_V][4] = {{1000, 1000, 1000, 1000}, {1500, 1000, 1000, 3000}, {1500, 1200, 1200, 1500},
+ {1500, 1200, 1200, 1200}, {1500, 1500, 1500, 2500}, {2000, 2000, 2000, 3000},
+ {3000, 3000, 3000, 3000}, {3000, 3000, 3000, 3000}};
static const char copy_head[] =
"# Hill Climb Racing keeps a copy of your progress here, so\n"
@@ -100,22 +125,61 @@ void save_restore_copy(void) {
static void defaults(void) {
memset(&sv, 0, sizeof sv);
+ sv.version = SAVE_VERSION;
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;
}
+/* a version 1 or 2 save into version 3: everything kept; an upgrade above its game's last level is brought down to it
+ * and what its levels above cost comes back as coins */
+static void from_v2(const SaveV2 *o, bool v1) {
+ sv.coins = o->coins;
+ sv.vehicles = o->vehicles & ((1 << OLD_V) - 1), sv.stages = o->stages & ((1 << OLD_S) - 1);
+ uint64_t refund = 0;
+ for (int v = 0; v < OLD_V; v++)
+ for (int u = 0; u < 4; u++) {
+ int l = o->level[v][u];
+ if (l < 1 || l > OLD_MAX[v][u]) l = 1;
+ for (; l > vehicles[v].max[u]; l--) refund += (uint64_t)OLD_COST[v][u] * (uint64_t)(l * l);
+ sv.level[v][u] = (uint8_t)l;
+ }
+ uint64_t c = sv.coins + refund;
+ sv.coins = c > 0xFFFFFFFFu ? 0xFFFFFFFFu : (uint32_t)c;
+ for (int st = 0; st < OLD_S; st++)
+ for (int v = 0; v < OLD_V; v++) sv.best[st][v] = o->best[st][v];
+ sv.vehicle = o->vehicle, sv.stage = o->stage, sv.seen_help = o->seen_help;
+ sv.runs = o->runs, sv.meters = o->meters, sv.flips = o->flips, sv.best_air_ms = o->best_air_ms;
+ sv.coins_earned = o->coins_earned;
+ if (!v1)
+ for (int st = 0; st < OLD_S; st++) sv.stage_level[st] = o->stage_level[st];
+}
+
void save_load(void) {
defaults();
uint32_t len;
const uint8_t *d = plat_load(SAVE_NAME, &len);
- if (!d || (len != sizeof(SaveFile) && len != 8 + SAVE_V1_SIZE)) return;
- SaveFile f;
- memset(&f, 0, sizeof f);
- memcpy(&f, d, len);
- if (f.magic != MAGIC || f.size != len - 8) return;
- sv = f.s;
+ if (!d || len < 8) return;
+ uint32_t magic, size;
+ memcpy(&magic, d, 4);
+ memcpy(&size, d + 4, 4);
+ if (magic != MAGIC || size != len - 8) return;
+ if (size == sizeof(Save)) {
+ Save s;
+ memcpy(&s, d + 8, sizeof s);
+ if (s.version != SAVE_VERSION) return;
+ sv = s;
+ } else if (size == sizeof(SaveV2) || size == SAVE_V1_SIZE) {
+ SaveV2 o;
+ memset(&o, 0, sizeof o);
+ memcpy(&o, d + 8, size);
+ from_v2(&o, size == SAVE_V1_SIZE);
+ } else {
+ return;
+ }
/* (whatever the file says, the first vehicle and stage are owned and levels stay in range) */
+ sv.version = SAVE_VERSION;
+ sv.vehicles &= (1 << NVEHICLES) - 1, sv.stages &= (1 << NSTAGES) - 1;
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;
@@ -127,6 +191,7 @@ void save_load(void) {
bool save_write(void) {
SaveFile f;
memset(&f, 0, sizeof f);
+ sv.version = SAVE_VERSION;
f.magic = MAGIC, f.size = sizeof(Save), f.s = sv;
bool ok = plat_save(SAVE_NAME, &f, sizeof f);
copy_write();
diff --git a/games/hillclimb/src/stage.c b/games/hillclimb/src/stage.c
index 8ce70672..63a1ae18 100644
--- a/games/hillclimb/src/stage.c
+++ b/games/hillclimb/src/stage.c
@@ -1,36 +1,43 @@
-/* The stages (stage.h): the game's own ground, ceilings, bridges, trees, coins, fuel cans; the levels. */
+/* The stages (stage.h): the game's own ground, ceilings, bridges, pits, trees, coins, fuel cans; the levels. */
#include <math.h>
+#include <stdlib.h>
#include "data.h"
#include "stage.h"
#define PI 3.14159265f
/* name, price, gravity, friction, coin multiplier and rows; sky, surface, ground, ceiling's surface, icon, particle;
- * ceiling, feature, clouds, stars; bridges and their spacing; levels; the surface's colour. Gravity, friction,
- * coins, ceilings, bridges are the game's (Stage::create, Stage*::get*), the prices and levels the game's
+ * ceiling, feature, clouds, stars; bridges and their spacing; levels; the surface's colour; pits. Gravity, friction,
+ * coins, ceilings, bridges, pits are the game's (Stage::create, Stage*::get*), the prices and levels the game's
* (StageManager::initialize). */
const Stage stages[NSTAGES] = {
{"Countryside", 0, 10, 0.6f, 1.25f, 0, IMG_SKY, IMG_SURF_COUNTRY, IMG_GROUND_COUNTRY, IMG_SURF_CAVE, IMG_STAGE_COUNTRY,
- IMG_GRASS, 0, FEAT_NONE, 1, 0, 1, 12.76214f, 70, 200, 200, 15, 0x7CC62B},
+ IMG_GRASS, 0, FEAT_NONE, 1, 0, 1, 12.76214f, 70, 200, 200, 15, 0x7CC62B, PIT_NONE},
{"Desert", 35000, 10, 0.5f, 1.75f, 0, IMG_SKY, IMG_SURF_DESERT, IMG_GROUND_DESERT, IMG_SURF_CAVE, IMG_STAGE_DESERT,
- IMG_DIRT, 0, FEAT_NONE, 1, 0, 1, 5.76214f, 110, 200, 200, 25, 0xE8D99A},
+ IMG_DIRT, 0, FEAT_NONE, 1, 0, 1, 5.76214f, 110, 200, 200, 25, 0xE8D99A, PIT_NONE},
{"Arctic", 75000, 10, 0.15f, 1.95f, 0, IMG_SKY, IMG_SURF_ARCTIC, IMG_GROUND_ARCTIC, IMG_SURF_CAVE, IMG_STAGE_ARCTIC,
- IMG_SNOW, 0, FEAT_NONE, 1, 0, 1, 12.76214f, 70, 200, 200, 30, 0xF2F6FA},
+ IMG_SNOW, 0, FEAT_NONE, 1, 0, 1, 12.76214f, 70, 200, 200, 30, 0xF2F6FA, PIT_NONE},
{"Highway", 125000, 10, 0.4f, 1.15f, 0, IMG_SKY_HIGHWAY, IMG_SURF_HIGHWAY, IMG_GROUND_HIGHWAY, IMG_SURF_CAVE,
- IMG_STAGE_HIGHWAY, IMG_SMOKE, 0, FEAT_NONE, 1, 0, 0, 7.76214f, 70, 600, 300, 25, 0x6E6E6E},
+ IMG_STAGE_HIGHWAY, IMG_SMOKE, 0, FEAT_NONE, 1, 0, 0, 7.76214f, 70, 600, 300, 25, 0x6E6E6E, PIT_NONE},
{"Cave", 150000, 10, 0.6f, 1.7f, -0.5f, IMG_SKY_CAVE, IMG_SURF_CAVE, IMG_GROUND_COUNTRY, IMG_SURF_CAVE, IMG_STAGE_CAVE,
- IMG_ROCKS, 1, FEAT_NONE, 0, 0, 1, 12.76214f, 70, 300, 300, 30, 0xB7B2A8},
+ IMG_ROCKS, 1, FEAT_NONE, 0, 0, 1, 12.76214f, 70, 300, 300, 30, 0xB7B2A8, PIT_NONE},
{"Moon", 175000, 3.5f, 0.8f, 1.95f, 0, IMG_SKY_MOON, IMG_SURF_MOON, IMG_GROUND_MOON, IMG_SURF_CAVE, IMG_STAGE_MOON,
- IMG_SMOKE, 0, FEAT_NONE, 0, 1, 0, 7.76214f, 70, 200, 300, 40, 0xB9BAD8},
+ IMG_SMOKE, 0, FEAT_NONE, 0, 1, 0, 7.76214f, 70, 200, 300, 40, 0xB9BAD8, PIT_NONE},
{"Mars", 250000, 5, 0.6f, 1.7f, -0.5f, IMG_SKY_MARS, IMG_SURF_MARS, IMG_GROUND_MARS, IMG_SURF_MARS, IMG_STAGE_MARS,
- IMG_ROCKS_MARS, 1, FEAT_NONE, 0, 0, 1, 12.76214f, 70, 200, 300, 40, 0xC77B5A},
+ IMG_ROCKS_MARS, 1, FEAT_NONE, 0, 0, 1, 12.76214f, 70, 200, 300, 40, 0xC77B5A, PIT_NONE},
{"Alien Planet", 750000, 10, 0.07f, 1.15f, 0, IMG_SKY_FOREST, IMG_SURF_ALIEN, IMG_GROUND_ALIEN, IMG_SURF_ALIEN,
- IMG_STAGE_ALIEN, IMG_SLIME, 0, FEAT_NONE, 0, 1, 0, 7.76214f, 70, 200, 300, 40, 0x6FA34A},
+ IMG_STAGE_ALIEN, IMG_SLIME, 0, FEAT_NONE, 0, 1, 0, 7.76214f, 70, 200, 300, 40, 0x6FA34A, PIT_NONE},
{"Arctic Cave", 800000, 10, 0.07f, 1.7f, -0.5f, IMG_SKY_ARCTIC_CAVE, IMG_SURF_ARCTIC, IMG_GROUND_ARCTIC,
IMG_SURF_ARCTIC, IMG_STAGE_ARCTIC_CAVE, IMG_SNOW, 1, FEAT_ICICLES, 0, 0, 1, 12.76214f, 70, 200, 300, 40,
- 0xEAF3F8},
+ 0xEAF3F8, PIT_NONE},
{"Forest", 850000, 10, 0.6f, 1.7f, 0, IMG_SKY_FOREST, IMG_SURF_FOREST, IMG_GROUND_FOREST, IMG_SURF_CAVE,
- IMG_STAGE_FOREST, IMG_GRASS, 0, FEAT_TREES, 1, 0, 1, 12.76214f, 70, 200, 250, 40, 0x4E9A2E},
+ IMG_STAGE_FOREST, IMG_GRASS, 0, FEAT_TREES, 1, 0, 1, 12.76214f, 70, 200, 250, 40, 0x4E9A2E, PIT_NONE},
+ {"Mountain", 850000, 10, 0.6f, 1.7f, 0, IMG_SKY_CLIFFS, IMG_SURF_CAVE, IMG_GROUND_CLIFFS, IMG_SURF_CAVE,
+ IMG_STAGE_MOUNTAIN, IMG_ROCKS, 0, FEAT_NONE, 1, 0, 1, 12.76214f, 70, 200, 250, 40, 0x8E8A84, PIT_NONE},
+ {"Mudpool", 1000000, 10, 0.1f, 1.25f, 0, IMG_SKY_MUD, IMG_SURF_MUD, IMG_GROUND_MUD, IMG_SURF_CAVE,
+ IMG_STAGE_MUDPOOL, IMG_DIRT_MUD, 0, FEAT_NONE, 0, 0, 0, 12.76214f, 70, 200, 250, 40, 0x8A6A44, PIT_MUD},
+ {"Volcano", 1000000, 10, 0.6f, 1.7f, -0.5f, IMG_SKY_VOLCANO, IMG_SURF_VOLCANO, IMG_GROUND_VOLCANO, IMG_SURF_CAVE,
+ IMG_STAGE_VOLCANO, IMG_ROCKS, 0, FEAT_NONE, 0, 0, 0, 12.76214f, 70, 200, 250, 40, 0x2E2A28, PIT_LAVA},
};
const Stage *stage = &stages[0];
@@ -159,8 +166,37 @@ static float h_forest(float x) {
return h * grow(u / 2000, 1.5f, 0.5f);
}
+/* the Mountain and the Volcano climb all the way (their u/3 and u/6) */
+static float h_mountain(float x) {
+ float u = 10 + 1.5f * x;
+ float h = 2 * cosf(u / 6.41f) +
+ (0.2f * sinf(u + sinf(0.415f * u)) + 0.25f * cosf(0.655f * u + sinf(0.215f * u))) * clampf(0.0015f * u, 0, 1) +
+ 2 * cosf(0.16f * u + sinf(0.3515f * u) + 2.411f) * clampf(0.00075f * u, 0, 1) +
+ 2 * cosf(0.1952f * u + sinf(1.215f * u) + 5.6f) * clampf(0.00275f * u, 0, 1) + u / 3;
+ return h * grow(u / 4000, 1.8f, 0.2f);
+}
+
+static float h_mudpool(float x) {
+ float u = 10 + 1.5f * x, s = sinf(0.25f * u);
+ float h = 2 * cosf(u / 10) + 0.2f * cosf(u + s) * clampf(0.0013f * u, 0, 1) +
+ 2 * cosf(0.17f * u + s) * clampf(0.00035f * u, 0, 1) +
+ 2 * cosf(0.0952f * u + sinf(0.15f * u)) * clampf(0.00125f * u, 0, 1) +
+ (4 * sinf(u / 30 + cosf(u / 32.14f)) * clampf(0.0007f * u, 0, 1) - 1);
+ return h * grow(u / 2000, 1.5f, 0.5f);
+}
+
+static float h_volcano(float x) {
+ float u = 10 + 1.5f * x;
+ float h = 2 * cosf(u / 6.41f) +
+ (0.2f * sinf(u + sinf(0.415f * u)) + 0.25f * cosf(0.855f * u + sinf(0.215f * u))) * clampf(0.0015f * u, 0, 1) +
+ 2 * cosf(0.3f * u + sinf(0.3515f * u) + 2.411f) * clampf(0.00075f * u, 0, 1) +
+ 2 * cosf(0.2052f * u + sinf(1.215f * u) + 5.6f) * clampf(0.00275f * u, 0, 0.1f) + u / 6;
+ return h * grow(u / 4000, 1.8f, 0.2f);
+}
+
static float (*const heights[NSTAGES])(float) = {h_countryside, h_desert, h_arctic, h_highway, h_cave, h_moon,
- h_mars, h_alien, h_arctic_cave, h_forest};
+ h_mars, h_alien, h_arctic_cave, h_forest, h_mountain, h_mudpool,
+ h_volcano};
/* the caves' ceiling over the ground (StageCave::getCaveHeightAtX); Mars opens up now and then */
static float cave_height(float x) {
@@ -178,70 +214,102 @@ static float cave_height(float x) {
return 50 + w * (c + top - 50);
}
-/* ------------------------------------------------------------------ bridges (GameContentLayer::addNewBridge) */
-#define MAXBRIDGE 400
-static float br_x0[MAXBRIDGE], br_len[MAXBRIDGE], br_y[MAXBRIDGE], br_shift[MAXBRIDGE];
-static int br_n; /* worked out so far */
+/* ------------------------------------------------------------------ bridges and pits (GameContentLayer::addNewBridge,
+ * addNewPit): a stage has one or the other, so they share their memory */
+#define MAXGAP 400
+static float gp_x0[MAXGAP], gp_len[MAXGAP], gp_y[MAXGAP], gp_shift[MAXGAP];
+static int gp_n; /* worked out so far */
-/* the stage's own height with the bridges so far taken out */
+/* the stage's own height with the bridges or pits so far taken out */
static float base_height(float x) { return heights[stage_id](x); }
-static void bridges_upto(int k) {
- while (br_n <= k && br_n < MAXBRIDGE) {
- int n = br_n;
- float x0 = n ? br_x0[n - 1] + (float)(int)(stage->bridge_d * (2 + sinf((float)n / stage->bridge_k))) : 120;
- float shift = n ? br_shift[n - 1] - br_len[n - 1] : 0;
- br_x0[n] = x0;
- br_len[n] = (float)(int)(13 + 5 * sinf((float)n * 2.172f));
- br_shift[n] = shift;
- br_y[n] = base_height(x0 + shift);
- br_n++;
+static float gap_start(void) { return stage->pits ? 110 : 120; }
+
+/* bridges: the first at 120 m, then every bridge_d (2 + sin(n / bridge_k)) m, 13 + 5 sin(2.172 n) m long; pits: the
+ * first at 110 m, then every getDistanceToNextPit(n) = 70 (2 + sin(n / 12.76214)) m (the same on both stages),
+ * 20 + 5 sin(2.172 n) m long. Each takes its length out of the road after it */
+static void gaps_upto(int k) {
+ while (gp_n <= k && gp_n < MAXGAP) {
+ int n = gp_n;
+ float x0 = gap_start(), len;
+ if (stage->pits) {
+ if (n) x0 = gp_x0[n - 1] + (float)(int)(70 * (2 + sinf((float)n / 12.76214f)));
+ len = (float)(int)(20 + 5 * sinf((float)n * 2.172f));
+ } else {
+ if (n) x0 = gp_x0[n - 1] + (float)(int)(stage->bridge_d * (2 + sinf((float)n / stage->bridge_k)));
+ len = (float)(int)(13 + 5 * sinf((float)n * 2.172f));
+ }
+ float shift = n ? gp_shift[n - 1] - gp_len[n - 1] : 0;
+ gp_x0[n] = x0;
+ gp_len[n] = len;
+ gp_shift[n] = shift;
+ gp_y[n] = base_height(x0 + shift);
+ gp_n++;
}
}
-bool stage_bridge_k(int k, float *x0, float *len, float *y) {
- if (!stage->bridges || k < 0 || k >= MAXBRIDGE) return false;
- bridges_upto(k);
- *x0 = br_x0[k], *len = br_len[k], *y = br_y[k];
+static bool gap_k(bool on, int k, float *x0, float *len, float *y) {
+ if (!on || k < 0 || k >= MAXGAP) return false;
+ gaps_upto(k);
+ *x0 = gp_x0[k], *len = gp_len[k], *y = gp_y[k];
return true;
}
+bool stage_bridge_k(int k, float *x0, float *len, float *y) { return gap_k(stage->bridges, k, x0, len, y); }
+bool stage_pit_k(int k, float *x0, float *len, float *y) { return gap_k(stage->pits, k, x0, len, y); }
-/* the last bridge starting before x, or -1 */
-static int bridge_before(float x) {
- if (!stage->bridges || x <= 120) return -1;
+/* the last bridge or pit starting before x, or -1 */
+static int gap_before(float x) {
+ if ((!stage->bridges && !stage->pits) || x <= gap_start()) return -1;
int k = 0;
for (;; k++) {
- bridges_upto(k + 1);
- if (k + 1 >= MAXBRIDGE - 1 || br_x0[k + 1] >= x) break;
+ gaps_upto(k + 1);
+ if (k + 1 >= MAXGAP - 1 || gp_x0[k + 1] >= x) break;
}
return k;
}
-int stage_bridge_first(float x) {
- int k = bridge_before(x);
+static int gap_first(float x) {
+ int k = gap_before(x);
if (k < 0) return 0;
- return br_x0[k] + br_len[k] < x ? k + 1 : k;
+ return gp_x0[k] + gp_len[k] < x ? k + 1 : k;
}
+int stage_bridge_first(float x) { return gap_first(x); }
+int stage_pit_first(float x) { return gap_first(x); }
+
+float stage_pit_depth(void) { return stage->pits == PIT_MUD ? 2.0f : stage->pits == PIT_LAVA ? 1.5f : 1.0f; }
+/* the ground: past a bridge or a pit the road goes on as from its start (blended in over 5 m); under a bridge, a
+ * canyon; in a pit, a dip stage_pit_depth deep */
float stage_floor(float x) {
- int k = bridge_before(x);
+ int k = gap_before(x);
if (k < 0) return base_height(x);
- float x0 = br_x0[k], len = br_len[k];
- /* past a bridge the road goes on as from its start (blended in over 5 m) */
+ float x0 = gp_x0[k], len = gp_len[k];
float b = powf(sinf(clampf((x - x0) / 5, 0, 1) * 3.14159265358979 * 0.5), 1.25f);
- float h = base_height(x + br_shift[k] - len * b);
- if (x < x0 + len) { /* under it, a canyon */
+ float h = base_height(x + gp_shift[k] - len * b);
+ if (x < x0 + len) {
float s = sinf((x - x0) / len * 3.1415f);
- float s1 = powf(s, 1.25f);
- h = br_y[k] - s1 * 8 - powf(s, 0.85f) * 20 * s1;
+ if (stage->pits) {
+ float d = clampf(9 * powf(s, 2.75f), 0, 1);
+ h = gp_y[k] - stage_pit_depth() * powf(s, 1.25f) * d;
+ } else {
+ float s1 = powf(s, 1.25f);
+ h = gp_y[k] - s1 * 8 - powf(s, 0.85f) * 20 * s1;
+ }
}
return h;
}
+/* is x on a bridge's deck or a pit's surface (that of the last one starting before k_x), and its height */
+static bool deck_at(float x, float k_x, float *y) {
+ int k = gap_before(k_x);
+ if (k < 0 || x >= gp_x0[k] + gp_len[k]) return false;
+ *y = gp_y[k];
+ return true;
+}
+
float stage_deck(float x) {
- int k = bridge_before(x);
- if (k >= 0 && x < br_x0[k] + br_len[k]) return br_y[k];
- return stage_floor(x);
+ float y;
+ return deck_at(x, x, &y) ? y : stage_floor(x);
}
/* ------------------------------------------------------------------ the ground as built: 0.5 m apart */
@@ -351,9 +419,9 @@ void stage_tree_fall(int k) {
/* ------------------------------------------------------------------ coins and fuel (GameContentLayer::addCoinChunk) */
/* the ground under a coin: a bridge's deck, or the highest of three points */
static float coin_floor(float x) {
- int k = bridge_before(x + 0.01f);
- if (k >= 0 && x < br_x0[k] + br_len[k]) return br_y[k];
- float h = stage_floor(x), v;
+ float h, v;
+ if (deck_at(x, x + 0.01f, &h)) return h;
+ h = stage_floor(x);
if ((v = stage_floor(x + 0.75f)) > h) h = v;
if ((v = stage_floor(x - 0.75f)) > h) h = v;
return h;
@@ -380,7 +448,7 @@ int stage_coin_group(int k, float *xs, float *ys, int *vals) {
/* chunks between cans (Stage*::getFuelDensity), after n cans */
static int fuel_density(int n) {
switch (stage_id) {
- case ST_ARCTIC: case ST_ARCTIC_CAVE: return n > 19 ? n - 16 : 3;
+ case ST_ARCTIC: case ST_ARCTIC_CAVE: case ST_VOLCANO: return n > 19 ? n - 16 : 3;
case ST_HIGHWAY: return 5 * n / 4 + 5;
case ST_CAVE: return 5 - n % 3;
case ST_MARS: return n / 3 + 5;
@@ -414,7 +482,10 @@ uint32_t stage_level_bonus(int n) { return stage->lvl_mult * stage_level_goal(n)
void stage_set(int s) {
stage = &stages[s], stage_id = s;
- br_n = 0;
+#ifdef HOST
+ if (stage->bridges && stage->pits) abort(); /* (tests: they share their memory) */
+#endif
+ gp_n = 0;
tr_n = 0, tr_count = 0, tr_group = 0, tr_next = 30;
can_n = 0, can_scan = 0, can_count = 0, can_dens = fuel_density(0);
for (int i = 0; i < VCACHE; i++) vkey[i] = rkey[i] = 0x7FFFFFFF;
diff --git a/games/hillclimb/src/stage.h b/games/hillclimb/src/stage.h
index 3d8f9912..f1c0b7ff 100644
--- a/games/hillclimb/src/stage.h
+++ b/games/hillclimb/src/stage.h
@@ -2,7 +2,8 @@
*
* A stage's ground is the game's own formula (its Stage*::getHeightAtX: sums of sines that grow with the distance),
* sampled every 0.5 m like the game's terrain. Rope bridges cross canyons every 70 to 210 m on most stages (the road
- * resumes after one at the height it had before it); caves have a ceiling over the ground; the Forest has pine trees.
+ * resumes after one at the height it had before it); caves have a ceiling over the ground; the Forest has pine trees;
+ * the Mudpool and the Volcano have pits of mud and lava (the road resumes after one as after a bridge).
* Coins come in a chunk every 30 m, worth more the further you go, fuel cans every few chunks, all as the game's
* GameContentLayer places them. Each stage has levels, kept from run to run, each with its bonus. */
#ifndef HC_STAGE_H
@@ -14,8 +15,9 @@ extern "C" {
#endif
enum { ST_COUNTRYSIDE, ST_DESERT, ST_ARCTIC, ST_HIGHWAY, ST_CAVE, ST_MOON, ST_MARS, ST_ALIEN, ST_ARCTIC_CAVE,
- ST_FOREST, NSTAGES };
+ ST_FOREST, ST_MOUNTAIN, ST_MUDPOOL, ST_VOLCANO, NSTAGES };
enum { FEAT_NONE, FEAT_BRIDGES, FEAT_TREES, FEAT_ICICLES };
+enum { PIT_NONE, PIT_MUD, PIT_LAVA };
typedef struct {
const char *name;
@@ -30,6 +32,7 @@ typedef struct {
uint16_t lvl_base, lvl_step; /* the game's levels (StageInfo): level n (from 0) ends at base + step n */
uint16_t lvl_mult; /* and pays mult x that + 2500 */
uint32_t surf_color; /* the surface's colour (particles, the map) */
+ uint8_t pits; /* PIT_*: pits of mud or lava (then no bridges: they share their memory) */
} Stage;
extern const Stage stages[NSTAGES];
@@ -42,7 +45,7 @@ float stage_floor(float x);
/* the ground as it is built: a point every 0.5 m (k: x = -40 + k / 2), lines between them */
float stage_vertex(int k);
float stage_ground(float x);
-/* the ground or a bridge's deck under x (getHeightWithBridgeOrPit) */
+/* the ground, a bridge's deck or a pit's surface under x (getHeightWithBridgeOrPit) */
float stage_deck(float x);
/* a cave's ceiling over x (GameContentLayer::getCeilingHeightAt), and as it is built (points every 0.5 m) */
bool stage_ceiling(float x, float *y);
@@ -53,6 +56,12 @@ bool stage_roof(float x, float *y);
bool stage_bridge_k(int k, float *x0, float *len, float *y);
int stage_bridge_first(float x); /* the first bridge that ends after x */
+/* pits (Mudpool, Volcano): the k-th one (from 0) starts at x0, is len meters long, its surface at y; false if
+ * none. Their depth (Pit::getDepth) */
+bool stage_pit_k(int k, float *x0, float *len, float *y);
+int stage_pit_first(float x); /* the first pit that ends after x */
+float stage_pit_depth(void);
+
/* trees (the Forest): the k-th one's foot; fallen ones are kept in a bit set */
bool stage_tree(int k, float *x, float *y);
int stage_tree_first(float x); /* the first tree at or after x */
diff --git a/games/hillclimb/src/vehicle.c b/games/hillclimb/src/vehicle.c
index 1a7af6b0..4a55ffc5 100644
--- a/games/hillclimb/src/vehicle.c
+++ b/games/hillclimb/src/vehicle.c
@@ -1,13 +1,13 @@
-/* The vehicles (vehicle.h). Their prices, upgrades, the upgrades' last levels and prices are the game's (Hill
- * Climb Racing Wiki); the Quad Bike's fourth upgrade is its 4WD, as the game's own saves name it (quadbike_awd), at
- * the game's price. How they drive is the game's own, in car.cpp. */
+/* The vehicles (vehicle.h). Their prices, upgrades and the upgrades' last levels and prices are the game's own
+ * (PlayerCarManager::initialize in its Android package, the same as the Hill Climb Racing Wiki's tables), and so
+ * are the descriptions. How they drive is the game's own, in car.cpp. */
#include "data.h"
#include "vehicle.h"
const char *const upgrade_names[NUPKINDS] = {"Engine", "Suspension", "Tires", "4WD", "Air Control", "Downforce",
- "Fuel", "Tracks"};
+ "Fuel", "Tracks", "Stability"};
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};
+ IMG_UP_DOWNFORCE, IMG_UP_FUEL, IMG_UP_TIRES, IMG_UP_DOWNFORCE};
const VehDef vehicles[NVEHICLES] = {
{"Hill Climber", "Bill's trusty jeep. Upgrade its 4WD to climb anything.", 0, IMG_ICON_JEEP,
@@ -16,19 +16,37 @@ const VehDef vehicles[NVEHICLES] = {
{UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AIR}, {12, 14, 16, 10}, {1500, 1000, 1000, 3000}},
{"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}},
+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AWD}, {14, 16, 18, 10}, {1000, 1000, 1000, 1000}},
{"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_AWD}, {13, 14, 16, 10}, {1500, 1200, 1200, 1200}},
+ IMG_ICON_QUAD, {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AWD}, {12, 14, 16, 10}, {1500, 1100, 1100, 1200}},
{"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}},
+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_DOWNFORCE}, {12, 14, 16, 10}, {1500, 1000, 1000, 3000}},
{"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}},
- {"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}},
+ 750000, IMG_ICON_RALLY, {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_DOWNFORCE}, {13, 14, 17, 10},
+ {1800, 1250, 1250, 3000}},
+ {"Dune Buggy", "Quick, good traction and a handy hill climbing vehicle!", 800000, IMG_ICON_BUGGY,
+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_FUEL}, {16, 15, 25, 20}, {2000, 1500, 1500, 1200}},
{"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}},
+ {UP_ENGINE, UP_SUSPENSION, UP_TRACKS, UP_FUEL}, {16, 15, 20, 20}, {1250, 1250, 1000, 1000}},
+ {"Tractor", "The tractor is slow and heavy but has great traction and plenty of torque (and a tendency to roll "
+ "over in steep terrain). Not recommended for caves.", 100000, IMG_ICON_TRACTOR,
+ {UP_ENGINE, UP_TIRES, UP_FUEL, UP_STABILITY}, {16, 15, 20, 15}, {1000, 1000, 1000, 1000}},
+ {"Tourist Bus", "Bill decided to take a shower and give people a ride while climbing hills! Not suitable for "
+ "cave levels!", 200000, IMG_ICON_BUS,
+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_FUEL}, {15, 15, 20, 25}, {1400, 1250, 1000, 1000}},
+ {"Super Diesel 4x4", "Ready for the super turbo whistle and black smoke? With powerful engine and large wheelbase "
+ "this really is an unique experience!", 500000, IMG_ICON_DIESEL,
+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_FUEL}, {15, 15, 20, 20}, {1400, 1250, 1000, 1000}},
+ {"Snow Mobile", "Great traction in the ice and snow. Fully upgraded it becomes a fun vehicle for other levels "
+ "too!", 1000000, IMG_ICON_SNOWMOBILE,
+ {UP_ENGINE, UP_SUSPENSION, UP_TRACKS, UP_FUEL}, {17, 15, 20, 20}, {1250, 1250, 1000, 1000}},
+ {"Truck", "Weight, power, turbo whistle and attitude! And upgradeable very large fuel tank!", 1000000,
+ IMG_ICON_TRUCK, {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_FUEL}, {15, 15, 20, 25}, {1400, 1250, 1000, 1000}},
};
+/* PlayerCarManager::initialize's order */
+const uint8_t vehicle_order[NVEHICLES] = {V_JEEP, V_BIKE, V_MONSTER, V_TRACTOR, V_QUAD, V_BUS, V_RACE,
+ V_DIESEL, V_RALLY, V_TANK, V_SNOWMOBILE, V_TRUCK, V_BUGGY};
+
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.h
index 13bb2d26..ac2cb4c6 100644
--- a/games/hillclimb/src/vehicle.h
+++ b/games/hillclimb/src/vehicle.h
@@ -7,8 +7,10 @@
extern "C" {
#endif
-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 };
+/* (the ids are the save's: new vehicles go at the end; the garage shows them in the game's order) */
+enum { V_JEEP, V_BIKE, V_MONSTER, V_QUAD, V_RACE, V_RALLY, V_BUGGY, V_TANK, V_TRACTOR, V_BUS, V_DIESEL, V_SNOWMOBILE,
+ V_TRUCK, NVEHICLES };
+enum { UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AWD, UP_AIR, UP_DOWNFORCE, UP_FUEL, UP_TRACKS, UP_STABILITY, NUPKINDS };
typedef struct {
const char *name, *about;
@@ -19,6 +21,7 @@ typedef struct {
} VehDef;
extern const VehDef vehicles[NVEHICLES];
+extern const uint8_t vehicle_order[NVEHICLES]; /* the garage's order, the game's */
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) */
diff --git a/games/hillclimb/tests/check.py b/games/hillclimb/tests/check.py
index 2efcea88..0fb9952d 100644
--- a/games/hillclimb/tests/check.py
+++ b/games/hillclimb/tests/check.py
@@ -1,26 +1,37 @@
#!/usr/bin/env python3
"""Checks of Hill Climb Racing on a computer (make test): the host build, with AddressSanitizer and UBSan, through
-the menus, buying, every stage with every vehicle, the ends of a run and the saves.
+the menus, buying, every stage's ground, every stage with every vehicle, each vehicle's numbers, the ends of a run,
+the saves (and the old versions' carried over) and random keys.
- python3 tests/check.py build/play"""
+ python3 tests/check.py build/play [--quick]"""
import os
import re
import shutil
+import struct
import subprocess
import sys
import tempfile
+from concurrent.futures import ThreadPoolExecutor
PLAY = sys.argv[1] if len(sys.argv) > 1 else "build/play"
+QUICK = "--quick" in sys.argv
ENV = dict(os.environ, ASAN_OPTIONS="detect_leaks=0", UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1")
failures = []
-STAGES = ["Countryside", "Desert", "Arctic", "Highway", "Cave", "Moon", "Mars", "Alien Planet", "Arctic Cave", "Forest"]
-VEHICLES = ["Hill Climber", "Motocross Bike", "Monster Truck", "Quad Bike", "Race Car", "Rally Car", "Dune Buggy", "Tank"]
+STAGES = ["Countryside", "Desert", "Arctic", "Highway", "Cave", "Moon", "Mars", "Alien Planet", "Arctic Cave", "Forest",
+ "Mountain", "Mudpool", "Volcano"]
+VEHICLES = ["Hill Climber", "Motocross Bike", "Monster Truck", "Quad Bike", "Race Car", "Rally Car", "Dune Buggy", "Tank",
+ "Tractor", "Tourist Bus", "Super Diesel 4x4", "Snow Mobile", "Truck"]
+NEW_STAGES, NEW_VEHICLES = range(10, 13), range(8, 13)
MODE_RUN, MODE_END = 4, 6
+def play(args, saves):
+ return subprocess.run([PLAY, "--saves", saves, "--out", os.path.join(saves, "shots")] + args, capture_output=True,
+ text=True, env=ENV, timeout=900)
+
+
def run(args, saves, what):
- p = subprocess.run([PLAY, "--saves", saves, "--out", os.path.join(saves, "shots")] + args, capture_output=True,
- text=True, env=ENV, timeout=900)
+ p = play(args, saves)
if p.returncode or "runtime error" in p.stderr or "AddressSanitizer" in p.stderr:
failures.append(f"{what}: crashed or a sanitizer error\n{p.stderr[-2000:]}")
return None
@@ -43,14 +54,94 @@ def fresh():
return tempfile.mkdtemp(prefix="hillclimb_check_")
+def drive(st, v, frames=2400, levels="6,6,6,6"):
+ """A player driving the stage with the vehicle: no crash, and it gets somewhere."""
+ d = fresh()
+ s = run(["--run", f"{st},{v}", "--levels", levels, "--auto", "--frames", str(frames)], d,
+ f"{STAGES[st]} with the {VEHICLES[v]}")
+ shutil.rmtree(d, ignore_errors=True)
+ return st, v, s
+
+
+# the version 3 save (src/game.h): offsets in hillclimb.sav, after its 8-byte header
+SAVE3 = 8 + 444
+OFF3 = dict(version=8, coins=12, vehicles=16, stages=18, level=20, best=72, vehicle=410, stage=411, seen_help=412,
+ runs=416, meters=420, flips=424, best_air=428, earned=432, stage_level=436)
+
+
+def old_save(version, coins, levels, best00, stage_level0):
+ """A save as versions 1 and 2 wrote it: 8 vehicles, 10 stages."""
+ body = struct.pack("<IHH", coins, 0xFF, 0x3FF)
+ lv = bytearray(32)
+ for v in range(8):
+ for u in range(4):
+ lv[v * 4 + u] = levels.get((v, u), 1)
+ body += bytes(lv)
+ best = [0] * 80
+ best[0] = best00
+ best[9 * 8 + 7] = 4321 # the Forest with the Tank
+ body += struct.pack("<80H", *best)
+ body += bytes([7, 9, 1, 0]) + struct.pack("<5I", 12, 3456, 7, 1500, 99999)
+ if version == 2:
+ sl = bytearray(10)
+ sl[0], sl[9] = stage_level0, 5
+ body += bytes(sl) + b"\0\0"
+ return b"HCR1" + struct.pack("<I", len(body)) + body
+
+
def main():
+ # every stage's ground: finite, bridges and pits apart, coins and fuel cans over the ground
+ for st in range(len(STAGES)):
+ p = subprocess.run([PLAY, "--ground", str(st)], capture_output=True, text=True, env=ENV, timeout=300)
+ check(p.returncode == 0 and "GROUND ok" in p.stdout, f"{STAGES[st]}'s ground: {p.stdout.strip()} {p.stderr[-500:]}")
+ if st == 11 or st == 12:
+ check(" pits 0 " not in p.stdout, f"{STAGES[st]} has no pits")
+
+ # each vehicle's numbers at level 1 and at its last levels: the game's (PlayerCar*'s constructors)
+ # speed, torque, tires, hz, damping, turbo cap, rate, 4WD, air, mass, wheels, soft tire balls; fuel
+ expect = {
+ 8: ([15 * 1.05, 20, 0.8 * 1.15, 5, 1.35, 0.5 * 1.15, 0.3 * 1.1, 0.5, 30, None, 2, 16], 1.2),
+ 9: ([15 * 1.05, 10, 0.75 * 1.115, 5, 0.2 * 1.11, 0.5 * 1.15, 0.3, 0.5, 90, None, 2, 0], 1.5 - 1.1 / 26),
+ 10: ([17 * 1.05, 20, 0.95 * 1.115, 3, 0.2 * 1.11, 0.5 * 1.15, 0.5, 0.5, 45, None, 2, 0], 1.5 - 0.9 / 21),
+ 11: ([45.9 * 1.048 * 0.55, 6, 0.5 * 1.1612, 3, 1 - 0.9, 0.87 * 1.14, 3.33, 0.5, 3.5, None, 7, 0], 1.5 - 0.9 / 21),
+ 12: ([15 * 1.05, 10, 0.75 * 1.115, 4, 0.2 * 1.11, 0.5 * 1.15, 0.3, 0.5, 90, None, 3, 0], 1.5 - 1.1 / 26),
+ }
+ for v, (want, fuel) in expect.items():
+ p = subprocess.run([PLAY, "--numbers", str(v), "--levels", "1,1,1,1"], capture_output=True, text=True, env=ENV)
+ got = [float(x) for x in p.stdout.split()[1:13]] if p.stdout.startswith("NUMBERS") else []
+ ok = len(got) == 12 and all(w is None or abs(g - w) <= 1e-4 * max(1, abs(w)) for g, w in zip(got, want))
+ ok = ok and abs(float(p.stdout.split()[-1]) - fuel) < 1e-4
+ check(ok, f"the {VEHICLES[v]}'s numbers: {p.stdout.strip()} (want {want}, fuel {fuel})")
+ check(len(got) == 12 and 0.5 < got[9] < 20, f"the {VEHICLES[v]}'s chassis weighs {got[9] if got else '?'}")
+ # at the last levels: the engine's, suspension's and tires' growth
+ last = {8: "16,15,20,15", 9: "15,15,20,25", 10: "15,15,20,20", 11: "17,15,20,20", 12: "15,15,20,25"}
+ tops = {8: (15 * 1.05 ** 16, 0.8 * 1.15 ** 15), 9: (15 * 1.05 ** 15, 0.75 * 1.115 ** 20),
+ 10: (17 * 1.05 ** 15, 0.95 * 1.115 ** 20), 11: (45.9 * 1.048 ** 17 * 0.55, 0.5 * 1.1612 ** 20),
+ 12: (15 * 1.05 ** 15, 0.75 * 1.115 ** 20)}
+ for v, lv in last.items():
+ p = subprocess.run([PLAY, "--numbers", str(v), "--levels", lv], capture_output=True, text=True, env=ENV)
+ got = [float(x) for x in p.stdout.split()[1:13]] if p.stdout.startswith("NUMBERS") else []
+ check(len(got) == 12 and abs(got[0] - tops[v][0]) < 1e-3 * tops[v][0] and abs(got[2] - tops[v][1]) < 1e-3 * tops[v][1],
+ f"the {VEHICLES[v]} at its last levels: {p.stdout.strip()}")
+ # the Snow Mobile's tracks grip three times on snow, 1.6 times on the Alien Planet
+ for st, k in ((2, 3), (8, 3), (7, 1.6)):
+ p = subprocess.run([PLAY, "--numbers", "11", "--levels", "1,1,1,1", "--run", f"{st},11"], capture_output=True,
+ text=True, env=ENV)
+ got = float(p.stdout.split()[3]) if p.stdout.startswith("NUMBERS") else 0
+ check(abs(got - 0.5 * 1.1612 * k) < 1e-4, f"the Snow Mobile's tracks on {STAGES[st]}: {got}")
+
# the menus: title, garage, stage, how to drive, then the run; Home there keeps the run's coins and quits
d = fresh()
keys = "30:ok,70:ok,110:ok,150:ok,170-900:right,950:home"
s = run(["--frames", "1000", "--keys", keys], d, "menus")
if s and check(s["running"] == 0, "Home did not quit"):
check(s["saved"] > 0 and s["saved"] == s["total"], f"the run's coins were not kept on Home: {s}")
- check(os.path.exists(os.path.join(d, "hillclimb.sav")), "no hillclimb.sav")
+ sav = os.path.join(d, "hillclimb.sav")
+ check(os.path.exists(sav), "no hillclimb.sav")
+ if os.path.exists(sav):
+ b = open(sav, "rb").read()
+ check(len(b) == SAVE3 and b[:4] == b"HCR1" and struct.unpack_from("<H", b, OFF3["version"])[0] == 3,
+ f"hillclimb.sav is not version 3 ({len(b)} bytes)")
copy = open(os.path.join(d, "hillclimb_saves.py"), "rb").read() if os.path.exists(
os.path.join(d, "hillclimb_saves.py")) else b""
check(b"#>hillclimb.sav:" in copy, "hillclimb_saves.py does not hold the save")
@@ -68,16 +159,58 @@ def main():
if s:
check(s["saved"] == 2000, f"two upgrades of 4,000 should leave 2,000 coins, not {s['saved']}")
shutil.rmtree(d, ignore_errors=True)
+ # the garage goes in the game's order: right from the Monster Truck is the Tractor (100,000), bought with OK, OK
+ d = fresh()
+ keys = "30:ok,60:right,80:right,100:right,130:ok,160:ok,200:home"
+ s = run(["--frames", "260", "--coins", "150000", "--keys", keys], d, "buying the Tractor")
+ if s:
+ check(s["saved"] == 50000, f"the Tractor should cost 100,000 of 150,000: {s['saved']} left")
+ b = open(os.path.join(d, "hillclimb.sav"), "rb").read()
+ check(struct.unpack_from("<H", b, OFF3["vehicles"])[0] == 1 | 1 << 8, "the Tractor is not owned")
+ shutil.rmtree(d, ignore_errors=True)
- # every stage with every vehicle, a player driving: no crash, and it gets somewhere
- for st in range(len(STAGES)):
- for v in range(len(VEHICLES)):
- d = fresh()
- s = run(["--run", f"{st},{v}", "--levels", "6,6,6,6", "--auto", "--frames", "2400"], d,
- f"{STAGES[st]} with the {VEHICLES[v]}")
+ # old saves (versions 1 and 2) carried over: coins, owned things, upgrades, bests, stats, levels kept; an upgrade
+ # over its game's last level (the Rally Car's engine 14 of 13) brought down and paid back (2,000 x 14 x 14)
+ for version in (1, 2):
+ d = fresh()
+ levels = {(5, 0): 14, (2, 2): 15, (0, 3): 10}
+ open(os.path.join(d, "hillclimb.sav"), "wb").write(old_save(version, 123456, levels, 777, 3))
+ s = run(["--frames", "40", "--keys", "30:home"], d, f"a version {version} save")
+ if s:
+ b = open(os.path.join(d, "hillclimb.sav"), "rb").read()
+ u16 = lambda o: struct.unpack_from("<H", b, o)[0]
+ u32 = lambda o: struct.unpack_from("<I", b, o)[0]
+ lv = lambda v, u: b[OFF3["level"] + v * 4 + u]
+ check(len(b) == SAVE3 and u16(OFF3["version"]) == 3, f"version {version} not saved again as 3")
+ check(u32(OFF3["coins"]) == 123456 + 2000 * 14 * 14, f"version {version}: coins {u32(OFF3['coins'])}")
+ check(u16(OFF3["vehicles"]) == 0xFF and u16(OFF3["stages"]) == 0x3FF, f"version {version}: owned things")
+ check(lv(5, 0) == 13 and lv(2, 2) == 15 and lv(0, 3) == 10, f"version {version}: upgrades")
+ check(u16(OFF3["best"]) == 777 and u16(OFF3["best"] + 2 * (9 * 13 + 7)) == 4321, f"version {version}: bests")
+ check(b[OFF3["vehicle"]] == 7 and b[OFF3["stage"]] == 9 and u32(OFF3["runs"]) == 12
+ and u32(OFF3["meters"]) == 3456 and u32(OFF3["earned"]) == 99999, f"version {version}: the rest")
+ if version == 2:
+ check(b[OFF3["stage_level"]] == 3 and b[OFF3["stage_level"] + 9] == 5, "version 2: stage levels")
+ shutil.rmtree(d, ignore_errors=True)
+ # a broken save: a fresh start, no crash
+ d = fresh()
+ open(os.path.join(d, "hillclimb.sav"), "wb").write(b"HCR1" + struct.pack("<I", 444) + bytes(range(256)) * 2)
+ s = run(["--frames", "40", "--keys", "30:home"], d, "a broken save")
+ shutil.rmtree(d, ignore_errors=True)
+
+ # every stage with every vehicle, a player driving: no crash, and it gets somewhere (the new ones on every stage
+ # and every vehicle on the new stages always; the rest unless --quick)
+ pairs = [(st, v) for st in range(len(STAGES)) for v in range(len(VEHICLES))
+ if not QUICK or st in NEW_STAGES or v in NEW_VEHICLES]
+ with ThreadPoolExecutor(max_workers=os.cpu_count() or 4) as pool:
+ for st, v, s in pool.map(lambda p: drive(*p), pairs):
if s:
check(s["dist"] > 60, f"{STAGES[st]} with the {VEHICLES[v]}: only {s['dist']} m")
- shutil.rmtree(d, ignore_errors=True)
+ # the new ones go on, well upgraded: 90 s on the new stages, and the new vehicles on stages they suit
+ long = [(10, 2), (10, 10), (11, 8), (11, 9), (12, 10), (12, 0), (2, 11), (0, 12), (0, 9)]
+ with ThreadPoolExecutor(max_workers=os.cpu_count() or 4) as pool:
+ for st, v, s in pool.map(lambda p: drive(*p, frames=5400, levels="12,12,12,10"), long):
+ if s:
+ check(s["dist"] > 400, f"90 s on {STAGES[st]} with the {VEHICLES[v]}: only {s['dist']} m")
# the ends of a run: Bill's neck (the bike flipped on the Moon, gas held) and an empty tank (reversing)
d = fresh()
@@ -98,6 +231,31 @@ def main():
check(s["level"] >= 2 and s["coins"] > 1000, f"a long run on the Countryside: {s}")
shutil.rmtree(d, ignore_errors=True)
+ # random keys through the menus and runs (with coins, so buying happens too): no crash, no sanitizer error
+ sessions = 60 if QUICK else 300
+
+ def fuzz(seed):
+ d = fresh()
+ p = play(["--fuzz", str(seed), "--coins", str(seed * 99991 % 6000000), "--frames", "4000"], d)
+ shutil.rmtree(d, ignore_errors=True)
+ bad = p.returncode or "runtime error" in p.stderr or "AddressSanitizer" in p.stderr
+ return seed, (p.stderr[-1500:] if bad else None)
+
+ def fuzz_run(seed): # straight into a run, on every stage with every vehicle in turn
+ d = fresh()
+ st, v = seed % len(STAGES), seed // len(STAGES) % len(VEHICLES)
+ lv = ",".join(str(1 + (seed * k) % 9) for k in (3, 5, 7, 2))
+ p = play(["--fuzz", str(seed), "--run", f"{st},{v}", "--levels", lv, "--frames", "3000"], d)
+ shutil.rmtree(d, ignore_errors=True)
+ bad = p.returncode or "runtime error" in p.stderr or "AddressSanitizer" in p.stderr
+ return seed, (p.stderr[-1500:] if bad else None)
+
+ with ThreadPoolExecutor(max_workers=os.cpu_count() or 4) as pool:
+ for seed, err in pool.map(fuzz, range(1, sessions + 1)):
+ check(err is None, f"random keys {seed}: {err}")
+ for seed, err in pool.map(fuzz_run, range(1, len(STAGES) * len(VEHICLES) + 1)):
+ check(err is None, f"random keys in a run {seed}: {err}")
+
for f in failures:
print("FAIL", f)
print("ok" if not failures else f"{len(failures)} failures")
diff --git a/games/hillclimb/tests/play.c b/games/hillclimb/tests/play.c
index ae38f9fb..8704dc4e 100644
--- a/games/hillclimb/tests/play.c
+++ b/games/hillclimb/tests/play.c
@@ -1,11 +1,15 @@
/* 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]
+ * [--run STAGE,VEHICLE] [--levels E,S,T,A] [--coins N] [--auto] [--trace N] [--fuzz SEED]
+ * [--numbers VEHICLE] [--ground STAGE]
*
* 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.
+ * --fuzz presses random keys (its own generator, the same on every computer) through menus and runs; --numbers
+ * prints the numbers a vehicle is built with (at --levels); --ground checks a stage's ground, bridges, pits and
+ * coins over 6 km.
* 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>
@@ -82,8 +86,75 @@ static uint32_t autopilot(void) {
return K_RIGHT;
}
+/* --fuzz: a key or two at random, changing every few frames (an LCG, not libc's rand: the same everywhere) */
+static uint32_t fuzz_state;
+static uint32_t fuzz_next(void) {
+ fuzz_state = fuzz_state * 1103515245u + 12345u;
+ return fuzz_state >> 8;
+}
+static uint32_t fuzz_keys(int f) {
+ static uint32_t k;
+ if (f % 6 == 0) {
+ static const uint32_t pool[] = {K_RIGHT, K_RIGHT, K_RIGHT, K_OK, K_OK, K_LEFT, K_LEFT, K_UP, K_DOWN, K_BACK, 0, 0};
+ uint32_t r = fuzz_next();
+ k = pool[r % 12];
+ if (r >> 12 & 1) k |= pool[(r >> 4) % 12];
+ if ((r >> 16) % 500 == 0) k = K_HOME; /* (now and then Home: the game saves and quits, and starts again) */
+ }
+ return k;
+}
+
+/* --ground: the stage's ground over 6 km: finite, its bridges and pits in order and apart, its coins and fuel cans
+ * over the ground; prints a line OK or what is wrong */
+static int ground_check(int s) {
+ stage_set(s);
+ float last = stage_floor(0);
+ for (float x = -40; x < 6000; x += 0.5f) {
+ float h = stage_floor(x);
+ if (!(h == h) || h > 1e6f || h < -1e6f) return printf("GROUND bad height %f at %f\n", h, x), 1;
+ float roof;
+ if (stage_ceiling(x, &roof) && roof <= stage_deck(x)) return printf("GROUND ceiling under the ground at %f\n", x), 1;
+ last = h;
+ }
+ (void)last;
+ float prev = -1e9f;
+ int nb = 0, np = 0;
+ for (int k = 0;; k++) {
+ float x0, len, y;
+ if (!stage_bridge_k(k, &x0, &len, &y) || x0 > 6000) break;
+ if (x0 < prev + 10 || len < 8 || len > 18) return printf("GROUND bridge %d at %f len %f\n", k, x0, len), 1;
+ prev = x0 + len, nb++;
+ }
+ prev = -1e9f;
+ for (int k = 0;; k++) {
+ float x0, len, y;
+ if (!stage_pit_k(k, &x0, &len, &y) || x0 > 6000) break;
+ if (x0 < prev + 10 || len < 15 || len > 25) return printf("GROUND pit %d at %f len %f\n", k, x0, len), 1;
+ if (stage_deck(x0 + len * 0.5f) != y || stage_floor(x0 + len * 0.5f) > y - 0.5f)
+ return printf("GROUND pit %d has no dip\n", k), 1;
+ prev = x0 + len, np++;
+ }
+ int coins = 0;
+ for (int k = 1; k < 200; 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++, coins++)
+ if (cy[i] < stage_floor(cx[i]) + 0.5f) return printf("GROUND coin under the ground at %f\n", cx[i]), 1;
+ }
+ int cans = 0;
+ float fx, fy;
+ while (stage_fuel(cans, &fx, &fy) && fx < 6000) {
+ if (fy < stage_floor(fx) + 0.5f) return printf("GROUND fuel can under the ground at %f\n", fx), 1;
+ cans++;
+ }
+ printf("GROUND ok bridges %d pits %d coins %d cans %d\n", nb, np, coins, cans);
+ return 0;
+}
+
int main(int argc, char **argv) {
- int frames = 600, run_stage = -1, run_vehicle = 0, trace = 0;
+ int frames = 600, run_stage = -1, run_vehicle = 0, trace = 0, numbers = -1;
+ bool fuzz = false;
bool autop = false;
const char *out = "build/shots";
int levels[4] = {1, 1, 1, 1};
@@ -110,6 +181,9 @@ int main(int argc, char **argv) {
else if (!strcmp(argv[i], "--nohud")) g_nohud = true;
else if (!strcmp(argv[i], "--flips")) autop = flipper = true;
else if (!strcmp(argv[i], "--trace")) trace = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--fuzz")) fuzz = true, fuzz_state = (uint32_t)atol(argv[++i]);
+ else if (!strcmp(argv[i], "--numbers")) numbers = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--ground")) return ground_check(atoi(argv[++i]));
else if (!strcmp(argv[i], "--things")) { /* where the first bridges, tunnels and fuel cans of a stage are */
stage_set(atoi(argv[++i]));
float b0, len, by, f, fy;
@@ -138,6 +212,20 @@ int main(int argc, char **argv) {
gfx_init(band);
game_init();
if (coins >= 0) sv.coins = (uint32_t)coins;
+ if (numbers >= 0) { /* the vehicle on the Countryside at those levels */
+ uint8_t lv[4];
+ for (int u = 0; u < 4; u++) lv[u] = (uint8_t)levels[u];
+ stage_set(run_stage >= 0 ? run_stage : 0);
+ Car car;
+ car_init(&car, numbers, lv);
+ float n[12];
+ car_numbers(n);
+ printf("NUMBERS");
+ for (int k = 0; k < 12; k++) printf(" %.6g", n[k]);
+ printf(" fuel %.6g\n", car_fuel_rate(numbers, lv));
+ car_free();
+ return 0;
+ }
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];
@@ -145,11 +233,16 @@ int main(int argc, char **argv) {
run_start(run_vehicle, run_stage);
g_mode = MODE_RUN;
}
- for (int f = 0; f < frames && g_running; f++) {
+ for (int f = 0; f < frames && (g_running || fuzz); f++) {
+ if (!g_running) { /* (--fuzz: the game quit; started again, from its save) */
+ g_running = true;
+ game_init();
+ }
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) k = autopilot(); /* (--keys take over while they are held) */
+ if (fuzz && !k) k = fuzz_keys(f);
host_keys = k;
game_frame(k);
host_time += 17;
@@ -166,6 +259,8 @@ int main(int argc, char **argv) {
run.car.ch.y, run.car.ch.a, car_speed(&run.car), run.fuel, run.car.air, run.car.dead,
run.dist, (unsigned)run_total());
}
+ extern long b2_heap_peak;
+ fprintf(stderr, "heap peak %ld\n", b2_heap_peak);
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);
diff --git a/games/hillclimb/tools/art.py b/games/hillclimb/tools/art.py
index 68c0c538..e6da1ee5 100644
--- a/games/hillclimb/tools/art.py
+++ b/games/hillclimb/tools/art.py
@@ -7,9 +7,12 @@ The wiki keeps the same pictures (the same 256 x 128 chassis canvases). tools/pa
(pictures at VPPM pixels a meter, pivots at their centres) and tools/preview.py draws each vehicle put together."""
# Each vehicle: its chassis picture and the size the game draws it (meters, centred on the chassis body); the
-# wheel's picture and the radius its 2.15 r square is drawn for (or for a cropped tyre: its radius in pixels);
-# Bill's legs on the bikes; tubes from chassis points (meters) to an axle (fork, swingarm): colour, radius;
-# extra pictures on the chassis: (picture, size, centre (meters), in front)
+# wheel's picture and the radius its 2.15 r square is drawn for (or for a cropped tyre: its radius in pixels; or
+# wheel_side x r; or wheel_reuse: another vehicle's tyre picture, drawn for wheel_r); Bill's legs on the bikes;
+# tubes from chassis points (meters) to an axle (fork, swingarm): colour, radius; extra pictures on the chassis:
+# (picture, size, centre (meters), in front); pictures the game puts behind the chassis' (under: picture, its centre
+# in the chassis picture's pixels); trim: their clear margins cut (the pivot kept). "game/" pictures are the game's
+# own files (tools/fetch.py).
VEHICLES = [
dict(id="jeep", name="Hill Climber", chassis="Chassis-hillclimber-red.png", size=(3.657, 1.829),
wheel="Common_Wheel_-_Type_1.png", wheel_r=0.4),
@@ -29,6 +32,21 @@ VEHICLES = [
dict(id="tank", name="Tank", chassis="Car-tank-fg.png", size=(5.689, 2.56),
wheel="Car-tank-tire.png", wheel_r=0.35,
layers=[("Car-tank-bg.png", (5.689, 2.56), (0, 0), False), ("Car-tank-cannon.png", (2.327, 1.164), (1.6, 0.8), True)]),
+ # 1.10.2's other five (PlayerCarTractor, PlayerCarTouristbus, PlayerCarDieselTruck, PlayerCarSnowMobile,
+ # PlayerCarTruck::create). The tractor's tyre is drawn 2 r square, the soft back one and the small front one
+ # alike; its steering wheel is a child of the chassis' picture at (260, 210) from its bottom left, behind it
+ dict(id="tractor", name="Tractor", chassis="game/car-tractor.png", size=(6.69257, 3.34629),
+ wheel="game/car-tractor-tire.png", wheel_r=1.09, wheel_side=2.0, trim=True,
+ under=[("game/car-tractor-steering-wheel.png", (260, 256 - 210))]),
+ dict(id="bus", name="Tourist Bus", chassis="game/car-touristbus.png", size=(8.46281, 4.2314),
+ wheel_reuse="monster", wheel_r=0.7, trim=True),
+ dict(id="diesel", name="Super Diesel 4x4", chassis="game/car-pickup.png", size=(5.50538, 2.75269),
+ wheel_reuse="monster", wheel_r=0.7, trim=True),
+ # (the snow mobile's track wheels: the tank's tyre 0.5474 m across for r 0.336)
+ dict(id="snowmobile", name="Snow Mobile", chassis="Car-snowmobile-body.png", size=(5.68889, 2.56),
+ wheel_reuse="tank", wheel_r=0.35 * 0.336 / (0.5474 / 2.15), legs=True, trim=True),
+ dict(id="truck", name="Truck", chassis="game/car-truck.png", size=(7.0137, 7.0137),
+ wheel_reuse="monster", wheel_r=0.7, trim=True),
]
# Bill: his head is drawn on his head (a circle of 0.33 m) as wide as the game draws it (0.855 m: 57 pixels of its
diff --git a/games/hillclimb/tools/fetch.py b/games/hillclimb/tools/fetch.py
index cf625b15..61fad06f 100644
--- a/games/hillclimb/tools/fetch.py
+++ b/games/hillclimb/tools/fetch.py
@@ -6,6 +6,9 @@
- 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/game/*.png: the pictures the wiki doesn't keep (the Tractor, Tourist Bus, Super Diesel 4x4 and Truck, the
+ bus' passengers, the Mountain's, Mudpool's and Volcano's sky, ground and icon, mud, lava and fire), from the game's
+ own files: the assets of its Android package 1.10.2, as archive.org keeps it (REF/game/hcr-1.10.2.apk, only read)
- 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."""
@@ -16,10 +19,21 @@ import sys
import time
import urllib.parse
import urllib.request
+import zipfile
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")
+GAME_APK = ("hcr-1.10.2.apk", "https://archive.org/download/hill-climb-racing-v.-1.10.2/Hill%20Climb%20Racing%20v.1.10.2%20MOD.apk",
+ "3f109505b18b4c707b9fd6570b2eeebb")
+GAME_FILES = [
+ "car-tractor.png", "car-tractor-tire.png", "car-tractor-exhaust.png", "car-tractor-steering-wheel.png",
+ "car-touristbus.png", "passanger1-head.png", "passanger2-head.png", "passanger3-head.png", "car-pickup.png",
+ "car-truck.png", "sky-bg-cliffs.png", "sky-bg-mud.png", "sky-bg-volcano.png", "lowres-terrain-cliffs-ground.png",
+ "lowres-terrain-mud.png", "lowres-terrain-mud-surface.png", "lowres-terrain-volcano.png",
+ "lowres-terrain-volcano-surface.png", "stage-icon-cliffs.png", "stage-icon-mud.png", "stage-icon-volcano.png",
+ "mud.png", "lava.png", "fire.png", "dirt-mud.png",
+]
FILES = [
# the vehicles: chassis, wheels, parts
@@ -52,7 +66,9 @@ FILES = [
# 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",
+ "Mission-vehicle-dunebuggy.png", "Mission-vehicle-tank.png", "Mission-vehicle-tractor.png",
+ "Mission-vehicle-touristbus.png", "Mission-vehicle-dieseltruck.png", "Mission-vehicle-snowmobile.png",
+ "Mission-vehicle-truck.png", "Car-snowmobile-body.png", "Car-snowmobile-ski.png",
"MainMenuUpgradeEngine.png", "MainMenuUpgradeSuspension.png", "MainMenuUpgradeTires.png",
"MainMenuUpgradeAWD.png", "MainMenuUpgradeBikeRotation.png", "MainMenuUpgradeDownforce.png",
"MainMenuUpgradeFuel.png",
@@ -94,6 +110,22 @@ def main():
with open(os.path.join(wiki, name), "wb") as f:
f.write(data)
print("wiki", name)
+ game = os.path.join(ref, "game")
+ os.makedirs(game, exist_ok=True)
+ if any(not os.path.exists(os.path.join(game, n)) for n in GAME_FILES):
+ apk = os.path.join(game, GAME_APK[0])
+ if not os.path.exists(apk):
+ data = get(GAME_APK[1])
+ if hashlib.md5(data).hexdigest() != GAME_APK[2]:
+ raise SystemExit("fetch: the game's package differs from the one the port was made from")
+ with open(apk, "wb") as f:
+ f.write(data)
+ print("game", GAME_APK[0])
+ with zipfile.ZipFile(apk) as z: # (only its pictures are read)
+ for n in GAME_FILES:
+ with open(os.path.join(game, n), "wb") as f:
+ f.write(z.read("assets/" + n))
+ print("game", n)
fonts = os.path.join(ref, "fonts")
os.makedirs(fonts, exist_ok=True)
if not os.path.exists(os.path.join(fonts, FONT[0])):
diff --git a/games/hillclimb/tools/pack.py b/games/hillclimb/tools/pack.py
index bf9094ee..9978faee 100644
--- a/games/hillclimb/tools/pack.py
+++ b/games/hillclimb/tools/pack.py
@@ -52,6 +52,15 @@ PICTURES = [
("SNOW", "Snow.png", None, ("w", 20), "c"),
("GRASS", "Countryside_Particle.png", None, ("w", 20), "c"),
("SLIME", "Alien-slime.png", None, ("w", 20), "c"),
+ ("DIRT_MUD", "game/dirt-mud.png", None, ("w", 20), "c"),
+ ("FIRE", "game/fire.png", None, ("w", 20), "c"),
+ # the new vehicles' parts on bodies of their own: the tractor's exhaust pipe (0.836571 x 1.67314 m), the snow
+ # mobile's ski (1.861818 x 0.930909 m across its two ski wheels), the bus' passengers' heads (0.96 m squares)
+ ("EXHAUST", "game/car-tractor-exhaust.png", None, ("ppm", 64 / 0.836571), "c"),
+ ("SKI", "Car-snowmobile-ski.png", None, ("ppm", 256 / 1.861818), "c"),
+ ("PASS1", "game/passanger1-head.png", None, ("ppm", 256 / 0.96), "c"),
+ ("PASS2", "game/passanger2-head.png", None, ("ppm", 256 / 0.96), "c"),
+ ("PASS3", "game/passanger3-head.png", None, ("ppm", 256 / 0.96), "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"),
@@ -60,6 +69,9 @@ PICTURES = [
("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"),
+ ("SKY_CLIFFS", "game/sky-bg-cliffs.png", None, ("size", 1, 32), "c"),
+ ("SKY_MUD", "game/sky-bg-mud.png", None, ("size", 1, 32), "c"),
+ ("SKY_VOLCANO", "game/sky-bg-volcano.png", None, ("size", 1, 32), "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"),
@@ -77,6 +89,14 @@ PICTURES = [
("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"),
+ ("GROUND_CLIFFS", "game/lowres-terrain-cliffs-ground.png", None, ("size", 128, 128), "c"),
+ ("SURF_MUD", "game/lowres-terrain-mud-surface.png", None, ("size", 256, 16), "c"),
+ ("GROUND_MUD", "game/lowres-terrain-mud.png", None, ("size", 128, 128), "c"),
+ ("SURF_VOLCANO", "game/lowres-terrain-volcano-surface.png", None, ("size", 256, 16), "c"),
+ ("GROUND_VOLCANO", "game/lowres-terrain-volcano.png", None, ("size", 128, 128), "c"),
+ # the pits' surfaces (Pit::draw: mud.png, lava.png)
+ ("PIT_MUD", "game/mud.png", None, ("size", 128, 32), "c"),
+ ("PIT_LAVA", "game/lava.png", None, ("size", 128, 16), "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"),
@@ -88,6 +108,9 @@ PICTURES = [
("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_MOUNTAIN", "game/stage-icon-cliffs.png", None, ("size", 144, 72), "c"),
+ ("STAGE_MUDPOOL", "game/stage-icon-mud.png", None, ("size", 144, 72), "c"),
+ ("STAGE_VOLCANO", "game/stage-icon-volcano.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"),
@@ -97,6 +120,11 @@ PICTURES = [
("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"),
+ ("ICON_TRACTOR", "Mission-vehicle-tractor.png", None, ("w", 112), "c"),
+ ("ICON_BUS", "Mission-vehicle-touristbus.png", None, ("w", 112), "c"),
+ ("ICON_DIESEL", "Mission-vehicle-dieseltruck.png", None, ("w", 112), "c"),
+ ("ICON_SNOWMOBILE", "Mission-vehicle-snowmobile.png", None, ("w", 112), "c"),
+ ("ICON_TRUCK", "Mission-vehicle-truck.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"),
@@ -120,6 +148,16 @@ PICTURES = [
("START", "Icon-start.png", None, ("w", 30), "c"),
]
+# the pickers' strips: each vehicle's and stage's picture small (48 colours)
+THUMBS_V = ["jeep", "bike", "monster", "quadbike", "racecar", "rallycar", "dunebuggy", "tank", "tractor", "touristbus",
+ "dieseltruck", "snowmobile", "truck"]
+THUMBS_S = ["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", "game/stage-icon-cliffs.png",
+ "game/stage-icon-mud.png", "game/stage-icon-volcano.png"]
+PICTURES += [(f"THUMB_V{i}", f"Mission-vehicle-{n}.png", "trim", ("h", 18), "c", 48) for i, n in enumerate(THUMBS_V)]
+PICTURES += [(f"THUMB_S{i}", n, None, ("size", 34, 17), "c", 48) for i, n in enumerate(THUMBS_S)]
+
# 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)]
@@ -131,9 +169,19 @@ def ref_path(ref, 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))
+ if name.startswith("game/"): # the game's own files (tools/fetch.py: its 1.10.2 package's assets)
+ return Image.open(os.path.join(ref, name)).convert("RGBA")
return Image.open(ref_path(ref, name)).convert("RGBA")
+def trimmed(im, piv):
+ """The picture without its fully clear margins, and its pivot moved with it."""
+ box = im.getbbox()
+ if not box:
+ return im, piv
+ return im.crop(box), (piv[0] - box[0], piv[1] - box[1])
+
+
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
@@ -178,8 +226,8 @@ 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)
+def picture(im, ppm, pivot, opaque=False, colors=256):
+ cols, idx = quantize(im, colors)
h, w = idx.shape
flags = 1 if opaque else 0
out = bytearray(struct.pack("<HHHHHhhH", w, h, len(cols), flags, int(round(ppm * 4)),
@@ -257,19 +305,33 @@ def vehicle_pictures(ref):
for v in art.VEHICLES:
cname, wname = "CH_" + v["id"].upper(), "WHEEL_" + v["id"].upper()
- im, piv = sized_on(load(ref, v["chassis"]), v["size"])
+ cim = load(ref, v["chassis"])
+ for (upic, at) in v.get("under", []): # pictures the game puts behind the chassis' (its children at z -1)
+ u = load(ref, upic)
+ back = Image.new("RGBA", cim.size)
+ back.alpha_composite(u, (round(at[0] - u.width / 2), round(at[1] - u.height / 2)))
+ back.alpha_composite(cim)
+ cim = back
+ im, piv = sized_on(cim, v["size"])
+ if v.get("trim"):
+ im, piv = trimmed(im, piv)
pics.append((cname, im, VPPM, piv, False))
- wim = load(ref, v["wheel"])
- if "wheel_px" in v: # a tyre cropped from a bigger picture: its radius in pixels is the wheel's 1.04 r
- side = wim.width / v["wheel_px"] * 1.04 * v["wheel_r"]
+ if "wheel_reuse" in v: # the same tyre picture as another vehicle's
+ wname = "WHEEL_" + v["wheel_reuse"].upper()
else:
- side = 2.15 * v["wheel_r"]
- im, piv = sized_on(wim, (side, side * wim.height / wim.width))
- pics.append((wname, im, VPPM, piv, False))
+ wim = load(ref, v["wheel"])
+ if "wheel_px" in v: # a tyre cropped from a bigger picture: its radius in pixels is the wheel's 1.04 r
+ side = wim.width / v["wheel_px"] * 1.04 * v["wheel_r"]
+ else:
+ side = v.get("wheel_side", 2.15) * v["wheel_r"]
+ im, piv = sized_on(wim, (side, side * wim.height / wim.width))
+ pics.append((wname, im, VPPM, piv, False))
layers = []
for (lpic, size, at, front) in v.get("layers", []):
- lname = "LAYER_" + lpic.split(".")[0].upper().replace("-", "_")
+ lname = "LAYER_" + lpic.split("/")[-1].split(".")[0].upper().replace("-", "_")
im, piv = sized_on(load(ref, lpic), size)
+ if v.get("trim"):
+ im, piv = trimmed(im, piv)
pics.append((lname, im, VPPM, piv, False))
layers.append((lname, at, front))
tubes = [(p[0], p[1], axi, col, r) for (p, axi, col, r) in v.get("tubes", [])]
@@ -367,17 +429,20 @@ def icon(ref):
def main():
ref = sys.argv[1]
pics = []
- for name, file, crop, how, pivot in PICTURES:
+ colors = {}
+ for name, file, crop, how, pivot, *more 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_"))
+ opaque = name.startswith(("GROUND_", "SKY", "MENU_BG", "STAGE_", "PIT_", "THUMB_S"))
pics.append((name, im, ppm, pv, opaque))
+ if more:
+ colors[name] = more[0]
vp, art_lines = vehicle_pictures(ref)
pics += vp
- blobs = [picture(im, ppm, pv, opaque) for _, im, ppm, pv, opaque in pics]
+ blobs = [picture(im, ppm, pv, opaque, colors.get(name, 256)) for name, 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))
diff --git a/tests/test_games.py b/tests/test_games.py
index 3f5f2a09..71fa2cc9 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -357,11 +357,11 @@ CHECKS = {
lambda v: v[:4] == b"S1SV" and v[6] == 1 and struct.unpack_from("<I", v, 28)[0] > 600),
# a simulation saved ("NPWD"); after the reinstall, from the copy, it goes on and is saved again
"numpowder": (lambda v: v[:4] == b"NPWD",) * 2,
- # a run banked ("HCR1", runs at 212) with a best on the Countryside (at 48); after the reinstall, from the copy,
- # a second one
- "hillclimb": (lambda v: v[:4] == b"HCR1" and struct.unpack_from("<I", v, 212)[0] == 1
- and struct.unpack_from("<H", v, 48)[0] > 0,
- lambda v: v[:4] == b"HCR1" and struct.unpack_from("<I", v, 212)[0] == 2),
+ # a run banked ("HCR1", save version 3 at 8, runs at 416) with a best on the Countryside (at 72); after the
+ # reinstall, from the copy, a second one
+ "hillclimb": (lambda v: v[:4] == b"HCR1" and struct.unpack_from("<H", v, 8)[0] == 3
+ and struct.unpack_from("<I", v, 416)[0] == 1 and struct.unpack_from("<H", v, 72)[0] > 0,
+ lambda v: v[:4] == b"HCR1" and struct.unpack_from("<I", v, 416)[0] == 2),
# a game saved ("HKSV", then the play time at 152); after the reinstall, from the copy, it goes on
"hollowknight": (lambda v: v[:4] == b"HKSV" and struct.unpack_from("<f", v, 152)[0] > 0,
lambda v: v[:4] == b"HKSV" and struct.unpack_from("<f", v, 152)[0] > 10),