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 game's own physics, on Box2D 2.2.1

Mason36385eaccc1c9f7
diff --git a/games/hillclimb/Makefile b/games/hillclimb/Makefile
index f3f3b018..f97cbbe8 100644
--- a/games/hillclimb/Makefile
+++ b/games/hillclimb/Makefile
@@ -1,4 +1,4 @@
-# Hill Climb Racing on the NumWorks calculator.
+# Hill Climb Racing on the NumWorks calculator (C, and the physics in C++ on Box2D 2.2.1: src/box2d).
# make output/hillclimb.nwa
# make check link it like the calculator does (output/hillclimb.bin)
# make host build/play: the game on a computer, for tests and screenshots
@@ -10,22 +10,30 @@ Q ?= @
TOOLCHAIN ?=
BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)
CC = $(BIN)arm-none-eabi-gcc
+CXX = $(BIN)arm-none-eabi-g++
NWLINK ?= npx --yes -- [email protected]
STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded
SIZE = $(BIN)arm-none-eabi-size
BUILD_DIR = output
REF ?=
-# the drawing and the physics run every frame at -O2; the rest is small at -Os
-HOT = src/gfx.c src/car.c src/stage.c
+# the drawing and the ground run every frame at -O2; the rest is small at -Os
+HOT = src/gfx.c src/stage.c
COLD = $(filter-out $(HOT) src/plat_host.c src/plat_eadk.c,$(wildcard src/*.c))
COLD_OBJ = $(patsubst src/%.c,$(BUILD_DIR)/cold/%.o,$(COLD))
HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
+# the physics: the game's vehicles (car.cpp) on Box2D 2.2.1, in C++ (no exceptions, no RTTI, no runtime)
+BOX2D = $(wildcard src/box2d/Box2D/*/*.cpp src/box2d/Box2D/*/*/*.cpp)
+BOX2D_H = $(wildcard src/box2d/Box2D/*/*.h src/box2d/Box2D/*/*/*.h)
+PHYS = src/car.cpp $(BOX2D)
+PHYS_OBJ = $(patsubst src/%.cpp,$(BUILD_DIR)/phys/%.o,$(PHYS))
CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DDATA_BIN='"src/data.bin"'
CFLAGS += -O2 -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)
+CXXFLAGS = $(filter-out -std=gnu11,$(CFLAGS)) -std=gnu++11 -fno-exceptions -fno-rtti -fno-threadsafe-statics
+CXXFLAGS += -fno-use-cxa-atexit -DNDEBUG -Isrc/box2d -Wno-unused-but-set-variable -Wno-class-memaccess
LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
@@ -45,9 +53,13 @@ $(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS)
@mkdir -p $(@D)
$(Q) $(CC) $(CFLAGS) -Os -c $< -o $@
-$(BUILD_DIR)/hillclimb.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o
+$(BUILD_DIR)/phys/%.o: src/%.cpp $(HEADERS) $(BOX2D_H)
+ @mkdir -p $(@D)
+ $(Q) $(CXX) $(CXXFLAGS) -c $< -o $@
+
+$(BUILD_DIR)/hillclimb.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(PHYS_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o
@echo "LD $@"
- $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(PHYS_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@
$(Q) $(STRIP) $@
$(Q) $(SIZE) $@
@@ -60,12 +72,20 @@ $(BUILD_DIR):
# on a computer: tests/play.c plays it with scripted keys and saves screenshots
HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST -DDATA_BIN='"src/data.bin"'
+HOST_CXXFLAGS = -std=gnu++11 -O2 -g -Wall -Wno-unused-parameter -Isrc -Isrc/box2d -DHOST -fno-exceptions -fno-rtti
HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined
HOST_SRC = $(filter-out src/plat_eadk.c src/main.c,$(wildcard src/*.c))
+HOST_PHYS = $(patsubst src/%.cpp,build/host/%.o,$(PHYS))
host: build/play
-build/play: $(HOST_SRC) tests/play.c src/data.S src/data.bin $(HEADERS)
+build/host/%.o: src/%.cpp $(HEADERS) $(BOX2D_H)
+ $(Q) mkdir -p $(@D)
+ $(Q) c++ $(HOST_CXXFLAGS) $(HOST_SAN) -c $< -o $@
+build/play: $(HOST_SRC) tests/play.c src/data.S src/data.bin $(HEADERS) $(HOST_PHYS)
$(Q) mkdir -p $(dir $@)
- $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/play.c src/data.S -lm -o $@
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) -c $(HOST_SRC) tests/play.c src/data.S
+ $(Q) mv *.o build/host/
+ $(Q) c++ $(HOST_SAN) $(addprefix build/host/,$(notdir $(HOST_SRC:.c=.o))) build/host/play.o build/host/data.o \
+ $(HOST_PHYS) -lm -o $@
@echo "HOST $@"
test: build/play
diff --git a/games/hillclimb/src/art.h b/games/hillclimb/src/art.h
index f05199c8..ce02d2ba 100644
--- a/games/hillclimb/src/art.h
+++ b/games/hillclimb/src/art.h
@@ -1,55 +1,26 @@
-/* Generated by tools/pack.py from tools/art.py: the vehicles put together, in meters. */
+/* Generated by tools/pack.py from tools/art.py: how the vehicles and Bill are drawn, in meters. */
#ifndef HC_ART_H
#define HC_ART_H
#include "data.h"
-#define BILL_NECK_X -0.015f
-#define BILL_NECK_Y 0.766f
-#define BILL_HEAD_X 0.085f /* the head's centre from the neck */
-#define BILL_HEAD_Y 0.322f
-#define BILL_HEAD_R 0.288f
+#define BILL_NECK_X -0.012f
+#define BILL_NECK_Y 0.600f
typedef struct {
- uint8_t chassis, wheel, naxles, legs, ntubes, nlayers, nhull;
- float axle[6][2], wheel_r[6]; /* from the chassis' origin: halfway between the first and last axles */
- float hips[2], lean; /* Bill's hips, and how far he leans back (radians) */
+ uint8_t chassis, wheel, legs, ntubes, nlayers;
+ float wheel_r; /* the radius the wheel's picture is drawn for */
float tube[2][5]; /* from (x, y) to axle (index), colour 0xRRGGBB, radius */
- float layer[2][4]; /* picture, its pivot's place (x, y), in front (1) or behind */
- float hull[16][2]; /* the chassis' outline, for the ground to push on */
+ float layer[2][4]; /* picture, its centre (x, y), in front (1) or behind */
} VehArt;
#define NVEH 8
static const VehArt veh_art[NVEH] = {
- {IMG_CH_JEEP, IMG_WHEEL_JEEP, 2, 0, 0, 0, 16,
- {{-1.075f, 0.000f}, {1.075f, 0.000f}}, {0.430f, 0.430f},
- {-0.104f, 0.638f}, 0.070f, {{0}}, {{0}},
- {{-1.713f, 0.111f}, {-1.600f, 0.631f}, {-1.283f, 0.936f}, {-0.756f, 1.009f}, {-0.229f, 1.082f}, {0.297f, 1.154f}, {0.805f, 1.099f}, {1.280f, 0.861f}, {1.741f, 0.609f}, {1.757f, 0.084f}, {1.341f, -0.148f}, {0.810f, -0.175f}, {0.278f, -0.180f}, {-0.253f, -0.180f}, {-0.785f, -0.175f}, {-1.316f, -0.138f}}}, /* Hill Climber */
- {IMG_CH_BIKE, IMG_WHEEL_BIKE, 2, 1, 2, 0, 15,
- {{-0.925f, 0.000f}, {0.925f, 0.000f}}, {0.440f, 0.440f},
- {-0.273f, 0.904f}, -0.279f, {{-0.021f, 0.231f, 0.000f, 5922406.0f, 0.090f}, {0.484f, 1.009f, 1.000f, 3159098.0f, 0.070f}}, {{0}},
- {{-1.366f, 0.978f}, {-0.970f, 1.054f}, {-0.573f, 1.129f}, {-0.176f, 1.205f}, {0.221f, 1.281f}, {0.593f, 1.190f}, {0.933f, 0.973f}, {1.260f, 0.737f}, {1.017f, 0.517f}, {0.662f, 0.325f}, {0.307f, 0.132f}, {-0.075f, 0.038f}, {-0.422f, 0.224f}, {-0.740f, 0.474f}, {-1.057f, 0.724f}}}, /* Motocross Bike */
- {IMG_CH_MONSTER, IMG_WHEEL_MONSTER, 2, 0, 0, 0, 16,
- {{-1.275f, 0.000f}, {1.275f, 0.000f}}, {0.620f, 0.620f},
- {-0.159f, 0.685f}, 0.070f, {{0}}, {{0}},
- {{-2.024f, 0.717f}, {-1.502f, 0.832f}, {-0.970f, 0.919f}, {-0.436f, 0.987f}, {0.100f, 1.037f}, {0.630f, 1.017f}, {1.146f, 0.862f}, {1.657f, 0.693f}, {1.846f, 0.289f}, {1.381f, 0.018f}, {0.864f, -0.122f}, {0.331f, -0.175f}, {-0.208f, -0.175f}, {-0.744f, -0.152f}, {-1.271f, -0.040f}, {-1.662f, 0.323f}}}, /* Monster Truck */
- {IMG_CH_QUAD, IMG_WHEEL_QUAD, 2, 1, 0, 0, 15,
- {{-0.875f, 0.000f}, {0.875f, 0.000f}}, {0.500f, 0.500f},
- {-0.152f, 0.863f}, -0.209f, {{0}}, {{0}},
- {{-1.400f, 0.863f}, {-0.992f, 0.942f}, {-0.584f, 1.021f}, {-0.176f, 1.100f}, {0.232f, 1.178f}, {0.630f, 1.094f}, {1.017f, 0.944f}, {1.325f, 0.718f}, {1.159f, 0.416f}, {0.766f, 0.282f}, {0.373f, 0.149f}, {-0.030f, 0.070f}, {-0.416f, 0.205f}, {-0.792f, 0.382f}, {-1.168f, 0.558f}}}, /* Quad Bike */
- {IMG_CH_RACE, IMG_WHEEL_RACE, 2, 0, 0, 0, 16,
- {{-1.225f, 0.000f}, {1.225f, 0.000f}}, {0.400f, 0.400f},
- {-0.121f, 0.311f}, 0.384f, {{0}}, {{0}},
- {{-2.260f, 1.225f}, {-1.715f, 1.212f}, {-1.183f, 1.066f}, {-0.653f, 0.908f}, {-0.124f, 0.749f}, {0.406f, 0.591f}, {0.928f, 0.409f}, {1.447f, 0.219f}, {1.502f, -0.072f}, {0.949f, -0.090f}, {0.396f, -0.104f}, {-0.157f, -0.104f}, {-0.707f, -0.083f}, {-1.236f, 0.078f}, {-1.701f, 0.363f}, {-2.121f, 0.722f}}}, /* Race Car */
- {IMG_CH_RALLY, IMG_WHEEL_RALLY, 2, 0, 0, 0, 16,
- {{-1.175f, 0.000f}, {1.175f, 0.000f}}, {0.420f, 0.420f},
- {-0.030f, 0.446f}, 0.105f, {{0}}, {{0}},
- {{-1.934f, 1.324f}, {-1.377f, 1.297f}, {-0.827f, 1.193f}, {-0.277f, 1.089f}, {0.270f, 0.974f}, {0.795f, 0.783f}, {1.321f, 0.592f}, {1.685f, 0.230f}, {1.410f, -0.048f}, {0.851f, -0.055f}, {0.291f, -0.059f}, {-0.268f, -0.059f}, {-0.827f, -0.041f}, {-1.384f, 0.017f}, {-1.857f, 0.209f}, {-1.917f, 0.765f}}}, /* Rally Car */
- {IMG_CH_BUGGY, IMG_WHEEL_BUGGY, 2, 0, 0, 0, 16,
- {{-1.150f, 0.000f}, {1.150f, 0.058f}}, {0.520f, 0.400f},
- {-0.597f, 0.320f}, 0.175f, {{0}}, {{0}},
- {{-1.674f, 0.611f}, {-1.281f, 0.763f}, {-0.865f, 0.884f}, {-0.438f, 0.853f}, {-0.010f, 0.788f}, {0.416f, 0.714f}, {0.823f, 0.565f}, {1.229f, 0.416f}, {1.344f, 0.030f}, {0.977f, -0.072f}, {0.544f, -0.066f}, {0.111f, -0.061f}, {-0.322f, -0.055f}, {-0.755f, -0.050f}, {-1.188f, -0.044f}, {-1.516f, 0.213f}}}, /* Dune Buggy */
- {IMG_CH_TANK, IMG_WHEEL_TANK, 5, 0, 0, 2, 16,
- {{-1.600f, 0.000f}, {-0.800f, -0.109f}, {0.000f, -0.109f}, {0.800f, -0.109f}, {1.600f, 0.000f}}, {0.300f, 0.300f, 0.300f, 0.300f, 0.300f},
- {0.036f, 0.945f}, 0.000f, {{0}}, {{IMG_LAYER_CAR_TANK_BG, -2.073f, 1.418f, 0}, {IMG_LAYER_CAR_TANK_CANNON, 0.218f, 2.218f, 1}},
- {{-2.309f, 1.036f}, {-1.819f, 1.316f}, {-1.218f, 1.494f}, {-0.608f, 1.622f}, {0.019f, 1.635f}, {0.627f, 1.533f}, {1.211f, 1.303f}, {1.795f, 1.074f}, {2.186f, 0.627f}, {1.800f, 0.430f}, {1.174f, 0.400f}, {0.546f, 0.400f}, {-0.081f, 0.400f}, {-0.709f, 0.400f}, {-1.336f, 0.400f}, {-1.937f, 0.561f}}}, /* Tank */
+ {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 */
+ {IMG_CH_MONSTER, IMG_WHEEL_MONSTER, 0, 0, 0, 0.700f, {{0}}, {{0}}}, /* Monster Truck */
+ {IMG_CH_QUAD, IMG_WHEEL_QUAD, 1, 0, 0, 0.600f, {{0}}, {{0}}}, /* Quad Bike */
+ {IMG_CH_RACE, IMG_WHEEL_RACE, 0, 0, 0, 0.500f, {{0}}, {{0}}}, /* Race Car */
+ {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 */
};
#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2ChainShape.cpp b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2ChainShape.cpp
new file mode 100644
index 00000000..f7bbe06b
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2ChainShape.cpp
@@ -0,0 +1,171 @@
+/*
+* Copyright (c) 2006-2010 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/Collision/Shapes/b2ChainShape.h>
+#include <Box2D/Collision/Shapes/b2EdgeShape.h>
+#include <new>
+#include <cstring>
+using namespace std;
+
+b2ChainShape::~b2ChainShape()
+{
+ b2Free(m_vertices);
+ m_vertices = NULL;
+ m_count = 0;
+}
+
+void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count)
+{
+ b2Assert(m_vertices == NULL && m_count == 0);
+ b2Assert(count >= 3);
+ m_count = count + 1;
+ m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2));
+ memcpy(m_vertices, vertices, count * sizeof(b2Vec2));
+ m_vertices[count] = m_vertices[0];
+ m_prevVertex = m_vertices[m_count - 2];
+ m_nextVertex = m_vertices[1];
+ m_hasPrevVertex = true;
+ m_hasNextVertex = true;
+}
+
+void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count)
+{
+ b2Assert(m_vertices == NULL && m_count == 0);
+ b2Assert(count >= 2);
+ m_count = count;
+ m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2));
+ memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2));
+ m_hasPrevVertex = false;
+ m_hasNextVertex = false;
+}
+
+void b2ChainShape::SetPrevVertex(const b2Vec2& prevVertex)
+{
+ m_prevVertex = prevVertex;
+ m_hasPrevVertex = true;
+}
+
+void b2ChainShape::SetNextVertex(const b2Vec2& nextVertex)
+{
+ m_nextVertex = nextVertex;
+ m_hasNextVertex = true;
+}
+
+b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const
+{
+ void* mem = allocator->Allocate(sizeof(b2ChainShape));
+ b2ChainShape* clone = new (mem) b2ChainShape;
+ clone->CreateChain(m_vertices, m_count);
+ clone->m_prevVertex = m_prevVertex;
+ clone->m_nextVertex = m_nextVertex;
+ clone->m_hasPrevVertex = m_hasPrevVertex;
+ clone->m_hasNextVertex = m_hasNextVertex;
+ return clone;
+}
+
+int32 b2ChainShape::GetChildCount() const
+{
+ // edge count = vertex count - 1
+ return m_count - 1;
+}
+
+void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const
+{
+ b2Assert(0 <= index && index < m_count - 1);
+ edge->m_type = b2Shape::e_edge;
+ edge->m_radius = m_radius;
+
+ edge->m_vertex1 = m_vertices[index + 0];
+ edge->m_vertex2 = m_vertices[index + 1];
+
+ if (index > 0)
+ {
+ edge->m_vertex0 = m_vertices[index - 1];
+ edge->m_hasVertex0 = true;
+ }
+ else
+ {
+ edge->m_vertex0 = m_prevVertex;
+ edge->m_hasVertex0 = m_hasPrevVertex;
+ }
+
+ if (index < m_count - 2)
+ {
+ edge->m_vertex3 = m_vertices[index + 2];
+ edge->m_hasVertex3 = true;
+ }
+ else
+ {
+ edge->m_vertex3 = m_nextVertex;
+ edge->m_hasVertex3 = m_hasNextVertex;
+ }
+}
+
+bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const
+{
+ B2_NOT_USED(xf);
+ B2_NOT_USED(p);
+ return false;
+}
+
+bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
+ const b2Transform& xf, int32 childIndex) const
+{
+ b2Assert(childIndex < m_count);
+
+ b2EdgeShape edgeShape;
+
+ int32 i1 = childIndex;
+ int32 i2 = childIndex + 1;
+ if (i2 == m_count)
+ {
+ i2 = 0;
+ }
+
+ edgeShape.m_vertex1 = m_vertices[i1];
+ edgeShape.m_vertex2 = m_vertices[i2];
+
+ return edgeShape.RayCast(output, input, xf, 0);
+}
+
+void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
+{
+ b2Assert(childIndex < m_count);
+
+ int32 i1 = childIndex;
+ int32 i2 = childIndex + 1;
+ if (i2 == m_count)
+ {
+ i2 = 0;
+ }
+
+ b2Vec2 v1 = b2Mul(xf, m_vertices[i1]);
+ b2Vec2 v2 = b2Mul(xf, m_vertices[i2]);
+
+ aabb->lowerBound = b2Min(v1, v2);
+ aabb->upperBound = b2Max(v1, v2);
+}
+
+void b2ChainShape::ComputeMass(b2MassData* massData, float32 density) const
+{
+ B2_NOT_USED(density);
+
+ massData->mass = 0.0f;
+ massData->center.SetZero();
+ massData->I = 0.0f;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2ChainShape.h b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2ChainShape.h
new file mode 100644
index 00000000..6aa41ea4
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2ChainShape.h
@@ -0,0 +1,102 @@
+/*
+* Copyright (c) 2006-2010 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_CHAIN_SHAPE_H
+#define B2_CHAIN_SHAPE_H
+
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+class b2EdgeShape;
+
+/// A chain shape is a free form sequence of line segments.
+/// The chain has two-sided collision, so you can use inside and outside collision.
+/// Therefore, you may use any winding order.
+/// Since there may be many vertices, they are allocated using b2Alloc.
+/// Connectivity information is used to create smooth collisions.
+/// WARNING: The chain will not collide properly if there are self-intersections.
+class b2ChainShape : public b2Shape
+{
+public:
+ b2ChainShape();
+
+ /// The destructor frees the vertices using b2Free.
+ ~b2ChainShape();
+
+ /// Create a loop. This automatically adjusts connectivity.
+ /// @param vertices an array of vertices, these are copied
+ /// @param count the vertex count
+ void CreateLoop(const b2Vec2* vertices, int32 count);
+
+ /// Create a chain with isolated end vertices.
+ /// @param vertices an array of vertices, these are copied
+ /// @param count the vertex count
+ void CreateChain(const b2Vec2* vertices, int32 count);
+
+ /// Establish connectivity to a vertex that precedes the first vertex.
+ /// Don't call this for loops.
+ void SetPrevVertex(const b2Vec2& prevVertex);
+
+ /// Establish connectivity to a vertex that follows the last vertex.
+ /// Don't call this for loops.
+ void SetNextVertex(const b2Vec2& nextVertex);
+
+ /// Implement b2Shape. Vertices are cloned using b2Alloc.
+ b2Shape* Clone(b2BlockAllocator* allocator) const;
+
+ /// @see b2Shape::GetChildCount
+ int32 GetChildCount() const;
+
+ /// Get a child edge.
+ void GetChildEdge(b2EdgeShape* edge, int32 index) const;
+
+ /// This always return false.
+ /// @see b2Shape::TestPoint
+ bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
+
+ /// Implement b2Shape.
+ bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
+ const b2Transform& transform, int32 childIndex) const;
+
+ /// @see b2Shape::ComputeAABB
+ void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const;
+
+ /// Chains have zero mass.
+ /// @see b2Shape::ComputeMass
+ void ComputeMass(b2MassData* massData, float32 density) const;
+
+ /// The vertices. Owned by this class.
+ b2Vec2* m_vertices;
+
+ /// The vertex count.
+ int32 m_count;
+
+ b2Vec2 m_prevVertex, m_nextVertex;
+ bool m_hasPrevVertex, m_hasNextVertex;
+};
+
+inline b2ChainShape::b2ChainShape()
+{
+ m_type = e_chain;
+ m_radius = b2_polygonRadius;
+ m_vertices = NULL;
+ m_count = 0;
+ m_hasPrevVertex = NULL;
+ m_hasNextVertex = NULL;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp
new file mode 100644
index 00000000..c03d662d
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2CircleShape.cpp
@@ -0,0 +1,100 @@
+/*
+* Copyright (c) 2006-2009 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/Collision/Shapes/b2CircleShape.h>
+#include <new>
+using namespace std;
+
+b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const
+{
+ void* mem = allocator->Allocate(sizeof(b2CircleShape));
+ b2CircleShape* clone = new (mem) b2CircleShape;
+ *clone = *this;
+ return clone;
+}
+
+int32 b2CircleShape::GetChildCount() const
+{
+ return 1;
+}
+
+bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const
+{
+ b2Vec2 center = transform.p + b2Mul(transform.q, m_p);
+ b2Vec2 d = p - center;
+ return b2Dot(d, d) <= m_radius * m_radius;
+}
+
+// Collision Detection in Interactive 3D Environments by Gino van den Bergen
+// From Section 3.1.2
+// x = s + a * r
+// norm(x) = radius
+bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
+ const b2Transform& transform, int32 childIndex) const
+{
+ B2_NOT_USED(childIndex);
+
+ b2Vec2 position = transform.p + b2Mul(transform.q, m_p);
+ b2Vec2 s = input.p1 - position;
+ float32 b = b2Dot(s, s) - m_radius * m_radius;
+
+ // Solve quadratic equation.
+ b2Vec2 r = input.p2 - input.p1;
+ float32 c = b2Dot(s, r);
+ float32 rr = b2Dot(r, r);
+ float32 sigma = c * c - rr * b;
+
+ // Check for negative discriminant and short segment.
+ if (sigma < 0.0f || rr < b2_epsilon)
+ {
+ return false;
+ }
+
+ // Find the point of intersection of the line with the circle.
+ float32 a = -(c + b2Sqrt(sigma));
+
+ // Is the intersection point on the segment?
+ if (0.0f <= a && a <= input.maxFraction * rr)
+ {
+ a /= rr;
+ output->fraction = a;
+ output->normal = s + a * r;
+ output->normal.Normalize();
+ return true;
+ }
+
+ return false;
+}
+
+void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const
+{
+ B2_NOT_USED(childIndex);
+
+ b2Vec2 p = transform.p + b2Mul(transform.q, m_p);
+ aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius);
+ aabb->upperBound.Set(p.x + m_radius, p.y + m_radius);
+}
+
+void b2CircleShape::ComputeMass(b2MassData* massData, float32 density) const
+{
+ massData->mass = density * b2_pi * m_radius * m_radius;
+ massData->center = m_p;
+
+ // inertia about the local origin
+ massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p));
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2CircleShape.h b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2CircleShape.h
new file mode 100644
index 00000000..6c1fd543
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2CircleShape.h
@@ -0,0 +1,91 @@
+/*
+* Copyright (c) 2006-2009 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_CIRCLE_SHAPE_H
+#define B2_CIRCLE_SHAPE_H
+
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+/// A circle shape.
+class b2CircleShape : public b2Shape
+{
+public:
+ b2CircleShape();
+
+ /// Implement b2Shape.
+ b2Shape* Clone(b2BlockAllocator* allocator) const;
+
+ /// @see b2Shape::GetChildCount
+ int32 GetChildCount() const;
+
+ /// Implement b2Shape.
+ bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
+
+ /// Implement b2Shape.
+ bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
+ const b2Transform& transform, int32 childIndex) const;
+
+ /// @see b2Shape::ComputeAABB
+ void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const;
+
+ /// @see b2Shape::ComputeMass
+ void ComputeMass(b2MassData* massData, float32 density) const;
+
+ /// Get the supporting vertex index in the given direction.
+ int32 GetSupport(const b2Vec2& d) const;
+
+ /// Get the supporting vertex in the given direction.
+ const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
+
+ /// Get the vertex count.
+ int32 GetVertexCount() const { return 1; }
+
+ /// Get a vertex by index. Used by b2Distance.
+ const b2Vec2& GetVertex(int32 index) const;
+
+ /// Position
+ b2Vec2 m_p;
+};
+
+inline b2CircleShape::b2CircleShape()
+{
+ m_type = e_circle;
+ m_radius = 0.0f;
+ m_p.SetZero();
+}
+
+inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const
+{
+ B2_NOT_USED(d);
+ return 0;
+}
+
+inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const
+{
+ B2_NOT_USED(d);
+ return m_p;
+}
+
+inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const
+{
+ B2_NOT_USED(index);
+ b2Assert(index == 0);
+ return m_p;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2EdgeShape.cpp b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2EdgeShape.cpp
new file mode 100644
index 00000000..e204160b
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2EdgeShape.cpp
@@ -0,0 +1,139 @@
+/*
+* Copyright (c) 2006-2010 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/Collision/Shapes/b2EdgeShape.h>
+#include <new>
+using namespace std;
+
+void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2)
+{
+ m_vertex1 = v1;
+ m_vertex2 = v2;
+ m_hasVertex0 = false;
+ m_hasVertex3 = false;
+}
+
+b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const
+{
+ void* mem = allocator->Allocate(sizeof(b2EdgeShape));
+ b2EdgeShape* clone = new (mem) b2EdgeShape;
+ *clone = *this;
+ return clone;
+}
+
+int32 b2EdgeShape::GetChildCount() const
+{
+ return 1;
+}
+
+bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const
+{
+ B2_NOT_USED(xf);
+ B2_NOT_USED(p);
+ return false;
+}
+
+// p = p1 + t * d
+// v = v1 + s * e
+// p1 + t * d = v1 + s * e
+// s * e - t * d = p1 - v1
+bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
+ const b2Transform& xf, int32 childIndex) const
+{
+ B2_NOT_USED(childIndex);
+
+ // Put the ray into the edge's frame of reference.
+ b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);
+ b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);
+ b2Vec2 d = p2 - p1;
+
+ b2Vec2 v1 = m_vertex1;
+ b2Vec2 v2 = m_vertex2;
+ b2Vec2 e = v2 - v1;
+ b2Vec2 normal(e.y, -e.x);
+ normal.Normalize();
+
+ // q = p1 + t * d
+ // dot(normal, q - v1) = 0
+ // dot(normal, p1 - v1) + t * dot(normal, d) = 0
+ float32 numerator = b2Dot(normal, v1 - p1);
+ float32 denominator = b2Dot(normal, d);
+
+ if (denominator == 0.0f)
+ {
+ return false;
+ }
+
+ float32 t = numerator / denominator;
+ if (t < 0.0f || input.maxFraction < t)
+ {
+ return false;
+ }
+
+ b2Vec2 q = p1 + t * d;
+
+ // q = v1 + s * r
+ // s = dot(q - v1, r) / dot(r, r)
+ b2Vec2 r = v2 - v1;
+ float32 rr = b2Dot(r, r);
+ if (rr == 0.0f)
+ {
+ return false;
+ }
+
+ float32 s = b2Dot(q - v1, r) / rr;
+ if (s < 0.0f || 1.0f < s)
+ {
+ return false;
+ }
+
+ output->fraction = t;
+ if (numerator > 0.0f)
+ {
+ output->normal = -normal;
+ }
+ else
+ {
+ output->normal = normal;
+ }
+ return true;
+}
+
+void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
+{
+ B2_NOT_USED(childIndex);
+
+ b2Vec2 v1 = b2Mul(xf, m_vertex1);
+ b2Vec2 v2 = b2Mul(xf, m_vertex2);
+
+ b2Vec2 lower = b2Min(v1, v2);
+ b2Vec2 upper = b2Max(v1, v2);
+
+ b2Vec2 r(m_radius, m_radius);
+ aabb->lowerBound = lower - r;
+ aabb->upperBound = upper + r;
+}
+
+void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const
+{
+ B2_NOT_USED(density);
+
+ massData->mass = 0.0f;
+ massData->center = 0.5f * (m_vertex1 + m_vertex2);
+ massData->I = 0.0f;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2EdgeShape.h b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2EdgeShape.h
new file mode 100644
index 00000000..99f822be
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2EdgeShape.h
@@ -0,0 +1,74 @@
+/*
+* Copyright (c) 2006-2010 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_EDGE_SHAPE_H
+#define B2_EDGE_SHAPE_H
+
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+/// A line segment (edge) shape. These can be connected in chains or loops
+/// to other edge shapes. The connectivity information is used to ensure
+/// correct contact normals.
+class b2EdgeShape : public b2Shape
+{
+public:
+ b2EdgeShape();
+
+ /// Set this as an isolated edge.
+ void Set(const b2Vec2& v1, const b2Vec2& v2);
+
+ /// Implement b2Shape.
+ b2Shape* Clone(b2BlockAllocator* allocator) const;
+
+ /// @see b2Shape::GetChildCount
+ int32 GetChildCount() const;
+
+ /// @see b2Shape::TestPoint
+ bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
+
+ /// Implement b2Shape.
+ bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
+ const b2Transform& transform, int32 childIndex) const;
+
+ /// @see b2Shape::ComputeAABB
+ void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const;
+
+ /// @see b2Shape::ComputeMass
+ void ComputeMass(b2MassData* massData, float32 density) const;
+
+ /// These are the edge vertices
+ b2Vec2 m_vertex1, m_vertex2;
+
+ /// Optional adjacent vertices. These are used for smooth collision.
+ b2Vec2 m_vertex0, m_vertex3;
+ bool m_hasVertex0, m_hasVertex3;
+};
+
+inline b2EdgeShape::b2EdgeShape()
+{
+ m_type = e_edge;
+ m_radius = b2_polygonRadius;
+ m_vertex0.x = 0.0f;
+ m_vertex0.y = 0.0f;
+ m_vertex3.x = 0.0f;
+ m_vertex3.y = 0.0f;
+ m_hasVertex0 = false;
+ m_hasVertex3 = false;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp
new file mode 100644
index 00000000..8be81333
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp
@@ -0,0 +1,361 @@
+/*
+* Copyright (c) 2006-2009 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/Collision/Shapes/b2PolygonShape.h>
+#include <new>
+
+b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const
+{
+ void* mem = allocator->Allocate(sizeof(b2PolygonShape));
+ b2PolygonShape* clone = new (mem) b2PolygonShape;
+ *clone = *this;
+ return clone;
+}
+
+void b2PolygonShape::SetAsBox(float32 hx, float32 hy)
+{
+ m_vertexCount = 4;
+ m_vertices[0].Set(-hx, -hy);
+ m_vertices[1].Set( hx, -hy);
+ m_vertices[2].Set( hx, hy);
+ m_vertices[3].Set(-hx, hy);
+ m_normals[0].Set(0.0f, -1.0f);
+ m_normals[1].Set(1.0f, 0.0f);
+ m_normals[2].Set(0.0f, 1.0f);
+ m_normals[3].Set(-1.0f, 0.0f);
+ m_centroid.SetZero();
+}
+
+void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle)
+{
+ m_vertexCount = 4;
+ m_vertices[0].Set(-hx, -hy);
+ m_vertices[1].Set( hx, -hy);
+ m_vertices[2].Set( hx, hy);
+ m_vertices[3].Set(-hx, hy);
+ m_normals[0].Set(0.0f, -1.0f);
+ m_normals[1].Set(1.0f, 0.0f);
+ m_normals[2].Set(0.0f, 1.0f);
+ m_normals[3].Set(-1.0f, 0.0f);
+ m_centroid = center;
+
+ b2Transform xf;
+ xf.p = center;
+ xf.q.Set(angle);
+
+ // Transform vertices and normals.
+ for (int32 i = 0; i < m_vertexCount; ++i)
+ {
+ m_vertices[i] = b2Mul(xf, m_vertices[i]);
+ m_normals[i] = b2Mul(xf.q, m_normals[i]);
+ }
+}
+
+int32 b2PolygonShape::GetChildCount() const
+{
+ return 1;
+}
+
+static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count)
+{
+ b2Assert(count >= 3);
+
+ b2Vec2 c; c.Set(0.0f, 0.0f);
+ float32 area = 0.0f;
+
+ // pRef is the reference point for forming triangles.
+ // It's location doesn't change the result (except for rounding error).
+ b2Vec2 pRef(0.0f, 0.0f);
+#if 0
+ // This code would put the reference point inside the polygon.
+ for (int32 i = 0; i < count; ++i)
+ {
+ pRef += vs[i];
+ }
+ pRef *= 1.0f / count;
+#endif
+
+ const float32 inv3 = 1.0f / 3.0f;
+
+ for (int32 i = 0; i < count; ++i)
+ {
+ // Triangle vertices.
+ b2Vec2 p1 = pRef;
+ b2Vec2 p2 = vs[i];
+ b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0];
+
+ b2Vec2 e1 = p2 - p1;
+ b2Vec2 e2 = p3 - p1;
+
+ float32 D = b2Cross(e1, e2);
+
+ float32 triangleArea = 0.5f * D;
+ area += triangleArea;
+
+ // Area weighted centroid
+ c += triangleArea * inv3 * (p1 + p2 + p3);
+ }
+
+ // Centroid
+ b2Assert(area > b2_epsilon);
+ c *= 1.0f / area;
+ return c;
+}
+
+void b2PolygonShape::Set(const b2Vec2* vertices, int32 count)
+{
+ b2Assert(3 <= count && count <= b2_maxPolygonVertices);
+ m_vertexCount = count;
+
+ // Copy vertices.
+ for (int32 i = 0; i < m_vertexCount; ++i)
+ {
+ m_vertices[i] = vertices[i];
+ }
+
+ // Compute normals. Ensure the edges have non-zero length.
+ for (int32 i = 0; i < m_vertexCount; ++i)
+ {
+ int32 i1 = i;
+ int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0;
+ b2Vec2 edge = m_vertices[i2] - m_vertices[i1];
+ b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon);
+ m_normals[i] = b2Cross(edge, 1.0f);
+ m_normals[i].Normalize();
+ }
+
+#ifdef _DEBUG
+ // Ensure the polygon is convex and the interior
+ // is to the left of each edge.
+ for (int32 i = 0; i < m_vertexCount; ++i)
+ {
+ int32 i1 = i;
+ int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0;
+ b2Vec2 edge = m_vertices[i2] - m_vertices[i1];
+
+ for (int32 j = 0; j < m_vertexCount; ++j)
+ {
+ // Don't check vertices on the current edge.
+ if (j == i1 || j == i2)
+ {
+ continue;
+ }
+
+ b2Vec2 r = m_vertices[j] - m_vertices[i1];
+
+ // If this crashes, your polygon is non-convex, has colinear edges,
+ // or the winding order is wrong.
+ float32 s = b2Cross(edge, r);
+ b2Assert(s > 0.0f && "ERROR: Please ensure your polygon is convex and has a CCW winding order");
+ }
+ }
+#endif
+
+ // Compute the polygon centroid.
+ m_centroid = ComputeCentroid(m_vertices, m_vertexCount);
+}
+
+bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const
+{
+ b2Vec2 pLocal = b2MulT(xf.q, p - xf.p);
+
+ for (int32 i = 0; i < m_vertexCount; ++i)
+ {
+ float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);
+ if (dot > 0.0f)
+ {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
+ const b2Transform& xf, int32 childIndex) const
+{
+ B2_NOT_USED(childIndex);
+
+ // Put the ray into the polygon's frame of reference.
+ b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);
+ b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);
+ b2Vec2 d = p2 - p1;
+
+ float32 lower = 0.0f, upper = input.maxFraction;
+
+ int32 index = -1;
+
+ for (int32 i = 0; i < m_vertexCount; ++i)
+ {
+ // p = p1 + a * d
+ // dot(normal, p - v) = 0
+ // dot(normal, p1 - v) + a * dot(normal, d) = 0
+ float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1);
+ float32 denominator = b2Dot(m_normals[i], d);
+
+ if (denominator == 0.0f)
+ {
+ if (numerator < 0.0f)
+ {
+ return false;
+ }
+ }
+ else
+ {
+ // Note: we want this predicate without division:
+ // lower < numerator / denominator, where denominator < 0
+ // Since denominator < 0, we have to flip the inequality:
+ // lower < numerator / denominator <==> denominator * lower > numerator.
+ if (denominator < 0.0f && numerator < lower * denominator)
+ {
+ // Increase lower.
+ // The segment enters this half-space.
+ lower = numerator / denominator;
+ index = i;
+ }
+ else if (denominator > 0.0f && numerator < upper * denominator)
+ {
+ // Decrease upper.
+ // The segment exits this half-space.
+ upper = numerator / denominator;
+ }
+ }
+
+ // The use of epsilon here causes the assert on lower to trip
+ // in some cases. Apparently the use of epsilon was to make edge
+ // shapes work, but now those are handled separately.
+ //if (upper < lower - b2_epsilon)
+ if (upper < lower)
+ {
+ return false;
+ }
+ }
+
+ b2Assert(0.0f <= lower && lower <= input.maxFraction);
+
+ if (index >= 0)
+ {
+ output->fraction = lower;
+ output->normal = b2Mul(xf.q, m_normals[index]);
+ return true;
+ }
+
+ return false;
+}
+
+void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
+{
+ B2_NOT_USED(childIndex);
+
+ b2Vec2 lower = b2Mul(xf, m_vertices[0]);
+ b2Vec2 upper = lower;
+
+ for (int32 i = 1; i < m_vertexCount; ++i)
+ {
+ b2Vec2 v = b2Mul(xf, m_vertices[i]);
+ lower = b2Min(lower, v);
+ upper = b2Max(upper, v);
+ }
+
+ b2Vec2 r(m_radius, m_radius);
+ aabb->lowerBound = lower - r;
+ aabb->upperBound = upper + r;
+}
+
+void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const
+{
+ // Polygon mass, centroid, and inertia.
+ // Let rho be the polygon density in mass per unit area.
+ // Then:
+ // mass = rho * int(dA)
+ // centroid.x = (1/mass) * rho * int(x * dA)
+ // centroid.y = (1/mass) * rho * int(y * dA)
+ // I = rho * int((x*x + y*y) * dA)
+ //
+ // We can compute these integrals by summing all the integrals
+ // for each triangle of the polygon. To evaluate the integral
+ // for a single triangle, we make a change of variables to
+ // the (u,v) coordinates of the triangle:
+ // x = x0 + e1x * u + e2x * v
+ // y = y0 + e1y * u + e2y * v
+ // where 0 <= u && 0 <= v && u + v <= 1.
+ //
+ // We integrate u from [0,1-v] and then v from [0,1].
+ // We also need to use the Jacobian of the transformation:
+ // D = cross(e1, e2)
+ //
+ // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
+ //
+ // The rest of the derivation is handled by computer algebra.
+
+ b2Assert(m_vertexCount >= 3);
+
+ b2Vec2 center; center.Set(0.0f, 0.0f);
+ float32 area = 0.0f;
+ float32 I = 0.0f;
+
+ // s is the reference point for forming triangles.
+ // It's location doesn't change the result (except for rounding error).
+ b2Vec2 s(0.0f, 0.0f);
+
+ // This code would put the reference point inside the polygon.
+ for (int32 i = 0; i < m_vertexCount; ++i)
+ {
+ s += m_vertices[i];
+ }
+ s *= 1.0f / m_vertexCount;
+
+ const float32 k_inv3 = 1.0f / 3.0f;
+
+ for (int32 i = 0; i < m_vertexCount; ++i)
+ {
+ // Triangle vertices.
+ b2Vec2 e1 = m_vertices[i] - s;
+ b2Vec2 e2 = i + 1 < m_vertexCount ? m_vertices[i+1] - s : m_vertices[0] - s;
+
+ float32 D = b2Cross(e1, e2);
+
+ float32 triangleArea = 0.5f * D;
+ area += triangleArea;
+
+ // Area weighted centroid
+ center += triangleArea * k_inv3 * (e1 + e2);
+
+ float32 ex1 = e1.x, ey1 = e1.y;
+ float32 ex2 = e2.x, ey2 = e2.y;
+
+ float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2;
+ float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2;
+
+ I += (0.25f * k_inv3 * D) * (intx2 + inty2);
+ }
+
+ // Total mass
+ massData->mass = density * area;
+
+ // Center of mass
+ b2Assert(area > b2_epsilon);
+ center *= 1.0f / area;
+ massData->center = center + s;
+
+ // Inertia tensor relative to the local origin (point s).
+ massData->I = density * I;
+
+ // Shift to center of mass then to original body origin.
+ massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center));
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2PolygonShape.h b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2PolygonShape.h
new file mode 100644
index 00000000..fd11bd16
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2PolygonShape.h
@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2006-2009 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_POLYGON_SHAPE_H
+#define B2_POLYGON_SHAPE_H
+
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+/// A convex polygon. It is assumed that the interior of the polygon is to
+/// the left of each edge.
+/// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices.
+/// In most cases you should not need many vertices for a convex polygon.
+class b2PolygonShape : public b2Shape
+{
+public:
+ b2PolygonShape();
+
+ /// Implement b2Shape.
+ b2Shape* Clone(b2BlockAllocator* allocator) const;
+
+ /// @see b2Shape::GetChildCount
+ int32 GetChildCount() const;
+
+ /// Copy vertices. This assumes the vertices define a convex polygon.
+ /// It is assumed that the exterior is the the right of each edge.
+ /// The count must be in the range [3, b2_maxPolygonVertices].
+ void Set(const b2Vec2* vertices, int32 vertexCount);
+
+ /// Build vertices to represent an axis-aligned box.
+ /// @param hx the half-width.
+ /// @param hy the half-height.
+ void SetAsBox(float32 hx, float32 hy);
+
+ /// Build vertices to represent an oriented box.
+ /// @param hx the half-width.
+ /// @param hy the half-height.
+ /// @param center the center of the box in local coordinates.
+ /// @param angle the rotation of the box in local coordinates.
+ void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle);
+
+ /// @see b2Shape::TestPoint
+ bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
+
+ /// Implement b2Shape.
+ bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
+ const b2Transform& transform, int32 childIndex) const;
+
+ /// @see b2Shape::ComputeAABB
+ void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const;
+
+ /// @see b2Shape::ComputeMass
+ void ComputeMass(b2MassData* massData, float32 density) const;
+
+ /// Get the vertex count.
+ int32 GetVertexCount() const { return m_vertexCount; }
+
+ /// Get a vertex by index.
+ const b2Vec2& GetVertex(int32 index) const;
+
+ b2Vec2 m_centroid;
+ b2Vec2 m_vertices[b2_maxPolygonVertices];
+ b2Vec2 m_normals[b2_maxPolygonVertices];
+ int32 m_vertexCount;
+};
+
+inline b2PolygonShape::b2PolygonShape()
+{
+ m_type = e_polygon;
+ m_radius = b2_polygonRadius;
+ m_vertexCount = 0;
+ m_centroid.SetZero();
+}
+
+inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const
+{
+ b2Assert(0 <= index && index < m_vertexCount);
+ return m_vertices[index];
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2Shape.h b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2Shape.h
new file mode 100644
index 00000000..fd7de262
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/Shapes/b2Shape.h
@@ -0,0 +1,101 @@
+/*
+* Copyright (c) 2006-2009 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_SHAPE_H
+#define B2_SHAPE_H
+
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Collision.h>
+
+/// This holds the mass data computed for a shape.
+struct b2MassData
+{
+ /// The mass of the shape, usually in kilograms.
+ float32 mass;
+
+ /// The position of the shape's centroid relative to the shape's origin.
+ b2Vec2 center;
+
+ /// The rotational inertia of the shape about the local origin.
+ float32 I;
+};
+
+/// A shape is used for collision detection. You can create a shape however you like.
+/// Shapes used for simulation in b2World are created automatically when a b2Fixture
+/// is created. Shapes may encapsulate a one or more child shapes.
+class b2Shape
+{
+public:
+
+ enum Type
+ {
+ e_circle = 0,
+ e_edge = 1,
+ e_polygon = 2,
+ e_chain = 3,
+ e_typeCount = 4
+ };
+
+ virtual ~b2Shape() {}
+
+ /// Clone the concrete shape using the provided allocator.
+ virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0;
+
+ /// Get the type of this shape. You can use this to down cast to the concrete shape.
+ /// @return the shape type.
+ Type GetType() const;
+
+ /// Get the number of child primitives.
+ virtual int32 GetChildCount() const = 0;
+
+ /// Test a point for containment in this shape. This only works for convex shapes.
+ /// @param xf the shape world transform.
+ /// @param p a point in world coordinates.
+ virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0;
+
+ /// Cast a ray against a child shape.
+ /// @param output the ray-cast results.
+ /// @param input the ray-cast input parameters.
+ /// @param transform the transform to be applied to the shape.
+ /// @param childIndex the child shape index
+ virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
+ const b2Transform& transform, int32 childIndex) const = 0;
+
+ /// Given a transform, compute the associated axis aligned bounding box for a child shape.
+ /// @param aabb returns the axis aligned box.
+ /// @param xf the world transform of the shape.
+ /// @param childIndex the child shape
+ virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0;
+
+ /// Compute the mass properties of this shape using its dimensions and density.
+ /// The inertia tensor is computed about the local origin.
+ /// @param massData returns the mass data for this shape.
+ /// @param density the density in kilograms per meter squared.
+ virtual void ComputeMass(b2MassData* massData, float32 density) const = 0;
+
+ Type m_type;
+ float32 m_radius;
+};
+
+inline b2Shape::Type b2Shape::GetType() const
+{
+ return m_type;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2BroadPhase.cpp b/games/hillclimb/src/box2d/Box2D/Collision/b2BroadPhase.cpp
new file mode 100644
index 00000000..2aa62f94
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2BroadPhase.cpp
@@ -0,0 +1,122 @@
+/*
+* Copyright (c) 2006-2009 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/Collision/b2BroadPhase.h>
+#include <cstring>
+using namespace std;
+
+b2BroadPhase::b2BroadPhase()
+{
+ m_proxyCount = 0;
+
+ m_pairCapacity = 16;
+ m_pairCount = 0;
+ m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));
+
+ m_moveCapacity = 16;
+ m_moveCount = 0;
+ m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
+}
+
+b2BroadPhase::~b2BroadPhase()
+{
+ b2Free(m_moveBuffer);
+ b2Free(m_pairBuffer);
+}
+
+int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData)
+{
+ int32 proxyId = m_tree.CreateProxy(aabb, userData);
+ ++m_proxyCount;
+ BufferMove(proxyId);
+ return proxyId;
+}
+
+void b2BroadPhase::DestroyProxy(int32 proxyId)
+{
+ UnBufferMove(proxyId);
+ --m_proxyCount;
+ m_tree.DestroyProxy(proxyId);
+}
+
+void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement)
+{
+ bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement);
+ if (buffer)
+ {
+ BufferMove(proxyId);
+ }
+}
+
+void b2BroadPhase::TouchProxy(int32 proxyId)
+{
+ BufferMove(proxyId);
+}
+
+void b2BroadPhase::BufferMove(int32 proxyId)
+{
+ if (m_moveCount == m_moveCapacity)
+ {
+ int32* oldBuffer = m_moveBuffer;
+ m_moveCapacity *= 2;
+ m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
+ memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32));
+ b2Free(oldBuffer);
+ }
+
+ m_moveBuffer[m_moveCount] = proxyId;
+ ++m_moveCount;
+}
+
+void b2BroadPhase::UnBufferMove(int32 proxyId)
+{
+ for (int32 i = 0; i < m_moveCount; ++i)
+ {
+ if (m_moveBuffer[i] == proxyId)
+ {
+ m_moveBuffer[i] = e_nullProxy;
+ return;
+ }
+ }
+}
+
+// This is called from b2DynamicTree::Query when we are gathering pairs.
+bool b2BroadPhase::QueryCallback(int32 proxyId)
+{
+ // A proxy cannot form a pair with itself.
+ if (proxyId == m_queryProxyId)
+ {
+ return true;
+ }
+
+ // Grow the pair buffer as needed.
+ if (m_pairCount == m_pairCapacity)
+ {
+ b2Pair* oldBuffer = m_pairBuffer;
+ m_pairCapacity *= 2;
+ m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));
+ memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair));
+ b2Free(oldBuffer);
+ }
+
+ m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId);
+ m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId);
+ ++m_pairCount;
+
+ return true;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2BroadPhase.h b/games/hillclimb/src/box2d/Box2D/Collision/b2BroadPhase.h
new file mode 100644
index 00000000..c7398c97
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2BroadPhase.h
@@ -0,0 +1,248 @@
+/*
+* Copyright (c) 2006-2009 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_BROAD_PHASE_H
+#define B2_BROAD_PHASE_H
+
+#include <Box2D/Common/b2Settings.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/b2DynamicTree.h>
+#include <algorithm>
+
+struct b2Pair
+{
+ int32 proxyIdA;
+ int32 proxyIdB;
+ int32 next;
+};
+
+/// The broad-phase is used for computing pairs and performing volume queries and ray casts.
+/// This broad-phase does not persist pairs. Instead, this reports potentially new pairs.
+/// It is up to the client to consume the new pairs and to track subsequent overlap.
+class b2BroadPhase
+{
+public:
+
+ enum
+ {
+ e_nullProxy = -1
+ };
+
+ b2BroadPhase();
+ ~b2BroadPhase();
+
+ /// Create a proxy with an initial AABB. Pairs are not reported until
+ /// UpdatePairs is called.
+ int32 CreateProxy(const b2AABB& aabb, void* userData);
+
+ /// Destroy a proxy. It is up to the client to remove any pairs.
+ void DestroyProxy(int32 proxyId);
+
+ /// Call MoveProxy as many times as you like, then when you are done
+ /// call UpdatePairs to finalized the proxy pairs (for your time step).
+ void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement);
+
+ /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs.
+ void TouchProxy(int32 proxyId);
+
+ /// Get the fat AABB for a proxy.
+ const b2AABB& GetFatAABB(int32 proxyId) const;
+
+ /// Get user data from a proxy. Returns NULL if the id is invalid.
+ void* GetUserData(int32 proxyId) const;
+
+ /// Test overlap of fat AABBs.
+ bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const;
+
+ /// Get the number of proxies.
+ int32 GetProxyCount() const;
+
+ /// Update the pairs. This results in pair callbacks. This can only add pairs.
+ template <typename T>
+ void UpdatePairs(T* callback);
+
+ /// Query an AABB for overlapping proxies. The callback class
+ /// is called for each proxy that overlaps the supplied AABB.
+ template <typename T>
+ void Query(T* callback, const b2AABB& aabb) const;
+
+ /// Ray-cast against the proxies in the tree. This relies on the callback
+ /// to perform a exact ray-cast in the case were the proxy contains a shape.
+ /// The callback also performs the any collision filtering. This has performance
+ /// roughly equal to k * log(n), where k is the number of collisions and n is the
+ /// number of proxies in the tree.
+ /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
+ /// @param callback a callback class that is called for each proxy that is hit by the ray.
+ template <typename T>
+ void RayCast(T* callback, const b2RayCastInput& input) const;
+
+ /// Get the height of the embedded tree.
+ int32 GetTreeHeight() const;
+
+ /// Get the balance of the embedded tree.
+ int32 GetTreeBalance() const;
+
+ /// Get the quality metric of the embedded tree.
+ float32 GetTreeQuality() const;
+
+private:
+
+ friend class b2DynamicTree;
+
+ void BufferMove(int32 proxyId);
+ void UnBufferMove(int32 proxyId);
+
+ bool QueryCallback(int32 proxyId);
+
+ b2DynamicTree m_tree;
+
+ int32 m_proxyCount;
+
+ int32* m_moveBuffer;
+ int32 m_moveCapacity;
+ int32 m_moveCount;
+
+ b2Pair* m_pairBuffer;
+ int32 m_pairCapacity;
+ int32 m_pairCount;
+
+ int32 m_queryProxyId;
+};
+
+/// This is used to sort pairs.
+inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2)
+{
+ if (pair1.proxyIdA < pair2.proxyIdA)
+ {
+ return true;
+ }
+
+ if (pair1.proxyIdA == pair2.proxyIdA)
+ {
+ return pair1.proxyIdB < pair2.proxyIdB;
+ }
+
+ return false;
+}
+
+inline void* b2BroadPhase::GetUserData(int32 proxyId) const
+{
+ return m_tree.GetUserData(proxyId);
+}
+
+inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const
+{
+ const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA);
+ const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB);
+ return b2TestOverlap(aabbA, aabbB);
+}
+
+inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const
+{
+ return m_tree.GetFatAABB(proxyId);
+}
+
+inline int32 b2BroadPhase::GetProxyCount() const
+{
+ return m_proxyCount;
+}
+
+inline int32 b2BroadPhase::GetTreeHeight() const
+{
+ return m_tree.GetHeight();
+}
+
+inline int32 b2BroadPhase::GetTreeBalance() const
+{
+ return m_tree.GetMaxBalance();
+}
+
+inline float32 b2BroadPhase::GetTreeQuality() const
+{
+ return m_tree.GetAreaRatio();
+}
+
+template <typename T>
+void b2BroadPhase::UpdatePairs(T* callback)
+{
+ // Reset pair buffer
+ m_pairCount = 0;
+
+ // Perform tree queries for all moving proxies.
+ for (int32 i = 0; i < m_moveCount; ++i)
+ {
+ m_queryProxyId = m_moveBuffer[i];
+ if (m_queryProxyId == e_nullProxy)
+ {
+ continue;
+ }
+
+ // We have to query the tree with the fat AABB so that
+ // we don't fail to create a pair that may touch later.
+ const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId);
+
+ // Query tree, create pairs and add them pair buffer.
+ m_tree.Query(this, fatAABB);
+ }
+
+ // Reset move buffer
+ m_moveCount = 0;
+
+ // Sort the pair buffer to expose duplicates.
+ std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan);
+
+ // Send the pairs back to the client.
+ int32 i = 0;
+ while (i < m_pairCount)
+ {
+ b2Pair* primaryPair = m_pairBuffer + i;
+ void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA);
+ void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB);
+
+ callback->AddPair(userDataA, userDataB);
+ ++i;
+
+ // Skip any duplicate pairs.
+ while (i < m_pairCount)
+ {
+ b2Pair* pair = m_pairBuffer + i;
+ if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB)
+ {
+ break;
+ }
+ ++i;
+ }
+ }
+
+ // Try to keep the tree balanced.
+ //m_tree.Rebalance(4);
+}
+
+template <typename T>
+inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const
+{
+ m_tree.Query(callback, aabb);
+}
+
+template <typename T>
+inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const
+{
+ m_tree.RayCast(callback, input);
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2CollideCircle.cpp b/games/hillclimb/src/box2d/Box2D/Collision/b2CollideCircle.cpp
new file mode 100644
index 00000000..0ad58f00
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2CollideCircle.cpp
@@ -0,0 +1,154 @@
+/*
+* Copyright (c) 2007-2009 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/Collision/b2Collision.h>
+#include <Box2D/Collision/Shapes/b2CircleShape.h>
+#include <Box2D/Collision/Shapes/b2PolygonShape.h>
+
+void b2CollideCircles(
+ b2Manifold* manifold,
+ const b2CircleShape* circleA, const b2Transform& xfA,
+ const b2CircleShape* circleB, const b2Transform& xfB)
+{
+ manifold->pointCount = 0;
+
+ b2Vec2 pA = b2Mul(xfA, circleA->m_p);
+ b2Vec2 pB = b2Mul(xfB, circleB->m_p);
+
+ b2Vec2 d = pB - pA;
+ float32 distSqr = b2Dot(d, d);
+ float32 rA = circleA->m_radius, rB = circleB->m_radius;
+ float32 radius = rA + rB;
+ if (distSqr > radius * radius)
+ {
+ return;
+ }
+
+ manifold->type = b2Manifold::e_circles;
+ manifold->localPoint = circleA->m_p;
+ manifold->localNormal.SetZero();
+ manifold->pointCount = 1;
+
+ manifold->points[0].localPoint = circleB->m_p;
+ manifold->points[0].id.key = 0;
+}
+
+void b2CollidePolygonAndCircle(
+ b2Manifold* manifold,
+ const b2PolygonShape* polygonA, const b2Transform& xfA,
+ const b2CircleShape* circleB, const b2Transform& xfB)
+{
+ manifold->pointCount = 0;
+
+ // Compute circle position in the frame of the polygon.
+ b2Vec2 c = b2Mul(xfB, circleB->m_p);
+ b2Vec2 cLocal = b2MulT(xfA, c);
+
+ // Find the min separating edge.
+ int32 normalIndex = 0;
+ float32 separation = -b2_maxFloat;
+ float32 radius = polygonA->m_radius + circleB->m_radius;
+ int32 vertexCount = polygonA->m_vertexCount;
+ const b2Vec2* vertices = polygonA->m_vertices;
+ const b2Vec2* normals = polygonA->m_normals;
+
+ for (int32 i = 0; i < vertexCount; ++i)
+ {
+ float32 s = b2Dot(normals[i], cLocal - vertices[i]);
+
+ if (s > radius)
+ {
+ // Early out.
+ return;
+ }
+
+ if (s > separation)
+ {
+ separation = s;
+ normalIndex = i;
+ }
+ }
+
+ // Vertices that subtend the incident face.
+ int32 vertIndex1 = normalIndex;
+ int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0;
+ b2Vec2 v1 = vertices[vertIndex1];
+ b2Vec2 v2 = vertices[vertIndex2];
+
+ // If the center is inside the polygon ...
+ if (separation < b2_epsilon)
+ {
+ manifold->pointCount = 1;
+ manifold->type = b2Manifold::e_faceA;
+ manifold->localNormal = normals[normalIndex];
+ manifold->localPoint = 0.5f * (v1 + v2);
+ manifold->points[0].localPoint = circleB->m_p;
+ manifold->points[0].id.key = 0;
+ return;
+ }
+
+ // Compute barycentric coordinates
+ float32 u1 = b2Dot(cLocal - v1, v2 - v1);
+ float32 u2 = b2Dot(cLocal - v2, v1 - v2);
+ if (u1 <= 0.0f)
+ {
+ if (b2DistanceSquared(cLocal, v1) > radius * radius)
+ {
+ return;
+ }
+
+ manifold->pointCount = 1;
+ manifold->type = b2Manifold::e_faceA;
+ manifold->localNormal = cLocal - v1;
+ manifold->localNormal.Normalize();
+ manifold->localPoint = v1;
+ manifold->points[0].localPoint = circleB->m_p;
+ manifold->points[0].id.key = 0;
+ }
+ else if (u2 <= 0.0f)
+ {
+ if (b2DistanceSquared(cLocal, v2) > radius * radius)
+ {
+ return;
+ }
+
+ manifold->pointCount = 1;
+ manifold->type = b2Manifold::e_faceA;
+ manifold->localNormal = cLocal - v2;
+ manifold->localNormal.Normalize();
+ manifold->localPoint = v2;
+ manifold->points[0].localPoint = circleB->m_p;
+ manifold->points[0].id.key = 0;
+ }
+ else
+ {
+ b2Vec2 faceCenter = 0.5f * (v1 + v2);
+ float32 separation = b2Dot(cLocal - faceCenter, normals[vertIndex1]);
+ if (separation > radius)
+ {
+ return;
+ }
+
+ manifold->pointCount = 1;
+ manifold->type = b2Manifold::e_faceA;
+ manifold->localNormal = normals[vertIndex1];
+ manifold->localPoint = faceCenter;
+ manifold->points[0].localPoint = circleB->m_p;
+ manifold->points[0].id.key = 0;
+ }
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2CollideEdge.cpp b/games/hillclimb/src/box2d/Box2D/Collision/b2CollideEdge.cpp
new file mode 100644
index 00000000..28196718
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2CollideEdge.cpp
@@ -0,0 +1,698 @@
+/*
+ * Copyright (c) 2007-2009 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/Collision/b2Collision.h>
+#include <Box2D/Collision/Shapes/b2CircleShape.h>
+#include <Box2D/Collision/Shapes/b2EdgeShape.h>
+#include <Box2D/Collision/Shapes/b2PolygonShape.h>
+
+
+// Compute contact points for edge versus circle.
+// This accounts for edge connectivity.
+void b2CollideEdgeAndCircle(b2Manifold* manifold,
+ const b2EdgeShape* edgeA, const b2Transform& xfA,
+ const b2CircleShape* circleB, const b2Transform& xfB)
+{
+ manifold->pointCount = 0;
+
+ // Compute circle in frame of edge
+ b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p));
+
+ b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2;
+ b2Vec2 e = B - A;
+
+ // Barycentric coordinates
+ float32 u = b2Dot(e, B - Q);
+ float32 v = b2Dot(e, Q - A);
+
+ float32 radius = edgeA->m_radius + circleB->m_radius;
+
+ b2ContactFeature cf;
+ cf.indexB = 0;
+ cf.typeB = b2ContactFeature::e_vertex;
+
+ // Region A
+ if (v <= 0.0f)
+ {
+ b2Vec2 P = A;
+ b2Vec2 d = Q - P;
+ float32 dd = b2Dot(d, d);
+ if (dd > radius * radius)
+ {
+ return;
+ }
+
+ // Is there an edge connected to A?
+ if (edgeA->m_hasVertex0)
+ {
+ b2Vec2 A1 = edgeA->m_vertex0;
+ b2Vec2 B1 = A;
+ b2Vec2 e1 = B1 - A1;
+ float32 u1 = b2Dot(e1, B1 - Q);
+
+ // Is the circle in Region AB of the previous edge?
+ if (u1 > 0.0f)
+ {
+ return;
+ }
+ }
+
+ cf.indexA = 0;
+ cf.typeA = b2ContactFeature::e_vertex;
+ manifold->pointCount = 1;
+ manifold->type = b2Manifold::e_circles;
+ manifold->localNormal.SetZero();
+ manifold->localPoint = P;
+ manifold->points[0].id.key = 0;
+ manifold->points[0].id.cf = cf;
+ manifold->points[0].localPoint = circleB->m_p;
+ return;
+ }
+
+ // Region B
+ if (u <= 0.0f)
+ {
+ b2Vec2 P = B;
+ b2Vec2 d = Q - P;
+ float32 dd = b2Dot(d, d);
+ if (dd > radius * radius)
+ {
+ return;
+ }
+
+ // Is there an edge connected to B?
+ if (edgeA->m_hasVertex3)
+ {
+ b2Vec2 B2 = edgeA->m_vertex3;
+ b2Vec2 A2 = B;
+ b2Vec2 e2 = B2 - A2;
+ float32 v2 = b2Dot(e2, Q - A2);
+
+ // Is the circle in Region AB of the next edge?
+ if (v2 > 0.0f)
+ {
+ return;
+ }
+ }
+
+ cf.indexA = 1;
+ cf.typeA = b2ContactFeature::e_vertex;
+ manifold->pointCount = 1;
+ manifold->type = b2Manifold::e_circles;
+ manifold->localNormal.SetZero();
+ manifold->localPoint = P;
+ manifold->points[0].id.key = 0;
+ manifold->points[0].id.cf = cf;
+ manifold->points[0].localPoint = circleB->m_p;
+ return;
+ }
+
+ // Region AB
+ float32 den = b2Dot(e, e);
+ b2Assert(den > 0.0f);
+ b2Vec2 P = (1.0f / den) * (u * A + v * B);
+ b2Vec2 d = Q - P;
+ float32 dd = b2Dot(d, d);
+ if (dd > radius * radius)
+ {
+ return;
+ }
+
+ b2Vec2 n(-e.y, e.x);
+ if (b2Dot(n, Q - A) < 0.0f)
+ {
+ n.Set(-n.x, -n.y);
+ }
+ n.Normalize();
+
+ cf.indexA = 0;
+ cf.typeA = b2ContactFeature::e_face;
+ manifold->pointCount = 1;
+ manifold->type = b2Manifold::e_faceA;
+ manifold->localNormal = n;
+ manifold->localPoint = A;
+ manifold->points[0].id.key = 0;
+ manifold->points[0].id.cf = cf;
+ manifold->points[0].localPoint = circleB->m_p;
+}
+
+// This structure is used to keep track of the best separating axis.
+struct b2EPAxis
+{
+ enum Type
+ {
+ e_unknown,
+ e_edgeA,
+ e_edgeB
+ };
+
+ Type type;
+ int32 index;
+ float32 separation;
+};
+
+// This holds polygon B expressed in frame A.
+struct b2TempPolygon
+{
+ b2Vec2 vertices[b2_maxPolygonVertices];
+ b2Vec2 normals[b2_maxPolygonVertices];
+ int32 count;
+};
+
+// Reference face used for clipping
+struct b2ReferenceFace
+{
+ int32 i1, i2;
+
+ b2Vec2 v1, v2;
+
+ b2Vec2 normal;
+
+ b2Vec2 sideNormal1;
+ float32 sideOffset1;
+
+ b2Vec2 sideNormal2;
+ float32 sideOffset2;
+};
+
+// This class collides and edge and a polygon, taking into account edge adjacency.
+struct b2EPCollider
+{
+ void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA,
+ const b2PolygonShape* polygonB, const b2Transform& xfB);
+ b2EPAxis ComputeEdgeSeparation();
+ b2EPAxis ComputePolygonSeparation();
+
+ enum VertexType
+ {
+ e_isolated,
+ e_concave,
+ e_convex
+ };
+
+ b2TempPolygon m_polygonB;
+
+ b2Transform m_xf;
+ b2Vec2 m_centroidB;
+ b2Vec2 m_v0, m_v1, m_v2, m_v3;
+ b2Vec2 m_normal0, m_normal1, m_normal2;
+ b2Vec2 m_normal;
+ VertexType m_type1, m_type2;
+ b2Vec2 m_lowerLimit, m_upperLimit;
+ float32 m_radius;
+ bool m_front;
+};
+
+// Algorithm:
+// 1. Classify v1 and v2
+// 2. Classify polygon centroid as front or back
+// 3. Flip normal if necessary
+// 4. Initialize normal range to [-pi, pi] about face normal
+// 5. Adjust normal range according to adjacent edges
+// 6. Visit each separating axes, only accept axes within the range
+// 7. Return if _any_ axis indicates separation
+// 8. Clip
+void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA,
+ const b2PolygonShape* polygonB, const b2Transform& xfB)
+{
+ m_xf = b2MulT(xfA, xfB);
+
+ m_centroidB = b2Mul(m_xf, polygonB->m_centroid);
+
+ m_v0 = edgeA->m_vertex0;
+ m_v1 = edgeA->m_vertex1;
+ m_v2 = edgeA->m_vertex2;
+ m_v3 = edgeA->m_vertex3;
+
+ bool hasVertex0 = edgeA->m_hasVertex0;
+ bool hasVertex3 = edgeA->m_hasVertex3;
+
+ b2Vec2 edge1 = m_v2 - m_v1;
+ edge1.Normalize();
+ m_normal1.Set(edge1.y, -edge1.x);
+ float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1);
+ float32 offset0 = 0.0f, offset2 = 0.0f;
+ bool convex1 = false, convex2 = false;
+
+ // Is there a preceding edge?
+ if (hasVertex0)
+ {
+ b2Vec2 edge0 = m_v1 - m_v0;
+ edge0.Normalize();
+ m_normal0.Set(edge0.y, -edge0.x);
+ convex1 = b2Cross(edge0, edge1) >= 0.0f;
+ offset0 = b2Dot(m_normal0, m_centroidB - m_v0);
+ }
+
+ // Is there a following edge?
+ if (hasVertex3)
+ {
+ b2Vec2 edge2 = m_v3 - m_v2;
+ edge2.Normalize();
+ m_normal2.Set(edge2.y, -edge2.x);
+ convex2 = b2Cross(edge1, edge2) > 0.0f;
+ offset2 = b2Dot(m_normal2, m_centroidB - m_v2);
+ }
+
+ // Determine front or back collision. Determine collision normal limits.
+ if (hasVertex0 && hasVertex3)
+ {
+ if (convex1 && convex2)
+ {
+ m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f;
+ if (m_front)
+ {
+ m_normal = m_normal1;
+ m_lowerLimit = m_normal0;
+ m_upperLimit = m_normal2;
+ }
+ else
+ {
+ m_normal = -m_normal1;
+ m_lowerLimit = -m_normal1;
+ m_upperLimit = -m_normal1;
+ }
+ }
+ else if (convex1)
+ {
+ m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f);
+ if (m_front)
+ {
+ m_normal = m_normal1;
+ m_lowerLimit = m_normal0;
+ m_upperLimit = m_normal1;
+ }
+ else
+ {
+ m_normal = -m_normal1;
+ m_lowerLimit = -m_normal2;
+ m_upperLimit = -m_normal1;
+ }
+ }
+ else if (convex2)
+ {
+ m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f);
+ if (m_front)
+ {
+ m_normal = m_normal1;
+ m_lowerLimit = m_normal1;
+ m_upperLimit = m_normal2;
+ }
+ else
+ {
+ m_normal = -m_normal1;
+ m_lowerLimit = -m_normal1;
+ m_upperLimit = -m_normal0;
+ }
+ }
+ else
+ {
+ m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f;
+ if (m_front)
+ {
+ m_normal = m_normal1;
+ m_lowerLimit = m_normal1;
+ m_upperLimit = m_normal1;
+ }
+ else
+ {
+ m_normal = -m_normal1;
+ m_lowerLimit = -m_normal2;
+ m_upperLimit = -m_normal0;
+ }
+ }
+ }
+ else if (hasVertex0)
+ {
+ if (convex1)
+ {
+ m_front = offset0 >= 0.0f || offset1 >= 0.0f;
+ if (m_front)
+ {
+ m_normal = m_normal1;
+ m_lowerLimit = m_normal0;
+ m_upperLimit = -m_normal1;
+ }
+ else
+ {
+ m_normal = -m_normal1;
+ m_lowerLimit = m_normal1;
+ m_upperLimit = -m_normal1;
+ }
+ }
+ else
+ {
+ m_front = offset0 >= 0.0f && offset1 >= 0.0f;
+ if (m_front)
+ {
+ m_normal = m_normal1;
+ m_lowerLimit = m_normal1;
+ m_upperLimit = -m_normal1;
+ }
+ else
+ {
+ m_normal = -m_normal1;
+ m_lowerLimit = m_normal1;
+ m_upperLimit = -m_normal0;
+ }
+ }
+ }
+ else if (hasVertex3)
+ {
+ if (convex2)
+ {
+ m_front = offset1 >= 0.0f || offset2 >= 0.0f;
+ if (m_front)
+ {
+ m_normal = m_normal1;
+ m_lowerLimit = -m_normal1;
+ m_upperLimit = m_normal2;
+ }
+ else
+ {
+ m_normal = -m_normal1;
+ m_lowerLimit = -m_normal1;
+ m_upperLimit = m_normal1;
+ }
+ }
+ else
+ {
+ m_front = offset1 >= 0.0f && offset2 >= 0.0f;
+ if (m_front)
+ {
+ m_normal = m_normal1;
+ m_lowerLimit = -m_normal1;
+ m_upperLimit = m_normal1;
+ }
+ else
+ {
+ m_normal = -m_normal1;
+ m_lowerLimit = -m_normal2;
+ m_upperLimit = m_normal1;
+ }
+ }
+ }
+ else
+ {
+ m_front = offset1 >= 0.0f;
+ if (m_front)
+ {
+ m_normal = m_normal1;
+ m_lowerLimit = -m_normal1;
+ m_upperLimit = -m_normal1;
+ }
+ else
+ {
+ m_normal = -m_normal1;
+ m_lowerLimit = m_normal1;
+ m_upperLimit = m_normal1;
+ }
+ }
+
+ // Get polygonB in frameA
+ m_polygonB.count = polygonB->m_vertexCount;
+ for (int32 i = 0; i < polygonB->m_vertexCount; ++i)
+ {
+ m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]);
+ m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]);
+ }
+
+ m_radius = 2.0f * b2_polygonRadius;
+
+ manifold->pointCount = 0;
+
+ b2EPAxis edgeAxis = ComputeEdgeSeparation();
+
+ // If no valid normal can be found than this edge should not collide.
+ if (edgeAxis.type == b2EPAxis::e_unknown)
+ {
+ return;
+ }
+
+ if (edgeAxis.separation > m_radius)
+ {
+ return;
+ }
+
+ b2EPAxis polygonAxis = ComputePolygonSeparation();
+ if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius)
+ {
+ return;
+ }
+
+ // Use hysteresis for jitter reduction.
+ const float32 k_relativeTol = 0.98f;
+ const float32 k_absoluteTol = 0.001f;
+
+ b2EPAxis primaryAxis;
+ if (polygonAxis.type == b2EPAxis::e_unknown)
+ {
+ primaryAxis = edgeAxis;
+ }
+ else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol)
+ {
+ primaryAxis = polygonAxis;
+ }
+ else
+ {
+ primaryAxis = edgeAxis;
+ }
+
+ b2ClipVertex ie[2];
+ b2ReferenceFace rf;
+ if (primaryAxis.type == b2EPAxis::e_edgeA)
+ {
+ manifold->type = b2Manifold::e_faceA;
+
+ // Search for the polygon normal that is most anti-parallel to the edge normal.
+ int32 bestIndex = 0;
+ float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]);
+ for (int32 i = 1; i < m_polygonB.count; ++i)
+ {
+ float32 value = b2Dot(m_normal, m_polygonB.normals[i]);
+ if (value < bestValue)
+ {
+ bestValue = value;
+ bestIndex = i;
+ }
+ }
+
+ int32 i1 = bestIndex;
+ int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0;
+
+ ie[0].v = m_polygonB.vertices[i1];
+ ie[0].id.cf.indexA = 0;
+ ie[0].id.cf.indexB = i1;
+ ie[0].id.cf.typeA = b2ContactFeature::e_face;
+ ie[0].id.cf.typeB = b2ContactFeature::e_vertex;
+
+ ie[1].v = m_polygonB.vertices[i2];
+ ie[1].id.cf.indexA = 0;
+ ie[1].id.cf.indexB = i2;
+ ie[1].id.cf.typeA = b2ContactFeature::e_face;
+ ie[1].id.cf.typeB = b2ContactFeature::e_vertex;
+
+ if (m_front)
+ {
+ rf.i1 = 0;
+ rf.i2 = 1;
+ rf.v1 = m_v1;
+ rf.v2 = m_v2;
+ rf.normal = m_normal1;
+ }
+ else
+ {
+ rf.i1 = 1;
+ rf.i2 = 0;
+ rf.v1 = m_v2;
+ rf.v2 = m_v1;
+ rf.normal = -m_normal1;
+ }
+ }
+ else
+ {
+ manifold->type = b2Manifold::e_faceB;
+
+ ie[0].v = m_v1;
+ ie[0].id.cf.indexA = 0;
+ ie[0].id.cf.indexB = primaryAxis.index;
+ ie[0].id.cf.typeA = b2ContactFeature::e_vertex;
+ ie[0].id.cf.typeB = b2ContactFeature::e_face;
+
+ ie[1].v = m_v2;
+ ie[1].id.cf.indexA = 0;
+ ie[1].id.cf.indexB = primaryAxis.index;
+ ie[1].id.cf.typeA = b2ContactFeature::e_vertex;
+ ie[1].id.cf.typeB = b2ContactFeature::e_face;
+
+ rf.i1 = primaryAxis.index;
+ rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0;
+ rf.v1 = m_polygonB.vertices[rf.i1];
+ rf.v2 = m_polygonB.vertices[rf.i2];
+ rf.normal = m_polygonB.normals[rf.i1];
+ }
+
+ rf.sideNormal1.Set(rf.normal.y, -rf.normal.x);
+ rf.sideNormal2 = -rf.sideNormal1;
+ rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1);
+ rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2);
+
+ // Clip incident edge against extruded edge1 side edges.
+ b2ClipVertex clipPoints1[2];
+ b2ClipVertex clipPoints2[2];
+ int32 np;
+
+ // Clip to box side 1
+ np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1);
+
+ if (np < b2_maxManifoldPoints)
+ {
+ return;
+ }
+
+ // Clip to negative box side 1
+ np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2);
+
+ if (np < b2_maxManifoldPoints)
+ {
+ return;
+ }
+
+ // Now clipPoints2 contains the clipped points.
+ if (primaryAxis.type == b2EPAxis::e_edgeA)
+ {
+ manifold->localNormal = rf.normal;
+ manifold->localPoint = rf.v1;
+ }
+ else
+ {
+ manifold->localNormal = polygonB->m_normals[rf.i1];
+ manifold->localPoint = polygonB->m_vertices[rf.i1];
+ }
+
+ int32 pointCount = 0;
+ for (int32 i = 0; i < b2_maxManifoldPoints; ++i)
+ {
+ float32 separation;
+
+ separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1);
+
+ if (separation <= m_radius)
+ {
+ b2ManifoldPoint* cp = manifold->points + pointCount;
+
+ if (primaryAxis.type == b2EPAxis::e_edgeA)
+ {
+ cp->localPoint = b2MulT(m_xf, clipPoints2[i].v);
+ cp->id = clipPoints2[i].id;
+ }
+ else
+ {
+ cp->localPoint = clipPoints2[i].v;
+ cp->id.cf.typeA = clipPoints2[i].id.cf.typeB;
+ cp->id.cf.typeB = clipPoints2[i].id.cf.typeA;
+ cp->id.cf.indexA = clipPoints2[i].id.cf.indexB;
+ cp->id.cf.indexB = clipPoints2[i].id.cf.indexA;
+ }
+
+ ++pointCount;
+ }
+ }
+
+ manifold->pointCount = pointCount;
+}
+
+b2EPAxis b2EPCollider::ComputeEdgeSeparation()
+{
+ b2EPAxis axis;
+ axis.type = b2EPAxis::e_edgeA;
+ axis.index = m_front ? 0 : 1;
+ axis.separation = FLT_MAX;
+
+ for (int32 i = 0; i < m_polygonB.count; ++i)
+ {
+ float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1);
+ if (s < axis.separation)
+ {
+ axis.separation = s;
+ }
+ }
+
+ return axis;
+}
+
+b2EPAxis b2EPCollider::ComputePolygonSeparation()
+{
+ b2EPAxis axis;
+ axis.type = b2EPAxis::e_unknown;
+ axis.index = -1;
+ axis.separation = -FLT_MAX;
+
+ b2Vec2 perp(-m_normal.y, m_normal.x);
+
+ for (int32 i = 0; i < m_polygonB.count; ++i)
+ {
+ b2Vec2 n = -m_polygonB.normals[i];
+
+ float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1);
+ float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2);
+ float32 s = b2Min(s1, s2);
+
+ if (s > m_radius)
+ {
+ // No collision
+ axis.type = b2EPAxis::e_edgeB;
+ axis.index = i;
+ axis.separation = s;
+ return axis;
+ }
+
+ // Adjacency
+ if (b2Dot(n, perp) >= 0.0f)
+ {
+ if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop)
+ {
+ continue;
+ }
+ }
+ else
+ {
+ if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop)
+ {
+ continue;
+ }
+ }
+
+ if (s > axis.separation)
+ {
+ axis.type = b2EPAxis::e_edgeB;
+ axis.index = i;
+ axis.separation = s;
+ }
+ }
+
+ return axis;
+}
+
+void b2CollideEdgeAndPolygon( b2Manifold* manifold,
+ const b2EdgeShape* edgeA, const b2Transform& xfA,
+ const b2PolygonShape* polygonB, const b2Transform& xfB)
+{
+ b2EPCollider collider;
+ collider.Collide(manifold, edgeA, xfA, polygonB, xfB);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2CollidePolygon.cpp b/games/hillclimb/src/box2d/Box2D/Collision/b2CollidePolygon.cpp
new file mode 100644
index 00000000..2f0946b9
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2CollidePolygon.cpp
@@ -0,0 +1,317 @@
+/*
+* Copyright (c) 2006-2009 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/Collision/b2Collision.h>
+#include <Box2D/Collision/Shapes/b2PolygonShape.h>
+
+// Find the separation between poly1 and poly2 for a give edge normal on poly1.
+static float32 b2EdgeSeparation(const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1,
+ const b2PolygonShape* poly2, const b2Transform& xf2)
+{
+ const b2Vec2* vertices1 = poly1->m_vertices;
+ const b2Vec2* normals1 = poly1->m_normals;
+
+ int32 count2 = poly2->m_vertexCount;
+ const b2Vec2* vertices2 = poly2->m_vertices;
+
+ b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount);
+
+ // Convert normal from poly1's frame into poly2's frame.
+ b2Vec2 normal1World = b2Mul(xf1.q, normals1[edge1]);
+ b2Vec2 normal1 = b2MulT(xf2.q, normal1World);
+
+ // Find support vertex on poly2 for -normal.
+ int32 index = 0;
+ float32 minDot = b2_maxFloat;
+
+ for (int32 i = 0; i < count2; ++i)
+ {
+ float32 dot = b2Dot(vertices2[i], normal1);
+ if (dot < minDot)
+ {
+ minDot = dot;
+ index = i;
+ }
+ }
+
+ b2Vec2 v1 = b2Mul(xf1, vertices1[edge1]);
+ b2Vec2 v2 = b2Mul(xf2, vertices2[index]);
+ float32 separation = b2Dot(v2 - v1, normal1World);
+ return separation;
+}
+
+// Find the max separation between poly1 and poly2 using edge normals from poly1.
+static float32 b2FindMaxSeparation(int32* edgeIndex,
+ const b2PolygonShape* poly1, const b2Transform& xf1,
+ const b2PolygonShape* poly2, const b2Transform& xf2)
+{
+ int32 count1 = poly1->m_vertexCount;
+ const b2Vec2* normals1 = poly1->m_normals;
+
+ // Vector pointing from the centroid of poly1 to the centroid of poly2.
+ b2Vec2 d = b2Mul(xf2, poly2->m_centroid) - b2Mul(xf1, poly1->m_centroid);
+ b2Vec2 dLocal1 = b2MulT(xf1.q, d);
+
+ // Find edge normal on poly1 that has the largest projection onto d.
+ int32 edge = 0;
+ float32 maxDot = -b2_maxFloat;
+ for (int32 i = 0; i < count1; ++i)
+ {
+ float32 dot = b2Dot(normals1[i], dLocal1);
+ if (dot > maxDot)
+ {
+ maxDot = dot;
+ edge = i;
+ }
+ }
+
+ // Get the separation for the edge normal.
+ float32 s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2);
+
+ // Check the separation for the previous edge normal.
+ int32 prevEdge = edge - 1 >= 0 ? edge - 1 : count1 - 1;
+ float32 sPrev = b2EdgeSeparation(poly1, xf1, prevEdge, poly2, xf2);
+
+ // Check the separation for the next edge normal.
+ int32 nextEdge = edge + 1 < count1 ? edge + 1 : 0;
+ float32 sNext = b2EdgeSeparation(poly1, xf1, nextEdge, poly2, xf2);
+
+ // Find the best edge and the search direction.
+ int32 bestEdge;
+ float32 bestSeparation;
+ int32 increment;
+ if (sPrev > s && sPrev > sNext)
+ {
+ increment = -1;
+ bestEdge = prevEdge;
+ bestSeparation = sPrev;
+ }
+ else if (sNext > s)
+ {
+ increment = 1;
+ bestEdge = nextEdge;
+ bestSeparation = sNext;
+ }
+ else
+ {
+ *edgeIndex = edge;
+ return s;
+ }
+
+ // Perform a local search for the best edge normal.
+ for ( ; ; )
+ {
+ if (increment == -1)
+ edge = bestEdge - 1 >= 0 ? bestEdge - 1 : count1 - 1;
+ else
+ edge = bestEdge + 1 < count1 ? bestEdge + 1 : 0;
+
+ s = b2EdgeSeparation(poly1, xf1, edge, poly2, xf2);
+
+ if (s > bestSeparation)
+ {
+ bestEdge = edge;
+ bestSeparation = s;
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ *edgeIndex = bestEdge;
+ return bestSeparation;
+}
+
+static void b2FindIncidentEdge(b2ClipVertex c[2],
+ const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1,
+ const b2PolygonShape* poly2, const b2Transform& xf2)
+{
+ const b2Vec2* normals1 = poly1->m_normals;
+
+ int32 count2 = poly2->m_vertexCount;
+ const b2Vec2* vertices2 = poly2->m_vertices;
+ const b2Vec2* normals2 = poly2->m_normals;
+
+ b2Assert(0 <= edge1 && edge1 < poly1->m_vertexCount);
+
+ // Get the normal of the reference edge in poly2's frame.
+ b2Vec2 normal1 = b2MulT(xf2.q, b2Mul(xf1.q, normals1[edge1]));
+
+ // Find the incident edge on poly2.
+ int32 index = 0;
+ float32 minDot = b2_maxFloat;
+ for (int32 i = 0; i < count2; ++i)
+ {
+ float32 dot = b2Dot(normal1, normals2[i]);
+ if (dot < minDot)
+ {
+ minDot = dot;
+ index = i;
+ }
+ }
+
+ // Build the clip vertices for the incident edge.
+ int32 i1 = index;
+ int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0;
+
+ c[0].v = b2Mul(xf2, vertices2[i1]);
+ c[0].id.cf.indexA = (uint8)edge1;
+ c[0].id.cf.indexB = (uint8)i1;
+ c[0].id.cf.typeA = b2ContactFeature::e_face;
+ c[0].id.cf.typeB = b2ContactFeature::e_vertex;
+
+ c[1].v = b2Mul(xf2, vertices2[i2]);
+ c[1].id.cf.indexA = (uint8)edge1;
+ c[1].id.cf.indexB = (uint8)i2;
+ c[1].id.cf.typeA = b2ContactFeature::e_face;
+ c[1].id.cf.typeB = b2ContactFeature::e_vertex;
+}
+
+// Find edge normal of max separation on A - return if separating axis is found
+// Find edge normal of max separation on B - return if separation axis is found
+// Choose reference edge as min(minA, minB)
+// Find incident edge
+// Clip
+
+// The normal points from 1 to 2
+void b2CollidePolygons(b2Manifold* manifold,
+ const b2PolygonShape* polyA, const b2Transform& xfA,
+ const b2PolygonShape* polyB, const b2Transform& xfB)
+{
+ manifold->pointCount = 0;
+ float32 totalRadius = polyA->m_radius + polyB->m_radius;
+
+ int32 edgeA = 0;
+ float32 separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB);
+ if (separationA > totalRadius)
+ return;
+
+ int32 edgeB = 0;
+ float32 separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA);
+ if (separationB > totalRadius)
+ return;
+
+ const b2PolygonShape* poly1; // reference polygon
+ const b2PolygonShape* poly2; // incident polygon
+ b2Transform xf1, xf2;
+ int32 edge1; // reference edge
+ uint8 flip;
+ const float32 k_relativeTol = 0.98f;
+ const float32 k_absoluteTol = 0.001f;
+
+ if (separationB > k_relativeTol * separationA + k_absoluteTol)
+ {
+ poly1 = polyB;
+ poly2 = polyA;
+ xf1 = xfB;
+ xf2 = xfA;
+ edge1 = edgeB;
+ manifold->type = b2Manifold::e_faceB;
+ flip = 1;
+ }
+ else
+ {
+ poly1 = polyA;
+ poly2 = polyB;
+ xf1 = xfA;
+ xf2 = xfB;
+ edge1 = edgeA;
+ manifold->type = b2Manifold::e_faceA;
+ flip = 0;
+ }
+
+ b2ClipVertex incidentEdge[2];
+ b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2);
+
+ int32 count1 = poly1->m_vertexCount;
+ const b2Vec2* vertices1 = poly1->m_vertices;
+
+ int32 iv1 = edge1;
+ int32 iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0;
+
+ b2Vec2 v11 = vertices1[iv1];
+ b2Vec2 v12 = vertices1[iv2];
+
+ b2Vec2 localTangent = v12 - v11;
+ localTangent.Normalize();
+
+ b2Vec2 localNormal = b2Cross(localTangent, 1.0f);
+ b2Vec2 planePoint = 0.5f * (v11 + v12);
+
+ b2Vec2 tangent = b2Mul(xf1.q, localTangent);
+ b2Vec2 normal = b2Cross(tangent, 1.0f);
+
+ v11 = b2Mul(xf1, v11);
+ v12 = b2Mul(xf1, v12);
+
+ // Face offset.
+ float32 frontOffset = b2Dot(normal, v11);
+
+ // Side offsets, extended by polytope skin thickness.
+ float32 sideOffset1 = -b2Dot(tangent, v11) + totalRadius;
+ float32 sideOffset2 = b2Dot(tangent, v12) + totalRadius;
+
+ // Clip incident edge against extruded edge1 side edges.
+ b2ClipVertex clipPoints1[2];
+ b2ClipVertex clipPoints2[2];
+ int np;
+
+ // Clip to box side 1
+ np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1, iv1);
+
+ if (np < 2)
+ return;
+
+ // Clip to negative box side 1
+ np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2);
+
+ if (np < 2)
+ {
+ return;
+ }
+
+ // Now clipPoints2 contains the clipped points.
+ manifold->localNormal = localNormal;
+ manifold->localPoint = planePoint;
+
+ int32 pointCount = 0;
+ for (int32 i = 0; i < b2_maxManifoldPoints; ++i)
+ {
+ float32 separation = b2Dot(normal, clipPoints2[i].v) - frontOffset;
+
+ if (separation <= totalRadius)
+ {
+ b2ManifoldPoint* cp = manifold->points + pointCount;
+ cp->localPoint = b2MulT(xf2, clipPoints2[i].v);
+ cp->id = clipPoints2[i].id;
+ if (flip)
+ {
+ // Swap features
+ b2ContactFeature cf = cp->id.cf;
+ cp->id.cf.indexA = cf.indexB;
+ cp->id.cf.indexB = cf.indexA;
+ cp->id.cf.typeA = cf.typeB;
+ cp->id.cf.typeB = cf.typeA;
+ }
+ ++pointCount;
+ }
+ }
+
+ manifold->pointCount = pointCount;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2Collision.cpp b/games/hillclimb/src/box2d/Box2D/Collision/b2Collision.cpp
new file mode 100644
index 00000000..4b092f0c
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2Collision.cpp
@@ -0,0 +1,249 @@
+/*
+* Copyright (c) 2007-2009 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/Collision/b2Collision.h>
+#include <Box2D/Collision/b2Distance.h>
+
+void b2WorldManifold::Initialize(const b2Manifold* manifold,
+ const b2Transform& xfA, float32 radiusA,
+ const b2Transform& xfB, float32 radiusB)
+{
+ if (manifold->pointCount == 0)
+ {
+ return;
+ }
+
+ switch (manifold->type)
+ {
+ case b2Manifold::e_circles:
+ {
+ normal.Set(1.0f, 0.0f);
+ b2Vec2 pointA = b2Mul(xfA, manifold->localPoint);
+ b2Vec2 pointB = b2Mul(xfB, manifold->points[0].localPoint);
+ if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon)
+ {
+ normal = pointB - pointA;
+ normal.Normalize();
+ }
+
+ b2Vec2 cA = pointA + radiusA * normal;
+ b2Vec2 cB = pointB - radiusB * normal;
+ points[0] = 0.5f * (cA + cB);
+ }
+ break;
+
+ case b2Manifold::e_faceA:
+ {
+ normal = b2Mul(xfA.q, manifold->localNormal);
+ b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint);
+
+ for (int32 i = 0; i < manifold->pointCount; ++i)
+ {
+ b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint);
+ b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, normal)) * normal;
+ b2Vec2 cB = clipPoint - radiusB * normal;
+ points[i] = 0.5f * (cA + cB);
+ }
+ }
+ break;
+
+ case b2Manifold::e_faceB:
+ {
+ normal = b2Mul(xfB.q, manifold->localNormal);
+ b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint);
+
+ for (int32 i = 0; i < manifold->pointCount; ++i)
+ {
+ b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint);
+ b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, normal)) * normal;
+ b2Vec2 cA = clipPoint - radiusA * normal;
+ points[i] = 0.5f * (cA + cB);
+ }
+
+ // Ensure normal points from A to B.
+ normal = -normal;
+ }
+ break;
+ }
+}
+
+void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints],
+ const b2Manifold* manifold1, const b2Manifold* manifold2)
+{
+ for (int32 i = 0; i < b2_maxManifoldPoints; ++i)
+ {
+ state1[i] = b2_nullState;
+ state2[i] = b2_nullState;
+ }
+
+ // Detect persists and removes.
+ for (int32 i = 0; i < manifold1->pointCount; ++i)
+ {
+ b2ContactID id = manifold1->points[i].id;
+
+ state1[i] = b2_removeState;
+
+ for (int32 j = 0; j < manifold2->pointCount; ++j)
+ {
+ if (manifold2->points[j].id.key == id.key)
+ {
+ state1[i] = b2_persistState;
+ break;
+ }
+ }
+ }
+
+ // Detect persists and adds.
+ for (int32 i = 0; i < manifold2->pointCount; ++i)
+ {
+ b2ContactID id = manifold2->points[i].id;
+
+ state2[i] = b2_addState;
+
+ for (int32 j = 0; j < manifold1->pointCount; ++j)
+ {
+ if (manifold1->points[j].id.key == id.key)
+ {
+ state2[i] = b2_persistState;
+ break;
+ }
+ }
+ }
+}
+
+// From Real-time Collision Detection, p179.
+bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const
+{
+ float32 tmin = -b2_maxFloat;
+ float32 tmax = b2_maxFloat;
+
+ b2Vec2 p = input.p1;
+ b2Vec2 d = input.p2 - input.p1;
+ b2Vec2 absD = b2Abs(d);
+
+ b2Vec2 normal;
+
+ for (int32 i = 0; i < 2; ++i)
+ {
+ if (absD(i) < b2_epsilon)
+ {
+ // Parallel.
+ if (p(i) < lowerBound(i) || upperBound(i) < p(i))
+ {
+ return false;
+ }
+ }
+ else
+ {
+ float32 inv_d = 1.0f / d(i);
+ float32 t1 = (lowerBound(i) - p(i)) * inv_d;
+ float32 t2 = (upperBound(i) - p(i)) * inv_d;
+
+ // Sign of the normal vector.
+ float32 s = -1.0f;
+
+ if (t1 > t2)
+ {
+ b2Swap(t1, t2);
+ s = 1.0f;
+ }
+
+ // Push the min up
+ if (t1 > tmin)
+ {
+ normal.SetZero();
+ normal(i) = s;
+ tmin = t1;
+ }
+
+ // Pull the max down
+ tmax = b2Min(tmax, t2);
+
+ if (tmin > tmax)
+ {
+ return false;
+ }
+ }
+ }
+
+ // Does the ray start inside the box?
+ // Does the ray intersect beyond the max fraction?
+ if (tmin < 0.0f || input.maxFraction < tmin)
+ {
+ return false;
+ }
+
+ // Intersection.
+ output->fraction = tmin;
+ output->normal = normal;
+ return true;
+}
+
+// Sutherland-Hodgman clipping.
+int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2],
+ const b2Vec2& normal, float32 offset, int32 vertexIndexA)
+{
+ // Start with no output points
+ int32 numOut = 0;
+
+ // Calculate the distance of end points to the line
+ float32 distance0 = b2Dot(normal, vIn[0].v) - offset;
+ float32 distance1 = b2Dot(normal, vIn[1].v) - offset;
+
+ // If the points are behind the plane
+ if (distance0 <= 0.0f) vOut[numOut++] = vIn[0];
+ if (distance1 <= 0.0f) vOut[numOut++] = vIn[1];
+
+ // If the points are on different sides of the plane
+ if (distance0 * distance1 < 0.0f)
+ {
+ // Find intersection point of edge and plane
+ float32 interp = distance0 / (distance0 - distance1);
+ vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v);
+
+ // VertexA is hitting edgeB.
+ vOut[numOut].id.cf.indexA = vertexIndexA;
+ vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB;
+ vOut[numOut].id.cf.typeA = b2ContactFeature::e_vertex;
+ vOut[numOut].id.cf.typeB = b2ContactFeature::e_face;
+ ++numOut;
+ }
+
+ return numOut;
+}
+
+bool b2TestOverlap( const b2Shape* shapeA, int32 indexA,
+ const b2Shape* shapeB, int32 indexB,
+ const b2Transform& xfA, const b2Transform& xfB)
+{
+ b2DistanceInput input;
+ input.proxyA.Set(shapeA, indexA);
+ input.proxyB.Set(shapeB, indexB);
+ input.transformA = xfA;
+ input.transformB = xfB;
+ input.useRadii = true;
+
+ b2SimplexCache cache;
+ cache.count = 0;
+
+ b2DistanceOutput output;
+
+ b2Distance(&output, &cache, &input);
+
+ return output.distance < 10.0f * b2_epsilon;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2Collision.h b/games/hillclimb/src/box2d/Box2D/Collision/b2Collision.h
new file mode 100644
index 00000000..27897f70
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2Collision.h
@@ -0,0 +1,276 @@
+/*
+* Copyright (c) 2006-2009 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_COLLISION_H
+#define B2_COLLISION_H
+
+#include <Box2D/Common/b2Math.h>
+#include <climits>
+
+/// @file
+/// Structures and functions used for computing contact points, distance
+/// queries, and TOI queries.
+
+class b2Shape;
+class b2CircleShape;
+class b2EdgeShape;
+class b2PolygonShape;
+
+const uint8 b2_nullFeature = UCHAR_MAX;
+
+/// The features that intersect to form the contact point
+/// This must be 4 bytes or less.
+struct b2ContactFeature
+{
+ enum Type
+ {
+ e_vertex = 0,
+ e_face = 1
+ };
+
+ uint8 indexA; ///< Feature index on shapeA
+ uint8 indexB; ///< Feature index on shapeB
+ uint8 typeA; ///< The feature type on shapeA
+ uint8 typeB; ///< The feature type on shapeB
+};
+
+/// Contact ids to facilitate warm starting.
+union b2ContactID
+{
+ b2ContactFeature cf;
+ uint32 key; ///< Used to quickly compare contact ids.
+};
+
+/// A manifold point is a contact point belonging to a contact
+/// manifold. It holds details related to the geometry and dynamics
+/// of the contact points.
+/// The local point usage depends on the manifold type:
+/// -e_circles: the local center of circleB
+/// -e_faceA: the local center of cirlceB or the clip point of polygonB
+/// -e_faceB: the clip point of polygonA
+/// This structure is stored across time steps, so we keep it small.
+/// Note: the impulses are used for internal caching and may not
+/// provide reliable contact forces, especially for high speed collisions.
+struct b2ManifoldPoint
+{
+ b2Vec2 localPoint; ///< usage depends on manifold type
+ float32 normalImpulse; ///< the non-penetration impulse
+ float32 tangentImpulse; ///< the friction impulse
+ b2ContactID id; ///< uniquely identifies a contact point between two shapes
+};
+
+/// A manifold for two touching convex shapes.
+/// Box2D supports multiple types of contact:
+/// - clip point versus plane with radius
+/// - point versus point with radius (circles)
+/// The local point usage depends on the manifold type:
+/// -e_circles: the local center of circleA
+/// -e_faceA: the center of faceA
+/// -e_faceB: the center of faceB
+/// Similarly the local normal usage:
+/// -e_circles: not used
+/// -e_faceA: the normal on polygonA
+/// -e_faceB: the normal on polygonB
+/// We store contacts in this way so that position correction can
+/// account for movement, which is critical for continuous physics.
+/// All contact scenarios must be expressed in one of these types.
+/// This structure is stored across time steps, so we keep it small.
+struct b2Manifold
+{
+ enum Type
+ {
+ e_circles,
+ e_faceA,
+ e_faceB
+ };
+
+ b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of contact
+ b2Vec2 localNormal; ///< not use for Type::e_points
+ b2Vec2 localPoint; ///< usage depends on manifold type
+ Type type;
+ int32 pointCount; ///< the number of manifold points
+};
+
+/// This is used to compute the current state of a contact manifold.
+struct b2WorldManifold
+{
+ /// Evaluate the manifold with supplied transforms. This assumes
+ /// modest motion from the original state. This does not change the
+ /// point count, impulses, etc. The radii must come from the shapes
+ /// that generated the manifold.
+ void Initialize(const b2Manifold* manifold,
+ const b2Transform& xfA, float32 radiusA,
+ const b2Transform& xfB, float32 radiusB);
+
+ b2Vec2 normal; ///< world vector pointing from A to B
+ b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point of intersection)
+};
+
+/// This is used for determining the state of contact points.
+enum b2PointState
+{
+ b2_nullState, ///< point does not exist
+ b2_addState, ///< point was added in the update
+ b2_persistState, ///< point persisted across the update
+ b2_removeState ///< point was removed in the update
+};
+
+/// Compute the point states given two manifolds. The states pertain to the transition from manifold1
+/// to manifold2. So state1 is either persist or remove while state2 is either add or persist.
+void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints],
+ const b2Manifold* manifold1, const b2Manifold* manifold2);
+
+/// Used for computing contact manifolds.
+struct b2ClipVertex
+{
+ b2Vec2 v;
+ b2ContactID id;
+};
+
+/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
+struct b2RayCastInput
+{
+ b2Vec2 p1, p2;
+ float32 maxFraction;
+};
+
+/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2
+/// come from b2RayCastInput.
+struct b2RayCastOutput
+{
+ b2Vec2 normal;
+ float32 fraction;
+};
+
+/// An axis aligned bounding box.
+struct b2AABB
+{
+ /// Verify that the bounds are sorted.
+ bool IsValid() const;
+
+ /// Get the center of the AABB.
+ b2Vec2 GetCenter() const
+ {
+ return 0.5f * (lowerBound + upperBound);
+ }
+
+ /// Get the extents of the AABB (half-widths).
+ b2Vec2 GetExtents() const
+ {
+ return 0.5f * (upperBound - lowerBound);
+ }
+
+ /// Get the perimeter length
+ float32 GetPerimeter() const
+ {
+ float32 wx = upperBound.x - lowerBound.x;
+ float32 wy = upperBound.y - lowerBound.y;
+ return 2.0f * (wx + wy);
+ }
+
+ /// Combine an AABB into this one.
+ void Combine(const b2AABB& aabb)
+ {
+ lowerBound = b2Min(lowerBound, aabb.lowerBound);
+ upperBound = b2Max(upperBound, aabb.upperBound);
+ }
+
+ /// Combine two AABBs into this one.
+ void Combine(const b2AABB& aabb1, const b2AABB& aabb2)
+ {
+ lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound);
+ upperBound = b2Max(aabb1.upperBound, aabb2.upperBound);
+ }
+
+ /// Does this aabb contain the provided AABB.
+ bool Contains(const b2AABB& aabb) const
+ {
+ bool result = true;
+ result = result && lowerBound.x <= aabb.lowerBound.x;
+ result = result && lowerBound.y <= aabb.lowerBound.y;
+ result = result && aabb.upperBound.x <= upperBound.x;
+ result = result && aabb.upperBound.y <= upperBound.y;
+ return result;
+ }
+
+ bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const;
+
+ b2Vec2 lowerBound; ///< the lower vertex
+ b2Vec2 upperBound; ///< the upper vertex
+};
+
+/// Compute the collision manifold between two circles.
+void b2CollideCircles(b2Manifold* manifold,
+ const b2CircleShape* circleA, const b2Transform& xfA,
+ const b2CircleShape* circleB, const b2Transform& xfB);
+
+/// Compute the collision manifold between a polygon and a circle.
+void b2CollidePolygonAndCircle(b2Manifold* manifold,
+ const b2PolygonShape* polygonA, const b2Transform& xfA,
+ const b2CircleShape* circleB, const b2Transform& xfB);
+
+/// Compute the collision manifold between two polygons.
+void b2CollidePolygons(b2Manifold* manifold,
+ const b2PolygonShape* polygonA, const b2Transform& xfA,
+ const b2PolygonShape* polygonB, const b2Transform& xfB);
+
+/// Compute the collision manifold between an edge and a circle.
+void b2CollideEdgeAndCircle(b2Manifold* manifold,
+ const b2EdgeShape* polygonA, const b2Transform& xfA,
+ const b2CircleShape* circleB, const b2Transform& xfB);
+
+/// Compute the collision manifold between an edge and a circle.
+void b2CollideEdgeAndPolygon(b2Manifold* manifold,
+ const b2EdgeShape* edgeA, const b2Transform& xfA,
+ const b2PolygonShape* circleB, const b2Transform& xfB);
+
+/// Clipping for contact manifolds.
+int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2],
+ const b2Vec2& normal, float32 offset, int32 vertexIndexA);
+
+/// Determine if two generic shapes overlap.
+bool b2TestOverlap( const b2Shape* shapeA, int32 indexA,
+ const b2Shape* shapeB, int32 indexB,
+ const b2Transform& xfA, const b2Transform& xfB);
+
+// ---------------- Inline Functions ------------------------------------------
+
+inline bool b2AABB::IsValid() const
+{
+ b2Vec2 d = upperBound - lowerBound;
+ bool valid = d.x >= 0.0f && d.y >= 0.0f;
+ valid = valid && lowerBound.IsValid() && upperBound.IsValid();
+ return valid;
+}
+
+inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b)
+{
+ b2Vec2 d1, d2;
+ d1 = b.lowerBound - a.upperBound;
+ d2 = a.lowerBound - b.upperBound;
+
+ if (d1.x > 0.0f || d1.y > 0.0f)
+ return false;
+
+ if (d2.x > 0.0f || d2.y > 0.0f)
+ return false;
+
+ return true;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2Distance.cpp b/games/hillclimb/src/box2d/Box2D/Collision/b2Distance.cpp
new file mode 100644
index 00000000..1010c8c0
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2Distance.cpp
@@ -0,0 +1,603 @@
+/*
+* Copyright (c) 2007-2009 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/Collision/b2Distance.h>
+#include <Box2D/Collision/Shapes/b2CircleShape.h>
+#include <Box2D/Collision/Shapes/b2EdgeShape.h>
+#include <Box2D/Collision/Shapes/b2ChainShape.h>
+#include <Box2D/Collision/Shapes/b2PolygonShape.h>
+
+// GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates.
+int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
+
+void b2DistanceProxy::Set(const b2Shape* shape, int32 index)
+{
+ switch (shape->GetType())
+ {
+ case b2Shape::e_circle:
+ {
+ const b2CircleShape* circle = (b2CircleShape*)shape;
+ m_vertices = &circle->m_p;
+ m_count = 1;
+ m_radius = circle->m_radius;
+ }
+ break;
+
+ case b2Shape::e_polygon:
+ {
+ const b2PolygonShape* polygon = (b2PolygonShape*)shape;
+ m_vertices = polygon->m_vertices;
+ m_count = polygon->m_vertexCount;
+ m_radius = polygon->m_radius;
+ }
+ break;
+
+ case b2Shape::e_chain:
+ {
+ const b2ChainShape* chain = (b2ChainShape*)shape;
+ b2Assert(0 <= index && index < chain->m_count);
+
+ m_buffer[0] = chain->m_vertices[index];
+ if (index + 1 < chain->m_count)
+ {
+ m_buffer[1] = chain->m_vertices[index + 1];
+ }
+ else
+ {
+ m_buffer[1] = chain->m_vertices[0];
+ }
+
+ m_vertices = m_buffer;
+ m_count = 2;
+ m_radius = chain->m_radius;
+ }
+ break;
+
+ case b2Shape::e_edge:
+ {
+ const b2EdgeShape* edge = (b2EdgeShape*)shape;
+ m_vertices = &edge->m_vertex1;
+ m_count = 2;
+ m_radius = edge->m_radius;
+ }
+ break;
+
+ default:
+ b2Assert(false);
+ }
+}
+
+
+struct b2SimplexVertex
+{
+ b2Vec2 wA; // support point in proxyA
+ b2Vec2 wB; // support point in proxyB
+ b2Vec2 w; // wB - wA
+ float32 a; // barycentric coordinate for closest point
+ int32 indexA; // wA index
+ int32 indexB; // wB index
+};
+
+struct b2Simplex
+{
+ void ReadCache( const b2SimplexCache* cache,
+ const b2DistanceProxy* proxyA, const b2Transform& transformA,
+ const b2DistanceProxy* proxyB, const b2Transform& transformB)
+ {
+ b2Assert(cache->count <= 3);
+
+ // Copy data from cache.
+ m_count = cache->count;
+ b2SimplexVertex* vertices = &m_v1;
+ for (int32 i = 0; i < m_count; ++i)
+ {
+ b2SimplexVertex* v = vertices + i;
+ v->indexA = cache->indexA[i];
+ v->indexB = cache->indexB[i];
+ b2Vec2 wALocal = proxyA->GetVertex(v->indexA);
+ b2Vec2 wBLocal = proxyB->GetVertex(v->indexB);
+ v->wA = b2Mul(transformA, wALocal);
+ v->wB = b2Mul(transformB, wBLocal);
+ v->w = v->wB - v->wA;
+ v->a = 0.0f;
+ }
+
+ // Compute the new simplex metric, if it is substantially different than
+ // old metric then flush the simplex.
+ if (m_count > 1)
+ {
+ float32 metric1 = cache->metric;
+ float32 metric2 = GetMetric();
+ if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon)
+ {
+ // Reset the simplex.
+ m_count = 0;
+ }
+ }
+
+ // If the cache is empty or invalid ...
+ if (m_count == 0)
+ {
+ b2SimplexVertex* v = vertices + 0;
+ v->indexA = 0;
+ v->indexB = 0;
+ b2Vec2 wALocal = proxyA->GetVertex(0);
+ b2Vec2 wBLocal = proxyB->GetVertex(0);
+ v->wA = b2Mul(transformA, wALocal);
+ v->wB = b2Mul(transformB, wBLocal);
+ v->w = v->wB - v->wA;
+ m_count = 1;
+ }
+ }
+
+ void WriteCache(b2SimplexCache* cache) const
+ {
+ cache->metric = GetMetric();
+ cache->count = uint16(m_count);
+ const b2SimplexVertex* vertices = &m_v1;
+ for (int32 i = 0; i < m_count; ++i)
+ {
+ cache->indexA[i] = uint8(vertices[i].indexA);
+ cache->indexB[i] = uint8(vertices[i].indexB);
+ }
+ }
+
+ b2Vec2 GetSearchDirection() const
+ {
+ switch (m_count)
+ {
+ case 1:
+ return -m_v1.w;
+
+ case 2:
+ {
+ b2Vec2 e12 = m_v2.w - m_v1.w;
+ float32 sgn = b2Cross(e12, -m_v1.w);
+ if (sgn > 0.0f)
+ {
+ // Origin is left of e12.
+ return b2Cross(1.0f, e12);
+ }
+ else
+ {
+ // Origin is right of e12.
+ return b2Cross(e12, 1.0f);
+ }
+ }
+
+ default:
+ b2Assert(false);
+ return b2Vec2_zero;
+ }
+ }
+
+ b2Vec2 GetClosestPoint() const
+ {
+ switch (m_count)
+ {
+ case 0:
+ b2Assert(false);
+ return b2Vec2_zero;
+
+ case 1:
+ return m_v1.w;
+
+ case 2:
+ return m_v1.a * m_v1.w + m_v2.a * m_v2.w;
+
+ case 3:
+ return b2Vec2_zero;
+
+ default:
+ b2Assert(false);
+ return b2Vec2_zero;
+ }
+ }
+
+ void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const
+ {
+ switch (m_count)
+ {
+ case 0:
+ b2Assert(false);
+ break;
+
+ case 1:
+ *pA = m_v1.wA;
+ *pB = m_v1.wB;
+ break;
+
+ case 2:
+ *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA;
+ *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB;
+ break;
+
+ case 3:
+ *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA;
+ *pB = *pA;
+ break;
+
+ default:
+ b2Assert(false);
+ break;
+ }
+ }
+
+ float32 GetMetric() const
+ {
+ switch (m_count)
+ {
+ case 0:
+ b2Assert(false);
+ return 0.0;
+
+ case 1:
+ return 0.0f;
+
+ case 2:
+ return b2Distance(m_v1.w, m_v2.w);
+
+ case 3:
+ return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w);
+
+ default:
+ b2Assert(false);
+ return 0.0f;
+ }
+ }
+
+ void Solve2();
+ void Solve3();
+
+ b2SimplexVertex m_v1, m_v2, m_v3;
+ int32 m_count;
+};
+
+
+// Solve a line segment using barycentric coordinates.
+//
+// p = a1 * w1 + a2 * w2
+// a1 + a2 = 1
+//
+// The vector from the origin to the closest point on the line is
+// perpendicular to the line.
+// e12 = w2 - w1
+// dot(p, e) = 0
+// a1 * dot(w1, e) + a2 * dot(w2, e) = 0
+//
+// 2-by-2 linear system
+// [1 1 ][a1] = [1]
+// [w1.e12 w2.e12][a2] = [0]
+//
+// Define
+// d12_1 = dot(w2, e12)
+// d12_2 = -dot(w1, e12)
+// d12 = d12_1 + d12_2
+//
+// Solution
+// a1 = d12_1 / d12
+// a2 = d12_2 / d12
+void b2Simplex::Solve2()
+{
+ b2Vec2 w1 = m_v1.w;
+ b2Vec2 w2 = m_v2.w;
+ b2Vec2 e12 = w2 - w1;
+
+ // w1 region
+ float32 d12_2 = -b2Dot(w1, e12);
+ if (d12_2 <= 0.0f)
+ {
+ // a2 <= 0, so we clamp it to 0
+ m_v1.a = 1.0f;
+ m_count = 1;
+ return;
+ }
+
+ // w2 region
+ float32 d12_1 = b2Dot(w2, e12);
+ if (d12_1 <= 0.0f)
+ {
+ // a1 <= 0, so we clamp it to 0
+ m_v2.a = 1.0f;
+ m_count = 1;
+ m_v1 = m_v2;
+ return;
+ }
+
+ // Must be in e12 region.
+ float32 inv_d12 = 1.0f / (d12_1 + d12_2);
+ m_v1.a = d12_1 * inv_d12;
+ m_v2.a = d12_2 * inv_d12;
+ m_count = 2;
+}
+
+// Possible regions:
+// - points[2]
+// - edge points[0]-points[2]
+// - edge points[1]-points[2]
+// - inside the triangle
+void b2Simplex::Solve3()
+{
+ b2Vec2 w1 = m_v1.w;
+ b2Vec2 w2 = m_v2.w;
+ b2Vec2 w3 = m_v3.w;
+
+ // Edge12
+ // [1 1 ][a1] = [1]
+ // [w1.e12 w2.e12][a2] = [0]
+ // a3 = 0
+ b2Vec2 e12 = w2 - w1;
+ float32 w1e12 = b2Dot(w1, e12);
+ float32 w2e12 = b2Dot(w2, e12);
+ float32 d12_1 = w2e12;
+ float32 d12_2 = -w1e12;
+
+ // Edge13
+ // [1 1 ][a1] = [1]
+ // [w1.e13 w3.e13][a3] = [0]
+ // a2 = 0
+ b2Vec2 e13 = w3 - w1;
+ float32 w1e13 = b2Dot(w1, e13);
+ float32 w3e13 = b2Dot(w3, e13);
+ float32 d13_1 = w3e13;
+ float32 d13_2 = -w1e13;
+
+ // Edge23
+ // [1 1 ][a2] = [1]
+ // [w2.e23 w3.e23][a3] = [0]
+ // a1 = 0
+ b2Vec2 e23 = w3 - w2;
+ float32 w2e23 = b2Dot(w2, e23);
+ float32 w3e23 = b2Dot(w3, e23);
+ float32 d23_1 = w3e23;
+ float32 d23_2 = -w2e23;
+
+ // Triangle123
+ float32 n123 = b2Cross(e12, e13);
+
+ float32 d123_1 = n123 * b2Cross(w2, w3);
+ float32 d123_2 = n123 * b2Cross(w3, w1);
+ float32 d123_3 = n123 * b2Cross(w1, w2);
+
+ // w1 region
+ if (d12_2 <= 0.0f && d13_2 <= 0.0f)
+ {
+ m_v1.a = 1.0f;
+ m_count = 1;
+ return;
+ }
+
+ // e12
+ if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f)
+ {
+ float32 inv_d12 = 1.0f / (d12_1 + d12_2);
+ m_v1.a = d12_1 * inv_d12;
+ m_v2.a = d12_2 * inv_d12;
+ m_count = 2;
+ return;
+ }
+
+ // e13
+ if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f)
+ {
+ float32 inv_d13 = 1.0f / (d13_1 + d13_2);
+ m_v1.a = d13_1 * inv_d13;
+ m_v3.a = d13_2 * inv_d13;
+ m_count = 2;
+ m_v2 = m_v3;
+ return;
+ }
+
+ // w2 region
+ if (d12_1 <= 0.0f && d23_2 <= 0.0f)
+ {
+ m_v2.a = 1.0f;
+ m_count = 1;
+ m_v1 = m_v2;
+ return;
+ }
+
+ // w3 region
+ if (d13_1 <= 0.0f && d23_1 <= 0.0f)
+ {
+ m_v3.a = 1.0f;
+ m_count = 1;
+ m_v1 = m_v3;
+ return;
+ }
+
+ // e23
+ if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f)
+ {
+ float32 inv_d23 = 1.0f / (d23_1 + d23_2);
+ m_v2.a = d23_1 * inv_d23;
+ m_v3.a = d23_2 * inv_d23;
+ m_count = 2;
+ m_v1 = m_v3;
+ return;
+ }
+
+ // Must be in triangle123
+ float32 inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3);
+ m_v1.a = d123_1 * inv_d123;
+ m_v2.a = d123_2 * inv_d123;
+ m_v3.a = d123_3 * inv_d123;
+ m_count = 3;
+}
+
+void b2Distance(b2DistanceOutput* output,
+ b2SimplexCache* cache,
+ const b2DistanceInput* input)
+{
+ ++b2_gjkCalls;
+
+ const b2DistanceProxy* proxyA = &input->proxyA;
+ const b2DistanceProxy* proxyB = &input->proxyB;
+
+ b2Transform transformA = input->transformA;
+ b2Transform transformB = input->transformB;
+
+ // Initialize the simplex.
+ b2Simplex simplex;
+ simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB);
+
+ // Get simplex vertices as an array.
+ b2SimplexVertex* vertices = &simplex.m_v1;
+ const int32 k_maxIters = 20;
+
+ // These store the vertices of the last simplex so that we
+ // can check for duplicates and prevent cycling.
+ int32 saveA[3], saveB[3];
+ int32 saveCount = 0;
+
+ b2Vec2 closestPoint = simplex.GetClosestPoint();
+ float32 distanceSqr1 = closestPoint.LengthSquared();
+ float32 distanceSqr2 = distanceSqr1;
+
+ // Main iteration loop.
+ int32 iter = 0;
+ while (iter < k_maxIters)
+ {
+ // Copy simplex so we can identify duplicates.
+ saveCount = simplex.m_count;
+ for (int32 i = 0; i < saveCount; ++i)
+ {
+ saveA[i] = vertices[i].indexA;
+ saveB[i] = vertices[i].indexB;
+ }
+
+ switch (simplex.m_count)
+ {
+ case 1:
+ break;
+
+ case 2:
+ simplex.Solve2();
+ break;
+
+ case 3:
+ simplex.Solve3();
+ break;
+
+ default:
+ b2Assert(false);
+ }
+
+ // If we have 3 points, then the origin is in the corresponding triangle.
+ if (simplex.m_count == 3)
+ {
+ break;
+ }
+
+ // Compute closest point.
+ b2Vec2 p = simplex.GetClosestPoint();
+ distanceSqr2 = p.LengthSquared();
+
+ // Ensure progress
+ if (distanceSqr2 >= distanceSqr1)
+ {
+ //break;
+ }
+ distanceSqr1 = distanceSqr2;
+
+ // Get search direction.
+ b2Vec2 d = simplex.GetSearchDirection();
+
+ // Ensure the search direction is numerically fit.
+ if (d.LengthSquared() < b2_epsilon * b2_epsilon)
+ {
+ // The origin is probably contained by a line segment
+ // or triangle. Thus the shapes are overlapped.
+
+ // We can't return zero here even though there may be overlap.
+ // In case the simplex is a point, segment, or triangle it is difficult
+ // to determine if the origin is contained in the CSO or very close to it.
+ break;
+ }
+
+ // Compute a tentative new simplex vertex using support points.
+ b2SimplexVertex* vertex = vertices + simplex.m_count;
+ vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d));
+ vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA));
+ b2Vec2 wBLocal;
+ vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d));
+ vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB));
+ vertex->w = vertex->wB - vertex->wA;
+
+ // Iteration count is equated to the number of support point calls.
+ ++iter;
+ ++b2_gjkIters;
+
+ // Check for duplicate support points. This is the main termination criteria.
+ bool duplicate = false;
+ for (int32 i = 0; i < saveCount; ++i)
+ {
+ if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i])
+ {
+ duplicate = true;
+ break;
+ }
+ }
+
+ // If we found a duplicate support point we must exit to avoid cycling.
+ if (duplicate)
+ {
+ break;
+ }
+
+ // New vertex is ok and needed.
+ ++simplex.m_count;
+ }
+
+ b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter);
+
+ // Prepare output.
+ simplex.GetWitnessPoints(&output->pointA, &output->pointB);
+ output->distance = b2Distance(output->pointA, output->pointB);
+ output->iterations = iter;
+
+ // Cache the simplex.
+ simplex.WriteCache(cache);
+
+ // Apply radii if requested.
+ if (input->useRadii)
+ {
+ float32 rA = proxyA->m_radius;
+ float32 rB = proxyB->m_radius;
+
+ if (output->distance > rA + rB && output->distance > b2_epsilon)
+ {
+ // Shapes are still no overlapped.
+ // Move the witness points to the outer surface.
+ output->distance -= rA + rB;
+ b2Vec2 normal = output->pointB - output->pointA;
+ normal.Normalize();
+ output->pointA += rA * normal;
+ output->pointB -= rB * normal;
+ }
+ else
+ {
+ // Shapes are overlapped when radii are considered.
+ // Move the witness points to the middle.
+ b2Vec2 p = 0.5f * (output->pointA + output->pointB);
+ output->pointA = p;
+ output->pointB = p;
+ output->distance = 0.0f;
+ }
+ }
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2Distance.h b/games/hillclimb/src/box2d/Box2D/Collision/b2Distance.h
new file mode 100644
index 00000000..54ed1e13
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2Distance.h
@@ -0,0 +1,141 @@
+
+/*
+* Copyright (c) 2006-2009 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_DISTANCE_H
+#define B2_DISTANCE_H
+
+#include <Box2D/Common/b2Math.h>
+
+class b2Shape;
+
+/// A distance proxy is used by the GJK algorithm.
+/// It encapsulates any shape.
+struct b2DistanceProxy
+{
+ b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {}
+
+ /// Initialize the proxy using the given shape. The shape
+ /// must remain in scope while the proxy is in use.
+ void Set(const b2Shape* shape, int32 index);
+
+ /// Get the supporting vertex index in the given direction.
+ int32 GetSupport(const b2Vec2& d) const;
+
+ /// Get the supporting vertex in the given direction.
+ const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
+
+ /// Get the vertex count.
+ int32 GetVertexCount() const;
+
+ /// Get a vertex by index. Used by b2Distance.
+ const b2Vec2& GetVertex(int32 index) const;
+
+ b2Vec2 m_buffer[2];
+ const b2Vec2* m_vertices;
+ int32 m_count;
+ float32 m_radius;
+};
+
+/// Used to warm start b2Distance.
+/// Set count to zero on first call.
+struct b2SimplexCache
+{
+ float32 metric; ///< length or area
+ uint16 count;
+ uint8 indexA[3]; ///< vertices on shape A
+ uint8 indexB[3]; ///< vertices on shape B
+};
+
+/// Input for b2Distance.
+/// You have to option to use the shape radii
+/// in the computation. Even
+struct b2DistanceInput
+{
+ b2DistanceProxy proxyA;
+ b2DistanceProxy proxyB;
+ b2Transform transformA;
+ b2Transform transformB;
+ bool useRadii;
+};
+
+/// Output for b2Distance.
+struct b2DistanceOutput
+{
+ b2Vec2 pointA; ///< closest point on shapeA
+ b2Vec2 pointB; ///< closest point on shapeB
+ float32 distance;
+ int32 iterations; ///< number of GJK iterations used
+};
+
+/// Compute the closest points between two shapes. Supports any combination of:
+/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output.
+/// On the first call set b2SimplexCache.count to zero.
+void b2Distance(b2DistanceOutput* output,
+ b2SimplexCache* cache,
+ const b2DistanceInput* input);
+
+
+//////////////////////////////////////////////////////////////////////////
+
+inline int32 b2DistanceProxy::GetVertexCount() const
+{
+ return m_count;
+}
+
+inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const
+{
+ b2Assert(0 <= index && index < m_count);
+ return m_vertices[index];
+}
+
+inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const
+{
+ int32 bestIndex = 0;
+ float32 bestValue = b2Dot(m_vertices[0], d);
+ for (int32 i = 1; i < m_count; ++i)
+ {
+ float32 value = b2Dot(m_vertices[i], d);
+ if (value > bestValue)
+ {
+ bestIndex = i;
+ bestValue = value;
+ }
+ }
+
+ return bestIndex;
+}
+
+inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const
+{
+ int32 bestIndex = 0;
+ float32 bestValue = b2Dot(m_vertices[0], d);
+ for (int32 i = 1; i < m_count; ++i)
+ {
+ float32 value = b2Dot(m_vertices[i], d);
+ if (value > bestValue)
+ {
+ bestIndex = i;
+ bestValue = value;
+ }
+ }
+
+ return m_vertices[bestIndex];
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2DynamicTree.cpp b/games/hillclimb/src/box2d/Box2D/Collision/b2DynamicTree.cpp
new file mode 100644
index 00000000..1a42c3a5
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2DynamicTree.cpp
@@ -0,0 +1,771 @@
+/*
+* Copyright (c) 2009 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/Collision/b2DynamicTree.h>
+#include <cstring>
+#include <cfloat>
+using namespace std;
+
+
+b2DynamicTree::b2DynamicTree()
+{
+ m_root = b2_nullNode;
+
+ m_nodeCapacity = 16;
+ m_nodeCount = 0;
+ m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode));
+ memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode));
+
+ // Build a linked list for the free list.
+ for (int32 i = 0; i < m_nodeCapacity - 1; ++i)
+ {
+ m_nodes[i].next = i + 1;
+ m_nodes[i].height = -1;
+ }
+ m_nodes[m_nodeCapacity-1].next = b2_nullNode;
+ m_nodes[m_nodeCapacity-1].height = -1;
+ m_freeList = 0;
+
+ m_path = 0;
+
+ m_insertionCount = 0;
+}
+
+b2DynamicTree::~b2DynamicTree()
+{
+ // This frees the entire tree in one shot.
+ b2Free(m_nodes);
+}
+
+// Allocate a node from the pool. Grow the pool if necessary.
+int32 b2DynamicTree::AllocateNode()
+{
+ // Expand the node pool as needed.
+ if (m_freeList == b2_nullNode)
+ {
+ b2Assert(m_nodeCount == m_nodeCapacity);
+
+ // The free list is empty. Rebuild a bigger pool.
+ b2TreeNode* oldNodes = m_nodes;
+ m_nodeCapacity *= 2;
+ m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode));
+ memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode));
+ b2Free(oldNodes);
+
+ // Build a linked list for the free list. The parent
+ // pointer becomes the "next" pointer.
+ for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i)
+ {
+ m_nodes[i].next = i + 1;
+ m_nodes[i].height = -1;
+ }
+ m_nodes[m_nodeCapacity-1].next = b2_nullNode;
+ m_nodes[m_nodeCapacity-1].height = -1;
+ m_freeList = m_nodeCount;
+ }
+
+ // Peel a node off the free list.
+ int32 nodeId = m_freeList;
+ m_freeList = m_nodes[nodeId].next;
+ m_nodes[nodeId].parent = b2_nullNode;
+ m_nodes[nodeId].child1 = b2_nullNode;
+ m_nodes[nodeId].child2 = b2_nullNode;
+ m_nodes[nodeId].height = 0;
+ m_nodes[nodeId].userData = NULL;
+ ++m_nodeCount;
+ return nodeId;
+}
+
+// Return a node to the pool.
+void b2DynamicTree::FreeNode(int32 nodeId)
+{
+ b2Assert(0 <= nodeId && nodeId < m_nodeCapacity);
+ b2Assert(0 < m_nodeCount);
+ m_nodes[nodeId].next = m_freeList;
+ m_nodes[nodeId].height = -1;
+ m_freeList = nodeId;
+ --m_nodeCount;
+}
+
+// Create a proxy in the tree as a leaf node. We return the index
+// of the node instead of a pointer so that we can grow
+// the node pool.
+int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData)
+{
+ int32 proxyId = AllocateNode();
+
+ // Fatten the aabb.
+ b2Vec2 r(b2_aabbExtension, b2_aabbExtension);
+ m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r;
+ m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r;
+ m_nodes[proxyId].userData = userData;
+ m_nodes[proxyId].height = 0;
+
+ InsertLeaf(proxyId);
+
+ return proxyId;
+}
+
+void b2DynamicTree::DestroyProxy(int32 proxyId)
+{
+ b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
+ b2Assert(m_nodes[proxyId].IsLeaf());
+
+ RemoveLeaf(proxyId);
+ FreeNode(proxyId);
+}
+
+bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement)
+{
+ b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
+
+ b2Assert(m_nodes[proxyId].IsLeaf());
+
+ if (m_nodes[proxyId].aabb.Contains(aabb))
+ {
+ return false;
+ }
+
+ RemoveLeaf(proxyId);
+
+ // Extend AABB.
+ b2AABB b = aabb;
+ b2Vec2 r(b2_aabbExtension, b2_aabbExtension);
+ b.lowerBound = b.lowerBound - r;
+ b.upperBound = b.upperBound + r;
+
+ // Predict AABB displacement.
+ b2Vec2 d = b2_aabbMultiplier * displacement;
+
+ if (d.x < 0.0f)
+ {
+ b.lowerBound.x += d.x;
+ }
+ else
+ {
+ b.upperBound.x += d.x;
+ }
+
+ if (d.y < 0.0f)
+ {
+ b.lowerBound.y += d.y;
+ }
+ else
+ {
+ b.upperBound.y += d.y;
+ }
+
+ m_nodes[proxyId].aabb = b;
+
+ InsertLeaf(proxyId);
+ return true;
+}
+
+void b2DynamicTree::InsertLeaf(int32 leaf)
+{
+ ++m_insertionCount;
+
+ if (m_root == b2_nullNode)
+ {
+ m_root = leaf;
+ m_nodes[m_root].parent = b2_nullNode;
+ return;
+ }
+
+ // Find the best sibling for this node
+ b2AABB leafAABB = m_nodes[leaf].aabb;
+ int32 index = m_root;
+ while (m_nodes[index].IsLeaf() == false)
+ {
+ int32 child1 = m_nodes[index].child1;
+ int32 child2 = m_nodes[index].child2;
+
+ float32 area = m_nodes[index].aabb.GetPerimeter();
+
+ b2AABB combinedAABB;
+ combinedAABB.Combine(m_nodes[index].aabb, leafAABB);
+ float32 combinedArea = combinedAABB.GetPerimeter();
+
+ // Cost of creating a new parent for this node and the new leaf
+ float32 cost = 2.0f * combinedArea;
+
+ // Minimum cost of pushing the leaf further down the tree
+ float32 inheritanceCost = 2.0f * (combinedArea - area);
+
+ // Cost of descending into child1
+ float32 cost1;
+ if (m_nodes[child1].IsLeaf())
+ {
+ b2AABB aabb;
+ aabb.Combine(leafAABB, m_nodes[child1].aabb);
+ cost1 = aabb.GetPerimeter() + inheritanceCost;
+ }
+ else
+ {
+ b2AABB aabb;
+ aabb.Combine(leafAABB, m_nodes[child1].aabb);
+ float32 oldArea = m_nodes[child1].aabb.GetPerimeter();
+ float32 newArea = aabb.GetPerimeter();
+ cost1 = (newArea - oldArea) + inheritanceCost;
+ }
+
+ // Cost of descending into child2
+ float32 cost2;
+ if (m_nodes[child2].IsLeaf())
+ {
+ b2AABB aabb;
+ aabb.Combine(leafAABB, m_nodes[child2].aabb);
+ cost2 = aabb.GetPerimeter() + inheritanceCost;
+ }
+ else
+ {
+ b2AABB aabb;
+ aabb.Combine(leafAABB, m_nodes[child2].aabb);
+ float32 oldArea = m_nodes[child2].aabb.GetPerimeter();
+ float32 newArea = aabb.GetPerimeter();
+ cost2 = newArea - oldArea + inheritanceCost;
+ }
+
+ // Descend according to the minimum cost.
+ if (cost < cost1 && cost < cost2)
+ {
+ break;
+ }
+
+ // Descend
+ if (cost1 < cost2)
+ {
+ index = child1;
+ }
+ else
+ {
+ index = child2;
+ }
+ }
+
+ int32 sibling = index;
+
+ // Create a new parent.
+ int32 oldParent = m_nodes[sibling].parent;
+ int32 newParent = AllocateNode();
+ m_nodes[newParent].parent = oldParent;
+ m_nodes[newParent].userData = NULL;
+ m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb);
+ m_nodes[newParent].height = m_nodes[sibling].height + 1;
+
+ if (oldParent != b2_nullNode)
+ {
+ // The sibling was not the root.
+ if (m_nodes[oldParent].child1 == sibling)
+ {
+ m_nodes[oldParent].child1 = newParent;
+ }
+ else
+ {
+ m_nodes[oldParent].child2 = newParent;
+ }
+
+ m_nodes[newParent].child1 = sibling;
+ m_nodes[newParent].child2 = leaf;
+ m_nodes[sibling].parent = newParent;
+ m_nodes[leaf].parent = newParent;
+ }
+ else
+ {
+ // The sibling was the root.
+ m_nodes[newParent].child1 = sibling;
+ m_nodes[newParent].child2 = leaf;
+ m_nodes[sibling].parent = newParent;
+ m_nodes[leaf].parent = newParent;
+ m_root = newParent;
+ }
+
+ // Walk back up the tree fixing heights and AABBs
+ index = m_nodes[leaf].parent;
+ while (index != b2_nullNode)
+ {
+ index = Balance(index);
+
+ int32 child1 = m_nodes[index].child1;
+ int32 child2 = m_nodes[index].child2;
+
+ b2Assert(child1 != b2_nullNode);
+ b2Assert(child2 != b2_nullNode);
+
+ m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height);
+ m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);
+
+ index = m_nodes[index].parent;
+ }
+
+ //Validate();
+}
+
+void b2DynamicTree::RemoveLeaf(int32 leaf)
+{
+ if (leaf == m_root)
+ {
+ m_root = b2_nullNode;
+ return;
+ }
+
+ int32 parent = m_nodes[leaf].parent;
+ int32 grandParent = m_nodes[parent].parent;
+ int32 sibling;
+ if (m_nodes[parent].child1 == leaf)
+ {
+ sibling = m_nodes[parent].child2;
+ }
+ else
+ {
+ sibling = m_nodes[parent].child1;
+ }
+
+ if (grandParent != b2_nullNode)
+ {
+ // Destroy parent and connect sibling to grandParent.
+ if (m_nodes[grandParent].child1 == parent)
+ {
+ m_nodes[grandParent].child1 = sibling;
+ }
+ else
+ {
+ m_nodes[grandParent].child2 = sibling;
+ }
+ m_nodes[sibling].parent = grandParent;
+ FreeNode(parent);
+
+ // Adjust ancestor bounds.
+ int32 index = grandParent;
+ while (index != b2_nullNode)
+ {
+ index = Balance(index);
+
+ int32 child1 = m_nodes[index].child1;
+ int32 child2 = m_nodes[index].child2;
+
+ m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);
+ m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height);
+
+ index = m_nodes[index].parent;
+ }
+ }
+ else
+ {
+ m_root = sibling;
+ m_nodes[sibling].parent = b2_nullNode;
+ FreeNode(parent);
+ }
+
+ //Validate();
+}
+
+// Perform a left or right rotation if node A is imbalanced.
+// Returns the new root index.
+int32 b2DynamicTree::Balance(int32 iA)
+{
+ b2Assert(iA != b2_nullNode);
+
+ b2TreeNode* A = m_nodes + iA;
+ if (A->IsLeaf() || A->height < 2)
+ {
+ return iA;
+ }
+
+ int32 iB = A->child1;
+ int32 iC = A->child2;
+ b2Assert(0 <= iB && iB < m_nodeCapacity);
+ b2Assert(0 <= iC && iC < m_nodeCapacity);
+
+ b2TreeNode* B = m_nodes + iB;
+ b2TreeNode* C = m_nodes + iC;
+
+ int32 balance = C->height - B->height;
+
+ // Rotate C up
+ if (balance > 1)
+ {
+ int32 iF = C->child1;
+ int32 iG = C->child2;
+ b2TreeNode* F = m_nodes + iF;
+ b2TreeNode* G = m_nodes + iG;
+ b2Assert(0 <= iF && iF < m_nodeCapacity);
+ b2Assert(0 <= iG && iG < m_nodeCapacity);
+
+ // Swap A and C
+ C->child1 = iA;
+ C->parent = A->parent;
+ A->parent = iC;
+
+ // A's old parent should point to C
+ if (C->parent != b2_nullNode)
+ {
+ if (m_nodes[C->parent].child1 == iA)
+ {
+ m_nodes[C->parent].child1 = iC;
+ }
+ else
+ {
+ b2Assert(m_nodes[C->parent].child2 == iA);
+ m_nodes[C->parent].child2 = iC;
+ }
+ }
+ else
+ {
+ m_root = iC;
+ }
+
+ // Rotate
+ if (F->height > G->height)
+ {
+ C->child2 = iF;
+ A->child2 = iG;
+ G->parent = iA;
+ A->aabb.Combine(B->aabb, G->aabb);
+ C->aabb.Combine(A->aabb, F->aabb);
+
+ A->height = 1 + b2Max(B->height, G->height);
+ C->height = 1 + b2Max(A->height, F->height);
+ }
+ else
+ {
+ C->child2 = iG;
+ A->child2 = iF;
+ F->parent = iA;
+ A->aabb.Combine(B->aabb, F->aabb);
+ C->aabb.Combine(A->aabb, G->aabb);
+
+ A->height = 1 + b2Max(B->height, F->height);
+ C->height = 1 + b2Max(A->height, G->height);
+ }
+
+ return iC;
+ }
+
+ // Rotate B up
+ if (balance < -1)
+ {
+ int32 iD = B->child1;
+ int32 iE = B->child2;
+ b2TreeNode* D = m_nodes + iD;
+ b2TreeNode* E = m_nodes + iE;
+ b2Assert(0 <= iD && iD < m_nodeCapacity);
+ b2Assert(0 <= iE && iE < m_nodeCapacity);
+
+ // Swap A and B
+ B->child1 = iA;
+ B->parent = A->parent;
+ A->parent = iB;
+
+ // A's old parent should point to B
+ if (B->parent != b2_nullNode)
+ {
+ if (m_nodes[B->parent].child1 == iA)
+ {
+ m_nodes[B->parent].child1 = iB;
+ }
+ else
+ {
+ b2Assert(m_nodes[B->parent].child2 == iA);
+ m_nodes[B->parent].child2 = iB;
+ }
+ }
+ else
+ {
+ m_root = iB;
+ }
+
+ // Rotate
+ if (D->height > E->height)
+ {
+ B->child2 = iD;
+ A->child1 = iE;
+ E->parent = iA;
+ A->aabb.Combine(C->aabb, E->aabb);
+ B->aabb.Combine(A->aabb, D->aabb);
+
+ A->height = 1 + b2Max(C->height, E->height);
+ B->height = 1 + b2Max(A->height, D->height);
+ }
+ else
+ {
+ B->child2 = iE;
+ A->child1 = iD;
+ D->parent = iA;
+ A->aabb.Combine(C->aabb, D->aabb);
+ B->aabb.Combine(A->aabb, E->aabb);
+
+ A->height = 1 + b2Max(C->height, D->height);
+ B->height = 1 + b2Max(A->height, E->height);
+ }
+
+ return iB;
+ }
+
+ return iA;
+}
+
+int32 b2DynamicTree::GetHeight() const
+{
+ if (m_root == b2_nullNode)
+ {
+ return 0;
+ }
+
+ return m_nodes[m_root].height;
+}
+
+//
+float32 b2DynamicTree::GetAreaRatio() const
+{
+ if (m_root == b2_nullNode)
+ {
+ return 0.0f;
+ }
+
+ const b2TreeNode* root = m_nodes + m_root;
+ float32 rootArea = root->aabb.GetPerimeter();
+
+ float32 totalArea = 0.0f;
+ for (int32 i = 0; i < m_nodeCapacity; ++i)
+ {
+ const b2TreeNode* node = m_nodes + i;
+ if (node->height < 0)
+ {
+ // Free node in pool
+ continue;
+ }
+
+ totalArea += node->aabb.GetPerimeter();
+ }
+
+ return totalArea / rootArea;
+}
+
+// Compute the height of a sub-tree.
+int32 b2DynamicTree::ComputeHeight(int32 nodeId) const
+{
+ b2Assert(0 <= nodeId && nodeId < m_nodeCapacity);
+ b2TreeNode* node = m_nodes + nodeId;
+
+ if (node->IsLeaf())
+ {
+ return 0;
+ }
+
+ int32 height1 = ComputeHeight(node->child1);
+ int32 height2 = ComputeHeight(node->child2);
+ return 1 + b2Max(height1, height2);
+}
+
+int32 b2DynamicTree::ComputeHeight() const
+{
+ int32 height = ComputeHeight(m_root);
+ return height;
+}
+
+void b2DynamicTree::ValidateStructure(int32 index) const
+{
+ if (index == b2_nullNode)
+ {
+ return;
+ }
+
+ if (index == m_root)
+ {
+ b2Assert(m_nodes[index].parent == b2_nullNode);
+ }
+
+ const b2TreeNode* node = m_nodes + index;
+
+ int32 child1 = node->child1;
+ int32 child2 = node->child2;
+
+ if (node->IsLeaf())
+ {
+ b2Assert(child1 == b2_nullNode);
+ b2Assert(child2 == b2_nullNode);
+ b2Assert(node->height == 0);
+ return;
+ }
+
+ b2Assert(0 <= child1 && child1 < m_nodeCapacity);
+ b2Assert(0 <= child2 && child2 < m_nodeCapacity);
+
+ b2Assert(m_nodes[child1].parent == index);
+ b2Assert(m_nodes[child2].parent == index);
+
+ ValidateStructure(child1);
+ ValidateStructure(child2);
+}
+
+void b2DynamicTree::ValidateMetrics(int32 index) const
+{
+ if (index == b2_nullNode)
+ {
+ return;
+ }
+
+ const b2TreeNode* node = m_nodes + index;
+
+ int32 child1 = node->child1;
+ int32 child2 = node->child2;
+
+ if (node->IsLeaf())
+ {
+ b2Assert(child1 == b2_nullNode);
+ b2Assert(child2 == b2_nullNode);
+ b2Assert(node->height == 0);
+ return;
+ }
+
+ b2Assert(0 <= child1 && child1 < m_nodeCapacity);
+ b2Assert(0 <= child2 && child2 < m_nodeCapacity);
+
+ int32 height1 = m_nodes[child1].height;
+ int32 height2 = m_nodes[child2].height;
+ int32 height;
+ height = 1 + b2Max(height1, height2);
+ b2Assert(node->height == height);
+
+ b2AABB aabb;
+ aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb);
+
+ b2Assert(aabb.lowerBound == node->aabb.lowerBound);
+ b2Assert(aabb.upperBound == node->aabb.upperBound);
+
+ ValidateMetrics(child1);
+ ValidateMetrics(child2);
+}
+
+void b2DynamicTree::Validate() const
+{
+ ValidateStructure(m_root);
+ ValidateMetrics(m_root);
+
+ int32 freeCount = 0;
+ int32 freeIndex = m_freeList;
+ while (freeIndex != b2_nullNode)
+ {
+ b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity);
+ freeIndex = m_nodes[freeIndex].next;
+ ++freeCount;
+ }
+
+ b2Assert(GetHeight() == ComputeHeight());
+
+ b2Assert(m_nodeCount + freeCount == m_nodeCapacity);
+}
+
+int32 b2DynamicTree::GetMaxBalance() const
+{
+ int32 maxBalance = 0;
+ for (int32 i = 0; i < m_nodeCapacity; ++i)
+ {
+ const b2TreeNode* node = m_nodes + i;
+ if (node->height <= 1)
+ {
+ continue;
+ }
+
+ b2Assert(node->IsLeaf() == false);
+
+ int32 child1 = node->child1;
+ int32 child2 = node->child2;
+ int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height);
+ maxBalance = b2Max(maxBalance, balance);
+ }
+
+ return maxBalance;
+}
+
+void b2DynamicTree::RebuildBottomUp()
+{
+ int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32));
+ int32 count = 0;
+
+ // Build array of leaves. Free the rest.
+ for (int32 i = 0; i < m_nodeCapacity; ++i)
+ {
+ if (m_nodes[i].height < 0)
+ {
+ // free node in pool
+ continue;
+ }
+
+ if (m_nodes[i].IsLeaf())
+ {
+ m_nodes[i].parent = b2_nullNode;
+ nodes[count] = i;
+ ++count;
+ }
+ else
+ {
+ FreeNode(i);
+ }
+ }
+
+ while (count > 1)
+ {
+ float32 minCost = b2_maxFloat;
+ int32 iMin = -1, jMin = -1;
+ for (int32 i = 0; i < count; ++i)
+ {
+ b2AABB aabbi = m_nodes[nodes[i]].aabb;
+
+ for (int32 j = i + 1; j < count; ++j)
+ {
+ b2AABB aabbj = m_nodes[nodes[j]].aabb;
+ b2AABB b;
+ b.Combine(aabbi, aabbj);
+ float32 cost = b.GetPerimeter();
+ if (cost < minCost)
+ {
+ iMin = i;
+ jMin = j;
+ minCost = cost;
+ }
+ }
+ }
+
+ int32 index1 = nodes[iMin];
+ int32 index2 = nodes[jMin];
+ b2TreeNode* child1 = m_nodes + index1;
+ b2TreeNode* child2 = m_nodes + index2;
+
+ int32 parentIndex = AllocateNode();
+ b2TreeNode* parent = m_nodes + parentIndex;
+ parent->child1 = index1;
+ parent->child2 = index2;
+ parent->height = 1 + b2Max(child1->height, child2->height);
+ parent->aabb.Combine(child1->aabb, child2->aabb);
+ parent->parent = b2_nullNode;
+
+ child1->parent = parentIndex;
+ child2->parent = parentIndex;
+
+ nodes[jMin] = nodes[count-1];
+ nodes[iMin] = parentIndex;
+ --count;
+ }
+
+ m_root = nodes[0];
+ b2Free(nodes);
+
+ Validate();
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2DynamicTree.h b/games/hillclimb/src/box2d/Box2D/Collision/b2DynamicTree.h
new file mode 100644
index 00000000..a9bfbf37
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2DynamicTree.h
@@ -0,0 +1,284 @@
+/*
+* Copyright (c) 2009 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_DYNAMIC_TREE_H
+#define B2_DYNAMIC_TREE_H
+
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Common/b2GrowableStack.h>
+
+#define b2_nullNode (-1)
+
+/// A node in the dynamic tree. The client does not interact with this directly.
+struct b2TreeNode
+{
+ bool IsLeaf() const
+ {
+ return child1 == b2_nullNode;
+ }
+
+ /// Enlarged AABB
+ b2AABB aabb;
+
+ void* userData;
+
+ union
+ {
+ int32 parent;
+ int32 next;
+ };
+
+ int32 child1;
+ int32 child2;
+
+ // leaf = 0, free node = -1
+ int32 height;
+};
+
+/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt.
+/// A dynamic tree arranges data in a binary tree to accelerate
+/// queries such as volume queries and ray casts. Leafs are proxies
+/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor
+/// so that the proxy AABB is bigger than the client object. This allows the client
+/// object to move by small amounts without triggering a tree update.
+///
+/// Nodes are pooled and relocatable, so we use node indices rather than pointers.
+class b2DynamicTree
+{
+public:
+ /// Constructing the tree initializes the node pool.
+ b2DynamicTree();
+
+ /// Destroy the tree, freeing the node pool.
+ ~b2DynamicTree();
+
+ /// Create a proxy. Provide a tight fitting AABB and a userData pointer.
+ int32 CreateProxy(const b2AABB& aabb, void* userData);
+
+ /// Destroy a proxy. This asserts if the id is invalid.
+ void DestroyProxy(int32 proxyId);
+
+ /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB,
+ /// then the proxy is removed from the tree and re-inserted. Otherwise
+ /// the function returns immediately.
+ /// @return true if the proxy was re-inserted.
+ bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement);
+
+ /// Get proxy user data.
+ /// @return the proxy user data or 0 if the id is invalid.
+ void* GetUserData(int32 proxyId) const;
+
+ /// Get the fat AABB for a proxy.
+ const b2AABB& GetFatAABB(int32 proxyId) const;
+
+ /// Query an AABB for overlapping proxies. The callback class
+ /// is called for each proxy that overlaps the supplied AABB.
+ template <typename T>
+ void Query(T* callback, const b2AABB& aabb) const;
+
+ /// Ray-cast against the proxies in the tree. This relies on the callback
+ /// to perform a exact ray-cast in the case were the proxy contains a shape.
+ /// The callback also performs the any collision filtering. This has performance
+ /// roughly equal to k * log(n), where k is the number of collisions and n is the
+ /// number of proxies in the tree.
+ /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
+ /// @param callback a callback class that is called for each proxy that is hit by the ray.
+ template <typename T>
+ void RayCast(T* callback, const b2RayCastInput& input) const;
+
+ /// Validate this tree. For testing.
+ void Validate() const;
+
+ /// Compute the height of the binary tree in O(N) time. Should not be
+ /// called often.
+ int32 GetHeight() const;
+
+ /// Get the maximum balance of an node in the tree. The balance is the difference
+ /// in height of the two children of a node.
+ int32 GetMaxBalance() const;
+
+ /// Get the ratio of the sum of the node areas to the root area.
+ float32 GetAreaRatio() const;
+
+ /// Build an optimal tree. Very expensive. For testing.
+ void RebuildBottomUp();
+
+private:
+
+ int32 AllocateNode();
+ void FreeNode(int32 node);
+
+ void InsertLeaf(int32 node);
+ void RemoveLeaf(int32 node);
+
+ int32 Balance(int32 index);
+
+ int32 ComputeHeight() const;
+ int32 ComputeHeight(int32 nodeId) const;
+
+ void ValidateStructure(int32 index) const;
+ void ValidateMetrics(int32 index) const;
+
+ int32 m_root;
+
+ b2TreeNode* m_nodes;
+ int32 m_nodeCount;
+ int32 m_nodeCapacity;
+
+ int32 m_freeList;
+
+ /// This is used to incrementally traverse the tree for re-balancing.
+ uint32 m_path;
+
+ int32 m_insertionCount;
+};
+
+inline void* b2DynamicTree::GetUserData(int32 proxyId) const
+{
+ b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
+ return m_nodes[proxyId].userData;
+}
+
+inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const
+{
+ b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
+ return m_nodes[proxyId].aabb;
+}
+
+template <typename T>
+inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const
+{
+ b2GrowableStack<int32, 256> stack;
+ stack.Push(m_root);
+
+ while (stack.GetCount() > 0)
+ {
+ int32 nodeId = stack.Pop();
+ if (nodeId == b2_nullNode)
+ {
+ continue;
+ }
+
+ const b2TreeNode* node = m_nodes + nodeId;
+
+ if (b2TestOverlap(node->aabb, aabb))
+ {
+ if (node->IsLeaf())
+ {
+ bool proceed = callback->QueryCallback(nodeId);
+ if (proceed == false)
+ {
+ return;
+ }
+ }
+ else
+ {
+ stack.Push(node->child1);
+ stack.Push(node->child2);
+ }
+ }
+ }
+}
+
+template <typename T>
+inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const
+{
+ b2Vec2 p1 = input.p1;
+ b2Vec2 p2 = input.p2;
+ b2Vec2 r = p2 - p1;
+ b2Assert(r.LengthSquared() > 0.0f);
+ r.Normalize();
+
+ // v is perpendicular to the segment.
+ b2Vec2 v = b2Cross(1.0f, r);
+ b2Vec2 abs_v = b2Abs(v);
+
+ // Separating axis for segment (Gino, p80).
+ // |dot(v, p1 - c)| > dot(|v|, h)
+
+ float32 maxFraction = input.maxFraction;
+
+ // Build a bounding box for the segment.
+ b2AABB segmentAABB;
+ {
+ b2Vec2 t = p1 + maxFraction * (p2 - p1);
+ segmentAABB.lowerBound = b2Min(p1, t);
+ segmentAABB.upperBound = b2Max(p1, t);
+ }
+
+ b2GrowableStack<int32, 256> stack;
+ stack.Push(m_root);
+
+ while (stack.GetCount() > 0)
+ {
+ int32 nodeId = stack.Pop();
+ if (nodeId == b2_nullNode)
+ {
+ continue;
+ }
+
+ const b2TreeNode* node = m_nodes + nodeId;
+
+ if (b2TestOverlap(node->aabb, segmentAABB) == false)
+ {
+ continue;
+ }
+
+ // Separating axis for segment (Gino, p80).
+ // |dot(v, p1 - c)| > dot(|v|, h)
+ b2Vec2 c = node->aabb.GetCenter();
+ b2Vec2 h = node->aabb.GetExtents();
+ float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h);
+ if (separation > 0.0f)
+ {
+ continue;
+ }
+
+ if (node->IsLeaf())
+ {
+ b2RayCastInput subInput;
+ subInput.p1 = input.p1;
+ subInput.p2 = input.p2;
+ subInput.maxFraction = maxFraction;
+
+ float32 value = callback->RayCastCallback(subInput, nodeId);
+
+ if (value == 0.0f)
+ {
+ // The client has terminated the ray cast.
+ return;
+ }
+
+ if (value > 0.0f)
+ {
+ // Update segment bounding box.
+ maxFraction = value;
+ b2Vec2 t = p1 + maxFraction * (p2 - p1);
+ segmentAABB.lowerBound = b2Min(p1, t);
+ segmentAABB.upperBound = b2Max(p1, t);
+ }
+ }
+ else
+ {
+ stack.Push(node->child1);
+ stack.Push(node->child2);
+ }
+ }
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2TimeOfImpact.cpp b/games/hillclimb/src/box2d/Box2D/Collision/b2TimeOfImpact.cpp
new file mode 100644
index 00000000..5c33e828
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2TimeOfImpact.cpp
@@ -0,0 +1,483 @@
+/*
+* Copyright (c) 2007-2009 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/Collision/b2Collision.h>
+#include <Box2D/Collision/b2Distance.h>
+#include <Box2D/Collision/b2TimeOfImpact.h>
+#include <Box2D/Collision/Shapes/b2CircleShape.h>
+#include <Box2D/Collision/Shapes/b2PolygonShape.h>
+
+#include <cstdio>
+using namespace std;
+
+int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters;
+int32 b2_toiRootIters, b2_toiMaxRootIters;
+
+struct b2SeparationFunction
+{
+ enum Type
+ {
+ e_points,
+ e_faceA,
+ e_faceB
+ };
+
+ // TODO_ERIN might not need to return the separation
+
+ float32 Initialize(const b2SimplexCache* cache,
+ const b2DistanceProxy* proxyA, const b2Sweep& sweepA,
+ const b2DistanceProxy* proxyB, const b2Sweep& sweepB,
+ float32 t1)
+ {
+ m_proxyA = proxyA;
+ m_proxyB = proxyB;
+ int32 count = cache->count;
+ b2Assert(0 < count && count < 3);
+
+ m_sweepA = sweepA;
+ m_sweepB = sweepB;
+
+ b2Transform xfA, xfB;
+ m_sweepA.GetTransform(&xfA, t1);
+ m_sweepB.GetTransform(&xfB, t1);
+
+ if (count == 1)
+ {
+ m_type = e_points;
+ b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]);
+ b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]);
+ b2Vec2 pointA = b2Mul(xfA, localPointA);
+ b2Vec2 pointB = b2Mul(xfB, localPointB);
+ m_axis = pointB - pointA;
+ float32 s = m_axis.Normalize();
+ return s;
+ }
+ else if (cache->indexA[0] == cache->indexA[1])
+ {
+ // Two points on B and one on A.
+ m_type = e_faceB;
+ b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]);
+ b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]);
+
+ m_axis = b2Cross(localPointB2 - localPointB1, 1.0f);
+ m_axis.Normalize();
+ b2Vec2 normal = b2Mul(xfB.q, m_axis);
+
+ m_localPoint = 0.5f * (localPointB1 + localPointB2);
+ b2Vec2 pointB = b2Mul(xfB, m_localPoint);
+
+ b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]);
+ b2Vec2 pointA = b2Mul(xfA, localPointA);
+
+ float32 s = b2Dot(pointA - pointB, normal);
+ if (s < 0.0f)
+ {
+ m_axis = -m_axis;
+ s = -s;
+ }
+ return s;
+ }
+ else
+ {
+ // Two points on A and one or two points on B.
+ m_type = e_faceA;
+ b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]);
+ b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]);
+
+ m_axis = b2Cross(localPointA2 - localPointA1, 1.0f);
+ m_axis.Normalize();
+ b2Vec2 normal = b2Mul(xfA.q, m_axis);
+
+ m_localPoint = 0.5f * (localPointA1 + localPointA2);
+ b2Vec2 pointA = b2Mul(xfA, m_localPoint);
+
+ b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]);
+ b2Vec2 pointB = b2Mul(xfB, localPointB);
+
+ float32 s = b2Dot(pointB - pointA, normal);
+ if (s < 0.0f)
+ {
+ m_axis = -m_axis;
+ s = -s;
+ }
+ return s;
+ }
+ }
+
+ float32 FindMinSeparation(int32* indexA, int32* indexB, float32 t) const
+ {
+ b2Transform xfA, xfB;
+ m_sweepA.GetTransform(&xfA, t);
+ m_sweepB.GetTransform(&xfB, t);
+
+ switch (m_type)
+ {
+ case e_points:
+ {
+ b2Vec2 axisA = b2MulT(xfA.q, m_axis);
+ b2Vec2 axisB = b2MulT(xfB.q, -m_axis);
+
+ *indexA = m_proxyA->GetSupport(axisA);
+ *indexB = m_proxyB->GetSupport(axisB);
+
+ b2Vec2 localPointA = m_proxyA->GetVertex(*indexA);
+ b2Vec2 localPointB = m_proxyB->GetVertex(*indexB);
+
+ b2Vec2 pointA = b2Mul(xfA, localPointA);
+ b2Vec2 pointB = b2Mul(xfB, localPointB);
+
+ float32 separation = b2Dot(pointB - pointA, m_axis);
+ return separation;
+ }
+
+ case e_faceA:
+ {
+ b2Vec2 normal = b2Mul(xfA.q, m_axis);
+ b2Vec2 pointA = b2Mul(xfA, m_localPoint);
+
+ b2Vec2 axisB = b2MulT(xfB.q, -normal);
+
+ *indexA = -1;
+ *indexB = m_proxyB->GetSupport(axisB);
+
+ b2Vec2 localPointB = m_proxyB->GetVertex(*indexB);
+ b2Vec2 pointB = b2Mul(xfB, localPointB);
+
+ float32 separation = b2Dot(pointB - pointA, normal);
+ return separation;
+ }
+
+ case e_faceB:
+ {
+ b2Vec2 normal = b2Mul(xfB.q, m_axis);
+ b2Vec2 pointB = b2Mul(xfB, m_localPoint);
+
+ b2Vec2 axisA = b2MulT(xfA.q, -normal);
+
+ *indexB = -1;
+ *indexA = m_proxyA->GetSupport(axisA);
+
+ b2Vec2 localPointA = m_proxyA->GetVertex(*indexA);
+ b2Vec2 pointA = b2Mul(xfA, localPointA);
+
+ float32 separation = b2Dot(pointA - pointB, normal);
+ return separation;
+ }
+
+ default:
+ b2Assert(false);
+ *indexA = -1;
+ *indexB = -1;
+ return 0.0f;
+ }
+ }
+
+ float32 Evaluate(int32 indexA, int32 indexB, float32 t) const
+ {
+ b2Transform xfA, xfB;
+ m_sweepA.GetTransform(&xfA, t);
+ m_sweepB.GetTransform(&xfB, t);
+
+ switch (m_type)
+ {
+ case e_points:
+ {
+ b2Vec2 axisA = b2MulT(xfA.q, m_axis);
+ b2Vec2 axisB = b2MulT(xfB.q, -m_axis);
+
+ b2Vec2 localPointA = m_proxyA->GetVertex(indexA);
+ b2Vec2 localPointB = m_proxyB->GetVertex(indexB);
+
+ b2Vec2 pointA = b2Mul(xfA, localPointA);
+ b2Vec2 pointB = b2Mul(xfB, localPointB);
+ float32 separation = b2Dot(pointB - pointA, m_axis);
+
+ return separation;
+ }
+
+ case e_faceA:
+ {
+ b2Vec2 normal = b2Mul(xfA.q, m_axis);
+ b2Vec2 pointA = b2Mul(xfA, m_localPoint);
+
+ b2Vec2 axisB = b2MulT(xfB.q, -normal);
+
+ b2Vec2 localPointB = m_proxyB->GetVertex(indexB);
+ b2Vec2 pointB = b2Mul(xfB, localPointB);
+
+ float32 separation = b2Dot(pointB - pointA, normal);
+ return separation;
+ }
+
+ case e_faceB:
+ {
+ b2Vec2 normal = b2Mul(xfB.q, m_axis);
+ b2Vec2 pointB = b2Mul(xfB, m_localPoint);
+
+ b2Vec2 axisA = b2MulT(xfA.q, -normal);
+
+ b2Vec2 localPointA = m_proxyA->GetVertex(indexA);
+ b2Vec2 pointA = b2Mul(xfA, localPointA);
+
+ float32 separation = b2Dot(pointA - pointB, normal);
+ return separation;
+ }
+
+ default:
+ b2Assert(false);
+ return 0.0f;
+ }
+ }
+
+ const b2DistanceProxy* m_proxyA;
+ const b2DistanceProxy* m_proxyB;
+ b2Sweep m_sweepA, m_sweepB;
+ Type m_type;
+ b2Vec2 m_localPoint;
+ b2Vec2 m_axis;
+};
+
+// CCD via the local separating axis method. This seeks progression
+// by computing the largest time at which separation is maintained.
+void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input)
+{
+ ++b2_toiCalls;
+
+ output->state = b2TOIOutput::e_unknown;
+ output->t = input->tMax;
+
+ const b2DistanceProxy* proxyA = &input->proxyA;
+ const b2DistanceProxy* proxyB = &input->proxyB;
+
+ b2Sweep sweepA = input->sweepA;
+ b2Sweep sweepB = input->sweepB;
+
+ // Large rotations can make the root finder fail, so we normalize the
+ // sweep angles.
+ sweepA.Normalize();
+ sweepB.Normalize();
+
+ float32 tMax = input->tMax;
+
+ float32 totalRadius = proxyA->m_radius + proxyB->m_radius;
+ float32 target = b2Max(b2_linearSlop, totalRadius - 3.0f * b2_linearSlop);
+ float32 tolerance = 0.25f * b2_linearSlop;
+ b2Assert(target > tolerance);
+
+ float32 t1 = 0.0f;
+ const int32 k_maxIterations = 20; // TODO_ERIN b2Settings
+ int32 iter = 0;
+
+ // Prepare input for distance query.
+ b2SimplexCache cache;
+ cache.count = 0;
+ b2DistanceInput distanceInput;
+ distanceInput.proxyA = input->proxyA;
+ distanceInput.proxyB = input->proxyB;
+ distanceInput.useRadii = false;
+
+ // The outer loop progressively attempts to compute new separating axes.
+ // This loop terminates when an axis is repeated (no progress is made).
+ for(;;)
+ {
+ b2Transform xfA, xfB;
+ sweepA.GetTransform(&xfA, t1);
+ sweepB.GetTransform(&xfB, t1);
+
+ // Get the distance between shapes. We can also use the results
+ // to get a separating axis.
+ distanceInput.transformA = xfA;
+ distanceInput.transformB = xfB;
+ b2DistanceOutput distanceOutput;
+ b2Distance(&distanceOutput, &cache, &distanceInput);
+
+ // If the shapes are overlapped, we give up on continuous collision.
+ if (distanceOutput.distance <= 0.0f)
+ {
+ // Failure!
+ output->state = b2TOIOutput::e_overlapped;
+ output->t = 0.0f;
+ break;
+ }
+
+ if (distanceOutput.distance < target + tolerance)
+ {
+ // Victory!
+ output->state = b2TOIOutput::e_touching;
+ output->t = t1;
+ break;
+ }
+
+ // Initialize the separating axis.
+ b2SeparationFunction fcn;
+ fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1);
+#if 0
+ // Dump the curve seen by the root finder
+ {
+ const int32 N = 100;
+ float32 dx = 1.0f / N;
+ float32 xs[N+1];
+ float32 fs[N+1];
+
+ float32 x = 0.0f;
+
+ for (int32 i = 0; i <= N; ++i)
+ {
+ sweepA.GetTransform(&xfA, x);
+ sweepB.GetTransform(&xfB, x);
+ float32 f = fcn.Evaluate(xfA, xfB) - target;
+
+ printf("%g %g\n", x, f);
+
+ xs[i] = x;
+ fs[i] = f;
+
+ x += dx;
+ }
+ }
+#endif
+
+ // Compute the TOI on the separating axis. We do this by successively
+ // resolving the deepest point. This loop is bounded by the number of vertices.
+ bool done = false;
+ float32 t2 = tMax;
+ int32 pushBackIter = 0;
+ for (;;)
+ {
+ // Find the deepest point at t2. Store the witness point indices.
+ int32 indexA, indexB;
+ float32 s2 = fcn.FindMinSeparation(&indexA, &indexB, t2);
+
+ // Is the final configuration separated?
+ if (s2 > target + tolerance)
+ {
+ // Victory!
+ output->state = b2TOIOutput::e_separated;
+ output->t = tMax;
+ done = true;
+ break;
+ }
+
+ // Has the separation reached tolerance?
+ if (s2 > target - tolerance)
+ {
+ // Advance the sweeps
+ t1 = t2;
+ break;
+ }
+
+ // Compute the initial separation of the witness points.
+ float32 s1 = fcn.Evaluate(indexA, indexB, t1);
+
+ // Check for initial overlap. This might happen if the root finder
+ // runs out of iterations.
+ if (s1 < target - tolerance)
+ {
+ output->state = b2TOIOutput::e_failed;
+ output->t = t1;
+ done = true;
+ break;
+ }
+
+ // Check for touching
+ if (s1 <= target + tolerance)
+ {
+ // Victory! t1 should hold the TOI (could be 0.0).
+ output->state = b2TOIOutput::e_touching;
+ output->t = t1;
+ done = true;
+ break;
+ }
+
+ // Compute 1D root of: f(x) - target = 0
+ int32 rootIterCount = 0;
+ float32 a1 = t1, a2 = t2;
+ for (;;)
+ {
+ // Use a mix of the secant rule and bisection.
+ float32 t;
+ if (rootIterCount & 1)
+ {
+ // Secant rule to improve convergence.
+ t = a1 + (target - s1) * (a2 - a1) / (s2 - s1);
+ }
+ else
+ {
+ // Bisection to guarantee progress.
+ t = 0.5f * (a1 + a2);
+ }
+
+ float32 s = fcn.Evaluate(indexA, indexB, t);
+
+ if (b2Abs(s - target) < tolerance)
+ {
+ // t2 holds a tentative value for t1
+ t2 = t;
+ break;
+ }
+
+ // Ensure we continue to bracket the root.
+ if (s > target)
+ {
+ a1 = t;
+ s1 = s;
+ }
+ else
+ {
+ a2 = t;
+ s2 = s;
+ }
+
+ ++rootIterCount;
+ ++b2_toiRootIters;
+
+ if (rootIterCount == 50)
+ {
+ break;
+ }
+ }
+
+ b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount);
+
+ ++pushBackIter;
+
+ if (pushBackIter == b2_maxPolygonVertices)
+ {
+ break;
+ }
+ }
+
+ ++iter;
+ ++b2_toiIters;
+
+ if (done)
+ {
+ break;
+ }
+
+ if (iter == k_maxIterations)
+ {
+ // Root finder got stuck. Semi-victory.
+ output->state = b2TOIOutput::e_failed;
+ output->t = t1;
+ break;
+ }
+ }
+
+ b2_toiMaxIters = b2Max(b2_toiMaxIters, iter);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Collision/b2TimeOfImpact.h b/games/hillclimb/src/box2d/Box2D/Collision/b2TimeOfImpact.h
new file mode 100644
index 00000000..179a1700
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Collision/b2TimeOfImpact.h
@@ -0,0 +1,58 @@
+/*
+* Copyright (c) 2006-2009 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_TIME_OF_IMPACT_H
+#define B2_TIME_OF_IMPACT_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Distance.h>
+
+/// Input parameters for b2TimeOfImpact
+struct b2TOIInput
+{
+ b2DistanceProxy proxyA;
+ b2DistanceProxy proxyB;
+ b2Sweep sweepA;
+ b2Sweep sweepB;
+ float32 tMax; // defines sweep interval [0, tMax]
+};
+
+// Output parameters for b2TimeOfImpact.
+struct b2TOIOutput
+{
+ enum State
+ {
+ e_unknown,
+ e_failed,
+ e_overlapped,
+ e_touching,
+ e_separated
+ };
+
+ State state;
+ float32 t;
+};
+
+/// Compute the upper bound on time before two shapes penetrate. Time is represented as
+/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate,
+/// non-tunneling collision. If you change the time interval, you should call this function
+/// again.
+/// Note: use b2Distance to compute the contact point and normal at the time of impact.
+void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input);
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2BlockAllocator.cpp b/games/hillclimb/src/box2d/Box2D/Common/b2BlockAllocator.cpp
new file mode 100644
index 00000000..f5060daa
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2BlockAllocator.cpp
@@ -0,0 +1,217 @@
+/*
+* Copyright (c) 2006-2009 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/Common/b2BlockAllocator.h>
+#include <cstdlib>
+#include <climits>
+#include <cstring>
+#include <memory>
+using namespace std;
+
+int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] =
+{
+ 16, // 0
+ 32, // 1
+ 64, // 2
+ 96, // 3
+ 128, // 4
+ 160, // 5
+ 192, // 6
+ 224, // 7
+ 256, // 8
+ 320, // 9
+ 384, // 10
+ 448, // 11
+ 512, // 12
+ 640, // 13
+};
+uint8 b2BlockAllocator::s_blockSizeLookup[b2_maxBlockSize + 1];
+bool b2BlockAllocator::s_blockSizeLookupInitialized;
+
+struct b2Chunk
+{
+ int32 blockSize;
+ b2Block* blocks;
+};
+
+struct b2Block
+{
+ b2Block* next;
+};
+
+b2BlockAllocator::b2BlockAllocator()
+{
+ b2Assert(b2_blockSizes < UCHAR_MAX);
+
+ m_chunkSpace = b2_chunkArrayIncrement;
+ m_chunkCount = 0;
+ m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk));
+
+ memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk));
+ memset(m_freeLists, 0, sizeof(m_freeLists));
+
+ if (s_blockSizeLookupInitialized == false)
+ {
+ int32 j = 0;
+ for (int32 i = 1; i <= b2_maxBlockSize; ++i)
+ {
+ b2Assert(j < b2_blockSizes);
+ if (i <= s_blockSizes[j])
+ {
+ s_blockSizeLookup[i] = (uint8)j;
+ }
+ else
+ {
+ ++j;
+ s_blockSizeLookup[i] = (uint8)j;
+ }
+ }
+
+ s_blockSizeLookupInitialized = true;
+ }
+}
+
+b2BlockAllocator::~b2BlockAllocator()
+{
+ for (int32 i = 0; i < m_chunkCount; ++i)
+ {
+ b2Free(m_chunks[i].blocks);
+ }
+
+ b2Free(m_chunks);
+}
+
+void* b2BlockAllocator::Allocate(int32 size)
+{
+ if (size == 0)
+ return NULL;
+
+ b2Assert(0 < size);
+
+ if (size > b2_maxBlockSize)
+ {
+ return b2Alloc(size);
+ }
+
+ int32 index = s_blockSizeLookup[size];
+ b2Assert(0 <= index && index < b2_blockSizes);
+
+ if (m_freeLists[index])
+ {
+ b2Block* block = m_freeLists[index];
+ m_freeLists[index] = block->next;
+ return block;
+ }
+ else
+ {
+ if (m_chunkCount == m_chunkSpace)
+ {
+ b2Chunk* oldChunks = m_chunks;
+ m_chunkSpace += b2_chunkArrayIncrement;
+ m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk));
+ memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk));
+ memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk));
+ b2Free(oldChunks);
+ }
+
+ b2Chunk* chunk = m_chunks + m_chunkCount;
+ chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize);
+#if defined(_DEBUG)
+ memset(chunk->blocks, 0xcd, b2_chunkSize);
+#endif
+ int32 blockSize = s_blockSizes[index];
+ chunk->blockSize = blockSize;
+ int32 blockCount = b2_chunkSize / blockSize;
+ b2Assert(blockCount * blockSize <= b2_chunkSize);
+ for (int32 i = 0; i < blockCount - 1; ++i)
+ {
+ b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i);
+ b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1));
+ block->next = next;
+ }
+ b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1));
+ last->next = NULL;
+
+ m_freeLists[index] = chunk->blocks->next;
+ ++m_chunkCount;
+
+ return chunk->blocks;
+ }
+}
+
+void b2BlockAllocator::Free(void* p, int32 size)
+{
+ if (size == 0)
+ {
+ return;
+ }
+
+ b2Assert(0 < size);
+
+ if (size > b2_maxBlockSize)
+ {
+ b2Free(p);
+ return;
+ }
+
+ int32 index = s_blockSizeLookup[size];
+ b2Assert(0 <= index && index < b2_blockSizes);
+
+#ifdef _DEBUG
+ // Verify the memory address and size is valid.
+ int32 blockSize = s_blockSizes[index];
+ bool found = false;
+ for (int32 i = 0; i < m_chunkCount; ++i)
+ {
+ b2Chunk* chunk = m_chunks + i;
+ if (chunk->blockSize != blockSize)
+ {
+ b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks ||
+ (int8*)chunk->blocks + b2_chunkSize <= (int8*)p);
+ }
+ else
+ {
+ if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize)
+ {
+ found = true;
+ }
+ }
+ }
+
+ b2Assert(found);
+
+ memset(p, 0xfd, blockSize);
+#endif
+
+ b2Block* block = (b2Block*)p;
+ block->next = m_freeLists[index];
+ m_freeLists[index] = block;
+}
+
+void b2BlockAllocator::Clear()
+{
+ for (int32 i = 0; i < m_chunkCount; ++i)
+ {
+ b2Free(m_chunks[i].blocks);
+ }
+
+ m_chunkCount = 0;
+ memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk));
+
+ memset(m_freeLists, 0, sizeof(m_freeLists));
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2BlockAllocator.h b/games/hillclimb/src/box2d/Box2D/Common/b2BlockAllocator.h
new file mode 100644
index 00000000..881b8f15
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2BlockAllocator.h
@@ -0,0 +1,63 @@
+/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): 2 KB chunks */
+/*
+* Copyright (c) 2006-2009 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_BLOCK_ALLOCATOR_H
+#define B2_BLOCK_ALLOCATOR_H
+
+#include <Box2D/Common/b2Settings.h>
+
+const int32 b2_chunkSize = 2 * 1024; // (16 KB in Box2D)
+const int32 b2_maxBlockSize = 640;
+const int32 b2_blockSizes = 14;
+const int32 b2_chunkArrayIncrement = 128;
+
+struct b2Block;
+struct b2Chunk;
+
+/// This is a small object allocator used for allocating small
+/// objects that persist for more than one time step.
+/// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp
+class b2BlockAllocator
+{
+public:
+ b2BlockAllocator();
+ ~b2BlockAllocator();
+
+ /// Allocate memory. This will use b2Alloc if the size is larger than b2_maxBlockSize.
+ void* Allocate(int32 size);
+
+ /// Free memory. This will use b2Free if the size is larger than b2_maxBlockSize.
+ void Free(void* p, int32 size);
+
+ void Clear();
+
+private:
+
+ b2Chunk* m_chunks;
+ int32 m_chunkCount;
+ int32 m_chunkSpace;
+
+ b2Block* m_freeLists[b2_blockSizes];
+
+ static int32 s_blockSizes[b2_blockSizes];
+ static uint8 s_blockSizeLookup[b2_maxBlockSize + 1];
+ static bool s_blockSizeLookupInitialized;
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2Draw.cpp b/games/hillclimb/src/box2d/Box2D/Common/b2Draw.cpp
new file mode 100644
index 00000000..327b5807
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2Draw.cpp
@@ -0,0 +1,44 @@
+/*
+* Copyright (c) 2011 Erin Catto http://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/Common/b2Draw.h>
+
+b2Draw::b2Draw()
+{
+ m_drawFlags = 0;
+}
+
+void b2Draw::SetFlags(uint32 flags)
+{
+ m_drawFlags = flags;
+}
+
+uint32 b2Draw::GetFlags() const
+{
+ return m_drawFlags;
+}
+
+void b2Draw::AppendFlags(uint32 flags)
+{
+ m_drawFlags |= flags;
+}
+
+void b2Draw::ClearFlags(uint32 flags)
+{
+ m_drawFlags &= ~flags;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2Draw.h b/games/hillclimb/src/box2d/Box2D/Common/b2Draw.h
new file mode 100644
index 00000000..de62dd61
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2Draw.h
@@ -0,0 +1,81 @@
+/*
+* Copyright (c) 2011 Erin Catto http://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/Common/b2Math.h>
+
+/// Color for debug drawing. Each value has the range [0,1].
+struct b2Color
+{
+ b2Color() {}
+ b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {}
+ void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; }
+ float32 r, g, b;
+};
+
+/// Implement and register this class with a b2World to provide debug drawing of physics
+/// entities in your game.
+class b2Draw
+{
+public:
+ b2Draw();
+
+ virtual ~b2Draw() {}
+
+ enum
+ {
+ e_shapeBit = 0x0001, ///< draw shapes
+ e_jointBit = 0x0002, ///< draw joint connections
+ e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes
+ e_pairBit = 0x0008, ///< draw broad-phase pairs
+ e_centerOfMassBit = 0x0010 ///< draw center of mass frame
+ };
+
+ /// Set the drawing flags.
+ void SetFlags(uint32 flags);
+
+ /// Get the drawing flags.
+ uint32 GetFlags() const;
+
+ /// Append flags to the current flags.
+ void AppendFlags(uint32 flags);
+
+ /// Clear flags from the current flags.
+ void ClearFlags(uint32 flags);
+
+ /// Draw a closed polygon provided in CCW order.
+ virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0;
+
+ /// Draw a solid closed polygon provided in CCW order.
+ virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0;
+
+ /// Draw a circle.
+ virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0;
+
+ /// Draw a solid circle.
+ virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0;
+
+ /// Draw a line segment.
+ virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0;
+
+ /// Draw a transform. Choose your own length scale.
+ /// @param xf a transform.
+ virtual void DrawTransform(const b2Transform& xf) = 0;
+
+protected:
+ uint32 m_drawFlags;
+};
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2GrowableStack.h b/games/hillclimb/src/box2d/Box2D/Common/b2GrowableStack.h
new file mode 100644
index 00000000..d2e07120
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2GrowableStack.h
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2010 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_GROWABLE_STACK_H
+#define B2_GROWABLE_STACK_H
+#include <Box2D/Common/b2Settings.h>
+#include <cstring>
+
+/// This is a growable LIFO stack with an initial capacity of N.
+/// If the stack size exceeds the initial capacity, the heap is used
+/// to increase the size of the stack.
+template <typename T, int32 N>
+class b2GrowableStack
+{
+public:
+ b2GrowableStack()
+ {
+ m_stack = m_array;
+ m_count = 0;
+ m_capacity = N;
+ }
+
+ ~b2GrowableStack()
+ {
+ if (m_stack != m_array)
+ {
+ b2Free(m_stack);
+ m_stack = NULL;
+ }
+ }
+
+ void Push(const T& element)
+ {
+ if (m_count == m_capacity)
+ {
+ T* old = m_stack;
+ m_capacity *= 2;
+ m_stack = (T*)b2Alloc(m_capacity * sizeof(T));
+ std::memcpy(m_stack, old, m_count * sizeof(T));
+ if (old != m_array)
+ {
+ b2Free(old);
+ }
+ }
+
+ m_stack[m_count] = element;
+ ++m_count;
+ }
+
+ T Pop()
+ {
+ b2Assert(m_count > 0);
+ --m_count;
+ return m_stack[m_count];
+ }
+
+ int32 GetCount()
+ {
+ return m_count;
+ }
+
+private:
+ T* m_stack;
+ T m_array[N];
+ int32 m_count;
+ int32 m_capacity;
+};
+
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2Math.cpp b/games/hillclimb/src/box2d/Box2D/Common/b2Math.cpp
new file mode 100644
index 00000000..4974fe18
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2Math.cpp
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2007-2009 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/Common/b2Math.h>
+
+const b2Vec2 b2Vec2_zero(0.0f, 0.0f);
+
+/// Solve A * x = b, where b is a column vector. This is more efficient
+/// than computing the inverse in one-shot cases.
+b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const
+{
+ float32 det = b2Dot(ex, b2Cross(ey, ez));
+ if (det != 0.0f)
+ {
+ det = 1.0f / det;
+ }
+ b2Vec3 x;
+ x.x = det * b2Dot(b, b2Cross(ey, ez));
+ x.y = det * b2Dot(ex, b2Cross(b, ez));
+ x.z = det * b2Dot(ex, b2Cross(ey, b));
+ return x;
+}
+
+/// Solve A * x = b, where b is a column vector. This is more efficient
+/// than computing the inverse in one-shot cases.
+b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const
+{
+ float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y;
+ float32 det = a11 * a22 - a12 * a21;
+ if (det != 0.0f)
+ {
+ det = 1.0f / det;
+ }
+ b2Vec2 x;
+ x.x = det * (a22 * b.x - a12 * b.y);
+ x.y = det * (a11 * b.y - a21 * b.x);
+ return x;
+}
+
+///
+void b2Mat33::GetInverse22(b2Mat33* M) const
+{
+ float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y;
+ float32 det = a * d - b * c;
+ if (det != 0.0f)
+ {
+ det = 1.0f / det;
+ }
+
+ M->ex.x = det * d; M->ey.x = -det * b; M->ex.z = 0.0f;
+ M->ex.y = -det * c; M->ey.y = det * a; M->ey.z = 0.0f;
+ M->ez.x = 0.0f; M->ez.y = 0.0f; M->ez.z = 0.0f;
+}
+
+/// Returns the zero matrix if singular.
+void b2Mat33::GetSymInverse33(b2Mat33* M) const
+{
+ float32 det = b2Dot(ex, b2Cross(ey, ez));
+ if (det != 0.0f)
+ {
+ det = 1.0f / det;
+ }
+
+ float32 a11 = ex.x, a12 = ey.x, a13 = ez.x;
+ float32 a22 = ey.y, a23 = ez.y;
+ float32 a33 = ez.z;
+
+ M->ex.x = det * (a22 * a33 - a23 * a23);
+ M->ex.y = det * (a13 * a23 - a12 * a33);
+ M->ex.z = det * (a12 * a23 - a13 * a22);
+
+ M->ey.x = M->ex.y;
+ M->ey.y = det * (a11 * a33 - a13 * a13);
+ M->ey.z = det * (a13 * a12 - a11 * a23);
+
+ M->ez.x = M->ex.z;
+ M->ez.y = M->ey.z;
+ M->ez.z = det * (a11 * a22 - a12 * a12);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2Math.h b/games/hillclimb/src/box2d/Box2D/Common/b2Math.h
new file mode 100644
index 00000000..9808258b
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2Math.h
@@ -0,0 +1,731 @@
+/*
+* Copyright (c) 2006-2009 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_MATH_H
+#define B2_MATH_H
+
+#include <Box2D/Common/b2Settings.h>
+
+#include <cmath>
+#include <cfloat>
+#include <cstddef>
+#include <limits>
+
+/// This function is used to ensure that a floating point number is
+/// not a NaN or infinity.
+inline bool b2IsValid(float32 x)
+{
+ if (x != x)
+ {
+ // NaN.
+ return false;
+ }
+
+ float32 infinity = std::numeric_limits<float32>::infinity();
+ return -infinity < x && x < infinity;
+}
+
+/// This is a approximate yet fast inverse square-root.
+inline float32 b2InvSqrt(float32 x)
+{
+ union
+ {
+ float32 x;
+ int32 i;
+ } convert;
+
+ convert.x = x;
+ float32 xhalf = 0.5f * x;
+ convert.i = 0x5f3759df - (convert.i >> 1);
+ x = convert.x;
+ x = x * (1.5f - xhalf * x * x);
+ return x;
+}
+
+#define b2Sqrt(x) std::sqrt(x)
+#define b2Atan2(y, x) std::atan2(y, x)
+
+/// A 2D column vector.
+struct b2Vec2
+{
+ /// Default constructor does nothing (for performance).
+ b2Vec2() {}
+
+ /// Construct using coordinates.
+ b2Vec2(float32 x, float32 y) : x(x), y(y) {}
+
+ /// Set this vector to all zeros.
+ void SetZero() { x = 0.0f; y = 0.0f; }
+
+ /// Set this vector to some specified coordinates.
+ void Set(float32 x_, float32 y_) { x = x_; y = y_; }
+
+ /// Negate this vector.
+ b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; }
+
+ /// Read from and indexed element.
+ float32 operator () (int32 i) const
+ {
+ return (&x)[i];
+ }
+
+ /// Write to an indexed element.
+ float32& operator () (int32 i)
+ {
+ return (&x)[i];
+ }
+
+ /// Add a vector to this vector.
+ void operator += (const b2Vec2& v)
+ {
+ x += v.x; y += v.y;
+ }
+
+ /// Subtract a vector from this vector.
+ void operator -= (const b2Vec2& v)
+ {
+ x -= v.x; y -= v.y;
+ }
+
+ /// Multiply this vector by a scalar.
+ void operator *= (float32 a)
+ {
+ x *= a; y *= a;
+ }
+
+ /// Get the length of this vector (the norm).
+ float32 Length() const
+ {
+ return b2Sqrt(x * x + y * y);
+ }
+
+ /// Get the length squared. For performance, use this instead of
+ /// b2Vec2::Length (if possible).
+ float32 LengthSquared() const
+ {
+ return x * x + y * y;
+ }
+
+ /// Convert this vector into a unit vector. Returns the length.
+ float32 Normalize()
+ {
+ float32 length = Length();
+ if (length < b2_epsilon)
+ {
+ return 0.0f;
+ }
+ float32 invLength = 1.0f / length;
+ x *= invLength;
+ y *= invLength;
+
+ return length;
+ }
+
+ /// Does this vector contain finite coordinates?
+ bool IsValid() const
+ {
+ return b2IsValid(x) && b2IsValid(y);
+ }
+
+ /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other)
+ b2Vec2 Skew() const
+ {
+ return b2Vec2(-y, x);
+ }
+
+ float32 x, y;
+};
+
+/// A 2D column vector with 3 elements.
+struct b2Vec3
+{
+ /// Default constructor does nothing (for performance).
+ b2Vec3() {}
+
+ /// Construct using coordinates.
+ b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {}
+
+ /// Set this vector to all zeros.
+ void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; }
+
+ /// Set this vector to some specified coordinates.
+ void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; }
+
+ /// Negate this vector.
+ b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; }
+
+ /// Add a vector to this vector.
+ void operator += (const b2Vec3& v)
+ {
+ x += v.x; y += v.y; z += v.z;
+ }
+
+ /// Subtract a vector from this vector.
+ void operator -= (const b2Vec3& v)
+ {
+ x -= v.x; y -= v.y; z -= v.z;
+ }
+
+ /// Multiply this vector by a scalar.
+ void operator *= (float32 s)
+ {
+ x *= s; y *= s; z *= s;
+ }
+
+ float32 x, y, z;
+};
+
+/// A 2-by-2 matrix. Stored in column-major order.
+struct b2Mat22
+{
+ /// The default constructor does nothing (for performance).
+ b2Mat22() {}
+
+ /// Construct this matrix using columns.
+ b2Mat22(const b2Vec2& c1, const b2Vec2& c2)
+ {
+ ex = c1;
+ ey = c2;
+ }
+
+ /// Construct this matrix using scalars.
+ b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22)
+ {
+ ex.x = a11; ex.y = a21;
+ ey.x = a12; ey.y = a22;
+ }
+
+ /// Initialize this matrix using columns.
+ void Set(const b2Vec2& c1, const b2Vec2& c2)
+ {
+ ex = c1;
+ ey = c2;
+ }
+
+ /// Set this to the identity matrix.
+ void SetIdentity()
+ {
+ ex.x = 1.0f; ey.x = 0.0f;
+ ex.y = 0.0f; ey.y = 1.0f;
+ }
+
+ /// Set this matrix to all zeros.
+ void SetZero()
+ {
+ ex.x = 0.0f; ey.x = 0.0f;
+ ex.y = 0.0f; ey.y = 0.0f;
+ }
+
+ b2Mat22 GetInverse() const
+ {
+ float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y;
+ b2Mat22 B;
+ float32 det = a * d - b * c;
+ if (det != 0.0f)
+ {
+ det = 1.0f / det;
+ }
+ B.ex.x = det * d; B.ey.x = -det * b;
+ B.ex.y = -det * c; B.ey.y = det * a;
+ return B;
+ }
+
+ /// Solve A * x = b, where b is a column vector. This is more efficient
+ /// than computing the inverse in one-shot cases.
+ b2Vec2 Solve(const b2Vec2& b) const
+ {
+ float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y;
+ float32 det = a11 * a22 - a12 * a21;
+ if (det != 0.0f)
+ {
+ det = 1.0f / det;
+ }
+ b2Vec2 x;
+ x.x = det * (a22 * b.x - a12 * b.y);
+ x.y = det * (a11 * b.y - a21 * b.x);
+ return x;
+ }
+
+ b2Vec2 ex, ey;
+};
+
+/// A 3-by-3 matrix. Stored in column-major order.
+struct b2Mat33
+{
+ /// The default constructor does nothing (for performance).
+ b2Mat33() {}
+
+ /// Construct this matrix using columns.
+ b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3)
+ {
+ ex = c1;
+ ey = c2;
+ ez = c3;
+ }
+
+ /// Set this matrix to all zeros.
+ void SetZero()
+ {
+ ex.SetZero();
+ ey.SetZero();
+ ez.SetZero();
+ }
+
+ /// Solve A * x = b, where b is a column vector. This is more efficient
+ /// than computing the inverse in one-shot cases.
+ b2Vec3 Solve33(const b2Vec3& b) const;
+
+ /// Solve A * x = b, where b is a column vector. This is more efficient
+ /// than computing the inverse in one-shot cases. Solve only the upper
+ /// 2-by-2 matrix equation.
+ b2Vec2 Solve22(const b2Vec2& b) const;
+
+ /// Get the inverse of this matrix as a 2-by-2.
+ /// Returns the zero matrix if singular.
+ void GetInverse22(b2Mat33* M) const;
+
+ /// Get the symmetric inverse of this matrix as a 3-by-3.
+ /// Returns the zero matrix if singular.
+ void GetSymInverse33(b2Mat33* M) const;
+
+ b2Vec3 ex, ey, ez;
+};
+
+/// Rotation
+struct b2Rot
+{
+ b2Rot() {}
+
+ /// Initialize from an angle in radians
+ explicit b2Rot(float32 angle)
+ {
+ /// TODO_ERIN optimize
+ s = sinf(angle);
+ c = cosf(angle);
+ }
+
+ /// Set using an angle in radians.
+ void Set(float32 angle)
+ {
+ /// TODO_ERIN optimize
+ s = sinf(angle);
+ c = cosf(angle);
+ }
+
+ /// Set to the identity rotation
+ void SetIdentity()
+ {
+ s = 0.0f;
+ c = 1.0f;
+ }
+
+ /// Get the angle in radians
+ float32 GetAngle() const
+ {
+ return b2Atan2(s, c);
+ }
+
+ /// Get the x-axis
+ b2Vec2 GetXAxis() const
+ {
+ return b2Vec2(c, s);
+ }
+
+ /// Get the u-axis
+ b2Vec2 GetYAxis() const
+ {
+ return b2Vec2(-s, c);
+ }
+
+ /// Sine and cosine
+ float32 s, c;
+};
+
+/// A transform contains translation and rotation. It is used to represent
+/// the position and orientation of rigid frames.
+struct b2Transform
+{
+ /// The default constructor does nothing.
+ b2Transform() {}
+
+ /// Initialize using a position vector and a rotation.
+ b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {}
+
+ /// Set this to the identity transform.
+ void SetIdentity()
+ {
+ p.SetZero();
+ q.SetIdentity();
+ }
+
+ /// Set this based on the position and angle.
+ void Set(const b2Vec2& position, float32 angle)
+ {
+ p = position;
+ q.Set(angle);
+ }
+
+ b2Vec2 p;
+ b2Rot q;
+};
+
+/// This describes the motion of a body/shape for TOI computation.
+/// Shapes are defined with respect to the body origin, which may
+/// no coincide with the center of mass. However, to support dynamics
+/// we must interpolate the center of mass position.
+struct b2Sweep
+{
+ /// Get the interpolated transform at a specific time.
+ /// @param beta is a factor in [0,1], where 0 indicates alpha0.
+ void GetTransform(b2Transform* xfb, float32 beta) const;
+
+ /// Advance the sweep forward, yielding a new initial state.
+ /// @param alpha the new initial time.
+ void Advance(float32 alpha);
+
+ /// Normalize the angles.
+ void Normalize();
+
+ b2Vec2 localCenter; ///< local center of mass position
+ b2Vec2 c0, c; ///< center world positions
+ float32 a0, a; ///< world angles
+
+ /// Fraction of the current time step in the range [0,1]
+ /// c0 and a0 are the positions at alpha0.
+ float32 alpha0;
+};
+
+/// Useful constant
+extern const b2Vec2 b2Vec2_zero;
+
+/// Perform the dot product on two vectors.
+inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b)
+{
+ return a.x * b.x + a.y * b.y;
+}
+
+/// Perform the cross product on two vectors. In 2D this produces a scalar.
+inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b)
+{
+ return a.x * b.y - a.y * b.x;
+}
+
+/// Perform the cross product on a vector and a scalar. In 2D this produces
+/// a vector.
+inline b2Vec2 b2Cross(const b2Vec2& a, float32 s)
+{
+ return b2Vec2(s * a.y, -s * a.x);
+}
+
+/// Perform the cross product on a scalar and a vector. In 2D this produces
+/// a vector.
+inline b2Vec2 b2Cross(float32 s, const b2Vec2& a)
+{
+ return b2Vec2(-s * a.y, s * a.x);
+}
+
+/// Multiply a matrix times a vector. If a rotation matrix is provided,
+/// then this transforms the vector from one frame to another.
+inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v)
+{
+ return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y);
+}
+
+/// Multiply a matrix transpose times a vector. If a rotation matrix is provided,
+/// then this transforms the vector from one frame to another (inverse transform).
+inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v)
+{
+ return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey));
+}
+
+/// Add two vectors component-wise.
+inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b)
+{
+ return b2Vec2(a.x + b.x, a.y + b.y);
+}
+
+/// Subtract two vectors component-wise.
+inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b)
+{
+ return b2Vec2(a.x - b.x, a.y - b.y);
+}
+
+inline b2Vec2 operator * (float32 s, const b2Vec2& a)
+{
+ return b2Vec2(s * a.x, s * a.y);
+}
+
+inline bool operator == (const b2Vec2& a, const b2Vec2& b)
+{
+ return a.x == b.x && a.y == b.y;
+}
+
+inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b)
+{
+ b2Vec2 c = a - b;
+ return c.Length();
+}
+
+inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b)
+{
+ b2Vec2 c = a - b;
+ return b2Dot(c, c);
+}
+
+inline b2Vec3 operator * (float32 s, const b2Vec3& a)
+{
+ return b2Vec3(s * a.x, s * a.y, s * a.z);
+}
+
+/// Add two vectors component-wise.
+inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b)
+{
+ return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
+}
+
+/// Subtract two vectors component-wise.
+inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b)
+{
+ return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
+}
+
+/// Perform the dot product on two vectors.
+inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b)
+{
+ return a.x * b.x + a.y * b.y + a.z * b.z;
+}
+
+/// Perform the cross product on two vectors.
+inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b)
+{
+ return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
+}
+
+inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B)
+{
+ return b2Mat22(A.ex + B.ex, A.ey + B.ey);
+}
+
+// A * B
+inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B)
+{
+ return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey));
+}
+
+// A^T * B
+inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B)
+{
+ b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex));
+ b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey));
+ return b2Mat22(c1, c2);
+}
+
+/// Multiply a matrix times a vector.
+inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v)
+{
+ return v.x * A.ex + v.y * A.ey + v.z * A.ez;
+}
+
+/// Multiply a matrix times a vector.
+inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v)
+{
+ return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y);
+}
+
+/// Multiply two rotations: q * r
+inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r)
+{
+ // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc]
+ // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc]
+ // s = qs * rc + qc * rs
+ // c = qc * rc - qs * rs
+ b2Rot qr;
+ qr.s = q.s * r.c + q.c * r.s;
+ qr.c = q.c * r.c - q.s * r.s;
+ return qr;
+}
+
+/// Transpose multiply two rotations: qT * r
+inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r)
+{
+ // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc]
+ // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc]
+ // s = qc * rs - qs * rc
+ // c = qc * rc + qs * rs
+ b2Rot qr;
+ qr.s = q.c * r.s - q.s * r.c;
+ qr.c = q.c * r.c + q.s * r.s;
+ return qr;
+}
+
+/// Rotate a vector
+inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v)
+{
+ return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y);
+}
+
+/// Inverse rotate a vector
+inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v)
+{
+ return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y);
+}
+
+inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v)
+{
+ float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x;
+ float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y;
+
+ return b2Vec2(x, y);
+}
+
+inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v)
+{
+ float32 px = v.x - T.p.x;
+ float32 py = v.y - T.p.y;
+ float32 x = (T.q.c * px + T.q.s * py);
+ float32 y = (-T.q.s * px + T.q.c * py);
+
+ return b2Vec2(x, y);
+}
+
+// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p
+// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p
+inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B)
+{
+ b2Transform C;
+ C.q = b2Mul(A.q, B.q);
+ C.p = b2Mul(A.q, B.p) + A.p;
+ return C;
+}
+
+// v2 = A.q' * (B.q * v1 + B.p - A.p)
+// = A.q' * B.q * v1 + A.q' * (B.p - A.p)
+inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B)
+{
+ b2Transform C;
+ C.q = b2MulT(A.q, B.q);
+ C.p = b2MulT(A.q, B.p - A.p);
+ return C;
+}
+
+template <typename T>
+inline T b2Abs(T a)
+{
+ return a > T(0) ? a : -a;
+}
+
+inline b2Vec2 b2Abs(const b2Vec2& a)
+{
+ return b2Vec2(b2Abs(a.x), b2Abs(a.y));
+}
+
+inline b2Mat22 b2Abs(const b2Mat22& A)
+{
+ return b2Mat22(b2Abs(A.ex), b2Abs(A.ey));
+}
+
+template <typename T>
+inline T b2Min(T a, T b)
+{
+ return a < b ? a : b;
+}
+
+inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b)
+{
+ return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y));
+}
+
+template <typename T>
+inline T b2Max(T a, T b)
+{
+ return a > b ? a : b;
+}
+
+inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b)
+{
+ return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y));
+}
+
+template <typename T>
+inline T b2Clamp(T a, T low, T high)
+{
+ return b2Max(low, b2Min(a, high));
+}
+
+inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high)
+{
+ return b2Max(low, b2Min(a, high));
+}
+
+template<typename T> inline void b2Swap(T& a, T& b)
+{
+ T tmp = a;
+ a = b;
+ b = tmp;
+}
+
+/// "Next Largest Power of 2
+/// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm
+/// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with
+/// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next
+/// largest power of 2. For a 32-bit value:"
+inline uint32 b2NextPowerOfTwo(uint32 x)
+{
+ x |= (x >> 1);
+ x |= (x >> 2);
+ x |= (x >> 4);
+ x |= (x >> 8);
+ x |= (x >> 16);
+ return x + 1;
+}
+
+inline bool b2IsPowerOfTwo(uint32 x)
+{
+ bool result = x > 0 && (x & (x - 1)) == 0;
+ return result;
+}
+
+inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const
+{
+ xf->p = (1.0f - beta) * c0 + beta * c;
+ float32 angle = (1.0f - beta) * a0 + beta * a;
+ xf->q.Set(angle);
+
+ // Shift to origin
+ xf->p -= b2Mul(xf->q, localCenter);
+}
+
+inline void b2Sweep::Advance(float32 alpha)
+{
+ b2Assert(alpha0 < 1.0f);
+ float32 beta = (alpha - alpha0) / (1.0f - alpha0);
+ c0 = (1.0f - beta) * c0 + beta * c;
+ a0 = (1.0f - beta) * a0 + beta * a;
+ alpha0 = alpha;
+}
+
+/// Normalize an angle in radians to be between -pi and pi
+inline void b2Sweep::Normalize()
+{
+ float32 twoPi = 2.0f * b2_pi;
+ float32 d = twoPi * floorf(a0 / twoPi);
+ a0 -= d;
+ a -= d;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2Settings.cpp b/games/hillclimb/src/box2d/Box2D/Common/b2Settings.cpp
new file mode 100644
index 00000000..01b3d5ad
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2Settings.cpp
@@ -0,0 +1,41 @@
+/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): b2Log prints nothing */
+/*
+* Copyright (c) 2006-2009 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/Common/b2Settings.h>
+#include <cstdlib>
+#include <cstdarg>
+
+b2Version b2_version = {2, 2, 1};
+
+// Memory allocators. Modify these to use your own allocator.
+void* b2Alloc(int32 size)
+{
+ return malloc(size);
+}
+
+void b2Free(void* mem)
+{
+ free(mem);
+}
+
+// You can modify this to use your logging facility.
+void b2Log(const char* string, ...)
+{
+ (void)string;
+}
\ No newline at end of file
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2Settings.h b/games/hillclimb/src/box2d/Box2D/Common/b2Settings.h
new file mode 100644
index 00000000..7e0a165b
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2Settings.h
@@ -0,0 +1,150 @@
+/*
+* Copyright (c) 2006-2009 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_SETTINGS_H
+#define B2_SETTINGS_H
+
+#include <cassert>
+#include <cmath>
+
+#define B2_NOT_USED(x) ((void)(x))
+#define b2Assert(A) assert(A)
+
+typedef signed char int8;
+typedef signed short int16;
+typedef signed int int32;
+typedef unsigned char uint8;
+typedef unsigned short uint16;
+typedef unsigned int uint32;
+typedef float float32;
+typedef double float64;
+
+#define b2_maxFloat FLT_MAX
+#define b2_epsilon FLT_EPSILON
+#define b2_pi 3.14159265359f
+
+/// @file
+/// Global tuning constants based on meters-kilograms-seconds (MKS) units.
+///
+
+// Collision
+
+/// The maximum number of contact points between two convex shapes. Do
+/// not change this value.
+#define b2_maxManifoldPoints 2
+
+/// The maximum number of vertices on a convex polygon. You cannot increase
+/// this too much because b2BlockAllocator has a maximum object size.
+#define b2_maxPolygonVertices 8
+
+/// This is used to fatten AABBs in the dynamic tree. This allows proxies
+/// to move by a small amount without triggering a tree adjustment.
+/// This is in meters.
+#define b2_aabbExtension 0.1f
+
+/// This is used to fatten AABBs in the dynamic tree. This is used to predict
+/// the future position based on the current displacement.
+/// This is a dimensionless multiplier.
+#define b2_aabbMultiplier 2.0f
+
+/// A small length used as a collision and constraint tolerance. Usually it is
+/// chosen to be numerically significant, but visually insignificant.
+#define b2_linearSlop 0.005f
+
+/// A small angle used as a collision and constraint tolerance. Usually it is
+/// chosen to be numerically significant, but visually insignificant.
+#define b2_angularSlop (2.0f / 180.0f * b2_pi)
+
+/// The radius of the polygon/edge shape skin. This should not be modified. Making
+/// this smaller means polygons will have an insufficient buffer for continuous collision.
+/// Making it larger may create artifacts for vertex collision.
+#define b2_polygonRadius (2.0f * b2_linearSlop)
+
+/// Maximum number of sub-steps per contact in continuous physics simulation.
+#define b2_maxSubSteps 8
+
+
+// Dynamics
+
+/// Maximum number of contacts to be handled to solve a TOI impact.
+#define b2_maxTOIContacts 32
+
+/// A velocity threshold for elastic collisions. Any collision with a relative linear
+/// velocity below this threshold will be treated as inelastic.
+#define b2_velocityThreshold 1.0f
+
+/// The maximum linear position correction used when solving constraints. This helps to
+/// prevent overshoot.
+#define b2_maxLinearCorrection 0.2f
+
+/// The maximum angular position correction used when solving constraints. This helps to
+/// prevent overshoot.
+#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi)
+
+/// The maximum linear velocity of a body. This limit is very large and is used
+/// to prevent numerical problems. You shouldn't need to adjust this.
+#define b2_maxTranslation 2.0f
+#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation)
+
+/// The maximum angular velocity of a body. This limit is very large and is used
+/// to prevent numerical problems. You shouldn't need to adjust this.
+#define b2_maxRotation (0.5f * b2_pi)
+#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation)
+
+/// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so
+/// that overlap is removed in one time step. However using values close to 1 often lead
+/// to overshoot.
+#define b2_baumgarte 0.2f
+#define b2_toiBaugarte 0.75f
+
+
+// Sleep
+
+/// The time that a body must be still before it will go to sleep.
+#define b2_timeToSleep 0.5f
+
+/// A body cannot sleep if its linear velocity is above this tolerance.
+#define b2_linearSleepTolerance 0.01f
+
+/// A body cannot sleep if its angular velocity is above this tolerance.
+#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi)
+
+// Memory Allocation
+
+/// Implement this function to use your own memory allocator.
+void* b2Alloc(int32 size);
+
+/// If you implement b2Alloc, you should also implement this function.
+void b2Free(void* mem);
+
+/// Logging function.
+void b2Log(const char* string, ...);
+
+/// Version numbering scheme.
+/// See http://en.wikipedia.org/wiki/Software_versioning
+struct b2Version
+{
+ int32 major; ///< significant changes
+ int32 minor; ///< incremental changes
+ int32 revision; ///< bug fixes
+};
+
+/// Current version.
+extern b2Version b2_version;
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2StackAllocator.cpp b/games/hillclimb/src/box2d/Box2D/Common/b2StackAllocator.cpp
new file mode 100644
index 00000000..4a862835
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2StackAllocator.cpp
@@ -0,0 +1,83 @@
+/*
+* Copyright (c) 2006-2009 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/Common/b2StackAllocator.h>
+#include <Box2D/Common/b2Math.h>
+
+b2StackAllocator::b2StackAllocator()
+{
+ m_index = 0;
+ m_allocation = 0;
+ m_maxAllocation = 0;
+ m_entryCount = 0;
+}
+
+b2StackAllocator::~b2StackAllocator()
+{
+ b2Assert(m_index == 0);
+ b2Assert(m_entryCount == 0);
+}
+
+void* b2StackAllocator::Allocate(int32 size)
+{
+ b2Assert(m_entryCount < b2_maxStackEntries);
+
+ b2StackEntry* entry = m_entries + m_entryCount;
+ entry->size = size;
+ if (m_index + size > b2_stackSize)
+ {
+ entry->data = (char*)b2Alloc(size);
+ entry->usedMalloc = true;
+ }
+ else
+ {
+ entry->data = m_data + m_index;
+ entry->usedMalloc = false;
+ m_index += size;
+ }
+
+ m_allocation += size;
+ m_maxAllocation = b2Max(m_maxAllocation, m_allocation);
+ ++m_entryCount;
+
+ return entry->data;
+}
+
+void b2StackAllocator::Free(void* p)
+{
+ b2Assert(m_entryCount > 0);
+ b2StackEntry* entry = m_entries + m_entryCount - 1;
+ b2Assert(p == entry->data);
+ if (entry->usedMalloc)
+ {
+ b2Free(p);
+ }
+ else
+ {
+ m_index -= entry->size;
+ }
+ m_allocation -= entry->size;
+ --m_entryCount;
+
+ p = NULL;
+}
+
+int32 b2StackAllocator::GetMaxAllocation() const
+{
+ return m_maxAllocation;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2StackAllocator.h b/games/hillclimb/src/box2d/Box2D/Common/b2StackAllocator.h
new file mode 100644
index 00000000..ecd5233c
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2StackAllocator.h
@@ -0,0 +1,61 @@
+/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): a 6 KB stack */
+/*
+* Copyright (c) 2006-2009 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_STACK_ALLOCATOR_H
+#define B2_STACK_ALLOCATOR_H
+
+#include <Box2D/Common/b2Settings.h>
+
+const int32 b2_stackSize = 6 * 1024; // (100k in Box2D; more comes from b2Alloc)
+const int32 b2_maxStackEntries = 32;
+
+struct b2StackEntry
+{
+ char* data;
+ int32 size;
+ bool usedMalloc;
+};
+
+// This is a stack allocator used for fast per step allocations.
+// You must nest allocate/free pairs. The code will assert
+// if you try to interleave multiple allocate/free pairs.
+class b2StackAllocator
+{
+public:
+ b2StackAllocator();
+ ~b2StackAllocator();
+
+ void* Allocate(int32 size);
+ void Free(void* p);
+
+ int32 GetMaxAllocation() const;
+
+private:
+
+ char m_data[b2_stackSize];
+ int32 m_index;
+
+ int32 m_allocation;
+ int32 m_maxAllocation;
+
+ b2StackEntry m_entries[b2_maxStackEntries];
+ int32 m_entryCount;
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2Timer.cpp b/games/hillclimb/src/box2d/Box2D/Common/b2Timer.cpp
new file mode 100644
index 00000000..4e424951
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2Timer.cpp
@@ -0,0 +1,33 @@
+/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): no clock (the profile is not used) */
+/*
+* Copyright (c) 2011 Erin Catto http://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/Common/b2Timer.h>
+
+b2Timer::b2Timer()
+{
+}
+
+void b2Timer::Reset()
+{
+}
+
+float32 b2Timer::GetMilliseconds() const
+{
+ return 0.0f;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Common/b2Timer.h b/games/hillclimb/src/box2d/Box2D/Common/b2Timer.h
new file mode 100644
index 00000000..19bde287
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Common/b2Timer.h
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2011 Erin Catto http://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/Common/b2Settings.h>
+
+/// Timer for profiling. This has platform specific code and may
+/// not work on every platform.
+class b2Timer
+{
+public:
+
+ /// Constructor
+ b2Timer();
+
+ /// Reset the timer.
+ void Reset();
+
+ /// Get the time since construction or the last reset.
+ float32 GetMilliseconds() const;
+
+private:
+
+#if defined(_WIN32)
+ float64 m_start;
+ static float64 s_invFrequency;
+#elif defined(__linux__) || defined (__APPLE__)
+ unsigned long m_start_sec;
+ unsigned long m_start_msec;
+#endif
+};
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp
new file mode 100644
index 00000000..3886dfd7
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2006-2010 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/Contacts/b2ChainAndCircleContact.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Collision/Shapes/b2ChainShape.h>
+#include <Box2D/Collision/Shapes/b2EdgeShape.h>
+
+#include <new>
+using namespace std;
+
+b2Contact* b2ChainAndCircleContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator)
+{
+ void* mem = allocator->Allocate(sizeof(b2ChainAndCircleContact));
+ return new (mem) b2ChainAndCircleContact(fixtureA, indexA, fixtureB, indexB);
+}
+
+void b2ChainAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
+{
+ ((b2ChainAndCircleContact*)contact)->~b2ChainAndCircleContact();
+ allocator->Free(contact, sizeof(b2ChainAndCircleContact));
+}
+
+b2ChainAndCircleContact::b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB)
+: b2Contact(fixtureA, indexA, fixtureB, indexB)
+{
+ b2Assert(m_fixtureA->GetType() == b2Shape::e_chain);
+ b2Assert(m_fixtureB->GetType() == b2Shape::e_circle);
+}
+
+void b2ChainAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
+{
+ b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape();
+ b2EdgeShape edge;
+ chain->GetChildEdge(&edge, m_indexA);
+ b2CollideEdgeAndCircle( manifold, &edge, xfA,
+ (b2CircleShape*)m_fixtureB->GetShape(), xfB);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h
new file mode 100644
index 00000000..2dad0b64
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2006-2009 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_CHAIN_AND_CIRCLE_CONTACT_H
+#define B2_CHAIN_AND_CIRCLE_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2ChainAndCircleContact : public b2Contact
+{
+public:
+ static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
+ b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
+ static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+ b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB);
+ ~b2ChainAndCircleContact() {}
+
+ void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp
new file mode 100644
index 00000000..02bcaaf6
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2006-2010 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/Contacts/b2ChainAndPolygonContact.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Collision/Shapes/b2ChainShape.h>
+#include <Box2D/Collision/Shapes/b2EdgeShape.h>
+
+#include <new>
+using namespace std;
+
+b2Contact* b2ChainAndPolygonContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator)
+{
+ void* mem = allocator->Allocate(sizeof(b2ChainAndPolygonContact));
+ return new (mem) b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB);
+}
+
+void b2ChainAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
+{
+ ((b2ChainAndPolygonContact*)contact)->~b2ChainAndPolygonContact();
+ allocator->Free(contact, sizeof(b2ChainAndPolygonContact));
+}
+
+b2ChainAndPolygonContact::b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB)
+: b2Contact(fixtureA, indexA, fixtureB, indexB)
+{
+ b2Assert(m_fixtureA->GetType() == b2Shape::e_chain);
+ b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon);
+}
+
+void b2ChainAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
+{
+ b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape();
+ b2EdgeShape edge;
+ chain->GetChildEdge(&edge, m_indexA);
+ b2CollideEdgeAndPolygon( manifold, &edge, xfA,
+ (b2PolygonShape*)m_fixtureB->GetShape(), xfB);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h
new file mode 100644
index 00000000..8f30ee86
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2006-2009 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_CHAIN_AND_POLYGON_CONTACT_H
+#define B2_CHAIN_AND_POLYGON_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2ChainAndPolygonContact : public b2Contact
+{
+public:
+ static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
+ b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
+ static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+ b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB);
+ ~b2ChainAndPolygonContact() {}
+
+ void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp
new file mode 100644
index 00000000..584ef2f1
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2CircleContact.cpp
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2006-2009 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/Contacts/b2CircleContact.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2WorldCallbacks.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Collision/b2TimeOfImpact.h>
+
+#include <new>
+using namespace std;
+
+b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator)
+{
+ void* mem = allocator->Allocate(sizeof(b2CircleContact));
+ return new (mem) b2CircleContact(fixtureA, fixtureB);
+}
+
+void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
+{
+ ((b2CircleContact*)contact)->~b2CircleContact();
+ allocator->Free(contact, sizeof(b2CircleContact));
+}
+
+b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
+ : b2Contact(fixtureA, 0, fixtureB, 0)
+{
+ b2Assert(m_fixtureA->GetType() == b2Shape::e_circle);
+ b2Assert(m_fixtureB->GetType() == b2Shape::e_circle);
+}
+
+void b2CircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
+{
+ b2CollideCircles(manifold,
+ (b2CircleShape*)m_fixtureA->GetShape(), xfA,
+ (b2CircleShape*)m_fixtureB->GetShape(), xfB);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h
new file mode 100644
index 00000000..aac1f0bd
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2CircleContact.h
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2006-2009 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_CIRCLE_CONTACT_H
+#define B2_CIRCLE_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2CircleContact : public b2Contact
+{
+public:
+ static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
+ b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
+ static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+ b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+ ~b2CircleContact() {}
+
+ void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp
new file mode 100644
index 00000000..557af7f0
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2Contact.cpp
@@ -0,0 +1,240 @@
+/*
+* Copyright (c) 2006-2009 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/Contacts/b2Contact.h>
+#include <Box2D/Dynamics/Contacts/b2CircleContact.h>
+#include <Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h>
+#include <Box2D/Dynamics/Contacts/b2PolygonContact.h>
+#include <Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h>
+#include <Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h>
+#include <Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h>
+#include <Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h>
+#include <Box2D/Dynamics/Contacts/b2ContactSolver.h>
+
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/b2TimeOfImpact.h>
+#include <Box2D/Collision/Shapes/b2Shape.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2World.h>
+
+b2ContactRegister b2Contact::s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount];
+bool b2Contact::s_initialized = false;
+
+void b2Contact::InitializeRegisters()
+{
+ AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle);
+ AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle);
+ AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon);
+ AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle);
+ AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon);
+ AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle);
+ AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon);
+}
+
+void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn,
+ b2Shape::Type type1, b2Shape::Type type2)
+{
+ b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount);
+ b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount);
+
+ s_registers[type1][type2].createFcn = createFcn;
+ s_registers[type1][type2].destroyFcn = destoryFcn;
+ s_registers[type1][type2].primary = true;
+
+ if (type1 != type2)
+ {
+ s_registers[type2][type1].createFcn = createFcn;
+ s_registers[type2][type1].destroyFcn = destoryFcn;
+ s_registers[type2][type1].primary = false;
+ }
+}
+
+b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator)
+{
+ if (s_initialized == false)
+ {
+ InitializeRegisters();
+ s_initialized = true;
+ }
+
+ b2Shape::Type type1 = fixtureA->GetType();
+ b2Shape::Type type2 = fixtureB->GetType();
+
+ b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount);
+ b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount);
+
+ b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn;
+ if (createFcn)
+ {
+ if (s_registers[type1][type2].primary)
+ {
+ return createFcn(fixtureA, indexA, fixtureB, indexB, allocator);
+ }
+ else
+ {
+ return createFcn(fixtureB, indexB, fixtureA, indexA, allocator);
+ }
+ }
+ else
+ {
+ return NULL;
+ }
+}
+
+void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
+{
+ b2Assert(s_initialized == true);
+
+ if (contact->m_manifold.pointCount > 0)
+ {
+ contact->GetFixtureA()->GetBody()->SetAwake(true);
+ contact->GetFixtureB()->GetBody()->SetAwake(true);
+ }
+
+ b2Shape::Type typeA = contact->GetFixtureA()->GetType();
+ b2Shape::Type typeB = contact->GetFixtureB()->GetType();
+
+ b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount);
+ b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount);
+
+ b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn;
+ destroyFcn(contact, allocator);
+}
+
+b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB)
+{
+ m_flags = e_enabledFlag;
+
+ m_fixtureA = fA;
+ m_fixtureB = fB;
+
+ m_indexA = indexA;
+ m_indexB = indexB;
+
+ m_manifold.pointCount = 0;
+
+ m_prev = NULL;
+ m_next = NULL;
+
+ m_nodeA.contact = NULL;
+ m_nodeA.prev = NULL;
+ m_nodeA.next = NULL;
+ m_nodeA.other = NULL;
+
+ m_nodeB.contact = NULL;
+ m_nodeB.prev = NULL;
+ m_nodeB.next = NULL;
+ m_nodeB.other = NULL;
+
+ m_toiCount = 0;
+
+ m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction);
+ m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution);
+}
+
+// Update the contact manifold and touching status.
+// Note: do not assume the fixture AABBs are overlapping or are valid.
+void b2Contact::Update(b2ContactListener* listener)
+{
+ b2Manifold oldManifold = m_manifold;
+
+ // Re-enable this contact.
+ m_flags |= e_enabledFlag;
+
+ bool touching = false;
+ bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag;
+
+ bool sensorA = m_fixtureA->IsSensor();
+ bool sensorB = m_fixtureB->IsSensor();
+ bool sensor = sensorA || sensorB;
+
+ b2Body* bodyA = m_fixtureA->GetBody();
+ b2Body* bodyB = m_fixtureB->GetBody();
+ const b2Transform& xfA = bodyA->GetTransform();
+ const b2Transform& xfB = bodyB->GetTransform();
+
+ // Is this contact a sensor?
+ if (sensor)
+ {
+ const b2Shape* shapeA = m_fixtureA->GetShape();
+ const b2Shape* shapeB = m_fixtureB->GetShape();
+ touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB);
+
+ // Sensors don't generate manifolds.
+ m_manifold.pointCount = 0;
+ }
+ else
+ {
+ Evaluate(&m_manifold, xfA, xfB);
+ touching = m_manifold.pointCount > 0;
+
+ // Match old contact ids to new contact ids and copy the
+ // stored impulses to warm start the solver.
+ for (int32 i = 0; i < m_manifold.pointCount; ++i)
+ {
+ b2ManifoldPoint* mp2 = m_manifold.points + i;
+ mp2->normalImpulse = 0.0f;
+ mp2->tangentImpulse = 0.0f;
+ b2ContactID id2 = mp2->id;
+
+ for (int32 j = 0; j < oldManifold.pointCount; ++j)
+ {
+ b2ManifoldPoint* mp1 = oldManifold.points + j;
+
+ if (mp1->id.key == id2.key)
+ {
+ mp2->normalImpulse = mp1->normalImpulse;
+ mp2->tangentImpulse = mp1->tangentImpulse;
+ break;
+ }
+ }
+ }
+
+ if (touching != wasTouching)
+ {
+ bodyA->SetAwake(true);
+ bodyB->SetAwake(true);
+ }
+ }
+
+ if (touching)
+ {
+ m_flags |= e_touchingFlag;
+ }
+ else
+ {
+ m_flags &= ~e_touchingFlag;
+ }
+
+ if (wasTouching == false && touching == true && listener)
+ {
+ listener->BeginContact(this);
+ }
+
+ if (wasTouching == true && touching == false && listener)
+ {
+ listener->EndContact(this);
+ }
+
+ if (sensor == false && touching && listener)
+ {
+ listener->PreSolve(this, &oldManifold);
+ }
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2Contact.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2Contact.h
new file mode 100644
index 00000000..7b5a6ab8
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2Contact.h
@@ -0,0 +1,331 @@
+/*
+* Copyright (c) 2006-2009 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_CONTACT_H
+#define B2_CONTACT_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/Shapes/b2Shape.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+
+class b2Body;
+class b2Contact;
+class b2Fixture;
+class b2World;
+class b2BlockAllocator;
+class b2StackAllocator;
+class b2ContactListener;
+
+/// Friction mixing law. The idea is to allow either fixture to drive the restitution to zero.
+/// For example, anything slides on ice.
+inline float32 b2MixFriction(float32 friction1, float32 friction2)
+{
+ return std::sqrt(friction1 * friction2);
+}
+
+/// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface.
+/// For example, a superball bounces on anything.
+inline float32 b2MixRestitution(float32 restitution1, float32 restitution2)
+{
+ return restitution1 > restitution2 ? restitution1 : restitution2;
+}
+
+typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA,
+ b2Fixture* fixtureB, int32 indexB,
+ b2BlockAllocator* allocator);
+typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator);
+
+struct b2ContactRegister
+{
+ b2ContactCreateFcn* createFcn;
+ b2ContactDestroyFcn* destroyFcn;
+ bool primary;
+};
+
+/// A contact edge is used to connect bodies and contacts together
+/// in a contact graph where each body is a node and each contact
+/// is an edge. A contact edge belongs to a doubly linked list
+/// maintained in each attached body. Each contact has two contact
+/// nodes, one for each attached body.
+struct b2ContactEdge
+{
+ b2Body* other; ///< provides quick access to the other body attached.
+ b2Contact* contact; ///< the contact
+ b2ContactEdge* prev; ///< the previous contact edge in the body's contact list
+ b2ContactEdge* next; ///< the next contact edge in the body's contact list
+};
+
+/// The class manages contact between two shapes. A contact exists for each overlapping
+/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist
+/// that has no contact points.
+class b2Contact
+{
+public:
+
+ /// Get the contact manifold. Do not modify the manifold unless you understand the
+ /// internals of Box2D.
+ b2Manifold* GetManifold();
+ const b2Manifold* GetManifold() const;
+
+ /// Get the world manifold.
+ void GetWorldManifold(b2WorldManifold* worldManifold) const;
+
+ /// Is this contact touching?
+ bool IsTouching() const;
+
+ /// Enable/disable this contact. This can be used inside the pre-solve
+ /// contact listener. The contact is only disabled for the current
+ /// time step (or sub-step in continuous collisions).
+ void SetEnabled(bool flag);
+
+ /// Has this contact been disabled?
+ bool IsEnabled() const;
+
+ /// Get the next contact in the world's contact list.
+ b2Contact* GetNext();
+ const b2Contact* GetNext() const;
+
+ /// Get fixture A in this contact.
+ b2Fixture* GetFixtureA();
+ const b2Fixture* GetFixtureA() const;
+
+ /// Get the child primitive index for fixture A.
+ int32 GetChildIndexA() const;
+
+ /// Get fixture B in this contact.
+ b2Fixture* GetFixtureB();
+ const b2Fixture* GetFixtureB() const;
+
+ /// Get the child primitive index for fixture B.
+ int32 GetChildIndexB() const;
+
+ /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve.
+ /// This value persists until set or reset.
+ void SetFriction(float32 friction);
+
+ /// Get the friction.
+ float32 GetFriction() const;
+
+ /// Reset the friction mixture to the default value.
+ void ResetFriction();
+
+ /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve.
+ /// The value persists until you set or reset.
+ void SetRestitution(float32 restitution);
+
+ /// Get the restitution.
+ float32 GetRestitution() const;
+
+ /// Reset the restitution to the default value.
+ void ResetRestitution();
+
+ /// Evaluate this contact with your own manifold and transforms.
+ virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0;
+
+protected:
+ friend class b2ContactManager;
+ friend class b2World;
+ friend class b2ContactSolver;
+ friend class b2Body;
+ friend class b2Fixture;
+
+ // Flags stored in m_flags
+ enum
+ {
+ // Used when crawling contact graph when forming islands.
+ e_islandFlag = 0x0001,
+
+ // Set when the shapes are touching.
+ e_touchingFlag = 0x0002,
+
+ // This contact can be disabled (by user)
+ e_enabledFlag = 0x0004,
+
+ // This contact needs filtering because a fixture filter was changed.
+ e_filterFlag = 0x0008,
+
+ // This bullet contact had a TOI event
+ e_bulletHitFlag = 0x0010,
+
+ // This contact has a valid TOI in m_toi
+ e_toiFlag = 0x0020
+ };
+
+ /// Flag this contact for filtering. Filtering will occur the next time step.
+ void FlagForFiltering();
+
+ static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn,
+ b2Shape::Type typeA, b2Shape::Type typeB);
+ static void InitializeRegisters();
+ static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
+ static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator);
+ static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+ b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {}
+ b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB);
+ virtual ~b2Contact() {}
+
+ void Update(b2ContactListener* listener);
+
+ static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount];
+ static bool s_initialized;
+
+ uint32 m_flags;
+
+ // World pool and list pointers.
+ b2Contact* m_prev;
+ b2Contact* m_next;
+
+ // Nodes for connecting bodies.
+ b2ContactEdge m_nodeA;
+ b2ContactEdge m_nodeB;
+
+ b2Fixture* m_fixtureA;
+ b2Fixture* m_fixtureB;
+
+ int32 m_indexA;
+ int32 m_indexB;
+
+ b2Manifold m_manifold;
+
+ int32 m_toiCount;
+ float32 m_toi;
+
+ float32 m_friction;
+ float32 m_restitution;
+};
+
+inline b2Manifold* b2Contact::GetManifold()
+{
+ return &m_manifold;
+}
+
+inline const b2Manifold* b2Contact::GetManifold() const
+{
+ return &m_manifold;
+}
+
+inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const
+{
+ const b2Body* bodyA = m_fixtureA->GetBody();
+ const b2Body* bodyB = m_fixtureB->GetBody();
+ const b2Shape* shapeA = m_fixtureA->GetShape();
+ const b2Shape* shapeB = m_fixtureB->GetShape();
+
+ worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius);
+}
+
+inline void b2Contact::SetEnabled(bool flag)
+{
+ if (flag)
+ {
+ m_flags |= e_enabledFlag;
+ }
+ else
+ {
+ m_flags &= ~e_enabledFlag;
+ }
+}
+
+inline bool b2Contact::IsEnabled() const
+{
+ return (m_flags & e_enabledFlag) == e_enabledFlag;
+}
+
+inline bool b2Contact::IsTouching() const
+{
+ return (m_flags & e_touchingFlag) == e_touchingFlag;
+}
+
+inline b2Contact* b2Contact::GetNext()
+{
+ return m_next;
+}
+
+inline const b2Contact* b2Contact::GetNext() const
+{
+ return m_next;
+}
+
+inline b2Fixture* b2Contact::GetFixtureA()
+{
+ return m_fixtureA;
+}
+
+inline const b2Fixture* b2Contact::GetFixtureA() const
+{
+ return m_fixtureA;
+}
+
+inline b2Fixture* b2Contact::GetFixtureB()
+{
+ return m_fixtureB;
+}
+
+inline int32 b2Contact::GetChildIndexA() const
+{
+ return m_indexA;
+}
+
+inline const b2Fixture* b2Contact::GetFixtureB() const
+{
+ return m_fixtureB;
+}
+
+inline int32 b2Contact::GetChildIndexB() const
+{
+ return m_indexB;
+}
+
+inline void b2Contact::FlagForFiltering()
+{
+ m_flags |= e_filterFlag;
+}
+
+inline void b2Contact::SetFriction(float32 friction)
+{
+ m_friction = friction;
+}
+
+inline float32 b2Contact::GetFriction() const
+{
+ return m_friction;
+}
+
+inline void b2Contact::ResetFriction()
+{
+ m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction);
+}
+
+inline void b2Contact::SetRestitution(float32 restitution)
+{
+ m_restitution = restitution;
+}
+
+inline float32 b2Contact::GetRestitution() const
+{
+ return m_restitution;
+}
+
+inline void b2Contact::ResetRestitution()
+{
+ m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution);
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp
new file mode 100644
index 00000000..c990d7fb
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.cpp
@@ -0,0 +1,832 @@
+/*
+* 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/Contacts/b2ContactSolver.h>
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2World.h>
+#include <Box2D/Common/b2StackAllocator.h>
+
+#define B2_DEBUG_SOLVER 0
+
+struct b2ContactPositionConstraint
+{
+ b2Vec2 localPoints[b2_maxManifoldPoints];
+ b2Vec2 localNormal;
+ b2Vec2 localPoint;
+ int32 indexA;
+ int32 indexB;
+ float32 invMassA, invMassB;
+ b2Vec2 localCenterA, localCenterB;
+ float32 invIA, invIB;
+ b2Manifold::Type type;
+ float32 radiusA, radiusB;
+ int32 pointCount;
+};
+
+b2ContactSolver::b2ContactSolver(b2ContactSolverDef* def)
+{
+ m_step = def->step;
+ m_allocator = def->allocator;
+ m_count = def->count;
+ m_positionConstraints = (b2ContactPositionConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactPositionConstraint));
+ m_velocityConstraints = (b2ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactVelocityConstraint));
+ m_positions = def->positions;
+ m_velocities = def->velocities;
+ m_contacts = def->contacts;
+
+ // Initialize position independent portions of the constraints.
+ for (int32 i = 0; i < m_count; ++i)
+ {
+ b2Contact* contact = m_contacts[i];
+
+ b2Fixture* fixtureA = contact->m_fixtureA;
+ b2Fixture* fixtureB = contact->m_fixtureB;
+ b2Shape* shapeA = fixtureA->GetShape();
+ b2Shape* shapeB = fixtureB->GetShape();
+ float32 radiusA = shapeA->m_radius;
+ float32 radiusB = shapeB->m_radius;
+ b2Body* bodyA = fixtureA->GetBody();
+ b2Body* bodyB = fixtureB->GetBody();
+ b2Manifold* manifold = contact->GetManifold();
+
+ int32 pointCount = manifold->pointCount;
+ b2Assert(pointCount > 0);
+
+ b2ContactVelocityConstraint* vc = m_velocityConstraints + i;
+ vc->friction = contact->m_friction;
+ vc->restitution = contact->m_restitution;
+ vc->indexA = bodyA->m_islandIndex;
+ vc->indexB = bodyB->m_islandIndex;
+ vc->invMassA = bodyA->m_invMass;
+ vc->invMassB = bodyB->m_invMass;
+ vc->invIA = bodyA->m_invI;
+ vc->invIB = bodyB->m_invI;
+ vc->contactIndex = i;
+ vc->pointCount = pointCount;
+ vc->K.SetZero();
+ vc->normalMass.SetZero();
+
+ b2ContactPositionConstraint* pc = m_positionConstraints + i;
+ pc->indexA = bodyA->m_islandIndex;
+ pc->indexB = bodyB->m_islandIndex;
+ pc->invMassA = bodyA->m_invMass;
+ pc->invMassB = bodyB->m_invMass;
+ pc->localCenterA = bodyA->m_sweep.localCenter;
+ pc->localCenterB = bodyB->m_sweep.localCenter;
+ pc->invIA = bodyA->m_invI;
+ pc->invIB = bodyB->m_invI;
+ pc->localNormal = manifold->localNormal;
+ pc->localPoint = manifold->localPoint;
+ pc->pointCount = pointCount;
+ pc->radiusA = radiusA;
+ pc->radiusB = radiusB;
+ pc->type = manifold->type;
+
+ for (int32 j = 0; j < pointCount; ++j)
+ {
+ b2ManifoldPoint* cp = manifold->points + j;
+ b2VelocityConstraintPoint* vcp = vc->points + j;
+
+ if (m_step.warmStarting)
+ {
+ vcp->normalImpulse = m_step.dtRatio * cp->normalImpulse;
+ vcp->tangentImpulse = m_step.dtRatio * cp->tangentImpulse;
+ }
+ else
+ {
+ vcp->normalImpulse = 0.0f;
+ vcp->tangentImpulse = 0.0f;
+ }
+
+ vcp->rA.SetZero();
+ vcp->rB.SetZero();
+ vcp->normalMass = 0.0f;
+ vcp->tangentMass = 0.0f;
+ vcp->velocityBias = 0.0f;
+
+ pc->localPoints[j] = cp->localPoint;
+ }
+ }
+}
+
+b2ContactSolver::~b2ContactSolver()
+{
+ m_allocator->Free(m_velocityConstraints);
+ m_allocator->Free(m_positionConstraints);
+}
+
+// Initialize position dependent portions of the velocity constraints.
+void b2ContactSolver::InitializeVelocityConstraints()
+{
+ for (int32 i = 0; i < m_count; ++i)
+ {
+ b2ContactVelocityConstraint* vc = m_velocityConstraints + i;
+ b2ContactPositionConstraint* pc = m_positionConstraints + i;
+
+ float32 radiusA = pc->radiusA;
+ float32 radiusB = pc->radiusB;
+ b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold();
+
+ int32 indexA = vc->indexA;
+ int32 indexB = vc->indexB;
+
+ float32 mA = vc->invMassA;
+ float32 mB = vc->invMassB;
+ float32 iA = vc->invIA;
+ float32 iB = vc->invIB;
+ b2Vec2 localCenterA = pc->localCenterA;
+ b2Vec2 localCenterB = pc->localCenterB;
+
+ b2Vec2 cA = m_positions[indexA].c;
+ float32 aA = m_positions[indexA].a;
+ b2Vec2 vA = m_velocities[indexA].v;
+ float32 wA = m_velocities[indexA].w;
+
+ b2Vec2 cB = m_positions[indexB].c;
+ float32 aB = m_positions[indexB].a;
+ b2Vec2 vB = m_velocities[indexB].v;
+ float32 wB = m_velocities[indexB].w;
+
+ b2Assert(manifold->pointCount > 0);
+
+ b2Transform xfA, xfB;
+ xfA.q.Set(aA);
+ xfB.q.Set(aB);
+ xfA.p = cA - b2Mul(xfA.q, localCenterA);
+ xfB.p = cB - b2Mul(xfB.q, localCenterB);
+
+ b2WorldManifold worldManifold;
+ worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB);
+
+ vc->normal = worldManifold.normal;
+
+ int32 pointCount = vc->pointCount;
+ for (int32 j = 0; j < pointCount; ++j)
+ {
+ b2VelocityConstraintPoint* vcp = vc->points + j;
+
+ vcp->rA = worldManifold.points[j] - cA;
+ vcp->rB = worldManifold.points[j] - cB;
+
+ float32 rnA = b2Cross(vcp->rA, vc->normal);
+ float32 rnB = b2Cross(vcp->rB, vc->normal);
+
+ float32 kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
+
+ vcp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
+
+ b2Vec2 tangent = b2Cross(vc->normal, 1.0f);
+
+ float32 rtA = b2Cross(vcp->rA, tangent);
+ float32 rtB = b2Cross(vcp->rB, tangent);
+
+ float32 kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
+
+ vcp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f;
+
+ // Setup a velocity bias for restitution.
+ vcp->velocityBias = 0.0f;
+ float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA));
+ if (vRel < -b2_velocityThreshold)
+ {
+ vcp->velocityBias = -vc->restitution * vRel;
+ }
+ }
+
+ // If we have two points, then prepare the block solver.
+ if (vc->pointCount == 2)
+ {
+ b2VelocityConstraintPoint* vcp1 = vc->points + 0;
+ b2VelocityConstraintPoint* vcp2 = vc->points + 1;
+
+ float32 rn1A = b2Cross(vcp1->rA, vc->normal);
+ float32 rn1B = b2Cross(vcp1->rB, vc->normal);
+ float32 rn2A = b2Cross(vcp2->rA, vc->normal);
+ float32 rn2B = b2Cross(vcp2->rB, vc->normal);
+
+ float32 k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B;
+ float32 k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B;
+ float32 k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B;
+
+ // Ensure a reasonable condition number.
+ const float32 k_maxConditionNumber = 1000.0f;
+ if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12))
+ {
+ // K is safe to invert.
+ vc->K.ex.Set(k11, k12);
+ vc->K.ey.Set(k12, k22);
+ vc->normalMass = vc->K.GetInverse();
+ }
+ else
+ {
+ // The constraints are redundant, just use one.
+ // TODO_ERIN use deepest?
+ vc->pointCount = 1;
+ }
+ }
+ }
+}
+
+void b2ContactSolver::WarmStart()
+{
+ // Warm start.
+ for (int32 i = 0; i < m_count; ++i)
+ {
+ b2ContactVelocityConstraint* vc = m_velocityConstraints + i;
+
+ int32 indexA = vc->indexA;
+ int32 indexB = vc->indexB;
+ float32 mA = vc->invMassA;
+ float32 iA = vc->invIA;
+ float32 mB = vc->invMassB;
+ float32 iB = vc->invIB;
+ int32 pointCount = vc->pointCount;
+
+ b2Vec2 vA = m_velocities[indexA].v;
+ float32 wA = m_velocities[indexA].w;
+ b2Vec2 vB = m_velocities[indexB].v;
+ float32 wB = m_velocities[indexB].w;
+
+ b2Vec2 normal = vc->normal;
+ b2Vec2 tangent = b2Cross(normal, 1.0f);
+
+ for (int32 j = 0; j < pointCount; ++j)
+ {
+ b2VelocityConstraintPoint* vcp = vc->points + j;
+ b2Vec2 P = vcp->normalImpulse * normal + vcp->tangentImpulse * tangent;
+ wA -= iA * b2Cross(vcp->rA, P);
+ vA -= mA * P;
+ wB += iB * b2Cross(vcp->rB, P);
+ vB += mB * P;
+ }
+
+ m_velocities[indexA].v = vA;
+ m_velocities[indexA].w = wA;
+ m_velocities[indexB].v = vB;
+ m_velocities[indexB].w = wB;
+ }
+}
+
+void b2ContactSolver::SolveVelocityConstraints()
+{
+ for (int32 i = 0; i < m_count; ++i)
+ {
+ b2ContactVelocityConstraint* vc = m_velocityConstraints + i;
+
+ int32 indexA = vc->indexA;
+ int32 indexB = vc->indexB;
+ float32 mA = vc->invMassA;
+ float32 iA = vc->invIA;
+ float32 mB = vc->invMassB;
+ float32 iB = vc->invIB;
+ int32 pointCount = vc->pointCount;
+
+ b2Vec2 vA = m_velocities[indexA].v;
+ float32 wA = m_velocities[indexA].w;
+ b2Vec2 vB = m_velocities[indexB].v;
+ float32 wB = m_velocities[indexB].w;
+
+ b2Vec2 normal = vc->normal;
+ b2Vec2 tangent = b2Cross(normal, 1.0f);
+ float32 friction = vc->friction;
+
+ b2Assert(pointCount == 1 || pointCount == 2);
+
+ // Solve tangent constraints first because non-penetration is more important
+ // than friction.
+ for (int32 j = 0; j < pointCount; ++j)
+ {
+ b2VelocityConstraintPoint* vcp = vc->points + j;
+
+ // Relative velocity at contact
+ b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA);
+
+ // Compute tangent force
+ float32 vt = b2Dot(dv, tangent);
+ float32 lambda = vcp->tangentMass * (-vt);
+
+ // b2Clamp the accumulated force
+ float32 maxFriction = friction * vcp->normalImpulse;
+ float32 newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction);
+ lambda = newImpulse - vcp->tangentImpulse;
+ vcp->tangentImpulse = newImpulse;
+
+ // Apply contact impulse
+ b2Vec2 P = lambda * tangent;
+
+ vA -= mA * P;
+ wA -= iA * b2Cross(vcp->rA, P);
+
+ vB += mB * P;
+ wB += iB * b2Cross(vcp->rB, P);
+ }
+
+ // Solve normal constraints
+ if (vc->pointCount == 1)
+ {
+ b2VelocityConstraintPoint* vcp = vc->points + 0;
+
+ // Relative velocity at contact
+ b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA);
+
+ // Compute normal impulse
+ float32 vn = b2Dot(dv, normal);
+ float32 lambda = -vcp->normalMass * (vn - vcp->velocityBias);
+
+ // b2Clamp the accumulated impulse
+ float32 newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f);
+ lambda = newImpulse - vcp->normalImpulse;
+ vcp->normalImpulse = newImpulse;
+
+ // Apply contact impulse
+ b2Vec2 P = lambda * normal;
+ vA -= mA * P;
+ wA -= iA * b2Cross(vcp->rA, P);
+
+ vB += mB * P;
+ wB += iB * b2Cross(vcp->rB, P);
+ }
+ else
+ {
+ // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite).
+ // Build the mini LCP for this contact patch
+ //
+ // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2
+ //
+ // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
+ // b = vn0 - velocityBias
+ //
+ // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i
+ // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases
+ // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid
+ // solution that satisfies the problem is chosen.
+ //
+ // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires
+ // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i).
+ //
+ // Substitute:
+ //
+ // x = a + d
+ //
+ // a := old total impulse
+ // x := new total impulse
+ // d := incremental impulse
+ //
+ // For the current iteration we extend the formula for the incremental impulse
+ // to compute the new total impulse:
+ //
+ // vn = A * d + b
+ // = A * (x - a) + b
+ // = A * x + b - A * a
+ // = A * x + b'
+ // b' = b - A * a;
+
+ b2VelocityConstraintPoint* cp1 = vc->points + 0;
+ b2VelocityConstraintPoint* cp2 = vc->points + 1;
+
+ b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse);
+ b2Assert(a.x >= 0.0f && a.y >= 0.0f);
+
+ // Relative velocity at contact
+ b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA);
+ b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA);
+
+ // Compute normal velocity
+ float32 vn1 = b2Dot(dv1, normal);
+ float32 vn2 = b2Dot(dv2, normal);
+
+ b2Vec2 b;
+ b.x = vn1 - cp1->velocityBias;
+ b.y = vn2 - cp2->velocityBias;
+
+ // Compute b'
+ b -= b2Mul(vc->K, a);
+
+ const float32 k_errorTol = 1e-3f;
+ B2_NOT_USED(k_errorTol);
+
+ for (;;)
+ {
+ //
+ // Case 1: vn = 0
+ //
+ // 0 = A * x + b'
+ //
+ // Solve for x:
+ //
+ // x = - inv(A) * b'
+ //
+ b2Vec2 x = - b2Mul(vc->normalMass, b);
+
+ if (x.x >= 0.0f && x.y >= 0.0f)
+ {
+ // Get the incremental impulse
+ b2Vec2 d = x - a;
+
+ // Apply incremental impulse
+ b2Vec2 P1 = d.x * normal;
+ b2Vec2 P2 = d.y * normal;
+ vA -= mA * (P1 + P2);
+ wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2));
+
+ vB += mB * (P1 + P2);
+ wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2));
+
+ // Accumulate
+ cp1->normalImpulse = x.x;
+ cp2->normalImpulse = x.y;
+
+#if B2_DEBUG_SOLVER == 1
+ // Postconditions
+ dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA);
+ dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA);
+
+ // Compute normal velocity
+ vn1 = b2Dot(dv1, normal);
+ vn2 = b2Dot(dv2, normal);
+
+ b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol);
+ b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol);
+#endif
+ break;
+ }
+
+ //
+ // Case 2: vn1 = 0 and x2 = 0
+ //
+ // 0 = a11 * x1 + a12 * 0 + b1'
+ // vn2 = a21 * x1 + a22 * 0 + b2'
+ //
+ x.x = - cp1->normalMass * b.x;
+ x.y = 0.0f;
+ vn1 = 0.0f;
+ vn2 = vc->K.ex.y * x.x + b.y;
+
+ if (x.x >= 0.0f && vn2 >= 0.0f)
+ {
+ // Get the incremental impulse
+ b2Vec2 d = x - a;
+
+ // Apply incremental impulse
+ b2Vec2 P1 = d.x * normal;
+ b2Vec2 P2 = d.y * normal;
+ vA -= mA * (P1 + P2);
+ wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2));
+
+ vB += mB * (P1 + P2);
+ wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2));
+
+ // Accumulate
+ cp1->normalImpulse = x.x;
+ cp2->normalImpulse = x.y;
+
+#if B2_DEBUG_SOLVER == 1
+ // Postconditions
+ dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA);
+
+ // Compute normal velocity
+ vn1 = b2Dot(dv1, normal);
+
+ b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol);
+#endif
+ break;
+ }
+
+
+ //
+ // Case 3: vn2 = 0 and x1 = 0
+ //
+ // vn1 = a11 * 0 + a12 * x2 + b1'
+ // 0 = a21 * 0 + a22 * x2 + b2'
+ //
+ x.x = 0.0f;
+ x.y = - cp2->normalMass * b.y;
+ vn1 = vc->K.ey.x * x.y + b.x;
+ vn2 = 0.0f;
+
+ if (x.y >= 0.0f && vn1 >= 0.0f)
+ {
+ // Resubstitute for the incremental impulse
+ b2Vec2 d = x - a;
+
+ // Apply incremental impulse
+ b2Vec2 P1 = d.x * normal;
+ b2Vec2 P2 = d.y * normal;
+ vA -= mA * (P1 + P2);
+ wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2));
+
+ vB += mB * (P1 + P2);
+ wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2));
+
+ // Accumulate
+ cp1->normalImpulse = x.x;
+ cp2->normalImpulse = x.y;
+
+#if B2_DEBUG_SOLVER == 1
+ // Postconditions
+ dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA);
+
+ // Compute normal velocity
+ vn2 = b2Dot(dv2, normal);
+
+ b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol);
+#endif
+ break;
+ }
+
+ //
+ // Case 4: x1 = 0 and x2 = 0
+ //
+ // vn1 = b1
+ // vn2 = b2;
+ x.x = 0.0f;
+ x.y = 0.0f;
+ vn1 = b.x;
+ vn2 = b.y;
+
+ if (vn1 >= 0.0f && vn2 >= 0.0f )
+ {
+ // Resubstitute for the incremental impulse
+ b2Vec2 d = x - a;
+
+ // Apply incremental impulse
+ b2Vec2 P1 = d.x * normal;
+ b2Vec2 P2 = d.y * normal;
+ vA -= mA * (P1 + P2);
+ wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2));
+
+ vB += mB * (P1 + P2);
+ wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2));
+
+ // Accumulate
+ cp1->normalImpulse = x.x;
+ cp2->normalImpulse = x.y;
+
+ break;
+ }
+
+ // No solution, give up. This is hit sometimes, but it doesn't seem to matter.
+ break;
+ }
+ }
+
+ m_velocities[indexA].v = vA;
+ m_velocities[indexA].w = wA;
+ m_velocities[indexB].v = vB;
+ m_velocities[indexB].w = wB;
+ }
+}
+
+void b2ContactSolver::StoreImpulses()
+{
+ for (int32 i = 0; i < m_count; ++i)
+ {
+ b2ContactVelocityConstraint* vc = m_velocityConstraints + i;
+ b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold();
+
+ for (int32 j = 0; j < vc->pointCount; ++j)
+ {
+ manifold->points[j].normalImpulse = vc->points[j].normalImpulse;
+ manifold->points[j].tangentImpulse = vc->points[j].tangentImpulse;
+ }
+ }
+}
+
+struct b2PositionSolverManifold
+{
+ void Initialize(b2ContactPositionConstraint* pc, const b2Transform& xfA, const b2Transform& xfB, int32 index)
+ {
+ b2Assert(pc->pointCount > 0);
+
+ switch (pc->type)
+ {
+ case b2Manifold::e_circles:
+ {
+ b2Vec2 pointA = b2Mul(xfA, pc->localPoint);
+ b2Vec2 pointB = b2Mul(xfB, pc->localPoints[0]);
+ normal = pointB - pointA;
+ normal.Normalize();
+ point = 0.5f * (pointA + pointB);
+ separation = b2Dot(pointB - pointA, normal) - pc->radiusA - pc->radiusB;
+ }
+ break;
+
+ case b2Manifold::e_faceA:
+ {
+ normal = b2Mul(xfA.q, pc->localNormal);
+ b2Vec2 planePoint = b2Mul(xfA, pc->localPoint);
+
+ b2Vec2 clipPoint = b2Mul(xfB, pc->localPoints[index]);
+ separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB;
+ point = clipPoint;
+ }
+ break;
+
+ case b2Manifold::e_faceB:
+ {
+ normal = b2Mul(xfB.q, pc->localNormal);
+ b2Vec2 planePoint = b2Mul(xfB, pc->localPoint);
+
+ b2Vec2 clipPoint = b2Mul(xfA, pc->localPoints[index]);
+ separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB;
+ point = clipPoint;
+
+ // Ensure normal points from A to B
+ normal = -normal;
+ }
+ break;
+ }
+ }
+
+ b2Vec2 normal;
+ b2Vec2 point;
+ float32 separation;
+};
+
+// Sequential solver.
+bool b2ContactSolver::SolvePositionConstraints()
+{
+ float32 minSeparation = 0.0f;
+
+ for (int32 i = 0; i < m_count; ++i)
+ {
+ b2ContactPositionConstraint* pc = m_positionConstraints + i;
+
+ int32 indexA = pc->indexA;
+ int32 indexB = pc->indexB;
+ b2Vec2 localCenterA = pc->localCenterA;
+ float32 mA = pc->invMassA;
+ float32 iA = pc->invIA;
+ b2Vec2 localCenterB = pc->localCenterB;
+ float32 mB = pc->invMassB;
+ float32 iB = pc->invIB;
+ int32 pointCount = pc->pointCount;
+
+ b2Vec2 cA = m_positions[indexA].c;
+ float32 aA = m_positions[indexA].a;
+
+ b2Vec2 cB = m_positions[indexB].c;
+ float32 aB = m_positions[indexB].a;
+
+ // Solve normal constraints
+ for (int32 j = 0; j < pointCount; ++j)
+ {
+ b2Transform xfA, xfB;
+ xfA.q.Set(aA);
+ xfB.q.Set(aB);
+ xfA.p = cA - b2Mul(xfA.q, localCenterA);
+ xfB.p = cB - b2Mul(xfB.q, localCenterB);
+
+ b2PositionSolverManifold psm;
+ psm.Initialize(pc, xfA, xfB, j);
+ b2Vec2 normal = psm.normal;
+
+ b2Vec2 point = psm.point;
+ float32 separation = psm.separation;
+
+ b2Vec2 rA = point - cA;
+ b2Vec2 rB = point - cB;
+
+ // Track max constraint error.
+ minSeparation = b2Min(minSeparation, separation);
+
+ // Prevent large corrections and allow slop.
+ float32 C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f);
+
+ // Compute the effective mass.
+ float32 rnA = b2Cross(rA, normal);
+ float32 rnB = b2Cross(rB, normal);
+ float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
+
+ // Compute normal impulse
+ float32 impulse = K > 0.0f ? - C / K : 0.0f;
+
+ b2Vec2 P = impulse * normal;
+
+ cA -= mA * P;
+ aA -= iA * b2Cross(rA, P);
+
+ cB += mB * P;
+ aB += iB * b2Cross(rB, P);
+ }
+
+ m_positions[indexA].c = cA;
+ m_positions[indexA].a = aA;
+
+ m_positions[indexB].c = cB;
+ m_positions[indexB].a = aB;
+ }
+
+ // We can't expect minSpeparation >= -b2_linearSlop because we don't
+ // push the separation above -b2_linearSlop.
+ return minSeparation >= -3.0f * b2_linearSlop;
+}
+
+// Sequential position solver for position constraints.
+bool b2ContactSolver::SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB)
+{
+ float32 minSeparation = 0.0f;
+
+ for (int32 i = 0; i < m_count; ++i)
+ {
+ b2ContactPositionConstraint* pc = m_positionConstraints + i;
+
+ int32 indexA = pc->indexA;
+ int32 indexB = pc->indexB;
+ b2Vec2 localCenterA = pc->localCenterA;
+ b2Vec2 localCenterB = pc->localCenterB;
+ int32 pointCount = pc->pointCount;
+
+ float32 mA = 0.0f;
+ float32 iA = 0.0f;
+ if (indexA == toiIndexA || indexA == toiIndexB)
+ {
+ mA = pc->invMassA;
+ iA = pc->invIA;
+ }
+
+ float32 mB = pc->invMassB;
+ float32 iB = pc->invIB;
+ if (indexB == toiIndexA || indexB == toiIndexB)
+ {
+ mB = pc->invMassB;
+ iB = pc->invIB;
+ }
+
+ b2Vec2 cA = m_positions[indexA].c;
+ float32 aA = m_positions[indexA].a;
+
+ b2Vec2 cB = m_positions[indexB].c;
+ float32 aB = m_positions[indexB].a;
+
+ // Solve normal constraints
+ for (int32 j = 0; j < pointCount; ++j)
+ {
+ b2Transform xfA, xfB;
+ xfA.q.Set(aA);
+ xfB.q.Set(aB);
+ xfA.p = cA - b2Mul(xfA.q, localCenterA);
+ xfB.p = cB - b2Mul(xfB.q, localCenterB);
+
+ b2PositionSolverManifold psm;
+ psm.Initialize(pc, xfA, xfB, j);
+ b2Vec2 normal = psm.normal;
+
+ b2Vec2 point = psm.point;
+ float32 separation = psm.separation;
+
+ b2Vec2 rA = point - cA;
+ b2Vec2 rB = point - cB;
+
+ // Track max constraint error.
+ minSeparation = b2Min(minSeparation, separation);
+
+ // Prevent large corrections and allow slop.
+ float32 C = b2Clamp(b2_toiBaugarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f);
+
+ // Compute the effective mass.
+ float32 rnA = b2Cross(rA, normal);
+ float32 rnB = b2Cross(rB, normal);
+ float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
+
+ // Compute normal impulse
+ float32 impulse = K > 0.0f ? - C / K : 0.0f;
+
+ b2Vec2 P = impulse * normal;
+
+ cA -= mA * P;
+ aA -= iA * b2Cross(rA, P);
+
+ cB += mB * P;
+ aB += iB * b2Cross(rB, P);
+ }
+
+ m_positions[indexA].c = cA;
+ m_positions[indexA].a = aA;
+
+ m_positions[indexB].c = cB;
+ m_positions[indexB].a = aB;
+ }
+
+ // We can't expect minSpeparation >= -b2_linearSlop because we don't
+ // push the separation above -b2_linearSlop.
+ return minSeparation >= -1.5f * b2_linearSlop;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h
new file mode 100644
index 00000000..ca9de04d
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2ContactSolver.h
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2006-2009 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_CONTACT_SOLVER_H
+#define B2_CONTACT_SOLVER_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+
+class b2Contact;
+class b2Body;
+class b2StackAllocator;
+struct b2ContactPositionConstraint;
+
+struct b2VelocityConstraintPoint
+{
+ b2Vec2 rA;
+ b2Vec2 rB;
+ float32 normalImpulse;
+ float32 tangentImpulse;
+ float32 normalMass;
+ float32 tangentMass;
+ float32 velocityBias;
+};
+
+struct b2ContactVelocityConstraint
+{
+ b2VelocityConstraintPoint points[b2_maxManifoldPoints];
+ b2Vec2 normal;
+ b2Mat22 normalMass;
+ b2Mat22 K;
+ int32 indexA;
+ int32 indexB;
+ float32 invMassA, invMassB;
+ float32 invIA, invIB;
+ float32 friction;
+ float32 restitution;
+ int32 pointCount;
+ int32 contactIndex;
+};
+
+struct b2ContactSolverDef
+{
+ b2TimeStep step;
+ b2Contact** contacts;
+ int32 count;
+ b2Position* positions;
+ b2Velocity* velocities;
+ b2StackAllocator* allocator;
+};
+
+class b2ContactSolver
+{
+public:
+ b2ContactSolver(b2ContactSolverDef* def);
+ ~b2ContactSolver();
+
+ void InitializeVelocityConstraints();
+
+ void WarmStart();
+ void SolveVelocityConstraints();
+ void StoreImpulses();
+
+ bool SolvePositionConstraints();
+ bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB);
+
+ b2TimeStep m_step;
+ b2Position* m_positions;
+ b2Velocity* m_velocities;
+ b2StackAllocator* m_allocator;
+ b2ContactPositionConstraint* m_positionConstraints;
+ b2ContactVelocityConstraint* m_velocityConstraints;
+ b2Contact** m_contacts;
+ int m_count;
+};
+
+#endif
+
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp
new file mode 100644
index 00000000..04336507
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2006-2010 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/Contacts/b2EdgeAndCircleContact.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+
+#include <new>
+using namespace std;
+
+b2Contact* b2EdgeAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator)
+{
+ void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact));
+ return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB);
+}
+
+void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
+{
+ ((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact();
+ allocator->Free(contact, sizeof(b2EdgeAndCircleContact));
+}
+
+b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
+: b2Contact(fixtureA, 0, fixtureB, 0)
+{
+ b2Assert(m_fixtureA->GetType() == b2Shape::e_edge);
+ b2Assert(m_fixtureB->GetType() == b2Shape::e_circle);
+}
+
+void b2EdgeAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
+{
+ b2CollideEdgeAndCircle( manifold,
+ (b2EdgeShape*)m_fixtureA->GetShape(), xfA,
+ (b2CircleShape*)m_fixtureB->GetShape(), xfB);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h
new file mode 100644
index 00000000..11b61b88
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2006-2009 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_EDGE_AND_CIRCLE_CONTACT_H
+#define B2_EDGE_AND_CIRCLE_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2EdgeAndCircleContact : public b2Contact
+{
+public:
+ static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
+ b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
+ static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+ b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+ ~b2EdgeAndCircleContact() {}
+
+ void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp
new file mode 100644
index 00000000..8bac536a
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2006-2010 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/Contacts/b2EdgeAndPolygonContact.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+
+#include <new>
+using namespace std;
+
+b2Contact* b2EdgeAndPolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator)
+{
+ void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact));
+ return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB);
+}
+
+void b2EdgeAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
+{
+ ((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact();
+ allocator->Free(contact, sizeof(b2EdgeAndPolygonContact));
+}
+
+b2EdgeAndPolygonContact::b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
+: b2Contact(fixtureA, 0, fixtureB, 0)
+{
+ b2Assert(m_fixtureA->GetType() == b2Shape::e_edge);
+ b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon);
+}
+
+void b2EdgeAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
+{
+ b2CollideEdgeAndPolygon( manifold,
+ (b2EdgeShape*)m_fixtureA->GetShape(), xfA,
+ (b2PolygonShape*)m_fixtureB->GetShape(), xfB);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h
new file mode 100644
index 00000000..74b27ee0
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2006-2009 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_EDGE_AND_POLYGON_CONTACT_H
+#define B2_EDGE_AND_POLYGON_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2EdgeAndPolygonContact : public b2Contact
+{
+public:
+ static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
+ b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
+ static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+ b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+ ~b2EdgeAndPolygonContact() {}
+
+ void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp
new file mode 100644
index 00000000..880f83e2
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2006-2009 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/Contacts/b2PolygonAndCircleContact.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+
+#include <new>
+using namespace std;
+
+b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator)
+{
+ void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact));
+ return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB);
+}
+
+void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
+{
+ ((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact();
+ allocator->Free(contact, sizeof(b2PolygonAndCircleContact));
+}
+
+b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
+: b2Contact(fixtureA, 0, fixtureB, 0)
+{
+ b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon);
+ b2Assert(m_fixtureB->GetType() == b2Shape::e_circle);
+}
+
+void b2PolygonAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
+{
+ b2CollidePolygonAndCircle( manifold,
+ (b2PolygonShape*)m_fixtureA->GetShape(), xfA,
+ (b2CircleShape*)m_fixtureB->GetShape(), xfB);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h
new file mode 100644
index 00000000..6beca16a
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h
@@ -0,0 +1,38 @@
+/*
+* Copyright (c) 2006-2009 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_POLYGON_AND_CIRCLE_CONTACT_H
+#define B2_POLYGON_AND_CIRCLE_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2PolygonAndCircleContact : public b2Contact
+{
+public:
+ static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
+ static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+ b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+ ~b2PolygonAndCircleContact() {}
+
+ void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp
new file mode 100644
index 00000000..52e1be87
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.cpp
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2006-2009 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/Contacts/b2PolygonContact.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Collision/b2TimeOfImpact.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2WorldCallbacks.h>
+
+#include <new>
+using namespace std;
+
+b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator)
+{
+ void* mem = allocator->Allocate(sizeof(b2PolygonContact));
+ return new (mem) b2PolygonContact(fixtureA, fixtureB);
+}
+
+void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator)
+{
+ ((b2PolygonContact*)contact)->~b2PolygonContact();
+ allocator->Free(contact, sizeof(b2PolygonContact));
+}
+
+b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB)
+ : b2Contact(fixtureA, 0, fixtureB, 0)
+{
+ b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon);
+ b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon);
+}
+
+void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB)
+{
+ b2CollidePolygons( manifold,
+ (b2PolygonShape*)m_fixtureA->GetShape(), xfA,
+ (b2PolygonShape*)m_fixtureB->GetShape(), xfB);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h
new file mode 100644
index 00000000..45932148
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Contacts/b2PolygonContact.h
@@ -0,0 +1,39 @@
+/*
+* Copyright (c) 2006-2009 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_POLYGON_CONTACT_H
+#define B2_POLYGON_CONTACT_H
+
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+class b2BlockAllocator;
+
+class b2PolygonContact : public b2Contact
+{
+public:
+ static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
+ b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
+ static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
+
+ b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
+ ~b2PolygonContact() {}
+
+ void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp
new file mode 100644
index 00000000..1ced7d9d
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.cpp
@@ -0,0 +1,260 @@
+/*
+* 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/b2DistanceJoint.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+
+// 1-D constrained system
+// m (v2 - v1) = lambda
+// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass.
+// x2 = x1 + h * v2
+
+// 1-D mass-damper-spring system
+// m (v2 - v1) + h * d * v2 + h * k *
+
+// C = norm(p2 - p1) - L
+// u = (p2 - p1) / norm(p2 - p1)
+// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
+// J = [-u -cross(r1, u) u cross(r2, u)]
+// K = J * invM * JT
+// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
+
+void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2,
+ const b2Vec2& anchor1, const b2Vec2& anchor2)
+{
+ bodyA = b1;
+ bodyB = b2;
+ localAnchorA = bodyA->GetLocalPoint(anchor1);
+ localAnchorB = bodyB->GetLocalPoint(anchor2);
+ b2Vec2 d = anchor2 - anchor1;
+ length = d.Length();
+}
+
+b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def)
+: b2Joint(def)
+{
+ m_localAnchorA = def->localAnchorA;
+ m_localAnchorB = def->localAnchorB;
+ m_length = def->length;
+ m_frequencyHz = def->frequencyHz;
+ m_dampingRatio = def->dampingRatio;
+ m_impulse = 0.0f;
+ m_gamma = 0.0f;
+ m_bias = 0.0f;
+}
+
+void b2DistanceJoint::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);
+
+ m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
+ m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
+ m_u = cB + m_rB - cA - m_rA;
+
+ // Handle singularity.
+ float32 length = m_u.Length();
+ if (length > b2_linearSlop)
+ {
+ m_u *= 1.0f / length;
+ }
+ else
+ {
+ m_u.Set(0.0f, 0.0f);
+ }
+
+ float32 crAu = b2Cross(m_rA, m_u);
+ float32 crBu = b2Cross(m_rB, m_u);
+ float32 invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu;
+
+ // Compute the effective mass matrix.
+ m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f;
+
+ if (m_frequencyHz > 0.0f)
+ {
+ float32 C = length - m_length;
+
+ // Frequency
+ float32 omega = 2.0f * b2_pi * m_frequencyHz;
+
+ // Damping coefficient
+ float32 d = 2.0f * m_mass * m_dampingRatio * omega;
+
+ // Spring stiffness
+ float32 k = m_mass * omega * omega;
+
+ // magic formulas
+ float32 h = data.step.dt;
+ m_gamma = h * (d + h * k);
+ m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f;
+ m_bias = C * h * k * m_gamma;
+
+ invMass += m_gamma;
+ m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f;
+ }
+ else
+ {
+ m_gamma = 0.0f;
+ m_bias = 0.0f;
+ }
+
+ if (data.step.warmStarting)
+ {
+ // Scale the impulse to support a variable time step.
+ m_impulse *= data.step.dtRatio;
+
+ b2Vec2 P = m_impulse * m_u;
+ vA -= m_invMassA * P;
+ wA -= m_invIA * b2Cross(m_rA, P);
+ vB += m_invMassB * P;
+ wB += m_invIB * b2Cross(m_rB, P);
+ }
+ else
+ {
+ m_impulse = 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 b2DistanceJoint::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;
+
+ // Cdot = dot(u, v + cross(w, r))
+ b2Vec2 vpA = vA + b2Cross(wA, m_rA);
+ b2Vec2 vpB = vB + b2Cross(wB, m_rB);
+ float32 Cdot = b2Dot(m_u, vpB - vpA);
+
+ float32 impulse = -m_mass * (Cdot + m_bias + m_gamma * m_impulse);
+ m_impulse += impulse;
+
+ b2Vec2 P = impulse * m_u;
+ vA -= m_invMassA * P;
+ wA -= m_invIA * b2Cross(m_rA, P);
+ vB += m_invMassB * P;
+ wB += m_invIB * b2Cross(m_rB, P);
+
+ 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 b2DistanceJoint::SolvePositionConstraints(const b2SolverData& data)
+{
+ if (m_frequencyHz > 0.0f)
+ {
+ // There is no position correction for soft distance constraints.
+ return true;
+ }
+
+ 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);
+
+ b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
+ b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
+ b2Vec2 u = cB + rB - cA - rA;
+
+ float32 length = u.Normalize();
+ float32 C = length - m_length;
+ C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection);
+
+ float32 impulse = -m_mass * C;
+ b2Vec2 P = impulse * u;
+
+ cA -= m_invMassA * P;
+ aA -= m_invIA * b2Cross(rA, P);
+ cB += m_invMassB * P;
+ aB += m_invIB * b2Cross(rB, P);
+
+ 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 b2Abs(C) < b2_linearSlop;
+}
+
+b2Vec2 b2DistanceJoint::GetAnchorA() const
+{
+ return m_bodyA->GetWorldPoint(m_localAnchorA);
+}
+
+b2Vec2 b2DistanceJoint::GetAnchorB() const
+{
+ return m_bodyB->GetWorldPoint(m_localAnchorB);
+}
+
+b2Vec2 b2DistanceJoint::GetReactionForce(float32 inv_dt) const
+{
+ b2Vec2 F = (inv_dt * m_impulse) * m_u;
+ return F;
+}
+
+float32 b2DistanceJoint::GetReactionTorque(float32 inv_dt) const
+{
+ B2_NOT_USED(inv_dt);
+ return 0.0f;
+}
+
+void b2DistanceJoint::Dump()
+{
+ int32 indexA = m_bodyA->m_islandIndex;
+ int32 indexB = m_bodyB->m_islandIndex;
+
+ b2Log(" b2DistanceJointDef 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.length = %.15lef;\n", m_length);
+ b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz);
+ b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio);
+ b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h
new file mode 100644
index 00000000..9d0528b9
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2DistanceJoint.h
@@ -0,0 +1,169 @@
+/*
+* Copyright (c) 2006-2007 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_DISTANCE_JOINT_H
+#define B2_DISTANCE_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Distance joint definition. This requires defining an
+/// anchor point on both bodies and the non-zero length of the
+/// distance joint. The definition uses local anchor points
+/// so that the initial configuration can violate the constraint
+/// slightly. This helps when saving and loading a game.
+/// @warning Do not use a zero or short length.
+struct b2DistanceJointDef : public b2JointDef
+{
+ b2DistanceJointDef()
+ {
+ type = e_distanceJoint;
+ localAnchorA.Set(0.0f, 0.0f);
+ localAnchorB.Set(0.0f, 0.0f);
+ length = 1.0f;
+ frequencyHz = 0.0f;
+ dampingRatio = 0.0f;
+ }
+
+ /// Initialize the bodies, anchors, and length using the world
+ /// anchors.
+ void Initialize(b2Body* bodyA, b2Body* bodyB,
+ const b2Vec2& anchorA, const b2Vec2& anchorB);
+
+ /// The local anchor point relative to bodyA's origin.
+ b2Vec2 localAnchorA;
+
+ /// The local anchor point relative to bodyB's origin.
+ b2Vec2 localAnchorB;
+
+ /// The natural length between the anchor points.
+ float32 length;
+
+ /// The mass-spring-damper frequency in Hertz. A value of 0
+ /// disables softness.
+ float32 frequencyHz;
+
+ /// The damping ratio. 0 = no damping, 1 = critical damping.
+ float32 dampingRatio;
+};
+
+/// A distance joint constrains two points on two bodies
+/// to remain at a fixed distance from each other. You can view
+/// this as a massless, rigid rod.
+class b2DistanceJoint : public b2Joint
+{
+public:
+
+ b2Vec2 GetAnchorA() const;
+ b2Vec2 GetAnchorB() const;
+
+ /// Get the reaction force given the inverse time step.
+ /// Unit is N.
+ b2Vec2 GetReactionForce(float32 inv_dt) const;
+
+ /// Get the reaction torque given the inverse time step.
+ /// Unit is N*m. This is always zero for a distance joint.
+ 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; }
+
+ /// Set/get the natural length.
+ /// Manipulating the length can lead to non-physical behavior when the frequency is zero.
+ void SetLength(float32 length);
+ float32 GetLength() const;
+
+ /// Set/get frequency in Hz.
+ void SetFrequency(float32 hz);
+ float32 GetFrequency() const;
+
+ /// Set/get damping ratio.
+ void SetDampingRatio(float32 ratio);
+ float32 GetDampingRatio() const;
+
+ /// Dump joint to dmLog
+ void Dump();
+
+protected:
+
+ friend class b2Joint;
+ b2DistanceJoint(const b2DistanceJointDef* data);
+
+ void InitVelocityConstraints(const b2SolverData& data);
+ void SolveVelocityConstraints(const b2SolverData& data);
+ bool SolvePositionConstraints(const b2SolverData& data);
+
+ float32 m_frequencyHz;
+ float32 m_dampingRatio;
+ float32 m_bias;
+
+ // Solver shared
+ b2Vec2 m_localAnchorA;
+ b2Vec2 m_localAnchorB;
+ float32 m_gamma;
+ float32 m_impulse;
+ float32 m_length;
+
+ // Solver temp
+ int32 m_indexA;
+ int32 m_indexB;
+ b2Vec2 m_u;
+ b2Vec2 m_rA;
+ b2Vec2 m_rB;
+ b2Vec2 m_localCenterA;
+ b2Vec2 m_localCenterB;
+ float32 m_invMassA;
+ float32 m_invMassB;
+ float32 m_invIA;
+ float32 m_invIB;
+ float32 m_mass;
+};
+
+inline void b2DistanceJoint::SetLength(float32 length)
+{
+ m_length = length;
+}
+
+inline float32 b2DistanceJoint::GetLength() const
+{
+ return m_length;
+}
+
+inline void b2DistanceJoint::SetFrequency(float32 hz)
+{
+ m_frequencyHz = hz;
+}
+
+inline float32 b2DistanceJoint::GetFrequency() const
+{
+ return m_frequencyHz;
+}
+
+inline void b2DistanceJoint::SetDampingRatio(float32 ratio)
+{
+ m_dampingRatio = ratio;
+}
+
+inline float32 b2DistanceJoint::GetDampingRatio() const
+{
+ return m_dampingRatio;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2Joint.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2Joint.cpp
new file mode 100644
index 00000000..6ad78b0f
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2Joint.cpp
@@ -0,0 +1,116 @@
+/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): only the distance, revolute and wheel joints are made */
+/*
+* Copyright (c) 2006-2007 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/b2Joint.h>
+#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>
+#include <Box2D/Dynamics/Joints/b2WheelJoint.h>
+#include <Box2D/Dynamics/Joints/b2RevoluteJoint.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2World.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+
+#include <new>
+
+b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator)
+{
+ b2Joint* joint = NULL;
+
+ switch (def->type)
+ {
+ case e_distanceJoint:
+ {
+ void* mem = allocator->Allocate(sizeof(b2DistanceJoint));
+ joint = new (mem) b2DistanceJoint((b2DistanceJointDef*)def);
+ }
+ break;
+
+ case e_revoluteJoint:
+ {
+ void* mem = allocator->Allocate(sizeof(b2RevoluteJoint));
+ joint = new (mem) b2RevoluteJoint((b2RevoluteJointDef*)def);
+ }
+ break;
+
+ case e_wheelJoint:
+ {
+ void* mem = allocator->Allocate(sizeof(b2WheelJoint));
+ joint = new (mem) b2WheelJoint((b2WheelJointDef*)def);
+ }
+ break;
+
+ default:
+ b2Assert(false);
+ break;
+ }
+
+ return joint;
+}
+
+void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator)
+{
+ joint->~b2Joint();
+ switch (joint->m_type)
+ {
+ case e_distanceJoint:
+ allocator->Free(joint, sizeof(b2DistanceJoint));
+ break;
+
+ case e_revoluteJoint:
+ allocator->Free(joint, sizeof(b2RevoluteJoint));
+ break;
+
+ case e_wheelJoint:
+ allocator->Free(joint, sizeof(b2WheelJoint));
+ break;
+
+ default:
+ b2Assert(false);
+ break;
+ }
+}
+
+b2Joint::b2Joint(const b2JointDef* def)
+{
+ b2Assert(def->bodyA != def->bodyB);
+
+ m_type = def->type;
+ m_prev = NULL;
+ m_next = NULL;
+ m_bodyA = def->bodyA;
+ m_bodyB = def->bodyB;
+ m_index = 0;
+ m_collideConnected = def->collideConnected;
+ m_islandFlag = false;
+ m_userData = def->userData;
+
+ m_edgeA.joint = NULL;
+ m_edgeA.other = NULL;
+ m_edgeA.prev = NULL;
+ m_edgeA.next = NULL;
+
+ m_edgeB.joint = NULL;
+ m_edgeB.other = NULL;
+ m_edgeB.prev = NULL;
+ m_edgeB.next = NULL;
+}
+
+bool b2Joint::IsActive() const
+{
+ return m_bodyA->IsActive() && m_bodyB->IsActive();
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2Joint.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2Joint.h
new file mode 100644
index 00000000..90154ccb
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2Joint.h
@@ -0,0 +1,222 @@
+/*
+* Copyright (c) 2006-2007 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_JOINT_H
+#define B2_JOINT_H
+
+#include <Box2D/Common/b2Math.h>
+
+class b2Body;
+class b2Joint;
+struct b2SolverData;
+class b2BlockAllocator;
+
+enum b2JointType
+{
+ e_unknownJoint,
+ e_revoluteJoint,
+ e_prismaticJoint,
+ e_distanceJoint,
+ e_pulleyJoint,
+ e_mouseJoint,
+ e_gearJoint,
+ e_wheelJoint,
+ e_weldJoint,
+ e_frictionJoint,
+ e_ropeJoint
+};
+
+enum b2LimitState
+{
+ e_inactiveLimit,
+ e_atLowerLimit,
+ e_atUpperLimit,
+ e_equalLimits
+};
+
+struct b2Jacobian
+{
+ b2Vec2 linear;
+ float32 angularA;
+ float32 angularB;
+};
+
+/// A joint edge is used to connect bodies and joints together
+/// in a joint graph where each body is a node and each joint
+/// is an edge. A joint edge belongs to a doubly linked list
+/// maintained in each attached body. Each joint has two joint
+/// nodes, one for each attached body.
+struct b2JointEdge
+{
+ b2Body* other; ///< provides quick access to the other body attached.
+ b2Joint* joint; ///< the joint
+ b2JointEdge* prev; ///< the previous joint edge in the body's joint list
+ b2JointEdge* next; ///< the next joint edge in the body's joint list
+};
+
+/// Joint definitions are used to construct joints.
+struct b2JointDef
+{
+ b2JointDef()
+ {
+ type = e_unknownJoint;
+ userData = NULL;
+ bodyA = NULL;
+ bodyB = NULL;
+ collideConnected = false;
+ }
+
+ /// The joint type is set automatically for concrete joint types.
+ b2JointType type;
+
+ /// Use this to attach application specific data to your joints.
+ void* userData;
+
+ /// The first attached body.
+ b2Body* bodyA;
+
+ /// The second attached body.
+ b2Body* bodyB;
+
+ /// Set this flag to true if the attached bodies should collide.
+ bool collideConnected;
+};
+
+/// The base joint class. Joints are used to constraint two bodies together in
+/// various fashions. Some joints also feature limits and motors.
+class b2Joint
+{
+public:
+
+ /// Get the type of the concrete joint.
+ b2JointType GetType() const;
+
+ /// Get the first body attached to this joint.
+ b2Body* GetBodyA();
+
+ /// Get the second body attached to this joint.
+ b2Body* GetBodyB();
+
+ /// Get the anchor point on bodyA in world coordinates.
+ virtual b2Vec2 GetAnchorA() const = 0;
+
+ /// Get the anchor point on bodyB in world coordinates.
+ virtual b2Vec2 GetAnchorB() const = 0;
+
+ /// Get the reaction force on bodyB at the joint anchor in Newtons.
+ virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0;
+
+ /// Get the reaction torque on bodyB in N*m.
+ virtual float32 GetReactionTorque(float32 inv_dt) const = 0;
+
+ /// Get the next joint the world joint list.
+ b2Joint* GetNext();
+ const b2Joint* GetNext() const;
+
+ /// Get the user data pointer.
+ void* GetUserData() const;
+
+ /// Set the user data pointer.
+ void SetUserData(void* data);
+
+ /// Short-cut function to determine if either body is inactive.
+ bool IsActive() const;
+
+ /// Get collide connected.
+ /// Note: modifying the collide connect flag won't work correctly because
+ /// the flag is only checked when fixture AABBs begin to overlap.
+ bool GetCollideConnected() const;
+
+ /// Dump this joint to the log file.
+ virtual void Dump() { b2Log("// Dump is not supported for this joint type.\n"); }
+
+protected:
+ friend class b2World;
+ friend class b2Body;
+ friend class b2Island;
+ friend class b2GearJoint;
+
+ static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator);
+ static void Destroy(b2Joint* joint, b2BlockAllocator* allocator);
+
+ b2Joint(const b2JointDef* def);
+ virtual ~b2Joint() {}
+
+ virtual void InitVelocityConstraints(const b2SolverData& data) = 0;
+ virtual void SolveVelocityConstraints(const b2SolverData& data) = 0;
+
+ // This returns true if the position errors are within tolerance.
+ virtual bool SolvePositionConstraints(const b2SolverData& data) = 0;
+
+ b2JointType m_type;
+ b2Joint* m_prev;
+ b2Joint* m_next;
+ b2JointEdge m_edgeA;
+ b2JointEdge m_edgeB;
+ b2Body* m_bodyA;
+ b2Body* m_bodyB;
+
+ int32 m_index;
+
+ bool m_islandFlag;
+ bool m_collideConnected;
+
+ void* m_userData;
+};
+
+inline b2JointType b2Joint::GetType() const
+{
+ return m_type;
+}
+
+inline b2Body* b2Joint::GetBodyA()
+{
+ return m_bodyA;
+}
+
+inline b2Body* b2Joint::GetBodyB()
+{
+ return m_bodyB;
+}
+
+inline b2Joint* b2Joint::GetNext()
+{
+ return m_next;
+}
+
+inline const b2Joint* b2Joint::GetNext() const
+{
+ return m_next;
+}
+
+inline void* b2Joint::GetUserData() const
+{
+ return m_userData;
+}
+
+inline void b2Joint::SetUserData(void* data)
+{
+ m_userData = data;
+}
+
+inline bool b2Joint::GetCollideConnected() const
+{
+ return m_collideConnected;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp
new file mode 100644
index 00000000..ffb17252
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp
@@ -0,0 +1,504 @@
+/*
+* 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/b2RevoluteJoint.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+
+// Point-to-point constraint
+// C = p2 - p1
+// Cdot = v2 - v1
+// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
+// J = [-I -r1_skew I r2_skew ]
+// Identity used:
+// w k % (rx i + ry j) = w * (-ry i + rx j)
+
+// Motor constraint
+// Cdot = w2 - w1
+// J = [0 0 -1 0 0 1]
+// K = invI1 + invI2
+
+void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor)
+{
+ bodyA = bA;
+ bodyB = bB;
+ localAnchorA = bodyA->GetLocalPoint(anchor);
+ localAnchorB = bodyB->GetLocalPoint(anchor);
+ referenceAngle = bodyB->GetAngle() - bodyA->GetAngle();
+}
+
+b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def)
+: b2Joint(def)
+{
+ m_localAnchorA = def->localAnchorA;
+ m_localAnchorB = def->localAnchorB;
+ m_referenceAngle = def->referenceAngle;
+
+ m_impulse.SetZero();
+ m_motorImpulse = 0.0f;
+
+ m_lowerAngle = def->lowerAngle;
+ m_upperAngle = def->upperAngle;
+ m_maxMotorTorque = def->maxMotorTorque;
+ m_motorSpeed = def->motorSpeed;
+ m_enableLimit = def->enableLimit;
+ m_enableMotor = def->enableMotor;
+ m_limitState = e_inactiveLimit;
+}
+
+void b2RevoluteJoint::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);
+
+ m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
+ m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
+
+ // J = [-I -r1_skew I r2_skew]
+ // [ 0 -1 0 1]
+ // r_skew = [-ry; rx]
+
+ // Matlab
+ // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
+ // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
+ // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
+
+ float32 mA = m_invMassA, mB = m_invMassB;
+ float32 iA = m_invIA, iB = m_invIB;
+
+ bool fixedRotation = (iA + iB == 0.0f);
+
+ m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB;
+ m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB;
+ m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB;
+ m_mass.ex.y = m_mass.ey.x;
+ m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB;
+ m_mass.ez.y = m_rA.x * iA + m_rB.x * iB;
+ m_mass.ex.z = m_mass.ez.x;
+ m_mass.ey.z = m_mass.ez.y;
+ m_mass.ez.z = iA + iB;
+
+ m_motorMass = iA + iB;
+ if (m_motorMass > 0.0f)
+ {
+ m_motorMass = 1.0f / m_motorMass;
+ }
+
+ if (m_enableMotor == false || fixedRotation)
+ {
+ m_motorImpulse = 0.0f;
+ }
+
+ if (m_enableLimit && fixedRotation == false)
+ {
+ float32 jointAngle = aB - aA - m_referenceAngle;
+ if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop)
+ {
+ m_limitState = e_equalLimits;
+ }
+ else if (jointAngle <= m_lowerAngle)
+ {
+ if (m_limitState != e_atLowerLimit)
+ {
+ m_impulse.z = 0.0f;
+ }
+ m_limitState = e_atLowerLimit;
+ }
+ else if (jointAngle >= m_upperAngle)
+ {
+ if (m_limitState != e_atUpperLimit)
+ {
+ m_impulse.z = 0.0f;
+ }
+ m_limitState = e_atUpperLimit;
+ }
+ else
+ {
+ m_limitState = e_inactiveLimit;
+ m_impulse.z = 0.0f;
+ }
+ }
+ else
+ {
+ m_limitState = e_inactiveLimit;
+ }
+
+ if (data.step.warmStarting)
+ {
+ // Scale impulses to support a variable time step.
+ m_impulse *= data.step.dtRatio;
+ m_motorImpulse *= data.step.dtRatio;
+
+ b2Vec2 P(m_impulse.x, m_impulse.y);
+
+ vA -= mA * P;
+ wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z);
+
+ vB += mB * P;
+ wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z);
+ }
+ 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 b2RevoluteJoint::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;
+
+ bool fixedRotation = (iA + iB == 0.0f);
+
+ // Solve motor constraint.
+ if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false)
+ {
+ float32 Cdot = wB - wA - m_motorSpeed;
+ float32 impulse = -m_motorMass * Cdot;
+ float32 oldImpulse = m_motorImpulse;
+ float32 maxImpulse = data.step.dt * m_maxMotorTorque;
+ m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
+ impulse = m_motorImpulse - oldImpulse;
+
+ wA -= iA * impulse;
+ wB += iB * impulse;
+ }
+
+ // Solve limit constraint.
+ if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false)
+ {
+ b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
+ float32 Cdot2 = wB - wA;
+ b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2);
+
+ b2Vec3 impulse = -m_mass.Solve33(Cdot);
+
+ if (m_limitState == e_equalLimits)
+ {
+ m_impulse += impulse;
+ }
+ else if (m_limitState == e_atLowerLimit)
+ {
+ float32 newImpulse = m_impulse.z + impulse.z;
+ if (newImpulse < 0.0f)
+ {
+ b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y);
+ b2Vec2 reduced = m_mass.Solve22(rhs);
+ impulse.x = reduced.x;
+ impulse.y = reduced.y;
+ impulse.z = -m_impulse.z;
+ m_impulse.x += reduced.x;
+ m_impulse.y += reduced.y;
+ m_impulse.z = 0.0f;
+ }
+ else
+ {
+ m_impulse += impulse;
+ }
+ }
+ else if (m_limitState == e_atUpperLimit)
+ {
+ float32 newImpulse = m_impulse.z + impulse.z;
+ if (newImpulse > 0.0f)
+ {
+ b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y);
+ b2Vec2 reduced = m_mass.Solve22(rhs);
+ impulse.x = reduced.x;
+ impulse.y = reduced.y;
+ impulse.z = -m_impulse.z;
+ m_impulse.x += reduced.x;
+ m_impulse.y += reduced.y;
+ m_impulse.z = 0.0f;
+ }
+ else
+ {
+ m_impulse += impulse;
+ }
+ }
+
+ b2Vec2 P(impulse.x, impulse.y);
+
+ vA -= mA * P;
+ wA -= iA * (b2Cross(m_rA, P) + impulse.z);
+
+ vB += mB * P;
+ wB += iB * (b2Cross(m_rB, P) + impulse.z);
+ }
+ else
+ {
+ // Solve point-to-point constraint
+ b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA);
+ b2Vec2 impulse = m_mass.Solve22(-Cdot);
+
+ m_impulse.x += impulse.x;
+ m_impulse.y += impulse.y;
+
+ vA -= mA * impulse;
+ wA -= iA * b2Cross(m_rA, impulse);
+
+ vB += mB * impulse;
+ wB += iB * b2Cross(m_rB, impulse);
+ }
+
+ 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 b2RevoluteJoint::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 angularError = 0.0f;
+ float32 positionError = 0.0f;
+
+ bool fixedRotation = (m_invIA + m_invIB == 0.0f);
+
+ // Solve angular limit constraint.
+ if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false)
+ {
+ float32 angle = aB - aA - m_referenceAngle;
+ float32 limitImpulse = 0.0f;
+
+ if (m_limitState == e_equalLimits)
+ {
+ // Prevent large angular corrections
+ float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection);
+ limitImpulse = -m_motorMass * C;
+ angularError = b2Abs(C);
+ }
+ else if (m_limitState == e_atLowerLimit)
+ {
+ float32 C = angle - m_lowerAngle;
+ angularError = -C;
+
+ // Prevent large angular corrections and allow some slop.
+ C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f);
+ limitImpulse = -m_motorMass * C;
+ }
+ else if (m_limitState == e_atUpperLimit)
+ {
+ float32 C = angle - m_upperAngle;
+ angularError = C;
+
+ // Prevent large angular corrections and allow some slop.
+ C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection);
+ limitImpulse = -m_motorMass * C;
+ }
+
+ aA -= m_invIA * limitImpulse;
+ aB += m_invIB * limitImpulse;
+ }
+
+ // Solve point-to-point constraint.
+ {
+ qA.Set(aA);
+ qB.Set(aB);
+ b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
+ b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
+
+ b2Vec2 C = cB + rB - cA - rA;
+ positionError = C.Length();
+
+ float32 mA = m_invMassA, mB = m_invMassB;
+ float32 iA = m_invIA, iB = m_invIB;
+
+ b2Mat22 K;
+ K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y;
+ K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y;
+ K.ey.x = K.ex.y;
+ K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x;
+
+ b2Vec2 impulse = -K.Solve(C);
+
+ cA -= mA * impulse;
+ aA -= iA * b2Cross(rA, impulse);
+
+ cB += mB * impulse;
+ aB += iB * b2Cross(rB, impulse);
+ }
+
+ 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 positionError <= b2_linearSlop && angularError <= b2_angularSlop;
+}
+
+b2Vec2 b2RevoluteJoint::GetAnchorA() const
+{
+ return m_bodyA->GetWorldPoint(m_localAnchorA);
+}
+
+b2Vec2 b2RevoluteJoint::GetAnchorB() const
+{
+ return m_bodyB->GetWorldPoint(m_localAnchorB);
+}
+
+b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const
+{
+ b2Vec2 P(m_impulse.x, m_impulse.y);
+ return inv_dt * P;
+}
+
+float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const
+{
+ return inv_dt * m_impulse.z;
+}
+
+float32 b2RevoluteJoint::GetJointAngle() const
+{
+ b2Body* bA = m_bodyA;
+ b2Body* bB = m_bodyB;
+ return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle;
+}
+
+float32 b2RevoluteJoint::GetJointSpeed() const
+{
+ b2Body* bA = m_bodyA;
+ b2Body* bB = m_bodyB;
+ return bB->m_angularVelocity - bA->m_angularVelocity;
+}
+
+bool b2RevoluteJoint::IsMotorEnabled() const
+{
+ return m_enableMotor;
+}
+
+void b2RevoluteJoint::EnableMotor(bool flag)
+{
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_enableMotor = flag;
+}
+
+float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const
+{
+ return inv_dt * m_motorImpulse;
+}
+
+void b2RevoluteJoint::SetMotorSpeed(float32 speed)
+{
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_motorSpeed = speed;
+}
+
+void b2RevoluteJoint::SetMaxMotorTorque(float32 torque)
+{
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_maxMotorTorque = torque;
+}
+
+bool b2RevoluteJoint::IsLimitEnabled() const
+{
+ return m_enableLimit;
+}
+
+void b2RevoluteJoint::EnableLimit(bool flag)
+{
+ if (flag != m_enableLimit)
+ {
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_enableLimit = flag;
+ m_impulse.z = 0.0f;
+ }
+}
+
+float32 b2RevoluteJoint::GetLowerLimit() const
+{
+ return m_lowerAngle;
+}
+
+float32 b2RevoluteJoint::GetUpperLimit() const
+{
+ return m_upperAngle;
+}
+
+void b2RevoluteJoint::SetLimits(float32 lower, float32 upper)
+{
+ b2Assert(lower <= upper);
+
+ if (lower != m_lowerAngle || upper != m_upperAngle)
+ {
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_impulse.z = 0.0f;
+ m_lowerAngle = lower;
+ m_upperAngle = upper;
+ }
+}
+
+void b2RevoluteJoint::Dump()
+{
+ int32 indexA = m_bodyA->m_islandIndex;
+ int32 indexB = m_bodyB->m_islandIndex;
+
+ b2Log(" b2RevoluteJointDef 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.referenceAngle = %.15lef;\n", m_referenceAngle);
+ b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit);
+ b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle);
+ b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle);
+ b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor);
+ b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed);
+ b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque);
+ b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h
new file mode 100644
index 00000000..e62cdbcc
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2RevoluteJoint.h
@@ -0,0 +1,204 @@
+/*
+* 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_REVOLUTE_JOINT_H
+#define B2_REVOLUTE_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Revolute joint definition. This requires defining an
+/// anchor point where the bodies are joined. The definition
+/// uses local anchor points so that the initial configuration
+/// can violate the constraint slightly. You also need to
+/// specify the initial relative angle for joint limits. This
+/// helps when saving and loading a game.
+/// The local anchor points are measured from the body's origin
+/// rather than the center of mass because:
+/// 1. you might not know where the center of mass will be.
+/// 2. if you add/remove shapes from a body and recompute the mass,
+/// the joints will be broken.
+struct b2RevoluteJointDef : public b2JointDef
+{
+ b2RevoluteJointDef()
+ {
+ type = e_revoluteJoint;
+ localAnchorA.Set(0.0f, 0.0f);
+ localAnchorB.Set(0.0f, 0.0f);
+ referenceAngle = 0.0f;
+ lowerAngle = 0.0f;
+ upperAngle = 0.0f;
+ maxMotorTorque = 0.0f;
+ motorSpeed = 0.0f;
+ enableLimit = false;
+ enableMotor = false;
+ }
+
+ /// Initialize the bodies, anchors, and reference angle using a world
+ /// anchor point.
+ void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
+
+ /// The local anchor point relative to bodyA's origin.
+ b2Vec2 localAnchorA;
+
+ /// The local anchor point relative to bodyB's origin.
+ b2Vec2 localAnchorB;
+
+ /// The bodyB angle minus bodyA angle in the reference state (radians).
+ float32 referenceAngle;
+
+ /// A flag to enable joint limits.
+ bool enableLimit;
+
+ /// The lower angle for the joint limit (radians).
+ float32 lowerAngle;
+
+ /// The upper angle for the joint limit (radians).
+ float32 upperAngle;
+
+ /// A flag to enable the joint motor.
+ bool enableMotor;
+
+ /// The desired motor speed. Usually in radians per second.
+ float32 motorSpeed;
+
+ /// The maximum motor torque used to achieve the desired motor speed.
+ /// Usually in N-m.
+ float32 maxMotorTorque;
+};
+
+/// A revolute joint constrains two bodies to share a common point while they
+/// are free to rotate about the point. The relative rotation about the shared
+/// point is the joint angle. You can limit the relative rotation with
+/// a joint limit that specifies a lower and upper angle. You can use a motor
+/// to drive the relative rotation about the shared point. A maximum motor torque
+/// is provided so that infinite forces are not generated.
+class b2RevoluteJoint : public b2Joint
+{
+public:
+ b2Vec2 GetAnchorA() const;
+ b2Vec2 GetAnchorB() 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; }
+
+ /// Get the reference angle.
+ float32 GetReferenceAngle() const { return m_referenceAngle; }
+
+ /// Get the current joint angle in radians.
+ float32 GetJointAngle() const;
+
+ /// Get the current joint angle speed in radians 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 in radians.
+ float32 GetLowerLimit() const;
+
+ /// Get the upper joint limit in radians.
+ float32 GetUpperLimit() const;
+
+ /// Set the joint limits in radians.
+ 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 in radians per second.
+ void SetMotorSpeed(float32 speed);
+
+ /// Get the motor speed in radians per second.
+ float32 GetMotorSpeed() const;
+
+ /// Set the maximum motor torque, usually in N-m.
+ void SetMaxMotorTorque(float32 torque);
+ float32 GetMaxMotorTorque() const { return m_maxMotorTorque; }
+
+ /// Get the reaction force given the inverse time step.
+ /// Unit is N.
+ b2Vec2 GetReactionForce(float32 inv_dt) const;
+
+ /// Get the reaction torque due to the joint limit given the inverse time step.
+ /// Unit is N*m.
+ float32 GetReactionTorque(float32 inv_dt) const;
+
+ /// Get the current motor torque given the inverse time step.
+ /// Unit is N*m.
+ float32 GetMotorTorque(float32 inv_dt) const;
+
+ /// Dump to b2Log.
+ void Dump();
+
+protected:
+
+ friend class b2Joint;
+ friend class b2GearJoint;
+
+ b2RevoluteJoint(const b2RevoluteJointDef* def);
+
+ void InitVelocityConstraints(const b2SolverData& data);
+ void SolveVelocityConstraints(const b2SolverData& data);
+ bool SolvePositionConstraints(const b2SolverData& data);
+
+ // Solver shared
+ b2Vec2 m_localAnchorA;
+ b2Vec2 m_localAnchorB;
+ b2Vec3 m_impulse;
+ float32 m_motorImpulse;
+
+ bool m_enableMotor;
+ float32 m_maxMotorTorque;
+ float32 m_motorSpeed;
+
+ bool m_enableLimit;
+ float32 m_referenceAngle;
+ float32 m_lowerAngle;
+ float32 m_upperAngle;
+
+ // Solver temp
+ int32 m_indexA;
+ int32 m_indexB;
+ b2Vec2 m_rA;
+ b2Vec2 m_rB;
+ b2Vec2 m_localCenterA;
+ b2Vec2 m_localCenterB;
+ float32 m_invMassA;
+ float32 m_invMassB;
+ float32 m_invIA;
+ float32 m_invIB;
+ b2Mat33 m_mass; // effective mass for point-to-point constraint.
+ float32 m_motorMass; // effective mass for motor/limit angular constraint.
+ b2LimitState m_limitState;
+};
+
+inline float32 b2RevoluteJoint::GetMotorSpeed() const
+{
+ return m_motorSpeed;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp
new file mode 100644
index 00000000..998c627d
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2WheelJoint.cpp
@@ -0,0 +1,419 @@
+/*
+* Copyright (c) 2006-2007 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/b2WheelJoint.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+
+// Linear constraint (point-to-line)
+// d = pB - pA = xB + rB - xA - rA
+// C = dot(ay, d)
+// Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA))
+// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB)
+// J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)]
+
+// Spring linear constraint
+// C = dot(ax, d)
+// Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB)
+// J = [-ax -cross(d+rA, ax) ax cross(rB, ax)]
+
+// Motor rotational constraint
+// Cdot = wB - wA
+// J = [0 0 -1 0 0 1]
+
+void b2WheelJointDef::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);
+}
+
+b2WheelJoint::b2WheelJoint(const b2WheelJointDef* def)
+: b2Joint(def)
+{
+ m_localAnchorA = def->localAnchorA;
+ m_localAnchorB = def->localAnchorB;
+ m_localXAxisA = def->localAxisA;
+ m_localYAxisA = b2Cross(1.0f, m_localXAxisA);
+
+ m_mass = 0.0f;
+ m_impulse = 0.0f;
+ m_motorMass = 0.0;
+ m_motorImpulse = 0.0f;
+ m_springMass = 0.0f;
+ m_springImpulse = 0.0f;
+
+ m_maxMotorTorque = def->maxMotorTorque;
+ m_motorSpeed = def->motorSpeed;
+ m_enableMotor = def->enableMotor;
+
+ m_frequencyHz = def->frequencyHz;
+ m_dampingRatio = def->dampingRatio;
+
+ m_bias = 0.0f;
+ m_gamma = 0.0f;
+
+ m_ax.SetZero();
+ m_ay.SetZero();
+}
+
+void b2WheelJoint::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;
+
+ float32 mA = m_invMassA, mB = m_invMassB;
+ float32 iA = m_invIA, iB = m_invIB;
+
+ 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 + rB - cA - rA;
+
+ // Point to line constraint
+ {
+ m_ay = b2Mul(qA, m_localYAxisA);
+ m_sAy = b2Cross(d + rA, m_ay);
+ m_sBy = b2Cross(rB, m_ay);
+
+ m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy;
+
+ if (m_mass > 0.0f)
+ {
+ m_mass = 1.0f / m_mass;
+ }
+ }
+
+ // Spring constraint
+ m_springMass = 0.0f;
+ m_bias = 0.0f;
+ m_gamma = 0.0f;
+ if (m_frequencyHz > 0.0f)
+ {
+ m_ax = b2Mul(qA, m_localXAxisA);
+ m_sAx = b2Cross(d + rA, m_ax);
+ m_sBx = b2Cross(rB, m_ax);
+
+ float32 invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx;
+
+ if (invMass > 0.0f)
+ {
+ m_springMass = 1.0f / invMass;
+
+ float32 C = b2Dot(d, m_ax);
+
+ // Frequency
+ float32 omega = 2.0f * b2_pi * m_frequencyHz;
+
+ // Damping coefficient
+ float32 d = 2.0f * m_springMass * m_dampingRatio * omega;
+
+ // Spring stiffness
+ float32 k = m_springMass * omega * omega;
+
+ // magic formulas
+ float32 h = data.step.dt;
+ m_gamma = h * (d + h * k);
+ if (m_gamma > 0.0f)
+ {
+ m_gamma = 1.0f / m_gamma;
+ }
+
+ m_bias = C * h * k * m_gamma;
+
+ m_springMass = invMass + m_gamma;
+ if (m_springMass > 0.0f)
+ {
+ m_springMass = 1.0f / m_springMass;
+ }
+ }
+ }
+ else
+ {
+ m_springImpulse = 0.0f;
+ }
+
+ // Rotational motor
+ if (m_enableMotor)
+ {
+ m_motorMass = iA + iB;
+ if (m_motorMass > 0.0f)
+ {
+ m_motorMass = 1.0f / m_motorMass;
+ }
+ }
+ else
+ {
+ m_motorMass = 0.0f;
+ m_motorImpulse = 0.0f;
+ }
+
+ if (data.step.warmStarting)
+ {
+ // Account for variable time step.
+ m_impulse *= data.step.dtRatio;
+ m_springImpulse *= data.step.dtRatio;
+ m_motorImpulse *= data.step.dtRatio;
+
+ b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax;
+ float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse;
+ float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse;
+
+ vA -= m_invMassA * P;
+ wA -= m_invIA * LA;
+
+ vB += m_invMassB * P;
+ wB += m_invIB * LB;
+ }
+ else
+ {
+ m_impulse = 0.0f;
+ m_springImpulse = 0.0f;
+ 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 b2WheelJoint::SolveVelocityConstraints(const b2SolverData& data)
+{
+ float32 mA = m_invMassA, mB = m_invMassB;
+ float32 iA = m_invIA, iB = m_invIB;
+
+ 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;
+
+ // Solve spring constraint
+ {
+ float32 Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA;
+ float32 impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse);
+ m_springImpulse += impulse;
+
+ b2Vec2 P = impulse * m_ax;
+ float32 LA = impulse * m_sAx;
+ float32 LB = impulse * m_sBx;
+
+ vA -= mA * P;
+ wA -= iA * LA;
+
+ vB += mB * P;
+ wB += iB * LB;
+ }
+
+ // Solve rotational motor constraint
+ {
+ float32 Cdot = wB - wA - m_motorSpeed;
+ float32 impulse = -m_motorMass * Cdot;
+
+ float32 oldImpulse = m_motorImpulse;
+ float32 maxImpulse = data.step.dt * m_maxMotorTorque;
+ m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
+ impulse = m_motorImpulse - oldImpulse;
+
+ wA -= iA * impulse;
+ wB += iB * impulse;
+ }
+
+ // Solve point to line constraint
+ {
+ float32 Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA;
+ float32 impulse = -m_mass * Cdot;
+ m_impulse += impulse;
+
+ b2Vec2 P = impulse * m_ay;
+ float32 LA = impulse * m_sAy;
+ float32 LB = impulse * m_sBy;
+
+ vA -= mA * P;
+ wA -= iA * LA;
+
+ vB += mB * P;
+ wB += iB * LB;
+ }
+
+ 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 b2WheelJoint::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);
+
+ b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
+ b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
+ b2Vec2 d = (cB - cA) + rB - rA;
+
+ b2Vec2 ay = b2Mul(qA, m_localYAxisA);
+
+ float32 sAy = b2Cross(d + rA, ay);
+ float32 sBy = b2Cross(rB, ay);
+
+ float32 C = b2Dot(d, ay);
+
+ float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy;
+
+ float32 impulse;
+ if (k != 0.0f)
+ {
+ impulse = - C / k;
+ }
+ else
+ {
+ impulse = 0.0f;
+ }
+
+ b2Vec2 P = impulse * ay;
+ float32 LA = impulse * sAy;
+ float32 LB = impulse * sBy;
+
+ cA -= m_invMassA * P;
+ aA -= m_invIA * LA;
+ cB += m_invMassB * P;
+ aB += m_invIB * 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 b2Abs(C) <= b2_linearSlop;
+}
+
+b2Vec2 b2WheelJoint::GetAnchorA() const
+{
+ return m_bodyA->GetWorldPoint(m_localAnchorA);
+}
+
+b2Vec2 b2WheelJoint::GetAnchorB() const
+{
+ return m_bodyB->GetWorldPoint(m_localAnchorB);
+}
+
+b2Vec2 b2WheelJoint::GetReactionForce(float32 inv_dt) const
+{
+ return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax);
+}
+
+float32 b2WheelJoint::GetReactionTorque(float32 inv_dt) const
+{
+ return inv_dt * m_motorImpulse;
+}
+
+float32 b2WheelJoint::GetJointTranslation() const
+{
+ b2Body* bA = m_bodyA;
+ b2Body* bB = m_bodyB;
+
+ b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA);
+ b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB);
+ b2Vec2 d = pB - pA;
+ b2Vec2 axis = bA->GetWorldVector(m_localXAxisA);
+
+ float32 translation = b2Dot(d, axis);
+ return translation;
+}
+
+float32 b2WheelJoint::GetJointSpeed() const
+{
+ float32 wA = m_bodyA->m_angularVelocity;
+ float32 wB = m_bodyB->m_angularVelocity;
+ return wB - wA;
+}
+
+bool b2WheelJoint::IsMotorEnabled() const
+{
+ return m_enableMotor;
+}
+
+void b2WheelJoint::EnableMotor(bool flag)
+{
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_enableMotor = flag;
+}
+
+void b2WheelJoint::SetMotorSpeed(float32 speed)
+{
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_motorSpeed = speed;
+}
+
+void b2WheelJoint::SetMaxMotorTorque(float32 torque)
+{
+ m_bodyA->SetAwake(true);
+ m_bodyB->SetAwake(true);
+ m_maxMotorTorque = torque;
+}
+
+float32 b2WheelJoint::GetMotorTorque(float32 inv_dt) const
+{
+ return inv_dt * m_motorImpulse;
+}
+
+void b2WheelJoint::Dump()
+{
+ int32 indexA = m_bodyA->m_islandIndex;
+ int32 indexB = m_bodyB->m_islandIndex;
+
+ b2Log(" b2WheelJointDef 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.enableMotor = bool(%d);\n", m_enableMotor);
+ b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed);
+ b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque);
+ b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz);
+ b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio);
+ b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h
new file mode 100644
index 00000000..9a8b1363
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/Joints/b2WheelJoint.h
@@ -0,0 +1,213 @@
+/*
+* 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_WHEEL_JOINT_H
+#define B2_WHEEL_JOINT_H
+
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+/// Wheel 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 b2WheelJointDef : public b2JointDef
+{
+ b2WheelJointDef()
+ {
+ type = e_wheelJoint;
+ localAnchorA.SetZero();
+ localAnchorB.SetZero();
+ localAxisA.Set(1.0f, 0.0f);
+ enableMotor = false;
+ maxMotorTorque = 0.0f;
+ motorSpeed = 0.0f;
+ frequencyHz = 2.0f;
+ dampingRatio = 0.7f;
+ }
+
+ /// Initialize the bodies, anchors, axis, and reference angle using the world
+ /// anchor and 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 axis in bodyA.
+ b2Vec2 localAxisA;
+
+ /// Enable/disable the joint motor.
+ bool enableMotor;
+
+ /// The maximum motor torque, usually in N-m.
+ float32 maxMotorTorque;
+
+ /// The desired motor speed in radians per second.
+ float32 motorSpeed;
+
+ /// Suspension frequency, zero indicates no suspension
+ float32 frequencyHz;
+
+ /// Suspension damping ratio, one indicates critical damping
+ float32 dampingRatio;
+};
+
+/// A wheel joint. This joint provides two degrees of freedom: translation
+/// along an axis fixed in bodyA and rotation in the plane. You can use a
+/// joint limit to restrict the range of motion and a joint motor to drive
+/// the rotation or to model rotational friction.
+/// This joint is designed for vehicle suspensions.
+class b2WheelJoint : public b2Joint
+{
+public:
+ void GetDefinition(b2WheelJointDef* def) const;
+
+ 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 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 motor enabled?
+ bool IsMotorEnabled() const;
+
+ /// Enable/disable the joint motor.
+ void EnableMotor(bool flag);
+
+ /// Set the motor speed, usually in radians per second.
+ void SetMotorSpeed(float32 speed);
+
+ /// Get the motor speed, usually in radians per second.
+ float32 GetMotorSpeed() const;
+
+ /// Set/Get the maximum motor force, usually in N-m.
+ void SetMaxMotorTorque(float32 torque);
+ float32 GetMaxMotorTorque() const;
+
+ /// Get the current motor torque given the inverse time step, usually in N-m.
+ float32 GetMotorTorque(float32 inv_dt) const;
+
+ /// Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring.
+ void SetSpringFrequencyHz(float32 hz);
+ float32 GetSpringFrequencyHz() const;
+
+ /// Set/Get the spring damping ratio
+ void SetSpringDampingRatio(float32 ratio);
+ float32 GetSpringDampingRatio() const;
+
+ /// Dump to b2Log
+ void Dump();
+
+protected:
+
+ friend class b2Joint;
+ b2WheelJoint(const b2WheelJointDef* def);
+
+ void InitVelocityConstraints(const b2SolverData& data);
+ void SolveVelocityConstraints(const b2SolverData& data);
+ bool SolvePositionConstraints(const b2SolverData& data);
+
+ float32 m_frequencyHz;
+ float32 m_dampingRatio;
+
+ // Solver shared
+ b2Vec2 m_localAnchorA;
+ b2Vec2 m_localAnchorB;
+ b2Vec2 m_localXAxisA;
+ b2Vec2 m_localYAxisA;
+
+ float32 m_impulse;
+ float32 m_motorImpulse;
+ float32 m_springImpulse;
+
+ float32 m_maxMotorTorque;
+ float32 m_motorSpeed;
+ bool m_enableMotor;
+
+ // 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_ax, m_ay;
+ float32 m_sAx, m_sBx;
+ float32 m_sAy, m_sBy;
+
+ float32 m_mass;
+ float32 m_motorMass;
+ float32 m_springMass;
+
+ float32 m_bias;
+ float32 m_gamma;
+};
+
+inline float32 b2WheelJoint::GetMotorSpeed() const
+{
+ return m_motorSpeed;
+}
+
+inline float32 b2WheelJoint::GetMaxMotorTorque() const
+{
+ return m_maxMotorTorque;
+}
+
+inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz)
+{
+ m_frequencyHz = hz;
+}
+
+inline float32 b2WheelJoint::GetSpringFrequencyHz() const
+{
+ return m_frequencyHz;
+}
+
+inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio)
+{
+ m_dampingRatio = ratio;
+}
+
+inline float32 b2WheelJoint::GetSpringDampingRatio() const
+{
+ return m_dampingRatio;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2Body.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Body.cpp
new file mode 100644
index 00000000..b50bf45a
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Body.cpp
@@ -0,0 +1,514 @@
+/*
+* Copyright (c) 2006-2007 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/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2World.h>
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+
+b2Body::b2Body(const b2BodyDef* bd, b2World* world)
+{
+ b2Assert(bd->position.IsValid());
+ b2Assert(bd->linearVelocity.IsValid());
+ b2Assert(b2IsValid(bd->angle));
+ b2Assert(b2IsValid(bd->angularVelocity));
+ b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f);
+ b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f);
+
+ m_flags = 0;
+
+ if (bd->bullet)
+ {
+ m_flags |= e_bulletFlag;
+ }
+ if (bd->fixedRotation)
+ {
+ m_flags |= e_fixedRotationFlag;
+ }
+ if (bd->allowSleep)
+ {
+ m_flags |= e_autoSleepFlag;
+ }
+ if (bd->awake)
+ {
+ m_flags |= e_awakeFlag;
+ }
+ if (bd->active)
+ {
+ m_flags |= e_activeFlag;
+ }
+
+ m_world = world;
+
+ m_xf.p = bd->position;
+ m_xf.q.Set(bd->angle);
+
+ m_sweep.localCenter.SetZero();
+ m_sweep.c0 = m_xf.p;
+ m_sweep.c = m_xf.p;
+ m_sweep.a0 = bd->angle;
+ m_sweep.a = bd->angle;
+ m_sweep.alpha0 = 0.0f;
+
+ m_jointList = NULL;
+ m_contactList = NULL;
+ m_prev = NULL;
+ m_next = NULL;
+
+ m_linearVelocity = bd->linearVelocity;
+ m_angularVelocity = bd->angularVelocity;
+
+ m_linearDamping = bd->linearDamping;
+ m_angularDamping = bd->angularDamping;
+ m_gravityScale = bd->gravityScale;
+
+ m_force.SetZero();
+ m_torque = 0.0f;
+
+ m_sleepTime = 0.0f;
+
+ m_type = bd->type;
+
+ if (m_type == b2_dynamicBody)
+ {
+ m_mass = 1.0f;
+ m_invMass = 1.0f;
+ }
+ else
+ {
+ m_mass = 0.0f;
+ m_invMass = 0.0f;
+ }
+
+ m_I = 0.0f;
+ m_invI = 0.0f;
+
+ m_userData = bd->userData;
+
+ m_fixtureList = NULL;
+ m_fixtureCount = 0;
+}
+
+b2Body::~b2Body()
+{
+ // shapes and joints are destroyed in b2World::Destroy
+}
+
+void b2Body::SetType(b2BodyType type)
+{
+ b2Assert(m_world->IsLocked() == false);
+ if (m_world->IsLocked() == true)
+ {
+ return;
+ }
+
+ if (m_type == type)
+ {
+ return;
+ }
+
+ m_type = type;
+
+ ResetMassData();
+
+ if (m_type == b2_staticBody)
+ {
+ m_linearVelocity.SetZero();
+ m_angularVelocity = 0.0f;
+ m_sweep.a0 = m_sweep.a;
+ m_sweep.c0 = m_sweep.c;
+ SynchronizeFixtures();
+ }
+
+ SetAwake(true);
+
+ m_force.SetZero();
+ m_torque = 0.0f;
+
+ // Since the body type changed, we need to flag contacts for filtering.
+ for (b2Fixture* f = m_fixtureList; f; f = f->m_next)
+ {
+ f->Refilter();
+ }
+}
+
+b2Fixture* b2Body::CreateFixture(const b2FixtureDef* def)
+{
+ b2Assert(m_world->IsLocked() == false);
+ if (m_world->IsLocked() == true)
+ {
+ return NULL;
+ }
+
+ b2BlockAllocator* allocator = &m_world->m_blockAllocator;
+
+ void* memory = allocator->Allocate(sizeof(b2Fixture));
+ b2Fixture* fixture = new (memory) b2Fixture;
+ fixture->Create(allocator, this, def);
+
+ if (m_flags & e_activeFlag)
+ {
+ b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
+ fixture->CreateProxies(broadPhase, m_xf);
+ }
+
+ fixture->m_next = m_fixtureList;
+ m_fixtureList = fixture;
+ ++m_fixtureCount;
+
+ fixture->m_body = this;
+
+ // Adjust mass properties if needed.
+ if (fixture->m_density > 0.0f)
+ {
+ ResetMassData();
+ }
+
+ // Let the world know we have a new fixture. This will cause new contacts
+ // to be created at the beginning of the next time step.
+ m_world->m_flags |= b2World::e_newFixture;
+
+ return fixture;
+}
+
+b2Fixture* b2Body::CreateFixture(const b2Shape* shape, float32 density)
+{
+ b2FixtureDef def;
+ def.shape = shape;
+ def.density = density;
+
+ return CreateFixture(&def);
+}
+
+void b2Body::DestroyFixture(b2Fixture* fixture)
+{
+ b2Assert(m_world->IsLocked() == false);
+ if (m_world->IsLocked() == true)
+ {
+ return;
+ }
+
+ b2Assert(fixture->m_body == this);
+
+ // Remove the fixture from this body's singly linked list.
+ b2Assert(m_fixtureCount > 0);
+ b2Fixture** node = &m_fixtureList;
+ bool found = false;
+ while (*node != NULL)
+ {
+ if (*node == fixture)
+ {
+ *node = fixture->m_next;
+ found = true;
+ break;
+ }
+
+ node = &(*node)->m_next;
+ }
+
+ // You tried to remove a shape that is not attached to this body.
+ b2Assert(found);
+
+ // Destroy any contacts associated with the fixture.
+ b2ContactEdge* edge = m_contactList;
+ while (edge)
+ {
+ b2Contact* c = edge->contact;
+ edge = edge->next;
+
+ b2Fixture* fixtureA = c->GetFixtureA();
+ b2Fixture* fixtureB = c->GetFixtureB();
+
+ if (fixture == fixtureA || fixture == fixtureB)
+ {
+ // This destroys the contact and removes it from
+ // this body's contact list.
+ m_world->m_contactManager.Destroy(c);
+ }
+ }
+
+ b2BlockAllocator* allocator = &m_world->m_blockAllocator;
+
+ if (m_flags & e_activeFlag)
+ {
+ b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
+ fixture->DestroyProxies(broadPhase);
+ }
+
+ fixture->Destroy(allocator);
+ fixture->m_body = NULL;
+ fixture->m_next = NULL;
+ fixture->~b2Fixture();
+ allocator->Free(fixture, sizeof(b2Fixture));
+
+ --m_fixtureCount;
+
+ // Reset the mass data.
+ ResetMassData();
+}
+
+void b2Body::ResetMassData()
+{
+ // Compute mass data from shapes. Each shape has its own density.
+ m_mass = 0.0f;
+ m_invMass = 0.0f;
+ m_I = 0.0f;
+ m_invI = 0.0f;
+ m_sweep.localCenter.SetZero();
+
+ // Static and kinematic bodies have zero mass.
+ if (m_type == b2_staticBody || m_type == b2_kinematicBody)
+ {
+ m_sweep.c0 = m_xf.p;
+ m_sweep.c = m_xf.p;
+ m_sweep.a0 = m_sweep.a;
+ return;
+ }
+
+ b2Assert(m_type == b2_dynamicBody);
+
+ // Accumulate mass over all fixtures.
+ b2Vec2 localCenter = b2Vec2_zero;
+ for (b2Fixture* f = m_fixtureList; f; f = f->m_next)
+ {
+ if (f->m_density == 0.0f)
+ {
+ continue;
+ }
+
+ b2MassData massData;
+ f->GetMassData(&massData);
+ m_mass += massData.mass;
+ localCenter += massData.mass * massData.center;
+ m_I += massData.I;
+ }
+
+ // Compute center of mass.
+ if (m_mass > 0.0f)
+ {
+ m_invMass = 1.0f / m_mass;
+ localCenter *= m_invMass;
+ }
+ else
+ {
+ // Force all dynamic bodies to have a positive mass.
+ m_mass = 1.0f;
+ m_invMass = 1.0f;
+ }
+
+ if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0)
+ {
+ // Center the inertia about the center of mass.
+ m_I -= m_mass * b2Dot(localCenter, localCenter);
+ b2Assert(m_I > 0.0f);
+ m_invI = 1.0f / m_I;
+
+ }
+ else
+ {
+ m_I = 0.0f;
+ m_invI = 0.0f;
+ }
+
+ // Move center of mass.
+ b2Vec2 oldCenter = m_sweep.c;
+ m_sweep.localCenter = localCenter;
+ m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter);
+
+ // Update center of mass velocity.
+ m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter);
+}
+
+void b2Body::SetMassData(const b2MassData* massData)
+{
+ b2Assert(m_world->IsLocked() == false);
+ if (m_world->IsLocked() == true)
+ {
+ return;
+ }
+
+ if (m_type != b2_dynamicBody)
+ {
+ return;
+ }
+
+ m_invMass = 0.0f;
+ m_I = 0.0f;
+ m_invI = 0.0f;
+
+ m_mass = massData->mass;
+ if (m_mass <= 0.0f)
+ {
+ m_mass = 1.0f;
+ }
+
+ m_invMass = 1.0f / m_mass;
+
+ if (massData->I > 0.0f && (m_flags & b2Body::e_fixedRotationFlag) == 0)
+ {
+ m_I = massData->I - m_mass * b2Dot(massData->center, massData->center);
+ b2Assert(m_I > 0.0f);
+ m_invI = 1.0f / m_I;
+ }
+
+ // Move center of mass.
+ b2Vec2 oldCenter = m_sweep.c;
+ m_sweep.localCenter = massData->center;
+ m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter);
+
+ // Update center of mass velocity.
+ m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter);
+}
+
+bool b2Body::ShouldCollide(const b2Body* other) const
+{
+ // At least one body should be dynamic.
+ if (m_type != b2_dynamicBody && other->m_type != b2_dynamicBody)
+ {
+ return false;
+ }
+
+ // Does a joint prevent collision?
+ for (b2JointEdge* jn = m_jointList; jn; jn = jn->next)
+ {
+ if (jn->other == other)
+ {
+ if (jn->joint->m_collideConnected == false)
+ {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+void b2Body::SetTransform(const b2Vec2& position, float32 angle)
+{
+ b2Assert(m_world->IsLocked() == false);
+ if (m_world->IsLocked() == true)
+ {
+ return;
+ }
+
+ m_xf.q.Set(angle);
+ m_xf.p = position;
+
+ m_sweep.c = b2Mul(m_xf, m_sweep.localCenter);
+ m_sweep.a = angle;
+
+ m_sweep.c0 = m_sweep.c;
+ m_sweep.a0 = angle;
+
+ b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
+ for (b2Fixture* f = m_fixtureList; f; f = f->m_next)
+ {
+ f->Synchronize(broadPhase, m_xf, m_xf);
+ }
+
+ m_world->m_contactManager.FindNewContacts();
+}
+
+void b2Body::SynchronizeFixtures()
+{
+ b2Transform xf1;
+ xf1.q.Set(m_sweep.a0);
+ xf1.p = m_sweep.c0 - b2Mul(xf1.q, m_sweep.localCenter);
+
+ b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
+ for (b2Fixture* f = m_fixtureList; f; f = f->m_next)
+ {
+ f->Synchronize(broadPhase, xf1, m_xf);
+ }
+}
+
+void b2Body::SetActive(bool flag)
+{
+ b2Assert(m_world->IsLocked() == false);
+
+ if (flag == IsActive())
+ {
+ return;
+ }
+
+ if (flag)
+ {
+ m_flags |= e_activeFlag;
+
+ // Create all proxies.
+ b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
+ for (b2Fixture* f = m_fixtureList; f; f = f->m_next)
+ {
+ f->CreateProxies(broadPhase, m_xf);
+ }
+
+ // Contacts are created the next time step.
+ }
+ else
+ {
+ m_flags &= ~e_activeFlag;
+
+ // Destroy all proxies.
+ b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase;
+ for (b2Fixture* f = m_fixtureList; f; f = f->m_next)
+ {
+ f->DestroyProxies(broadPhase);
+ }
+
+ // Destroy the attached contacts.
+ b2ContactEdge* ce = m_contactList;
+ while (ce)
+ {
+ b2ContactEdge* ce0 = ce;
+ ce = ce->next;
+ m_world->m_contactManager.Destroy(ce0->contact);
+ }
+ m_contactList = NULL;
+ }
+}
+
+void b2Body::Dump()
+{
+ int32 bodyIndex = m_islandIndex;
+
+ b2Log("{\n");
+ b2Log(" b2BodyDef bd;\n");
+ b2Log(" bd.type = b2BodyType(%d);\n", m_type);
+ b2Log(" bd.position.Set(%.15lef, %.15lef);\n", m_xf.p.x, m_xf.p.y);
+ b2Log(" bd.angle = %.15lef;\n", m_sweep.a);
+ b2Log(" bd.linearVelocity.Set(%.15lef, %.15lef);\n", m_linearVelocity.x, m_linearVelocity.y);
+ b2Log(" bd.angularVelocity = %.15lef;\n", m_angularVelocity);
+ b2Log(" bd.linearDamping = %.15lef;\n", m_linearDamping);
+ b2Log(" bd.angularDamping = %.15lef;\n", m_angularDamping);
+ b2Log(" bd.allowSleep = bool(%d);\n", m_flags & e_autoSleepFlag);
+ b2Log(" bd.awake = bool(%d);\n", m_flags & e_awakeFlag);
+ b2Log(" bd.fixedRotation = bool(%d);\n", m_flags & e_fixedRotationFlag);
+ b2Log(" bd.bullet = bool(%d);\n", m_flags & e_bulletFlag);
+ b2Log(" bd.active = bool(%d);\n", m_flags & e_activeFlag);
+ b2Log(" bd.gravityScale = %.15lef;\n", m_gravityScale);
+ b2Log(" bodies[%d] = m_world->CreateBody(&bd);\n", m_islandIndex);
+ b2Log("\n");
+ for (b2Fixture* f = m_fixtureList; f; f = f->m_next)
+ {
+ b2Log(" {\n");
+ f->Dump(bodyIndex);
+ b2Log(" }\n");
+ }
+ b2Log("}\n");
+}
\ No newline at end of file
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2Body.h b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Body.h
new file mode 100644
index 00000000..73f2cb41
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Body.h
@@ -0,0 +1,846 @@
+/*
+* 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_BODY_H
+#define B2_BODY_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Collision/Shapes/b2Shape.h>
+#include <memory>
+
+class b2Fixture;
+class b2Joint;
+class b2Contact;
+class b2Controller;
+class b2World;
+struct b2FixtureDef;
+struct b2JointEdge;
+struct b2ContactEdge;
+
+/// The body type.
+/// static: zero mass, zero velocity, may be manually moved
+/// kinematic: zero mass, non-zero velocity set by user, moved by solver
+/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver
+enum b2BodyType
+{
+ b2_staticBody = 0,
+ b2_kinematicBody,
+ b2_dynamicBody
+
+ // TODO_ERIN
+ //b2_bulletBody,
+};
+
+/// A body definition holds all the data needed to construct a rigid body.
+/// You can safely re-use body definitions. Shapes are added to a body after construction.
+struct b2BodyDef
+{
+ /// This constructor sets the body definition default values.
+ b2BodyDef()
+ {
+ userData = NULL;
+ position.Set(0.0f, 0.0f);
+ angle = 0.0f;
+ linearVelocity.Set(0.0f, 0.0f);
+ angularVelocity = 0.0f;
+ linearDamping = 0.0f;
+ angularDamping = 0.0f;
+ allowSleep = true;
+ awake = true;
+ fixedRotation = false;
+ bullet = false;
+ type = b2_staticBody;
+ active = true;
+ gravityScale = 1.0f;
+ }
+
+ /// The body type: static, kinematic, or dynamic.
+ /// Note: if a dynamic body would have zero mass, the mass is set to one.
+ b2BodyType type;
+
+ /// The world position of the body. Avoid creating bodies at the origin
+ /// since this can lead to many overlapping shapes.
+ b2Vec2 position;
+
+ /// The world angle of the body in radians.
+ float32 angle;
+
+ /// The linear velocity of the body's origin in world co-ordinates.
+ b2Vec2 linearVelocity;
+
+ /// The angular velocity of the body.
+ float32 angularVelocity;
+
+ /// Linear damping is use to reduce the linear velocity. The damping parameter
+ /// can be larger than 1.0f but the damping effect becomes sensitive to the
+ /// time step when the damping parameter is large.
+ float32 linearDamping;
+
+ /// Angular damping is use to reduce the angular velocity. The damping parameter
+ /// can be larger than 1.0f but the damping effect becomes sensitive to the
+ /// time step when the damping parameter is large.
+ float32 angularDamping;
+
+ /// Set this flag to false if this body should never fall asleep. Note that
+ /// this increases CPU usage.
+ bool allowSleep;
+
+ /// Is this body initially awake or sleeping?
+ bool awake;
+
+ /// Should this body be prevented from rotating? Useful for characters.
+ bool fixedRotation;
+
+ /// Is this a fast moving body that should be prevented from tunneling through
+ /// other moving bodies? Note that all bodies are prevented from tunneling through
+ /// kinematic and static bodies. This setting is only considered on dynamic bodies.
+ /// @warning You should use this flag sparingly since it increases processing time.
+ bool bullet;
+
+ /// Does this body start out active?
+ bool active;
+
+ /// Use this to store application specific body data.
+ void* userData;
+
+ /// Scale the gravity applied to this body.
+ float32 gravityScale;
+};
+
+/// A rigid body. These are created via b2World::CreateBody.
+class b2Body
+{
+public:
+ /// Creates a fixture and attach it to this body. Use this function if you need
+ /// to set some fixture parameters, like friction. Otherwise you can create the
+ /// fixture directly from a shape.
+ /// If the density is non-zero, this function automatically updates the mass of the body.
+ /// Contacts are not created until the next time step.
+ /// @param def the fixture definition.
+ /// @warning This function is locked during callbacks.
+ b2Fixture* CreateFixture(const b2FixtureDef* def);
+
+ /// Creates a fixture from a shape and attach it to this body.
+ /// This is a convenience function. Use b2FixtureDef if you need to set parameters
+ /// like friction, restitution, user data, or filtering.
+ /// If the density is non-zero, this function automatically updates the mass of the body.
+ /// @param shape the shape to be cloned.
+ /// @param density the shape density (set to zero for static bodies).
+ /// @warning This function is locked during callbacks.
+ b2Fixture* CreateFixture(const b2Shape* shape, float32 density);
+
+ /// Destroy a fixture. This removes the fixture from the broad-phase and
+ /// destroys all contacts associated with this fixture. This will
+ /// automatically adjust the mass of the body if the body is dynamic and the
+ /// fixture has positive density.
+ /// All fixtures attached to a body are implicitly destroyed when the body is destroyed.
+ /// @param fixture the fixture to be removed.
+ /// @warning This function is locked during callbacks.
+ void DestroyFixture(b2Fixture* fixture);
+
+ /// Set the position of the body's origin and rotation.
+ /// This breaks any contacts and wakes the other bodies.
+ /// Manipulating a body's transform may cause non-physical behavior.
+ /// @param position the world position of the body's local origin.
+ /// @param angle the world rotation in radians.
+ void SetTransform(const b2Vec2& position, float32 angle);
+
+ /// Get the body transform for the body's origin.
+ /// @return the world transform of the body's origin.
+ const b2Transform& GetTransform() const;
+
+ /// Get the world body origin position.
+ /// @return the world position of the body's origin.
+ const b2Vec2& GetPosition() const;
+
+ /// Get the angle in radians.
+ /// @return the current world rotation angle in radians.
+ float32 GetAngle() const;
+
+ /// Get the world position of the center of mass.
+ const b2Vec2& GetWorldCenter() const;
+
+ /// Get the local position of the center of mass.
+ const b2Vec2& GetLocalCenter() const;
+
+ /// Set the linear velocity of the center of mass.
+ /// @param v the new linear velocity of the center of mass.
+ void SetLinearVelocity(const b2Vec2& v);
+
+ /// Get the linear velocity of the center of mass.
+ /// @return the linear velocity of the center of mass.
+ b2Vec2 GetLinearVelocity() const;
+
+ /// Set the angular velocity.
+ /// @param omega the new angular velocity in radians/second.
+ void SetAngularVelocity(float32 omega);
+
+ /// Get the angular velocity.
+ /// @return the angular velocity in radians/second.
+ float32 GetAngularVelocity() const;
+
+ /// Apply a force at a world point. If the force is not
+ /// applied at the center of mass, it will generate a torque and
+ /// affect the angular velocity. This wakes up the body.
+ /// @param force the world force vector, usually in Newtons (N).
+ /// @param point the world position of the point of application.
+ void ApplyForce(const b2Vec2& force, const b2Vec2& point);
+
+ /// Apply a force to the center of mass. This wakes up the body.
+ /// @param force the world force vector, usually in Newtons (N).
+ void ApplyForceToCenter(const b2Vec2& force);
+
+ /// Apply a torque. This affects the angular velocity
+ /// without affecting the linear velocity of the center of mass.
+ /// This wakes up the body.
+ /// @param torque about the z-axis (out of the screen), usually in N-m.
+ void ApplyTorque(float32 torque);
+
+ /// Apply an impulse at a point. This immediately modifies the velocity.
+ /// It also modifies the angular velocity if the point of application
+ /// is not at the center of mass. This wakes up the body.
+ /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s.
+ /// @param point the world position of the point of application.
+ void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point);
+
+ /// Apply an angular impulse.
+ /// @param impulse the angular impulse in units of kg*m*m/s
+ void ApplyAngularImpulse(float32 impulse);
+
+ /// Get the total mass of the body.
+ /// @return the mass, usually in kilograms (kg).
+ float32 GetMass() const;
+
+ /// Get the rotational inertia of the body about the local origin.
+ /// @return the rotational inertia, usually in kg-m^2.
+ float32 GetInertia() const;
+
+ /// Get the mass data of the body.
+ /// @return a struct containing the mass, inertia and center of the body.
+ void GetMassData(b2MassData* data) const;
+
+ /// Set the mass properties to override the mass properties of the fixtures.
+ /// Note that this changes the center of mass position.
+ /// Note that creating or destroying fixtures can also alter the mass.
+ /// This function has no effect if the body isn't dynamic.
+ /// @param massData the mass properties.
+ void SetMassData(const b2MassData* data);
+
+ /// This resets the mass properties to the sum of the mass properties of the fixtures.
+ /// This normally does not need to be called unless you called SetMassData to override
+ /// the mass and you later want to reset the mass.
+ void ResetMassData();
+
+ /// Get the world coordinates of a point given the local coordinates.
+ /// @param localPoint a point on the body measured relative the the body's origin.
+ /// @return the same point expressed in world coordinates.
+ b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const;
+
+ /// Get the world coordinates of a vector given the local coordinates.
+ /// @param localVector a vector fixed in the body.
+ /// @return the same vector expressed in world coordinates.
+ b2Vec2 GetWorldVector(const b2Vec2& localVector) const;
+
+ /// Gets a local point relative to the body's origin given a world point.
+ /// @param a point in world coordinates.
+ /// @return the corresponding local point relative to the body's origin.
+ b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const;
+
+ /// Gets a local vector given a world vector.
+ /// @param a vector in world coordinates.
+ /// @return the corresponding local vector.
+ b2Vec2 GetLocalVector(const b2Vec2& worldVector) const;
+
+ /// Get the world linear velocity of a world point attached to this body.
+ /// @param a point in world coordinates.
+ /// @return the world velocity of a point.
+ b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const;
+
+ /// Get the world velocity of a local point.
+ /// @param a point in local coordinates.
+ /// @return the world velocity of a point.
+ b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const;
+
+ /// Get the linear damping of the body.
+ float32 GetLinearDamping() const;
+
+ /// Set the linear damping of the body.
+ void SetLinearDamping(float32 linearDamping);
+
+ /// Get the angular damping of the body.
+ float32 GetAngularDamping() const;
+
+ /// Set the angular damping of the body.
+ void SetAngularDamping(float32 angularDamping);
+
+ /// Get the gravity scale of the body.
+ float32 GetGravityScale() const;
+
+ /// Set the gravity scale of the body.
+ void SetGravityScale(float32 scale);
+
+ /// Set the type of this body. This may alter the mass and velocity.
+ void SetType(b2BodyType type);
+
+ /// Get the type of this body.
+ b2BodyType GetType() const;
+
+ /// Should this body be treated like a bullet for continuous collision detection?
+ void SetBullet(bool flag);
+
+ /// Is this body treated like a bullet for continuous collision detection?
+ bool IsBullet() const;
+
+ /// You can disable sleeping on this body. If you disable sleeping, the
+ /// body will be woken.
+ void SetSleepingAllowed(bool flag);
+
+ /// Is this body allowed to sleep
+ bool IsSleepingAllowed() const;
+
+ /// Set the sleep state of the body. A sleeping body has very
+ /// low CPU cost.
+ /// @param flag set to true to put body to sleep, false to wake it.
+ void SetAwake(bool flag);
+
+ /// Get the sleeping state of this body.
+ /// @return true if the body is sleeping.
+ bool IsAwake() const;
+
+ /// Set the active state of the body. An inactive body is not
+ /// simulated and cannot be collided with or woken up.
+ /// If you pass a flag of true, all fixtures will be added to the
+ /// broad-phase.
+ /// If you pass a flag of false, all fixtures will be removed from
+ /// the broad-phase and all contacts will be destroyed.
+ /// Fixtures and joints are otherwise unaffected. You may continue
+ /// to create/destroy fixtures and joints on inactive bodies.
+ /// Fixtures on an inactive body are implicitly inactive and will
+ /// not participate in collisions, ray-casts, or queries.
+ /// Joints connected to an inactive body are implicitly inactive.
+ /// An inactive body is still owned by a b2World object and remains
+ /// in the body list.
+ void SetActive(bool flag);
+
+ /// Get the active state of the body.
+ bool IsActive() const;
+
+ /// Set this body to have fixed rotation. This causes the mass
+ /// to be reset.
+ void SetFixedRotation(bool flag);
+
+ /// Does this body have fixed rotation?
+ bool IsFixedRotation() const;
+
+ /// Get the list of all fixtures attached to this body.
+ b2Fixture* GetFixtureList();
+ const b2Fixture* GetFixtureList() const;
+
+ /// Get the list of all joints attached to this body.
+ b2JointEdge* GetJointList();
+ const b2JointEdge* GetJointList() const;
+
+ /// Get the list of all contacts attached to this body.
+ /// @warning this list changes during the time step and you may
+ /// miss some collisions if you don't use b2ContactListener.
+ b2ContactEdge* GetContactList();
+ const b2ContactEdge* GetContactList() const;
+
+ /// Get the next body in the world's body list.
+ b2Body* GetNext();
+ const b2Body* GetNext() const;
+
+ /// Get the user data pointer that was provided in the body definition.
+ void* GetUserData() const;
+
+ /// Set the user data. Use this to store your application specific data.
+ void SetUserData(void* data);
+
+ /// Get the parent world of this body.
+ b2World* GetWorld();
+ const b2World* GetWorld() const;
+
+ /// Dump this body to a log file
+ void Dump();
+
+private:
+
+ friend class b2World;
+ friend class b2Island;
+ friend class b2ContactManager;
+ friend class b2ContactSolver;
+ friend class b2Contact;
+
+ friend class b2DistanceJoint;
+ friend class b2GearJoint;
+ friend class b2WheelJoint;
+ friend class b2MouseJoint;
+ friend class b2PrismaticJoint;
+ friend class b2PulleyJoint;
+ friend class b2RevoluteJoint;
+ friend class b2WeldJoint;
+ friend class b2FrictionJoint;
+ friend class b2RopeJoint;
+
+ // m_flags
+ enum
+ {
+ e_islandFlag = 0x0001,
+ e_awakeFlag = 0x0002,
+ e_autoSleepFlag = 0x0004,
+ e_bulletFlag = 0x0008,
+ e_fixedRotationFlag = 0x0010,
+ e_activeFlag = 0x0020,
+ e_toiFlag = 0x0040
+ };
+
+ b2Body(const b2BodyDef* bd, b2World* world);
+ ~b2Body();
+
+ void SynchronizeFixtures();
+ void SynchronizeTransform();
+
+ // This is used to prevent connected bodies from colliding.
+ // It may lie, depending on the collideConnected flag.
+ bool ShouldCollide(const b2Body* other) const;
+
+ void Advance(float32 t);
+
+ b2BodyType m_type;
+
+ uint16 m_flags;
+
+ int32 m_islandIndex;
+
+ b2Transform m_xf; // the body origin transform
+ b2Sweep m_sweep; // the swept motion for CCD
+
+ b2Vec2 m_linearVelocity;
+ float32 m_angularVelocity;
+
+ b2Vec2 m_force;
+ float32 m_torque;
+
+ b2World* m_world;
+ b2Body* m_prev;
+ b2Body* m_next;
+
+ b2Fixture* m_fixtureList;
+ int32 m_fixtureCount;
+
+ b2JointEdge* m_jointList;
+ b2ContactEdge* m_contactList;
+
+ float32 m_mass, m_invMass;
+
+ // Rotational inertia about the center of mass.
+ float32 m_I, m_invI;
+
+ float32 m_linearDamping;
+ float32 m_angularDamping;
+ float32 m_gravityScale;
+
+ float32 m_sleepTime;
+
+ void* m_userData;
+};
+
+inline b2BodyType b2Body::GetType() const
+{
+ return m_type;
+}
+
+inline const b2Transform& b2Body::GetTransform() const
+{
+ return m_xf;
+}
+
+inline const b2Vec2& b2Body::GetPosition() const
+{
+ return m_xf.p;
+}
+
+inline float32 b2Body::GetAngle() const
+{
+ return m_sweep.a;
+}
+
+inline const b2Vec2& b2Body::GetWorldCenter() const
+{
+ return m_sweep.c;
+}
+
+inline const b2Vec2& b2Body::GetLocalCenter() const
+{
+ return m_sweep.localCenter;
+}
+
+inline void b2Body::SetLinearVelocity(const b2Vec2& v)
+{
+ if (m_type == b2_staticBody)
+ {
+ return;
+ }
+
+ if (b2Dot(v,v) > 0.0f)
+ {
+ SetAwake(true);
+ }
+
+ m_linearVelocity = v;
+}
+
+inline b2Vec2 b2Body::GetLinearVelocity() const
+{
+ return m_linearVelocity;
+}
+
+inline void b2Body::SetAngularVelocity(float32 w)
+{
+ if (m_type == b2_staticBody)
+ {
+ return;
+ }
+
+ if (w * w > 0.0f)
+ {
+ SetAwake(true);
+ }
+
+ m_angularVelocity = w;
+}
+
+inline float32 b2Body::GetAngularVelocity() const
+{
+ return m_angularVelocity;
+}
+
+inline float32 b2Body::GetMass() const
+{
+ return m_mass;
+}
+
+inline float32 b2Body::GetInertia() const
+{
+ return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
+}
+
+inline void b2Body::GetMassData(b2MassData* data) const
+{
+ data->mass = m_mass;
+ data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
+ data->center = m_sweep.localCenter;
+}
+
+inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const
+{
+ return b2Mul(m_xf, localPoint);
+}
+
+inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const
+{
+ return b2Mul(m_xf.q, localVector);
+}
+
+inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const
+{
+ return b2MulT(m_xf, worldPoint);
+}
+
+inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const
+{
+ return b2MulT(m_xf.q, worldVector);
+}
+
+inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const
+{
+ return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c);
+}
+
+inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const
+{
+ return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint));
+}
+
+inline float32 b2Body::GetLinearDamping() const
+{
+ return m_linearDamping;
+}
+
+inline void b2Body::SetLinearDamping(float32 linearDamping)
+{
+ m_linearDamping = linearDamping;
+}
+
+inline float32 b2Body::GetAngularDamping() const
+{
+ return m_angularDamping;
+}
+
+inline void b2Body::SetAngularDamping(float32 angularDamping)
+{
+ m_angularDamping = angularDamping;
+}
+
+inline float32 b2Body::GetGravityScale() const
+{
+ return m_gravityScale;
+}
+
+inline void b2Body::SetGravityScale(float32 scale)
+{
+ m_gravityScale = scale;
+}
+
+inline void b2Body::SetBullet(bool flag)
+{
+ if (flag)
+ {
+ m_flags |= e_bulletFlag;
+ }
+ else
+ {
+ m_flags &= ~e_bulletFlag;
+ }
+}
+
+inline bool b2Body::IsBullet() const
+{
+ return (m_flags & e_bulletFlag) == e_bulletFlag;
+}
+
+inline void b2Body::SetAwake(bool flag)
+{
+ if (flag)
+ {
+ if ((m_flags & e_awakeFlag) == 0)
+ {
+ m_flags |= e_awakeFlag;
+ m_sleepTime = 0.0f;
+ }
+ }
+ else
+ {
+ m_flags &= ~e_awakeFlag;
+ m_sleepTime = 0.0f;
+ m_linearVelocity.SetZero();
+ m_angularVelocity = 0.0f;
+ m_force.SetZero();
+ m_torque = 0.0f;
+ }
+}
+
+inline bool b2Body::IsAwake() const
+{
+ return (m_flags & e_awakeFlag) == e_awakeFlag;
+}
+
+inline bool b2Body::IsActive() const
+{
+ return (m_flags & e_activeFlag) == e_activeFlag;
+}
+
+inline void b2Body::SetFixedRotation(bool flag)
+{
+ if (flag)
+ {
+ m_flags |= e_fixedRotationFlag;
+ }
+ else
+ {
+ m_flags &= ~e_fixedRotationFlag;
+ }
+
+ ResetMassData();
+}
+
+inline bool b2Body::IsFixedRotation() const
+{
+ return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag;
+}
+
+inline void b2Body::SetSleepingAllowed(bool flag)
+{
+ if (flag)
+ {
+ m_flags |= e_autoSleepFlag;
+ }
+ else
+ {
+ m_flags &= ~e_autoSleepFlag;
+ SetAwake(true);
+ }
+}
+
+inline bool b2Body::IsSleepingAllowed() const
+{
+ return (m_flags & e_autoSleepFlag) == e_autoSleepFlag;
+}
+
+inline b2Fixture* b2Body::GetFixtureList()
+{
+ return m_fixtureList;
+}
+
+inline const b2Fixture* b2Body::GetFixtureList() const
+{
+ return m_fixtureList;
+}
+
+inline b2JointEdge* b2Body::GetJointList()
+{
+ return m_jointList;
+}
+
+inline const b2JointEdge* b2Body::GetJointList() const
+{
+ return m_jointList;
+}
+
+inline b2ContactEdge* b2Body::GetContactList()
+{
+ return m_contactList;
+}
+
+inline const b2ContactEdge* b2Body::GetContactList() const
+{
+ return m_contactList;
+}
+
+inline b2Body* b2Body::GetNext()
+{
+ return m_next;
+}
+
+inline const b2Body* b2Body::GetNext() const
+{
+ return m_next;
+}
+
+inline void b2Body::SetUserData(void* data)
+{
+ m_userData = data;
+}
+
+inline void* b2Body::GetUserData() const
+{
+ return m_userData;
+}
+
+inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point)
+{
+ if (m_type != b2_dynamicBody)
+ {
+ return;
+ }
+
+ if (IsAwake() == false)
+ {
+ SetAwake(true);
+ }
+
+ m_force += force;
+ m_torque += b2Cross(point - m_sweep.c, force);
+}
+
+inline void b2Body::ApplyForceToCenter(const b2Vec2& force)
+{
+ if (m_type != b2_dynamicBody)
+ {
+ return;
+ }
+
+ if (IsAwake() == false)
+ {
+ SetAwake(true);
+ }
+
+ m_force += force;
+}
+
+inline void b2Body::ApplyTorque(float32 torque)
+{
+ if (m_type != b2_dynamicBody)
+ {
+ return;
+ }
+
+ if (IsAwake() == false)
+ {
+ SetAwake(true);
+ }
+
+ m_torque += torque;
+}
+
+inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point)
+{
+ if (m_type != b2_dynamicBody)
+ {
+ return;
+ }
+
+ if (IsAwake() == false)
+ {
+ SetAwake(true);
+ }
+ m_linearVelocity += m_invMass * impulse;
+ m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse);
+}
+
+inline void b2Body::ApplyAngularImpulse(float32 impulse)
+{
+ if (m_type != b2_dynamicBody)
+ {
+ return;
+ }
+
+ if (IsAwake() == false)
+ {
+ SetAwake(true);
+ }
+ m_angularVelocity += m_invI * impulse;
+}
+
+inline void b2Body::SynchronizeTransform()
+{
+ m_xf.q.Set(m_sweep.a);
+ m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter);
+}
+
+inline void b2Body::Advance(float32 alpha)
+{
+ // Advance to the new safe time. This doesn't sync the broad-phase.
+ m_sweep.Advance(alpha);
+ m_sweep.c = m_sweep.c0;
+ m_sweep.a = m_sweep.a0;
+ m_xf.q.Set(m_sweep.a);
+ m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter);
+}
+
+inline b2World* b2Body::GetWorld()
+{
+ return m_world;
+}
+
+inline const b2World* b2Body::GetWorld() const
+{
+ return m_world;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2ContactManager.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/b2ContactManager.cpp
new file mode 100644
index 00000000..5ac12b35
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2ContactManager.cpp
@@ -0,0 +1,293 @@
+/*
+* Copyright (c) 2006-2009 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/b2ContactManager.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2WorldCallbacks.h>
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+
+b2ContactFilter b2_defaultFilter;
+b2ContactListener b2_defaultListener;
+
+b2ContactManager::b2ContactManager()
+{
+ m_contactList = NULL;
+ m_contactCount = 0;
+ m_contactFilter = &b2_defaultFilter;
+ m_contactListener = &b2_defaultListener;
+ m_allocator = NULL;
+}
+
+void b2ContactManager::Destroy(b2Contact* c)
+{
+ b2Fixture* fixtureA = c->GetFixtureA();
+ b2Fixture* fixtureB = c->GetFixtureB();
+ b2Body* bodyA = fixtureA->GetBody();
+ b2Body* bodyB = fixtureB->GetBody();
+
+ if (m_contactListener && c->IsTouching())
+ {
+ m_contactListener->EndContact(c);
+ }
+
+ // Remove from the world.
+ if (c->m_prev)
+ {
+ c->m_prev->m_next = c->m_next;
+ }
+
+ if (c->m_next)
+ {
+ c->m_next->m_prev = c->m_prev;
+ }
+
+ if (c == m_contactList)
+ {
+ m_contactList = c->m_next;
+ }
+
+ // Remove from body 1
+ if (c->m_nodeA.prev)
+ {
+ c->m_nodeA.prev->next = c->m_nodeA.next;
+ }
+
+ if (c->m_nodeA.next)
+ {
+ c->m_nodeA.next->prev = c->m_nodeA.prev;
+ }
+
+ if (&c->m_nodeA == bodyA->m_contactList)
+ {
+ bodyA->m_contactList = c->m_nodeA.next;
+ }
+
+ // Remove from body 2
+ if (c->m_nodeB.prev)
+ {
+ c->m_nodeB.prev->next = c->m_nodeB.next;
+ }
+
+ if (c->m_nodeB.next)
+ {
+ c->m_nodeB.next->prev = c->m_nodeB.prev;
+ }
+
+ if (&c->m_nodeB == bodyB->m_contactList)
+ {
+ bodyB->m_contactList = c->m_nodeB.next;
+ }
+
+ // Call the factory.
+ b2Contact::Destroy(c, m_allocator);
+ --m_contactCount;
+}
+
+// This is the top level collision call for the time step. Here
+// all the narrow phase collision is processed for the world
+// contact list.
+void b2ContactManager::Collide()
+{
+ // Update awake contacts.
+ b2Contact* c = m_contactList;
+ while (c)
+ {
+ b2Fixture* fixtureA = c->GetFixtureA();
+ b2Fixture* fixtureB = c->GetFixtureB();
+ int32 indexA = c->GetChildIndexA();
+ int32 indexB = c->GetChildIndexB();
+ b2Body* bodyA = fixtureA->GetBody();
+ b2Body* bodyB = fixtureB->GetBody();
+
+ // Is this contact flagged for filtering?
+ if (c->m_flags & b2Contact::e_filterFlag)
+ {
+ // Should these bodies collide?
+ if (bodyB->ShouldCollide(bodyA) == false)
+ {
+ b2Contact* cNuke = c;
+ c = cNuke->GetNext();
+ Destroy(cNuke);
+ continue;
+ }
+
+ // Check user filtering.
+ if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false)
+ {
+ b2Contact* cNuke = c;
+ c = cNuke->GetNext();
+ Destroy(cNuke);
+ continue;
+ }
+
+ // Clear the filtering flag.
+ c->m_flags &= ~b2Contact::e_filterFlag;
+ }
+
+ bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody;
+ bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody;
+
+ // At least one body must be awake and it must be dynamic or kinematic.
+ if (activeA == false && activeB == false)
+ {
+ c = c->GetNext();
+ continue;
+ }
+
+ int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId;
+ int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId;
+ bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB);
+
+ // Here we destroy contacts that cease to overlap in the broad-phase.
+ if (overlap == false)
+ {
+ b2Contact* cNuke = c;
+ c = cNuke->GetNext();
+ Destroy(cNuke);
+ continue;
+ }
+
+ // The contact persists.
+ c->Update(m_contactListener);
+ c = c->GetNext();
+ }
+}
+
+void b2ContactManager::FindNewContacts()
+{
+ m_broadPhase.UpdatePairs(this);
+}
+
+void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB)
+{
+ b2FixtureProxy* proxyA = (b2FixtureProxy*)proxyUserDataA;
+ b2FixtureProxy* proxyB = (b2FixtureProxy*)proxyUserDataB;
+
+ b2Fixture* fixtureA = proxyA->fixture;
+ b2Fixture* fixtureB = proxyB->fixture;
+
+ int32 indexA = proxyA->childIndex;
+ int32 indexB = proxyB->childIndex;
+
+ b2Body* bodyA = fixtureA->GetBody();
+ b2Body* bodyB = fixtureB->GetBody();
+
+ // Are the fixtures on the same body?
+ if (bodyA == bodyB)
+ {
+ return;
+ }
+
+ // TODO_ERIN use a hash table to remove a potential bottleneck when both
+ // bodies have a lot of contacts.
+ // Does a contact already exist?
+ b2ContactEdge* edge = bodyB->GetContactList();
+ while (edge)
+ {
+ if (edge->other == bodyA)
+ {
+ b2Fixture* fA = edge->contact->GetFixtureA();
+ b2Fixture* fB = edge->contact->GetFixtureB();
+ int32 iA = edge->contact->GetChildIndexA();
+ int32 iB = edge->contact->GetChildIndexB();
+
+ if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB)
+ {
+ // A contact already exists.
+ return;
+ }
+
+ if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA)
+ {
+ // A contact already exists.
+ return;
+ }
+ }
+
+ edge = edge->next;
+ }
+
+ // Does a joint override collision? Is at least one body dynamic?
+ if (bodyB->ShouldCollide(bodyA) == false)
+ {
+ return;
+ }
+
+ // Check user filtering.
+ if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false)
+ {
+ return;
+ }
+
+ // Call the factory.
+ b2Contact* c = b2Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator);
+ if (c == NULL)
+ {
+ return;
+ }
+
+ // Contact creation may swap fixtures.
+ fixtureA = c->GetFixtureA();
+ fixtureB = c->GetFixtureB();
+ indexA = c->GetChildIndexA();
+ indexB = c->GetChildIndexB();
+ bodyA = fixtureA->GetBody();
+ bodyB = fixtureB->GetBody();
+
+ // Insert into the world.
+ c->m_prev = NULL;
+ c->m_next = m_contactList;
+ if (m_contactList != NULL)
+ {
+ m_contactList->m_prev = c;
+ }
+ m_contactList = c;
+
+ // Connect to island graph.
+
+ // Connect to body A
+ c->m_nodeA.contact = c;
+ c->m_nodeA.other = bodyB;
+
+ c->m_nodeA.prev = NULL;
+ c->m_nodeA.next = bodyA->m_contactList;
+ if (bodyA->m_contactList != NULL)
+ {
+ bodyA->m_contactList->prev = &c->m_nodeA;
+ }
+ bodyA->m_contactList = &c->m_nodeA;
+
+ // Connect to body B
+ c->m_nodeB.contact = c;
+ c->m_nodeB.other = bodyA;
+
+ c->m_nodeB.prev = NULL;
+ c->m_nodeB.next = bodyB->m_contactList;
+ if (bodyB->m_contactList != NULL)
+ {
+ bodyB->m_contactList->prev = &c->m_nodeB;
+ }
+ bodyB->m_contactList = &c->m_nodeB;
+
+ // Wake up the bodies
+ bodyA->SetAwake(true);
+ bodyB->SetAwake(true);
+
+ ++m_contactCount;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2ContactManager.h b/games/hillclimb/src/box2d/Box2D/Dynamics/b2ContactManager.h
new file mode 100644
index 00000000..dc1f77fe
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2ContactManager.h
@@ -0,0 +1,52 @@
+/*
+* Copyright (c) 2006-2009 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_CONTACT_MANAGER_H
+#define B2_CONTACT_MANAGER_H
+
+#include <Box2D/Collision/b2BroadPhase.h>
+
+class b2Contact;
+class b2ContactFilter;
+class b2ContactListener;
+class b2BlockAllocator;
+
+// Delegate of b2World.
+class b2ContactManager
+{
+public:
+ b2ContactManager();
+
+ // Broad-phase callback.
+ void AddPair(void* proxyUserDataA, void* proxyUserDataB);
+
+ void FindNewContacts();
+
+ void Destroy(b2Contact* c);
+
+ void Collide();
+
+ b2BroadPhase m_broadPhase;
+ b2Contact* m_contactList;
+ int32 m_contactCount;
+ b2ContactFilter* m_contactFilter;
+ b2ContactListener* m_contactListener;
+ b2BlockAllocator* m_allocator;
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2Fixture.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Fixture.cpp
new file mode 100644
index 00000000..77537b27
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Fixture.cpp
@@ -0,0 +1,303 @@
+/*
+* Copyright (c) 2006-2009 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/b2Fixture.h>
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+#include <Box2D/Dynamics/b2World.h>
+#include <Box2D/Collision/Shapes/b2CircleShape.h>
+#include <Box2D/Collision/Shapes/b2EdgeShape.h>
+#include <Box2D/Collision/Shapes/b2PolygonShape.h>
+#include <Box2D/Collision/Shapes/b2ChainShape.h>
+#include <Box2D/Collision/b2BroadPhase.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+
+b2Fixture::b2Fixture()
+{
+ m_userData = NULL;
+ m_body = NULL;
+ m_next = NULL;
+ m_proxies = NULL;
+ m_proxyCount = 0;
+ m_shape = NULL;
+ m_density = 0.0f;
+}
+
+void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def)
+{
+ m_userData = def->userData;
+ m_friction = def->friction;
+ m_restitution = def->restitution;
+
+ m_body = body;
+ m_next = NULL;
+
+ m_filter = def->filter;
+
+ m_isSensor = def->isSensor;
+
+ m_shape = def->shape->Clone(allocator);
+
+ // Reserve proxy space
+ int32 childCount = m_shape->GetChildCount();
+ m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy));
+ for (int32 i = 0; i < childCount; ++i)
+ {
+ m_proxies[i].fixture = NULL;
+ m_proxies[i].proxyId = b2BroadPhase::e_nullProxy;
+ }
+ m_proxyCount = 0;
+
+ m_density = def->density;
+}
+
+void b2Fixture::Destroy(b2BlockAllocator* allocator)
+{
+ // The proxies must be destroyed before calling this.
+ b2Assert(m_proxyCount == 0);
+
+ // Free the proxy array.
+ int32 childCount = m_shape->GetChildCount();
+ allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy));
+ m_proxies = NULL;
+
+ // Free the child shape.
+ switch (m_shape->m_type)
+ {
+ case b2Shape::e_circle:
+ {
+ b2CircleShape* s = (b2CircleShape*)m_shape;
+ s->~b2CircleShape();
+ allocator->Free(s, sizeof(b2CircleShape));
+ }
+ break;
+
+ case b2Shape::e_edge:
+ {
+ b2EdgeShape* s = (b2EdgeShape*)m_shape;
+ s->~b2EdgeShape();
+ allocator->Free(s, sizeof(b2EdgeShape));
+ }
+ break;
+
+ case b2Shape::e_polygon:
+ {
+ b2PolygonShape* s = (b2PolygonShape*)m_shape;
+ s->~b2PolygonShape();
+ allocator->Free(s, sizeof(b2PolygonShape));
+ }
+ break;
+
+ case b2Shape::e_chain:
+ {
+ b2ChainShape* s = (b2ChainShape*)m_shape;
+ s->~b2ChainShape();
+ allocator->Free(s, sizeof(b2ChainShape));
+ }
+ break;
+
+ default:
+ b2Assert(false);
+ break;
+ }
+
+ m_shape = NULL;
+}
+
+void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf)
+{
+ b2Assert(m_proxyCount == 0);
+
+ // Create proxies in the broad-phase.
+ m_proxyCount = m_shape->GetChildCount();
+
+ for (int32 i = 0; i < m_proxyCount; ++i)
+ {
+ b2FixtureProxy* proxy = m_proxies + i;
+ m_shape->ComputeAABB(&proxy->aabb, xf, i);
+ proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy);
+ proxy->fixture = this;
+ proxy->childIndex = i;
+ }
+}
+
+void b2Fixture::DestroyProxies(b2BroadPhase* broadPhase)
+{
+ // Destroy proxies in the broad-phase.
+ for (int32 i = 0; i < m_proxyCount; ++i)
+ {
+ b2FixtureProxy* proxy = m_proxies + i;
+ broadPhase->DestroyProxy(proxy->proxyId);
+ proxy->proxyId = b2BroadPhase::e_nullProxy;
+ }
+
+ m_proxyCount = 0;
+}
+
+void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2)
+{
+ if (m_proxyCount == 0)
+ {
+ return;
+ }
+
+ for (int32 i = 0; i < m_proxyCount; ++i)
+ {
+ b2FixtureProxy* proxy = m_proxies + i;
+
+ // Compute an AABB that covers the swept shape (may miss some rotation effect).
+ b2AABB aabb1, aabb2;
+ m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex);
+ m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex);
+
+ proxy->aabb.Combine(aabb1, aabb2);
+
+ b2Vec2 displacement = transform2.p - transform1.p;
+
+ broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement);
+ }
+}
+
+void b2Fixture::SetFilterData(const b2Filter& filter)
+{
+ m_filter = filter;
+
+ Refilter();
+}
+
+void b2Fixture::Refilter()
+{
+ if (m_body == NULL)
+ {
+ return;
+ }
+
+ // Flag associated contacts for filtering.
+ b2ContactEdge* edge = m_body->GetContactList();
+ while (edge)
+ {
+ b2Contact* contact = edge->contact;
+ b2Fixture* fixtureA = contact->GetFixtureA();
+ b2Fixture* fixtureB = contact->GetFixtureB();
+ if (fixtureA == this || fixtureB == this)
+ {
+ contact->FlagForFiltering();
+ }
+
+ edge = edge->next;
+ }
+
+ b2World* world = m_body->GetWorld();
+
+ if (world == NULL)
+ {
+ return;
+ }
+
+ // Touch each proxy so that new pairs may be created
+ b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase;
+ for (int32 i = 0; i < m_proxyCount; ++i)
+ {
+ broadPhase->TouchProxy(m_proxies[i].proxyId);
+ }
+}
+
+void b2Fixture::SetSensor(bool sensor)
+{
+ if (sensor != m_isSensor)
+ {
+ m_body->SetAwake(true);
+ m_isSensor = sensor;
+ }
+}
+
+void b2Fixture::Dump(int32 bodyIndex)
+{
+ b2Log(" b2FixtureDef fd;\n");
+ b2Log(" fd.friction = %.15lef;\n", m_friction);
+ b2Log(" fd.restitution = %.15lef;\n", m_restitution);
+ b2Log(" fd.density = %.15lef;\n", m_density);
+ b2Log(" fd.isSensor = bool(%d);\n", m_isSensor);
+ b2Log(" fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits);
+ b2Log(" fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits);
+ b2Log(" fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex);
+
+ switch (m_shape->m_type)
+ {
+ case b2Shape::e_circle:
+ {
+ b2CircleShape* s = (b2CircleShape*)m_shape;
+ b2Log(" b2CircleShape shape;\n");
+ b2Log(" shape.m_radius = %.15lef;\n", s->m_radius);
+ b2Log(" shape.m_p.Set(%.15lef, %.15lef);\n", s->m_p.x, s->m_p.y);
+ }
+ break;
+
+ case b2Shape::e_edge:
+ {
+ b2EdgeShape* s = (b2EdgeShape*)m_shape;
+ b2Log(" b2EdgeShape shape;\n");
+ b2Log(" shape.m_radius = %.15lef;\n", s->m_radius);
+ b2Log(" shape.m_vertex0.Set(%.15lef, %.15lef);\n", s->m_vertex0.x, s->m_vertex0.y);
+ b2Log(" shape.m_vertex1.Set(%.15lef, %.15lef);\n", s->m_vertex1.x, s->m_vertex1.y);
+ b2Log(" shape.m_vertex2.Set(%.15lef, %.15lef);\n", s->m_vertex2.x, s->m_vertex2.y);
+ b2Log(" shape.m_vertex3.Set(%.15lef, %.15lef);\n", s->m_vertex3.x, s->m_vertex3.y);
+ b2Log(" shape.m_hasVertex0 = bool(%d);\n", s->m_hasVertex0);
+ b2Log(" shape.m_hasVertex3 = bool(%d);\n", s->m_hasVertex3);
+ }
+ break;
+
+ case b2Shape::e_polygon:
+ {
+ b2PolygonShape* s = (b2PolygonShape*)m_shape;
+ b2Log(" b2PolygonShape shape;\n");
+ b2Log(" b2Vec2 vs[%d];\n", b2_maxPolygonVertices);
+ for (int32 i = 0; i < s->m_vertexCount; ++i)
+ {
+ b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y);
+ }
+ b2Log(" shape.Set(vs, %d);\n", s->m_vertexCount);
+ }
+ break;
+
+ case b2Shape::e_chain:
+ {
+ b2ChainShape* s = (b2ChainShape*)m_shape;
+ b2Log(" b2ChainShape shape;\n");
+ b2Log(" b2Vec2 vs[%d];\n", s->m_count);
+ for (int32 i = 0; i < s->m_count; ++i)
+ {
+ b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y);
+ }
+ b2Log(" shape.CreateChain(vs, %d);\n", s->m_count);
+ b2Log(" shape.m_prevVertex.Set(%.15lef, %.15lef);\n", s->m_prevVertex.x, s->m_prevVertex.y);
+ b2Log(" shape.m_nextVertex.Set(%.15lef, %.15lef);\n", s->m_nextVertex.x, s->m_nextVertex.y);
+ b2Log(" shape.m_hasPrevVertex = bool(%d);\n", s->m_hasPrevVertex);
+ b2Log(" shape.m_hasNextVertex = bool(%d);\n", s->m_hasNextVertex);
+ }
+ break;
+
+ default:
+ return;
+ }
+
+ b2Log("\n");
+ b2Log(" fd.shape = &shape;\n");
+ b2Log("\n");
+ b2Log(" bodies[%d]->CreateFixture(&fd);\n", bodyIndex);
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2Fixture.h b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Fixture.h
new file mode 100644
index 00000000..5ebd0c3f
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Fixture.h
@@ -0,0 +1,345 @@
+/*
+* Copyright (c) 2006-2009 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_FIXTURE_H
+#define B2_FIXTURE_H
+
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/Shapes/b2Shape.h>
+
+class b2BlockAllocator;
+class b2Body;
+class b2BroadPhase;
+class b2Fixture;
+
+/// This holds contact filtering data.
+struct b2Filter
+{
+ b2Filter()
+ {
+ categoryBits = 0x0001;
+ maskBits = 0xFFFF;
+ groupIndex = 0;
+ }
+
+ /// The collision category bits. Normally you would just set one bit.
+ uint16 categoryBits;
+
+ /// The collision mask bits. This states the categories that this
+ /// shape would accept for collision.
+ uint16 maskBits;
+
+ /// Collision groups allow a certain group of objects to never collide (negative)
+ /// or always collide (positive). Zero means no collision group. Non-zero group
+ /// filtering always wins against the mask bits.
+ int16 groupIndex;
+};
+
+/// A fixture definition is used to create a fixture. This class defines an
+/// abstract fixture definition. You can reuse fixture definitions safely.
+struct b2FixtureDef
+{
+ /// The constructor sets the default fixture definition values.
+ b2FixtureDef()
+ {
+ shape = NULL;
+ userData = NULL;
+ friction = 0.2f;
+ restitution = 0.0f;
+ density = 0.0f;
+ isSensor = false;
+ }
+
+ /// The shape, this must be set. The shape will be cloned, so you
+ /// can create the shape on the stack.
+ const b2Shape* shape;
+
+ /// Use this to store application specific fixture data.
+ void* userData;
+
+ /// The friction coefficient, usually in the range [0,1].
+ float32 friction;
+
+ /// The restitution (elasticity) usually in the range [0,1].
+ float32 restitution;
+
+ /// The density, usually in kg/m^2.
+ float32 density;
+
+ /// A sensor shape collects contact information but never generates a collision
+ /// response.
+ bool isSensor;
+
+ /// Contact filtering data.
+ b2Filter filter;
+};
+
+/// This proxy is used internally to connect fixtures to the broad-phase.
+struct b2FixtureProxy
+{
+ b2AABB aabb;
+ b2Fixture* fixture;
+ int32 childIndex;
+ int32 proxyId;
+};
+
+/// A fixture is used to attach a shape to a body for collision detection. A fixture
+/// inherits its transform from its parent. Fixtures hold additional non-geometric data
+/// such as friction, collision filters, etc.
+/// Fixtures are created via b2Body::CreateFixture.
+/// @warning you cannot reuse fixtures.
+class b2Fixture
+{
+public:
+ /// Get the type of the child shape. You can use this to down cast to the concrete shape.
+ /// @return the shape type.
+ b2Shape::Type GetType() const;
+
+ /// Get the child shape. You can modify the child shape, however you should not change the
+ /// number of vertices because this will crash some collision caching mechanisms.
+ /// Manipulating the shape may lead to non-physical behavior.
+ b2Shape* GetShape();
+ const b2Shape* GetShape() const;
+
+ /// Set if this fixture is a sensor.
+ void SetSensor(bool sensor);
+
+ /// Is this fixture a sensor (non-solid)?
+ /// @return the true if the shape is a sensor.
+ bool IsSensor() const;
+
+ /// Set the contact filtering data. This will not update contacts until the next time
+ /// step when either parent body is active and awake.
+ /// This automatically calls Refilter.
+ void SetFilterData(const b2Filter& filter);
+
+ /// Get the contact filtering data.
+ const b2Filter& GetFilterData() const;
+
+ /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide.
+ void Refilter();
+
+ /// Get the parent body of this fixture. This is NULL if the fixture is not attached.
+ /// @return the parent body.
+ b2Body* GetBody();
+ const b2Body* GetBody() const;
+
+ /// Get the next fixture in the parent body's fixture list.
+ /// @return the next shape.
+ b2Fixture* GetNext();
+ const b2Fixture* GetNext() const;
+
+ /// Get the user data that was assigned in the fixture definition. Use this to
+ /// store your application specific data.
+ void* GetUserData() const;
+
+ /// Set the user data. Use this to store your application specific data.
+ void SetUserData(void* data);
+
+ /// Test a point for containment in this fixture.
+ /// @param p a point in world coordinates.
+ bool TestPoint(const b2Vec2& p) const;
+
+ /// Cast a ray against this shape.
+ /// @param output the ray-cast results.
+ /// @param input the ray-cast input parameters.
+ bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const;
+
+ /// Get the mass data for this fixture. The mass data is based on the density and
+ /// the shape. The rotational inertia is about the shape's origin. This operation
+ /// may be expensive.
+ void GetMassData(b2MassData* massData) const;
+
+ /// Set the density of this fixture. This will _not_ automatically adjust the mass
+ /// of the body. You must call b2Body::ResetMassData to update the body's mass.
+ void SetDensity(float32 density);
+
+ /// Get the density of this fixture.
+ float32 GetDensity() const;
+
+ /// Get the coefficient of friction.
+ float32 GetFriction() const;
+
+ /// Set the coefficient of friction. This will _not_ change the friction of
+ /// existing contacts.
+ void SetFriction(float32 friction);
+
+ /// Get the coefficient of restitution.
+ float32 GetRestitution() const;
+
+ /// Set the coefficient of restitution. This will _not_ change the restitution of
+ /// existing contacts.
+ void SetRestitution(float32 restitution);
+
+ /// Get the fixture's AABB. This AABB may be enlarge and/or stale.
+ /// If you need a more accurate AABB, compute it using the shape and
+ /// the body transform.
+ const b2AABB& GetAABB(int32 childIndex) const;
+
+ /// Dump this fixture to the log file.
+ void Dump(int32 bodyIndex);
+
+protected:
+
+ friend class b2Body;
+ friend class b2World;
+ friend class b2Contact;
+ friend class b2ContactManager;
+
+ b2Fixture();
+
+ // We need separation create/destroy functions from the constructor/destructor because
+ // the destructor cannot access the allocator (no destructor arguments allowed by C++).
+ void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def);
+ void Destroy(b2BlockAllocator* allocator);
+
+ // These support body activation/deactivation.
+ void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf);
+ void DestroyProxies(b2BroadPhase* broadPhase);
+
+ void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2);
+
+ float32 m_density;
+
+ b2Fixture* m_next;
+ b2Body* m_body;
+
+ b2Shape* m_shape;
+
+ float32 m_friction;
+ float32 m_restitution;
+
+ b2FixtureProxy* m_proxies;
+ int32 m_proxyCount;
+
+ b2Filter m_filter;
+
+ bool m_isSensor;
+
+ void* m_userData;
+};
+
+inline b2Shape::Type b2Fixture::GetType() const
+{
+ return m_shape->GetType();
+}
+
+inline b2Shape* b2Fixture::GetShape()
+{
+ return m_shape;
+}
+
+inline const b2Shape* b2Fixture::GetShape() const
+{
+ return m_shape;
+}
+
+inline bool b2Fixture::IsSensor() const
+{
+ return m_isSensor;
+}
+
+inline const b2Filter& b2Fixture::GetFilterData() const
+{
+ return m_filter;
+}
+
+inline void* b2Fixture::GetUserData() const
+{
+ return m_userData;
+}
+
+inline void b2Fixture::SetUserData(void* data)
+{
+ m_userData = data;
+}
+
+inline b2Body* b2Fixture::GetBody()
+{
+ return m_body;
+}
+
+inline const b2Body* b2Fixture::GetBody() const
+{
+ return m_body;
+}
+
+inline b2Fixture* b2Fixture::GetNext()
+{
+ return m_next;
+}
+
+inline const b2Fixture* b2Fixture::GetNext() const
+{
+ return m_next;
+}
+
+inline void b2Fixture::SetDensity(float32 density)
+{
+ b2Assert(b2IsValid(density) && density >= 0.0f);
+ m_density = density;
+}
+
+inline float32 b2Fixture::GetDensity() const
+{
+ return m_density;
+}
+
+inline float32 b2Fixture::GetFriction() const
+{
+ return m_friction;
+}
+
+inline void b2Fixture::SetFriction(float32 friction)
+{
+ m_friction = friction;
+}
+
+inline float32 b2Fixture::GetRestitution() const
+{
+ return m_restitution;
+}
+
+inline void b2Fixture::SetRestitution(float32 restitution)
+{
+ m_restitution = restitution;
+}
+
+inline bool b2Fixture::TestPoint(const b2Vec2& p) const
+{
+ return m_shape->TestPoint(m_body->GetTransform(), p);
+}
+
+inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const
+{
+ return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex);
+}
+
+inline void b2Fixture::GetMassData(b2MassData* massData) const
+{
+ m_shape->ComputeMass(massData, m_density);
+}
+
+inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const
+{
+ b2Assert(0 <= childIndex && childIndex < m_proxyCount);
+ return m_proxies[childIndex].aabb;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2Island.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Island.cpp
new file mode 100644
index 00000000..0e2129cf
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Island.cpp
@@ -0,0 +1,539 @@
+/*
+* 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/Collision/b2Distance.h>
+#include <Box2D/Dynamics/b2Island.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2World.h>
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+#include <Box2D/Dynamics/Contacts/b2ContactSolver.h>
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+#include <Box2D/Common/b2StackAllocator.h>
+#include <Box2D/Common/b2Timer.h>
+
+/*
+Position Correction Notes
+=========================
+I tried the several algorithms for position correction of the 2D revolute joint.
+I looked at these systems:
+- simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s.
+- suspension bridge with 30 1m long planks of length 1m.
+- multi-link chain with 30 1m long links.
+
+Here are the algorithms:
+
+Baumgarte - A fraction of the position error is added to the velocity error. There is no
+separate position solver.
+
+Pseudo Velocities - After the velocity solver and position integration,
+the position error, Jacobian, and effective mass are recomputed. Then
+the velocity constraints are solved with pseudo velocities and a fraction
+of the position error is added to the pseudo velocity error. The pseudo
+velocities are initialized to zero and there is no warm-starting. After
+the position solver, the pseudo velocities are added to the positions.
+This is also called the First Order World method or the Position LCP method.
+
+Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the
+position error is re-computed for each constraint and the positions are updated
+after the constraint is solved. The radius vectors (aka Jacobians) are
+re-computed too (otherwise the algorithm has horrible instability). The pseudo
+velocity states are not needed because they are effectively zero at the beginning
+of each iteration. Since we have the current position error, we allow the
+iterations to terminate early if the error becomes smaller than b2_linearSlop.
+
+Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed
+each time a constraint is solved.
+
+Here are the results:
+Baumgarte - this is the cheapest algorithm but it has some stability problems,
+especially with the bridge. The chain links separate easily close to the root
+and they jitter as they struggle to pull together. This is one of the most common
+methods in the field. The big drawback is that the position correction artificially
+affects the momentum, thus leading to instabilities and false bounce. I used a
+bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller
+factor makes joints and contacts more spongy.
+
+Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is
+stable. However, joints still separate with large angular velocities. Drag the
+simple pendulum in a circle quickly and the joint will separate. The chain separates
+easily and does not recover. I used a bias factor of 0.2. A larger value lead to
+the bridge collapsing when a heavy cube drops on it.
+
+Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo
+Velocities, but in other ways it is worse. The bridge and chain are much more
+stable, but the simple pendulum goes unstable at high angular velocities.
+
+Full NGS - stable in all tests. The joints display good stiffness. The bridge
+still sags, but this is better than infinite forces.
+
+Recommendations
+Pseudo Velocities are not really worthwhile because the bridge and chain cannot
+recover from joint separation. In other cases the benefit over Baumgarte is small.
+
+Modified NGS is not a robust method for the revolute joint due to the violent
+instability seen in the simple pendulum. Perhaps it is viable with other constraint
+types, especially scalar constraints where the effective mass is a scalar.
+
+This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities
+and is very fast. I don't think we can escape Baumgarte, especially in highly
+demanding cases where high constraint fidelity is not needed.
+
+Full NGS is robust and easy on the eyes. I recommend this as an option for
+higher fidelity simulation and certainly for suspension bridges and long chains.
+Full NGS might be a good choice for ragdolls, especially motorized ragdolls where
+joint separation can be problematic. The number of NGS iterations can be reduced
+for better performance without harming robustness much.
+
+Each joint in a can be handled differently in the position solver. So I recommend
+a system where the user can select the algorithm on a per joint basis. I would
+probably default to the slower Full NGS and let the user select the faster
+Baumgarte method in performance critical scenarios.
+*/
+
+/*
+Cache Performance
+
+The Box2D solvers are dominated by cache misses. Data structures are designed
+to increase the number of cache hits. Much of misses are due to random access
+to body data. The constraint structures are iterated over linearly, which leads
+to few cache misses.
+
+The bodies are not accessed during iteration. Instead read only data, such as
+the mass values are stored with the constraints. The mutable data are the constraint
+impulses and the bodies velocities/positions. The impulses are held inside the
+constraint structures. The body velocities/positions are held in compact, temporary
+arrays to increase the number of cache hits. Linear and angular velocity are
+stored in a single array since multiple arrays lead to multiple misses.
+*/
+
+/*
+2D Rotation
+
+R = [cos(theta) -sin(theta)]
+ [sin(theta) cos(theta) ]
+
+thetaDot = omega
+
+Let q1 = cos(theta), q2 = sin(theta).
+R = [q1 -q2]
+ [q2 q1]
+
+q1Dot = -thetaDot * q2
+q2Dot = thetaDot * q1
+
+q1_new = q1_old - dt * w * q2
+q2_new = q2_old + dt * w * q1
+then normalize.
+
+This might be faster than computing sin+cos.
+However, we can compute sin+cos of the same angle fast.
+*/
+
+b2Island::b2Island(
+ int32 bodyCapacity,
+ int32 contactCapacity,
+ int32 jointCapacity,
+ b2StackAllocator* allocator,
+ b2ContactListener* listener)
+{
+ m_bodyCapacity = bodyCapacity;
+ m_contactCapacity = contactCapacity;
+ m_jointCapacity = jointCapacity;
+ m_bodyCount = 0;
+ m_contactCount = 0;
+ m_jointCount = 0;
+
+ m_allocator = allocator;
+ m_listener = listener;
+
+ m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*));
+ m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*));
+ m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*));
+
+ m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity));
+ m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position));
+}
+
+b2Island::~b2Island()
+{
+ // Warning: the order should reverse the constructor order.
+ m_allocator->Free(m_positions);
+ m_allocator->Free(m_velocities);
+ m_allocator->Free(m_joints);
+ m_allocator->Free(m_contacts);
+ m_allocator->Free(m_bodies);
+}
+
+void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep)
+{
+ b2Timer timer;
+
+ float32 h = step.dt;
+
+ // Integrate velocities and apply damping. Initialize the body state.
+ for (int32 i = 0; i < m_bodyCount; ++i)
+ {
+ b2Body* b = m_bodies[i];
+
+ b2Vec2 c = b->m_sweep.c;
+ float32 a = b->m_sweep.a;
+ b2Vec2 v = b->m_linearVelocity;
+ float32 w = b->m_angularVelocity;
+
+ // Store positions for continuous collision.
+ b->m_sweep.c0 = b->m_sweep.c;
+ b->m_sweep.a0 = b->m_sweep.a;
+
+ if (b->m_type == b2_dynamicBody)
+ {
+ // Integrate velocities.
+ v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force);
+ w += h * b->m_invI * b->m_torque;
+
+ // Apply damping.
+ // ODE: dv/dt + c * v = 0
+ // Solution: v(t) = v0 * exp(-c * t)
+ // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt)
+ // v2 = exp(-c * dt) * v1
+ // Taylor expansion:
+ // v2 = (1.0f - c * dt) * v1
+ v *= b2Clamp(1.0f - h * b->m_linearDamping, 0.0f, 1.0f);
+ w *= b2Clamp(1.0f - h * b->m_angularDamping, 0.0f, 1.0f);
+ }
+
+ m_positions[i].c = c;
+ m_positions[i].a = a;
+ m_velocities[i].v = v;
+ m_velocities[i].w = w;
+ }
+
+ timer.Reset();
+
+ // Solver data
+ b2SolverData solverData;
+ solverData.step = step;
+ solverData.positions = m_positions;
+ solverData.velocities = m_velocities;
+
+ // Initialize velocity constraints.
+ b2ContactSolverDef contactSolverDef;
+ contactSolverDef.step = step;
+ contactSolverDef.contacts = m_contacts;
+ contactSolverDef.count = m_contactCount;
+ contactSolverDef.positions = m_positions;
+ contactSolverDef.velocities = m_velocities;
+ contactSolverDef.allocator = m_allocator;
+
+ b2ContactSolver contactSolver(&contactSolverDef);
+ contactSolver.InitializeVelocityConstraints();
+
+ if (step.warmStarting)
+ {
+ contactSolver.WarmStart();
+ }
+
+ for (int32 i = 0; i < m_jointCount; ++i)
+ {
+ m_joints[i]->InitVelocityConstraints(solverData);
+ }
+
+ profile->solveInit = timer.GetMilliseconds();
+
+ // Solve velocity constraints
+ timer.Reset();
+ for (int32 i = 0; i < step.velocityIterations; ++i)
+ {
+ for (int32 j = 0; j < m_jointCount; ++j)
+ {
+ m_joints[j]->SolveVelocityConstraints(solverData);
+ }
+
+ contactSolver.SolveVelocityConstraints();
+ }
+
+ // Store impulses for warm starting
+ contactSolver.StoreImpulses();
+ profile->solveVelocity = timer.GetMilliseconds();
+
+ // Integrate positions
+ for (int32 i = 0; i < m_bodyCount; ++i)
+ {
+ b2Vec2 c = m_positions[i].c;
+ float32 a = m_positions[i].a;
+ b2Vec2 v = m_velocities[i].v;
+ float32 w = m_velocities[i].w;
+
+ // Check for large velocities
+ b2Vec2 translation = h * v;
+ if (b2Dot(translation, translation) > b2_maxTranslationSquared)
+ {
+ float32 ratio = b2_maxTranslation / translation.Length();
+ v *= ratio;
+ }
+
+ float32 rotation = h * w;
+ if (rotation * rotation > b2_maxRotationSquared)
+ {
+ float32 ratio = b2_maxRotation / b2Abs(rotation);
+ w *= ratio;
+ }
+
+ // Integrate
+ c += h * v;
+ a += h * w;
+
+ m_positions[i].c = c;
+ m_positions[i].a = a;
+ m_velocities[i].v = v;
+ m_velocities[i].w = w;
+ }
+
+ // Solve position constraints
+ timer.Reset();
+ bool positionSolved = false;
+ for (int32 i = 0; i < step.positionIterations; ++i)
+ {
+ bool contactsOkay = contactSolver.SolvePositionConstraints();
+
+ bool jointsOkay = true;
+ for (int32 i = 0; i < m_jointCount; ++i)
+ {
+ bool jointOkay = m_joints[i]->SolvePositionConstraints(solverData);
+ jointsOkay = jointsOkay && jointOkay;
+ }
+
+ if (contactsOkay && jointsOkay)
+ {
+ // Exit early if the position errors are small.
+ positionSolved = true;
+ break;
+ }
+ }
+
+ // Copy state buffers back to the bodies
+ for (int32 i = 0; i < m_bodyCount; ++i)
+ {
+ b2Body* body = m_bodies[i];
+ body->m_sweep.c = m_positions[i].c;
+ body->m_sweep.a = m_positions[i].a;
+ body->m_linearVelocity = m_velocities[i].v;
+ body->m_angularVelocity = m_velocities[i].w;
+ body->SynchronizeTransform();
+ }
+
+ profile->solvePosition = timer.GetMilliseconds();
+
+ Report(contactSolver.m_velocityConstraints);
+
+ if (allowSleep)
+ {
+ float32 minSleepTime = b2_maxFloat;
+
+ const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance;
+ const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance;
+
+ for (int32 i = 0; i < m_bodyCount; ++i)
+ {
+ b2Body* b = m_bodies[i];
+ if (b->GetType() == b2_staticBody)
+ {
+ continue;
+ }
+
+ if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 ||
+ b->m_angularVelocity * b->m_angularVelocity > angTolSqr ||
+ b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr)
+ {
+ b->m_sleepTime = 0.0f;
+ minSleepTime = 0.0f;
+ }
+ else
+ {
+ b->m_sleepTime += h;
+ minSleepTime = b2Min(minSleepTime, b->m_sleepTime);
+ }
+ }
+
+ if (minSleepTime >= b2_timeToSleep && positionSolved)
+ {
+ for (int32 i = 0; i < m_bodyCount; ++i)
+ {
+ b2Body* b = m_bodies[i];
+ b->SetAwake(false);
+ }
+ }
+ }
+}
+
+void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB)
+{
+ b2Assert(toiIndexA < m_bodyCount);
+ b2Assert(toiIndexB < m_bodyCount);
+
+ // Initialize the body state.
+ for (int32 i = 0; i < m_bodyCount; ++i)
+ {
+ b2Body* b = m_bodies[i];
+ m_positions[i].c = b->m_sweep.c;
+ m_positions[i].a = b->m_sweep.a;
+ m_velocities[i].v = b->m_linearVelocity;
+ m_velocities[i].w = b->m_angularVelocity;
+ }
+
+ b2ContactSolverDef contactSolverDef;
+ contactSolverDef.contacts = m_contacts;
+ contactSolverDef.count = m_contactCount;
+ contactSolverDef.allocator = m_allocator;
+ contactSolverDef.step = subStep;
+ contactSolverDef.positions = m_positions;
+ contactSolverDef.velocities = m_velocities;
+ b2ContactSolver contactSolver(&contactSolverDef);
+
+ // Solve position constraints.
+ for (int32 i = 0; i < subStep.positionIterations; ++i)
+ {
+ bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB);
+ if (contactsOkay)
+ {
+ break;
+ }
+ }
+
+#if 0
+ // Is the new position really safe?
+ for (int32 i = 0; i < m_contactCount; ++i)
+ {
+ b2Contact* c = m_contacts[i];
+ b2Fixture* fA = c->GetFixtureA();
+ b2Fixture* fB = c->GetFixtureB();
+
+ b2Body* bA = fA->GetBody();
+ b2Body* bB = fB->GetBody();
+
+ int32 indexA = c->GetChildIndexA();
+ int32 indexB = c->GetChildIndexB();
+
+ b2DistanceInput input;
+ input.proxyA.Set(fA->GetShape(), indexA);
+ input.proxyB.Set(fB->GetShape(), indexB);
+ input.transformA = bA->GetTransform();
+ input.transformB = bB->GetTransform();
+ input.useRadii = false;
+
+ b2DistanceOutput output;
+ b2SimplexCache cache;
+ cache.count = 0;
+ b2Distance(&output, &cache, &input);
+
+ if (output.distance == 0 || cache.count == 3)
+ {
+ cache.count += 0;
+ }
+ }
+#endif
+
+ // Leap of faith to new safe state.
+ m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c;
+ m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a;
+ m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c;
+ m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a;
+
+ // No warm starting is needed for TOI events because warm
+ // starting impulses were applied in the discrete solver.
+ contactSolver.InitializeVelocityConstraints();
+
+ // Solve velocity constraints.
+ for (int32 i = 0; i < subStep.velocityIterations; ++i)
+ {
+ contactSolver.SolveVelocityConstraints();
+ }
+
+ // Don't store the TOI contact forces for warm starting
+ // because they can be quite large.
+
+ float32 h = subStep.dt;
+
+ // Integrate positions
+ for (int32 i = 0; i < m_bodyCount; ++i)
+ {
+ b2Vec2 c = m_positions[i].c;
+ float32 a = m_positions[i].a;
+ b2Vec2 v = m_velocities[i].v;
+ float32 w = m_velocities[i].w;
+
+ // Check for large velocities
+ b2Vec2 translation = h * v;
+ if (b2Dot(translation, translation) > b2_maxTranslationSquared)
+ {
+ float32 ratio = b2_maxTranslation / translation.Length();
+ v *= ratio;
+ }
+
+ float32 rotation = h * w;
+ if (rotation * rotation > b2_maxRotationSquared)
+ {
+ float32 ratio = b2_maxRotation / b2Abs(rotation);
+ w *= ratio;
+ }
+
+ // Integrate
+ c += h * v;
+ a += h * w;
+
+ m_positions[i].c = c;
+ m_positions[i].a = a;
+ m_velocities[i].v = v;
+ m_velocities[i].w = w;
+
+ // Sync bodies
+ b2Body* body = m_bodies[i];
+ body->m_sweep.c = c;
+ body->m_sweep.a = a;
+ body->m_linearVelocity = v;
+ body->m_angularVelocity = w;
+ body->SynchronizeTransform();
+ }
+
+ Report(contactSolver.m_velocityConstraints);
+}
+
+void b2Island::Report(const b2ContactVelocityConstraint* constraints)
+{
+ if (m_listener == NULL)
+ {
+ return;
+ }
+
+ for (int32 i = 0; i < m_contactCount; ++i)
+ {
+ b2Contact* c = m_contacts[i];
+
+ const b2ContactVelocityConstraint* vc = constraints + i;
+
+ b2ContactImpulse impulse;
+ impulse.count = vc->pointCount;
+ for (int32 j = 0; j < vc->pointCount; ++j)
+ {
+ impulse.normalImpulses[j] = vc->points[j].normalImpulse;
+ impulse.tangentImpulses[j] = vc->points[j].tangentImpulse;
+ }
+
+ m_listener->PostSolve(c, &impulse);
+ }
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2Island.h b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Island.h
new file mode 100644
index 00000000..ef3d9b1d
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2Island.h
@@ -0,0 +1,93 @@
+/*
+* Copyright (c) 2006-2009 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_ISLAND_H
+#define B2_ISLAND_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+
+class b2Contact;
+class b2Joint;
+class b2StackAllocator;
+class b2ContactListener;
+struct b2ContactVelocityConstraint;
+struct b2Profile;
+
+/// This is an internal class.
+class b2Island
+{
+public:
+ b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity,
+ b2StackAllocator* allocator, b2ContactListener* listener);
+ ~b2Island();
+
+ void Clear()
+ {
+ m_bodyCount = 0;
+ m_contactCount = 0;
+ m_jointCount = 0;
+ }
+
+ void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep);
+
+ void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB);
+
+ void Add(b2Body* body)
+ {
+ b2Assert(m_bodyCount < m_bodyCapacity);
+ body->m_islandIndex = m_bodyCount;
+ m_bodies[m_bodyCount] = body;
+ ++m_bodyCount;
+ }
+
+ void Add(b2Contact* contact)
+ {
+ b2Assert(m_contactCount < m_contactCapacity);
+ m_contacts[m_contactCount++] = contact;
+ }
+
+ void Add(b2Joint* joint)
+ {
+ b2Assert(m_jointCount < m_jointCapacity);
+ m_joints[m_jointCount++] = joint;
+ }
+
+ void Report(const b2ContactVelocityConstraint* constraints);
+
+ b2StackAllocator* m_allocator;
+ b2ContactListener* m_listener;
+
+ b2Body** m_bodies;
+ b2Contact** m_contacts;
+ b2Joint** m_joints;
+
+ b2Position* m_positions;
+ b2Velocity* m_velocities;
+
+ int32 m_bodyCount;
+ int32 m_jointCount;
+ int32 m_contactCount;
+
+ int32 m_bodyCapacity;
+ int32 m_contactCapacity;
+ int32 m_jointCapacity;
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2TimeStep.h b/games/hillclimb/src/box2d/Box2D/Dynamics/b2TimeStep.h
new file mode 100644
index 00000000..abe6fb6e
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2TimeStep.h
@@ -0,0 +1,70 @@
+/*
+* 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_TIME_STEP_H
+#define B2_TIME_STEP_H
+
+#include <Box2D/Common/b2Math.h>
+
+/// Profiling data. Times are in milliseconds.
+struct b2Profile
+{
+ float32 step;
+ float32 collide;
+ float32 solve;
+ float32 solveInit;
+ float32 solveVelocity;
+ float32 solvePosition;
+ float32 broadphase;
+ float32 solveTOI;
+};
+
+/// This is an internal structure.
+struct b2TimeStep
+{
+ float32 dt; // time step
+ float32 inv_dt; // inverse time step (0 if dt == 0).
+ float32 dtRatio; // dt * inv_dt0
+ int32 velocityIterations;
+ int32 positionIterations;
+ bool warmStarting;
+};
+
+/// This is an internal structure.
+struct b2Position
+{
+ b2Vec2 c;
+ float32 a;
+};
+
+/// This is an internal structure.
+struct b2Velocity
+{
+ b2Vec2 v;
+ float32 w;
+};
+
+/// Solver Data
+struct b2SolverData
+{
+ b2TimeStep step;
+ b2Position* positions;
+ b2Velocity* velocities;
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2World.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/b2World.cpp
new file mode 100644
index 00000000..d23b55f7
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2World.cpp
@@ -0,0 +1,1320 @@
+/* Altered for NumPlay's Hill Climb Racing (NumWorks calculator): no debug drawing (and no pulley joint) */
+/*
+* 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/b2World.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2Island.h>
+#include <Box2D/Dynamics/Joints/b2Joint.h>
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+#include <Box2D/Dynamics/Contacts/b2ContactSolver.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Collision/b2BroadPhase.h>
+#include <Box2D/Collision/Shapes/b2CircleShape.h>
+#include <Box2D/Collision/Shapes/b2EdgeShape.h>
+#include <Box2D/Collision/Shapes/b2ChainShape.h>
+#include <Box2D/Collision/Shapes/b2PolygonShape.h>
+#include <Box2D/Collision/b2TimeOfImpact.h>
+#include <Box2D/Common/b2Draw.h>
+#include <Box2D/Common/b2Timer.h>
+#include <new>
+
+b2World::b2World(const b2Vec2& gravity)
+{
+ m_destructionListener = NULL;
+ m_debugDraw = NULL;
+
+ m_bodyList = NULL;
+ m_jointList = NULL;
+
+ m_bodyCount = 0;
+ m_jointCount = 0;
+
+ m_warmStarting = true;
+ m_continuousPhysics = true;
+ m_subStepping = false;
+
+ m_stepComplete = true;
+
+ m_allowSleep = true;
+ m_gravity = gravity;
+
+ m_flags = e_clearForces;
+
+ m_inv_dt0 = 0.0f;
+
+ m_contactManager.m_allocator = &m_blockAllocator;
+
+ memset(&m_profile, 0, sizeof(b2Profile));
+}
+
+b2World::~b2World()
+{
+ // Some shapes allocate using b2Alloc.
+ b2Body* b = m_bodyList;
+ while (b)
+ {
+ b2Body* bNext = b->m_next;
+
+ b2Fixture* f = b->m_fixtureList;
+ while (f)
+ {
+ b2Fixture* fNext = f->m_next;
+ f->m_proxyCount = 0;
+ f->Destroy(&m_blockAllocator);
+ f = fNext;
+ }
+
+ b = bNext;
+ }
+}
+
+void b2World::SetDestructionListener(b2DestructionListener* listener)
+{
+ m_destructionListener = listener;
+}
+
+void b2World::SetContactFilter(b2ContactFilter* filter)
+{
+ m_contactManager.m_contactFilter = filter;
+}
+
+void b2World::SetContactListener(b2ContactListener* listener)
+{
+ m_contactManager.m_contactListener = listener;
+}
+
+void b2World::SetDebugDraw(b2Draw* debugDraw)
+{
+ m_debugDraw = debugDraw;
+}
+
+b2Body* b2World::CreateBody(const b2BodyDef* def)
+{
+ b2Assert(IsLocked() == false);
+ if (IsLocked())
+ {
+ return NULL;
+ }
+
+ void* mem = m_blockAllocator.Allocate(sizeof(b2Body));
+ b2Body* b = new (mem) b2Body(def, this);
+
+ // Add to world doubly linked list.
+ b->m_prev = NULL;
+ b->m_next = m_bodyList;
+ if (m_bodyList)
+ {
+ m_bodyList->m_prev = b;
+ }
+ m_bodyList = b;
+ ++m_bodyCount;
+
+ return b;
+}
+
+void b2World::DestroyBody(b2Body* b)
+{
+ b2Assert(m_bodyCount > 0);
+ b2Assert(IsLocked() == false);
+ if (IsLocked())
+ {
+ return;
+ }
+
+ // Delete the attached joints.
+ b2JointEdge* je = b->m_jointList;
+ while (je)
+ {
+ b2JointEdge* je0 = je;
+ je = je->next;
+
+ if (m_destructionListener)
+ {
+ m_destructionListener->SayGoodbye(je0->joint);
+ }
+
+ DestroyJoint(je0->joint);
+
+ b->m_jointList = je;
+ }
+ b->m_jointList = NULL;
+
+ // Delete the attached contacts.
+ b2ContactEdge* ce = b->m_contactList;
+ while (ce)
+ {
+ b2ContactEdge* ce0 = ce;
+ ce = ce->next;
+ m_contactManager.Destroy(ce0->contact);
+ }
+ b->m_contactList = NULL;
+
+ // Delete the attached fixtures. This destroys broad-phase proxies.
+ b2Fixture* f = b->m_fixtureList;
+ while (f)
+ {
+ b2Fixture* f0 = f;
+ f = f->m_next;
+
+ if (m_destructionListener)
+ {
+ m_destructionListener->SayGoodbye(f0);
+ }
+
+ f0->DestroyProxies(&m_contactManager.m_broadPhase);
+ f0->Destroy(&m_blockAllocator);
+ f0->~b2Fixture();
+ m_blockAllocator.Free(f0, sizeof(b2Fixture));
+
+ b->m_fixtureList = f;
+ b->m_fixtureCount -= 1;
+ }
+ b->m_fixtureList = NULL;
+ b->m_fixtureCount = 0;
+
+ // Remove world body list.
+ if (b->m_prev)
+ {
+ b->m_prev->m_next = b->m_next;
+ }
+
+ if (b->m_next)
+ {
+ b->m_next->m_prev = b->m_prev;
+ }
+
+ if (b == m_bodyList)
+ {
+ m_bodyList = b->m_next;
+ }
+
+ --m_bodyCount;
+ b->~b2Body();
+ m_blockAllocator.Free(b, sizeof(b2Body));
+}
+
+b2Joint* b2World::CreateJoint(const b2JointDef* def)
+{
+ b2Assert(IsLocked() == false);
+ if (IsLocked())
+ {
+ return NULL;
+ }
+
+ b2Joint* j = b2Joint::Create(def, &m_blockAllocator);
+
+ // Connect to the world list.
+ j->m_prev = NULL;
+ j->m_next = m_jointList;
+ if (m_jointList)
+ {
+ m_jointList->m_prev = j;
+ }
+ m_jointList = j;
+ ++m_jointCount;
+
+ // Connect to the bodies' doubly linked lists.
+ j->m_edgeA.joint = j;
+ j->m_edgeA.other = j->m_bodyB;
+ j->m_edgeA.prev = NULL;
+ j->m_edgeA.next = j->m_bodyA->m_jointList;
+ if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA;
+ j->m_bodyA->m_jointList = &j->m_edgeA;
+
+ j->m_edgeB.joint = j;
+ j->m_edgeB.other = j->m_bodyA;
+ j->m_edgeB.prev = NULL;
+ j->m_edgeB.next = j->m_bodyB->m_jointList;
+ if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB;
+ j->m_bodyB->m_jointList = &j->m_edgeB;
+
+ b2Body* bodyA = def->bodyA;
+ b2Body* bodyB = def->bodyB;
+
+ // If the joint prevents collisions, then flag any contacts for filtering.
+ if (def->collideConnected == false)
+ {
+ b2ContactEdge* edge = bodyB->GetContactList();
+ while (edge)
+ {
+ if (edge->other == bodyA)
+ {
+ // Flag the contact for filtering at the next time step (where either
+ // body is awake).
+ edge->contact->FlagForFiltering();
+ }
+
+ edge = edge->next;
+ }
+ }
+
+ // Note: creating a joint doesn't wake the bodies.
+
+ return j;
+}
+
+void b2World::DestroyJoint(b2Joint* j)
+{
+ b2Assert(IsLocked() == false);
+ if (IsLocked())
+ {
+ return;
+ }
+
+ bool collideConnected = j->m_collideConnected;
+
+ // Remove from the doubly linked list.
+ if (j->m_prev)
+ {
+ j->m_prev->m_next = j->m_next;
+ }
+
+ if (j->m_next)
+ {
+ j->m_next->m_prev = j->m_prev;
+ }
+
+ if (j == m_jointList)
+ {
+ m_jointList = j->m_next;
+ }
+
+ // Disconnect from island graph.
+ b2Body* bodyA = j->m_bodyA;
+ b2Body* bodyB = j->m_bodyB;
+
+ // Wake up connected bodies.
+ bodyA->SetAwake(true);
+ bodyB->SetAwake(true);
+
+ // Remove from body 1.
+ if (j->m_edgeA.prev)
+ {
+ j->m_edgeA.prev->next = j->m_edgeA.next;
+ }
+
+ if (j->m_edgeA.next)
+ {
+ j->m_edgeA.next->prev = j->m_edgeA.prev;
+ }
+
+ if (&j->m_edgeA == bodyA->m_jointList)
+ {
+ bodyA->m_jointList = j->m_edgeA.next;
+ }
+
+ j->m_edgeA.prev = NULL;
+ j->m_edgeA.next = NULL;
+
+ // Remove from body 2
+ if (j->m_edgeB.prev)
+ {
+ j->m_edgeB.prev->next = j->m_edgeB.next;
+ }
+
+ if (j->m_edgeB.next)
+ {
+ j->m_edgeB.next->prev = j->m_edgeB.prev;
+ }
+
+ if (&j->m_edgeB == bodyB->m_jointList)
+ {
+ bodyB->m_jointList = j->m_edgeB.next;
+ }
+
+ j->m_edgeB.prev = NULL;
+ j->m_edgeB.next = NULL;
+
+ b2Joint::Destroy(j, &m_blockAllocator);
+
+ b2Assert(m_jointCount > 0);
+ --m_jointCount;
+
+ // If the joint prevents collisions, then flag any contacts for filtering.
+ if (collideConnected == false)
+ {
+ b2ContactEdge* edge = bodyB->GetContactList();
+ while (edge)
+ {
+ if (edge->other == bodyA)
+ {
+ // Flag the contact for filtering at the next time step (where either
+ // body is awake).
+ edge->contact->FlagForFiltering();
+ }
+
+ edge = edge->next;
+ }
+ }
+}
+
+//
+void b2World::SetAllowSleeping(bool flag)
+{
+ if (flag == m_allowSleep)
+ {
+ return;
+ }
+
+ m_allowSleep = flag;
+ if (m_allowSleep == false)
+ {
+ for (b2Body* b = m_bodyList; b; b = b->m_next)
+ {
+ b->SetAwake(true);
+ }
+ }
+}
+
+// Find islands, integrate and solve constraints, solve position constraints
+void b2World::Solve(const b2TimeStep& step)
+{
+ m_profile.solveInit = 0.0f;
+ m_profile.solveVelocity = 0.0f;
+ m_profile.solvePosition = 0.0f;
+
+ // Size the island for the worst case.
+ b2Island island(m_bodyCount,
+ m_contactManager.m_contactCount,
+ m_jointCount,
+ &m_stackAllocator,
+ m_contactManager.m_contactListener);
+
+ // Clear all the island flags.
+ for (b2Body* b = m_bodyList; b; b = b->m_next)
+ {
+ b->m_flags &= ~b2Body::e_islandFlag;
+ }
+ for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
+ {
+ c->m_flags &= ~b2Contact::e_islandFlag;
+ }
+ for (b2Joint* j = m_jointList; j; j = j->m_next)
+ {
+ j->m_islandFlag = false;
+ }
+
+ // Build and simulate all awake islands.
+ int32 stackSize = m_bodyCount;
+ b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*));
+ for (b2Body* seed = m_bodyList; seed; seed = seed->m_next)
+ {
+ if (seed->m_flags & b2Body::e_islandFlag)
+ {
+ continue;
+ }
+
+ if (seed->IsAwake() == false || seed->IsActive() == false)
+ {
+ continue;
+ }
+
+ // The seed can be dynamic or kinematic.
+ if (seed->GetType() == b2_staticBody)
+ {
+ continue;
+ }
+
+ // Reset island and stack.
+ island.Clear();
+ int32 stackCount = 0;
+ stack[stackCount++] = seed;
+ seed->m_flags |= b2Body::e_islandFlag;
+
+ // Perform a depth first search (DFS) on the constraint graph.
+ while (stackCount > 0)
+ {
+ // Grab the next body off the stack and add it to the island.
+ b2Body* b = stack[--stackCount];
+ b2Assert(b->IsActive() == true);
+ island.Add(b);
+
+ // Make sure the body is awake.
+ b->SetAwake(true);
+
+ // To keep islands as small as possible, we don't
+ // propagate islands across static bodies.
+ if (b->GetType() == b2_staticBody)
+ {
+ continue;
+ }
+
+ // Search all contacts connected to this body.
+ for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next)
+ {
+ b2Contact* contact = ce->contact;
+
+ // Has this contact already been added to an island?
+ if (contact->m_flags & b2Contact::e_islandFlag)
+ {
+ continue;
+ }
+
+ // Is this contact solid and touching?
+ if (contact->IsEnabled() == false ||
+ contact->IsTouching() == false)
+ {
+ continue;
+ }
+
+ // Skip sensors.
+ bool sensorA = contact->m_fixtureA->m_isSensor;
+ bool sensorB = contact->m_fixtureB->m_isSensor;
+ if (sensorA || sensorB)
+ {
+ continue;
+ }
+
+ island.Add(contact);
+ contact->m_flags |= b2Contact::e_islandFlag;
+
+ b2Body* other = ce->other;
+
+ // Was the other body already added to this island?
+ if (other->m_flags & b2Body::e_islandFlag)
+ {
+ continue;
+ }
+
+ b2Assert(stackCount < stackSize);
+ stack[stackCount++] = other;
+ other->m_flags |= b2Body::e_islandFlag;
+ }
+
+ // Search all joints connect to this body.
+ for (b2JointEdge* je = b->m_jointList; je; je = je->next)
+ {
+ if (je->joint->m_islandFlag == true)
+ {
+ continue;
+ }
+
+ b2Body* other = je->other;
+
+ // Don't simulate joints connected to inactive bodies.
+ if (other->IsActive() == false)
+ {
+ continue;
+ }
+
+ island.Add(je->joint);
+ je->joint->m_islandFlag = true;
+
+ if (other->m_flags & b2Body::e_islandFlag)
+ {
+ continue;
+ }
+
+ b2Assert(stackCount < stackSize);
+ stack[stackCount++] = other;
+ other->m_flags |= b2Body::e_islandFlag;
+ }
+ }
+
+ b2Profile profile;
+ island.Solve(&profile, step, m_gravity, m_allowSleep);
+ m_profile.solveInit += profile.solveInit;
+ m_profile.solveVelocity += profile.solveVelocity;
+ m_profile.solvePosition += profile.solvePosition;
+
+ // Post solve cleanup.
+ for (int32 i = 0; i < island.m_bodyCount; ++i)
+ {
+ // Allow static bodies to participate in other islands.
+ b2Body* b = island.m_bodies[i];
+ if (b->GetType() == b2_staticBody)
+ {
+ b->m_flags &= ~b2Body::e_islandFlag;
+ }
+ }
+ }
+
+ m_stackAllocator.Free(stack);
+
+ {
+ b2Timer timer;
+ // Synchronize fixtures, check for out of range bodies.
+ for (b2Body* b = m_bodyList; b; b = b->GetNext())
+ {
+ // If a body was not in an island then it did not move.
+ if ((b->m_flags & b2Body::e_islandFlag) == 0)
+ {
+ continue;
+ }
+
+ if (b->GetType() == b2_staticBody)
+ {
+ continue;
+ }
+
+ // Update fixtures (for broad-phase).
+ b->SynchronizeFixtures();
+ }
+
+ // Look for new contacts.
+ m_contactManager.FindNewContacts();
+ m_profile.broadphase = timer.GetMilliseconds();
+ }
+}
+
+// Find TOI contacts and solve them.
+void b2World::SolveTOI(const b2TimeStep& step)
+{
+ b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener);
+
+ if (m_stepComplete)
+ {
+ for (b2Body* b = m_bodyList; b; b = b->m_next)
+ {
+ b->m_flags &= ~b2Body::e_islandFlag;
+ b->m_sweep.alpha0 = 0.0f;
+ }
+
+ for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
+ {
+ // Invalidate TOI
+ c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag);
+ c->m_toiCount = 0;
+ c->m_toi = 1.0f;
+ }
+ }
+
+ // Find TOI events and solve them.
+ for (;;)
+ {
+ // Find the first TOI.
+ b2Contact* minContact = NULL;
+ float32 minAlpha = 1.0f;
+
+ for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
+ {
+ // Is this contact disabled?
+ if (c->IsEnabled() == false)
+ {
+ continue;
+ }
+
+ // Prevent excessive sub-stepping.
+ if (c->m_toiCount > b2_maxSubSteps)
+ {
+ continue;
+ }
+
+ float32 alpha = 1.0f;
+ if (c->m_flags & b2Contact::e_toiFlag)
+ {
+ // This contact has a valid cached TOI.
+ alpha = c->m_toi;
+ }
+ else
+ {
+ b2Fixture* fA = c->GetFixtureA();
+ b2Fixture* fB = c->GetFixtureB();
+
+ // Is there a sensor?
+ if (fA->IsSensor() || fB->IsSensor())
+ {
+ continue;
+ }
+
+ b2Body* bA = fA->GetBody();
+ b2Body* bB = fB->GetBody();
+
+ b2BodyType typeA = bA->m_type;
+ b2BodyType typeB = bB->m_type;
+ b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody);
+
+ bool activeA = bA->IsAwake() && typeA != b2_staticBody;
+ bool activeB = bB->IsAwake() && typeB != b2_staticBody;
+
+ // Is at least one body active (awake and dynamic or kinematic)?
+ if (activeA == false && activeB == false)
+ {
+ continue;
+ }
+
+ bool collideA = bA->IsBullet() || typeA != b2_dynamicBody;
+ bool collideB = bB->IsBullet() || typeB != b2_dynamicBody;
+
+ // Are these two non-bullet dynamic bodies?
+ if (collideA == false && collideB == false)
+ {
+ continue;
+ }
+
+ // Compute the TOI for this contact.
+ // Put the sweeps onto the same time interval.
+ float32 alpha0 = bA->m_sweep.alpha0;
+
+ if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0)
+ {
+ alpha0 = bB->m_sweep.alpha0;
+ bA->m_sweep.Advance(alpha0);
+ }
+ else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0)
+ {
+ alpha0 = bA->m_sweep.alpha0;
+ bB->m_sweep.Advance(alpha0);
+ }
+
+ b2Assert(alpha0 < 1.0f);
+
+ int32 indexA = c->GetChildIndexA();
+ int32 indexB = c->GetChildIndexB();
+
+ // Compute the time of impact in interval [0, minTOI]
+ b2TOIInput input;
+ input.proxyA.Set(fA->GetShape(), indexA);
+ input.proxyB.Set(fB->GetShape(), indexB);
+ input.sweepA = bA->m_sweep;
+ input.sweepB = bB->m_sweep;
+ input.tMax = 1.0f;
+
+ b2TOIOutput output;
+ b2TimeOfImpact(&output, &input);
+
+ // Beta is the fraction of the remaining portion of the .
+ float32 beta = output.t;
+ if (output.state == b2TOIOutput::e_touching)
+ {
+ alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f);
+ }
+ else
+ {
+ alpha = 1.0f;
+ }
+
+ c->m_toi = alpha;
+ c->m_flags |= b2Contact::e_toiFlag;
+ }
+
+ if (alpha < minAlpha)
+ {
+ // This is the minimum TOI found so far.
+ minContact = c;
+ minAlpha = alpha;
+ }
+ }
+
+ if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha)
+ {
+ // No more TOI events. Done!
+ m_stepComplete = true;
+ break;
+ }
+
+ // Advance the bodies to the TOI.
+ b2Fixture* fA = minContact->GetFixtureA();
+ b2Fixture* fB = minContact->GetFixtureB();
+ b2Body* bA = fA->GetBody();
+ b2Body* bB = fB->GetBody();
+
+ b2Sweep backup1 = bA->m_sweep;
+ b2Sweep backup2 = bB->m_sweep;
+
+ bA->Advance(minAlpha);
+ bB->Advance(minAlpha);
+
+ // The TOI contact likely has some new contact points.
+ minContact->Update(m_contactManager.m_contactListener);
+ minContact->m_flags &= ~b2Contact::e_toiFlag;
+ ++minContact->m_toiCount;
+
+ // Is the contact solid?
+ if (minContact->IsEnabled() == false || minContact->IsTouching() == false)
+ {
+ // Restore the sweeps.
+ minContact->SetEnabled(false);
+ bA->m_sweep = backup1;
+ bB->m_sweep = backup2;
+ bA->SynchronizeTransform();
+ bB->SynchronizeTransform();
+ continue;
+ }
+
+ bA->SetAwake(true);
+ bB->SetAwake(true);
+
+ // Build the island
+ island.Clear();
+ island.Add(bA);
+ island.Add(bB);
+ island.Add(minContact);
+
+ bA->m_flags |= b2Body::e_islandFlag;
+ bB->m_flags |= b2Body::e_islandFlag;
+ minContact->m_flags |= b2Contact::e_islandFlag;
+
+ // Get contacts on bodyA and bodyB.
+ b2Body* bodies[2] = {bA, bB};
+ for (int32 i = 0; i < 2; ++i)
+ {
+ b2Body* body = bodies[i];
+ if (body->m_type == b2_dynamicBody)
+ {
+ for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next)
+ {
+ if (island.m_bodyCount == island.m_bodyCapacity)
+ {
+ break;
+ }
+
+ if (island.m_contactCount == island.m_contactCapacity)
+ {
+ break;
+ }
+
+ b2Contact* contact = ce->contact;
+
+ // Has this contact already been added to the island?
+ if (contact->m_flags & b2Contact::e_islandFlag)
+ {
+ continue;
+ }
+
+ // Only add static, kinematic, or bullet bodies.
+ b2Body* other = ce->other;
+ if (other->m_type == b2_dynamicBody &&
+ body->IsBullet() == false && other->IsBullet() == false)
+ {
+ continue;
+ }
+
+ // Skip sensors.
+ bool sensorA = contact->m_fixtureA->m_isSensor;
+ bool sensorB = contact->m_fixtureB->m_isSensor;
+ if (sensorA || sensorB)
+ {
+ continue;
+ }
+
+ // Tentatively advance the body to the TOI.
+ b2Sweep backup = other->m_sweep;
+ if ((other->m_flags & b2Body::e_islandFlag) == 0)
+ {
+ other->Advance(minAlpha);
+ }
+
+ // Update the contact points
+ contact->Update(m_contactManager.m_contactListener);
+
+ // Was the contact disabled by the user?
+ if (contact->IsEnabled() == false)
+ {
+ other->m_sweep = backup;
+ other->SynchronizeTransform();
+ continue;
+ }
+
+ // Are there contact points?
+ if (contact->IsTouching() == false)
+ {
+ other->m_sweep = backup;
+ other->SynchronizeTransform();
+ continue;
+ }
+
+ // Add the contact to the island
+ contact->m_flags |= b2Contact::e_islandFlag;
+ island.Add(contact);
+
+ // Has the other body already been added to the island?
+ if (other->m_flags & b2Body::e_islandFlag)
+ {
+ continue;
+ }
+
+ // Add the other body to the island.
+ other->m_flags |= b2Body::e_islandFlag;
+
+ if (other->m_type != b2_staticBody)
+ {
+ other->SetAwake(true);
+ }
+
+ island.Add(other);
+ }
+ }
+ }
+
+ b2TimeStep subStep;
+ subStep.dt = (1.0f - minAlpha) * step.dt;
+ subStep.inv_dt = 1.0f / subStep.dt;
+ subStep.dtRatio = 1.0f;
+ subStep.positionIterations = 20;
+ subStep.velocityIterations = step.velocityIterations;
+ subStep.warmStarting = false;
+ island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex);
+
+ // Reset island flags and synchronize broad-phase proxies.
+ for (int32 i = 0; i < island.m_bodyCount; ++i)
+ {
+ b2Body* body = island.m_bodies[i];
+ body->m_flags &= ~b2Body::e_islandFlag;
+
+ if (body->m_type != b2_dynamicBody)
+ {
+ continue;
+ }
+
+ body->SynchronizeFixtures();
+
+ // Invalidate all contact TOIs on this displaced body.
+ for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next)
+ {
+ ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag);
+ }
+ }
+
+ // Commit fixture proxy movements to the broad-phase so that new contacts are created.
+ // Also, some contacts can be destroyed.
+ m_contactManager.FindNewContacts();
+
+ if (m_subStepping)
+ {
+ m_stepComplete = false;
+ break;
+ }
+ }
+}
+
+void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations)
+{
+ b2Timer stepTimer;
+
+ // If new fixtures were added, we need to find the new contacts.
+ if (m_flags & e_newFixture)
+ {
+ m_contactManager.FindNewContacts();
+ m_flags &= ~e_newFixture;
+ }
+
+ m_flags |= e_locked;
+
+ b2TimeStep step;
+ step.dt = dt;
+ step.velocityIterations = velocityIterations;
+ step.positionIterations = positionIterations;
+ if (dt > 0.0f)
+ {
+ step.inv_dt = 1.0f / dt;
+ }
+ else
+ {
+ step.inv_dt = 0.0f;
+ }
+
+ step.dtRatio = m_inv_dt0 * dt;
+
+ step.warmStarting = m_warmStarting;
+
+ // Update contacts. This is where some contacts are destroyed.
+ {
+ b2Timer timer;
+ m_contactManager.Collide();
+ m_profile.collide = timer.GetMilliseconds();
+ }
+
+ // Integrate velocities, solve velocity constraints, and integrate positions.
+ if (m_stepComplete && step.dt > 0.0f)
+ {
+ b2Timer timer;
+ Solve(step);
+ m_profile.solve = timer.GetMilliseconds();
+ }
+
+ // Handle TOI events.
+ if (m_continuousPhysics && step.dt > 0.0f)
+ {
+ b2Timer timer;
+ SolveTOI(step);
+ m_profile.solveTOI = timer.GetMilliseconds();
+ }
+
+ if (step.dt > 0.0f)
+ {
+ m_inv_dt0 = step.inv_dt;
+ }
+
+ if (m_flags & e_clearForces)
+ {
+ ClearForces();
+ }
+
+ m_flags &= ~e_locked;
+
+ m_profile.step = stepTimer.GetMilliseconds();
+}
+
+void b2World::ClearForces()
+{
+ for (b2Body* body = m_bodyList; body; body = body->GetNext())
+ {
+ body->m_force.SetZero();
+ body->m_torque = 0.0f;
+ }
+}
+
+struct b2WorldQueryWrapper
+{
+ bool QueryCallback(int32 proxyId)
+ {
+ b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId);
+ return callback->ReportFixture(proxy->fixture);
+ }
+
+ const b2BroadPhase* broadPhase;
+ b2QueryCallback* callback;
+};
+
+void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const
+{
+ b2WorldQueryWrapper wrapper;
+ wrapper.broadPhase = &m_contactManager.m_broadPhase;
+ wrapper.callback = callback;
+ m_contactManager.m_broadPhase.Query(&wrapper, aabb);
+}
+
+struct b2WorldRayCastWrapper
+{
+ float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId)
+ {
+ void* userData = broadPhase->GetUserData(proxyId);
+ b2FixtureProxy* proxy = (b2FixtureProxy*)userData;
+ b2Fixture* fixture = proxy->fixture;
+ int32 index = proxy->childIndex;
+ b2RayCastOutput output;
+ bool hit = fixture->RayCast(&output, input, index);
+
+ if (hit)
+ {
+ float32 fraction = output.fraction;
+ b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2;
+ return callback->ReportFixture(fixture, point, output.normal, fraction);
+ }
+
+ return input.maxFraction;
+ }
+
+ const b2BroadPhase* broadPhase;
+ b2RayCastCallback* callback;
+};
+
+void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const
+{
+ b2WorldRayCastWrapper wrapper;
+ wrapper.broadPhase = &m_contactManager.m_broadPhase;
+ wrapper.callback = callback;
+ b2RayCastInput input;
+ input.maxFraction = 1.0f;
+ input.p1 = point1;
+ input.p2 = point2;
+ m_contactManager.m_broadPhase.RayCast(&wrapper, input);
+}
+
+#if 0 /* (no debug drawing) */
+void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color)
+{
+ switch (fixture->GetType())
+ {
+ case b2Shape::e_circle:
+ {
+ b2CircleShape* circle = (b2CircleShape*)fixture->GetShape();
+
+ b2Vec2 center = b2Mul(xf, circle->m_p);
+ float32 radius = circle->m_radius;
+ b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f));
+
+ m_debugDraw->DrawSolidCircle(center, radius, axis, color);
+ }
+ break;
+
+ case b2Shape::e_edge:
+ {
+ b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape();
+ b2Vec2 v1 = b2Mul(xf, edge->m_vertex1);
+ b2Vec2 v2 = b2Mul(xf, edge->m_vertex2);
+ m_debugDraw->DrawSegment(v1, v2, color);
+ }
+ break;
+
+ case b2Shape::e_chain:
+ {
+ b2ChainShape* chain = (b2ChainShape*)fixture->GetShape();
+ int32 count = chain->m_count;
+ const b2Vec2* vertices = chain->m_vertices;
+
+ b2Vec2 v1 = b2Mul(xf, vertices[0]);
+ for (int32 i = 1; i < count; ++i)
+ {
+ b2Vec2 v2 = b2Mul(xf, vertices[i]);
+ m_debugDraw->DrawSegment(v1, v2, color);
+ m_debugDraw->DrawCircle(v1, 0.05f, color);
+ v1 = v2;
+ }
+ }
+ break;
+
+ case b2Shape::e_polygon:
+ {
+ b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape();
+ int32 vertexCount = poly->m_vertexCount;
+ b2Assert(vertexCount <= b2_maxPolygonVertices);
+ b2Vec2 vertices[b2_maxPolygonVertices];
+
+ for (int32 i = 0; i < vertexCount; ++i)
+ {
+ vertices[i] = b2Mul(xf, poly->m_vertices[i]);
+ }
+
+ m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color);
+ }
+ break;
+
+ default:
+ break;
+ }
+}
+
+void b2World::DrawJoint(b2Joint* joint)
+{
+ b2Body* bodyA = joint->GetBodyA();
+ b2Body* bodyB = joint->GetBodyB();
+ const b2Transform& xf1 = bodyA->GetTransform();
+ const b2Transform& xf2 = bodyB->GetTransform();
+ b2Vec2 x1 = xf1.p;
+ b2Vec2 x2 = xf2.p;
+ b2Vec2 p1 = joint->GetAnchorA();
+ b2Vec2 p2 = joint->GetAnchorB();
+
+ b2Color color(0.5f, 0.8f, 0.8f);
+
+ switch (joint->GetType())
+ {
+ case e_distanceJoint:
+ m_debugDraw->DrawSegment(p1, p2, color);
+ break;
+
+ case e_pulleyJoint:
+ {
+ b2PulleyJoint* pulley = (b2PulleyJoint*)joint;
+ b2Vec2 s1 = pulley->GetGroundAnchorA();
+ b2Vec2 s2 = pulley->GetGroundAnchorB();
+ m_debugDraw->DrawSegment(s1, p1, color);
+ m_debugDraw->DrawSegment(s2, p2, color);
+ m_debugDraw->DrawSegment(s1, s2, color);
+ }
+ break;
+
+ case e_mouseJoint:
+ // don't draw this
+ break;
+
+ default:
+ m_debugDraw->DrawSegment(x1, p1, color);
+ m_debugDraw->DrawSegment(p1, p2, color);
+ m_debugDraw->DrawSegment(x2, p2, color);
+ }
+}
+
+void b2World::DrawDebugData()
+{
+ if (m_debugDraw == NULL)
+ {
+ return;
+ }
+
+ uint32 flags = m_debugDraw->GetFlags();
+
+ if (flags & b2Draw::e_shapeBit)
+ {
+ for (b2Body* b = m_bodyList; b; b = b->GetNext())
+ {
+ const b2Transform& xf = b->GetTransform();
+ for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
+ {
+ if (b->IsActive() == false)
+ {
+ DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f));
+ }
+ else if (b->GetType() == b2_staticBody)
+ {
+ DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f));
+ }
+ else if (b->GetType() == b2_kinematicBody)
+ {
+ DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f));
+ }
+ else if (b->IsAwake() == false)
+ {
+ DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f));
+ }
+ else
+ {
+ DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f));
+ }
+ }
+ }
+ }
+
+ if (flags & b2Draw::e_jointBit)
+ {
+ for (b2Joint* j = m_jointList; j; j = j->GetNext())
+ {
+ DrawJoint(j);
+ }
+ }
+
+ if (flags & b2Draw::e_pairBit)
+ {
+ b2Color color(0.3f, 0.9f, 0.9f);
+ for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext())
+ {
+ //b2Fixture* fixtureA = c->GetFixtureA();
+ //b2Fixture* fixtureB = c->GetFixtureB();
+
+ //b2Vec2 cA = fixtureA->GetAABB().GetCenter();
+ //b2Vec2 cB = fixtureB->GetAABB().GetCenter();
+
+ //m_debugDraw->DrawSegment(cA, cB, color);
+ }
+ }
+
+ if (flags & b2Draw::e_aabbBit)
+ {
+ b2Color color(0.9f, 0.3f, 0.9f);
+ b2BroadPhase* bp = &m_contactManager.m_broadPhase;
+
+ for (b2Body* b = m_bodyList; b; b = b->GetNext())
+ {
+ if (b->IsActive() == false)
+ {
+ continue;
+ }
+
+ for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
+ {
+ for (int32 i = 0; i < f->m_proxyCount; ++i)
+ {
+ b2FixtureProxy* proxy = f->m_proxies + i;
+ b2AABB aabb = bp->GetFatAABB(proxy->proxyId);
+ b2Vec2 vs[4];
+ vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y);
+ vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y);
+ vs[2].Set(aabb.upperBound.x, aabb.upperBound.y);
+ vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y);
+
+ m_debugDraw->DrawPolygon(vs, 4, color);
+ }
+ }
+ }
+ }
+
+ if (flags & b2Draw::e_centerOfMassBit)
+ {
+ for (b2Body* b = m_bodyList; b; b = b->GetNext())
+ {
+ b2Transform xf = b->GetTransform();
+ xf.p = b->GetWorldCenter();
+ m_debugDraw->DrawTransform(xf);
+ }
+ }
+}
+
+#endif
+
+int32 b2World::GetProxyCount() const
+{
+ return m_contactManager.m_broadPhase.GetProxyCount();
+}
+
+int32 b2World::GetTreeHeight() const
+{
+ return m_contactManager.m_broadPhase.GetTreeHeight();
+}
+
+int32 b2World::GetTreeBalance() const
+{
+ return m_contactManager.m_broadPhase.GetTreeBalance();
+}
+
+float32 b2World::GetTreeQuality() const
+{
+ return m_contactManager.m_broadPhase.GetTreeQuality();
+}
+
+void b2World::Dump()
+{
+ if ((m_flags & e_locked) == e_locked)
+ {
+ return;
+ }
+
+ b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y);
+ b2Log("m_world->SetGravity(g);\n");
+
+ b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount);
+ b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount);
+ int32 i = 0;
+ for (b2Body* b = m_bodyList; b; b = b->m_next)
+ {
+ b->m_islandIndex = i;
+ b->Dump();
+ ++i;
+ }
+
+ i = 0;
+ for (b2Joint* j = m_jointList; j; j = j->m_next)
+ {
+ j->m_index = i;
+ ++i;
+ }
+
+ // First pass on joints, skip gear joints.
+ for (b2Joint* j = m_jointList; j; j = j->m_next)
+ {
+ if (j->m_type == e_gearJoint)
+ {
+ continue;
+ }
+
+ b2Log("{\n");
+ j->Dump();
+ b2Log("}\n");
+ }
+
+ // Second pass on joints, only gear joints.
+ for (b2Joint* j = m_jointList; j; j = j->m_next)
+ {
+ if (j->m_type != e_gearJoint)
+ {
+ continue;
+ }
+
+ b2Log("{\n");
+ j->Dump();
+ b2Log("}\n");
+ }
+
+ b2Log("b2Free(joints);\n");
+ b2Log("b2Free(bodies);\n");
+ b2Log("joints = NULL;\n");
+ b2Log("bodies = NULL;\n");
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2World.h b/games/hillclimb/src/box2d/Box2D/Dynamics/b2World.h
new file mode 100644
index 00000000..eba75727
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2World.h
@@ -0,0 +1,349 @@
+/*
+* 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_WORLD_H
+#define B2_WORLD_H
+
+#include <Box2D/Common/b2Math.h>
+#include <Box2D/Common/b2BlockAllocator.h>
+#include <Box2D/Common/b2StackAllocator.h>
+#include <Box2D/Dynamics/b2ContactManager.h>
+#include <Box2D/Dynamics/b2WorldCallbacks.h>
+#include <Box2D/Dynamics/b2TimeStep.h>
+
+struct b2AABB;
+struct b2BodyDef;
+struct b2Color;
+struct b2JointDef;
+class b2Body;
+class b2Draw;
+class b2Fixture;
+class b2Joint;
+
+/// The world class manages all physics entities, dynamic simulation,
+/// and asynchronous queries. The world also contains efficient memory
+/// management facilities.
+class b2World
+{
+public:
+ /// Construct a world object.
+ /// @param gravity the world gravity vector.
+ b2World(const b2Vec2& gravity);
+
+ /// Destruct the world. All physics entities are destroyed and all heap memory is released.
+ ~b2World();
+
+ /// Register a destruction listener. The listener is owned by you and must
+ /// remain in scope.
+ void SetDestructionListener(b2DestructionListener* listener);
+
+ /// Register a contact filter to provide specific control over collision.
+ /// Otherwise the default filter is used (b2_defaultFilter). The listener is
+ /// owned by you and must remain in scope.
+ void SetContactFilter(b2ContactFilter* filter);
+
+ /// Register a contact event listener. The listener is owned by you and must
+ /// remain in scope.
+ void SetContactListener(b2ContactListener* listener);
+
+ /// Register a routine for debug drawing. The debug draw functions are called
+ /// inside with b2World::DrawDebugData method. The debug draw object is owned
+ /// by you and must remain in scope.
+ void SetDebugDraw(b2Draw* debugDraw);
+
+ /// Create a rigid body given a definition. No reference to the definition
+ /// is retained.
+ /// @warning This function is locked during callbacks.
+ b2Body* CreateBody(const b2BodyDef* def);
+
+ /// Destroy a rigid body given a definition. No reference to the definition
+ /// is retained. This function is locked during callbacks.
+ /// @warning This automatically deletes all associated shapes and joints.
+ /// @warning This function is locked during callbacks.
+ void DestroyBody(b2Body* body);
+
+ /// Create a joint to constrain bodies together. No reference to the definition
+ /// is retained. This may cause the connected bodies to cease colliding.
+ /// @warning This function is locked during callbacks.
+ b2Joint* CreateJoint(const b2JointDef* def);
+
+ /// Destroy a joint. This may cause the connected bodies to begin colliding.
+ /// @warning This function is locked during callbacks.
+ void DestroyJoint(b2Joint* joint);
+
+ /// Take a time step. This performs collision detection, integration,
+ /// and constraint solution.
+ /// @param timeStep the amount of time to simulate, this should not vary.
+ /// @param velocityIterations for the velocity constraint solver.
+ /// @param positionIterations for the position constraint solver.
+ void Step( float32 timeStep,
+ int32 velocityIterations,
+ int32 positionIterations);
+
+ /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically
+ /// after each call to Step. The default behavior is modified by calling SetAutoClearForces.
+ /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain
+ /// a fixed sized time step under a variable frame-rate.
+ /// When you perform sub-stepping you will disable auto clearing of forces and instead call
+ /// ClearForces after all sub-steps are complete in one pass of your game loop.
+ /// @see SetAutoClearForces
+ void ClearForces();
+
+ /// Call this to draw shapes and other debug draw data.
+ void DrawDebugData();
+
+ /// Query the world for all fixtures that potentially overlap the
+ /// provided AABB.
+ /// @param callback a user implemented callback class.
+ /// @param aabb the query box.
+ void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const;
+
+ /// Ray-cast the world for all fixtures in the path of the ray. Your callback
+ /// controls whether you get the closest point, any point, or n-points.
+ /// The ray-cast ignores shapes that contain the starting point.
+ /// @param callback a user implemented callback class.
+ /// @param point1 the ray starting point
+ /// @param point2 the ray ending point
+ void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const;
+
+ /// Get the world body list. With the returned body, use b2Body::GetNext to get
+ /// the next body in the world list. A NULL body indicates the end of the list.
+ /// @return the head of the world body list.
+ b2Body* GetBodyList();
+ const b2Body* GetBodyList() const;
+
+ /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get
+ /// the next joint in the world list. A NULL joint indicates the end of the list.
+ /// @return the head of the world joint list.
+ b2Joint* GetJointList();
+ const b2Joint* GetJointList() const;
+
+ /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get
+ /// the next contact in the world list. A NULL contact indicates the end of the list.
+ /// @return the head of the world contact list.
+ /// @warning contacts are created and destroyed in the middle of a time step.
+ /// Use b2ContactListener to avoid missing contacts.
+ b2Contact* GetContactList();
+ const b2Contact* GetContactList() const;
+
+ /// Enable/disable sleep.
+ void SetAllowSleeping(bool flag);
+ bool GetAllowSleeping() const { return m_allowSleep; }
+
+ /// Enable/disable warm starting. For testing.
+ void SetWarmStarting(bool flag) { m_warmStarting = flag; }
+ bool GetWarmStarting() const { return m_warmStarting; }
+
+ /// Enable/disable continuous physics. For testing.
+ void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; }
+ bool GetContinuousPhysics() const { return m_continuousPhysics; }
+
+ /// Enable/disable single stepped continuous physics. For testing.
+ void SetSubStepping(bool flag) { m_subStepping = flag; }
+ bool GetSubStepping() const { return m_subStepping; }
+
+ /// Get the number of broad-phase proxies.
+ int32 GetProxyCount() const;
+
+ /// Get the number of bodies.
+ int32 GetBodyCount() const;
+
+ /// Get the number of joints.
+ int32 GetJointCount() const;
+
+ /// Get the number of contacts (each may have 0 or more contact points).
+ int32 GetContactCount() const;
+
+ /// Get the height of the dynamic tree.
+ int32 GetTreeHeight() const;
+
+ /// Get the balance of the dynamic tree.
+ int32 GetTreeBalance() const;
+
+ /// Get the quality metric of the dynamic tree. The smaller the better.
+ /// The minimum is 1.
+ float32 GetTreeQuality() const;
+
+ /// Change the global gravity vector.
+ void SetGravity(const b2Vec2& gravity);
+
+ /// Get the global gravity vector.
+ b2Vec2 GetGravity() const;
+
+ /// Is the world locked (in the middle of a time step).
+ bool IsLocked() const;
+
+ /// Set flag to control automatic clearing of forces after each time step.
+ void SetAutoClearForces(bool flag);
+
+ /// Get the flag that controls automatic clearing of forces after each time step.
+ bool GetAutoClearForces() const;
+
+ /// Get the contact manager for testing.
+ const b2ContactManager& GetContactManager() const;
+
+ /// Get the current profile.
+ const b2Profile& GetProfile() const;
+
+ /// Dump the world into the log file.
+ /// @warning this should be called outside of a time step.
+ void Dump();
+
+private:
+
+ // m_flags
+ enum
+ {
+ e_newFixture = 0x0001,
+ e_locked = 0x0002,
+ e_clearForces = 0x0004
+ };
+
+ friend class b2Body;
+ friend class b2Fixture;
+ friend class b2ContactManager;
+ friend class b2Controller;
+
+ void Solve(const b2TimeStep& step);
+ void SolveTOI(const b2TimeStep& step);
+
+ void DrawJoint(b2Joint* joint);
+ void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color);
+
+ b2BlockAllocator m_blockAllocator;
+ b2StackAllocator m_stackAllocator;
+
+ int32 m_flags;
+
+ b2ContactManager m_contactManager;
+
+ b2Body* m_bodyList;
+ b2Joint* m_jointList;
+
+ int32 m_bodyCount;
+ int32 m_jointCount;
+
+ b2Vec2 m_gravity;
+ bool m_allowSleep;
+
+ b2DestructionListener* m_destructionListener;
+ b2Draw* m_debugDraw;
+
+ // This is used to compute the time step ratio to
+ // support a variable time step.
+ float32 m_inv_dt0;
+
+ // These are for debugging the solver.
+ bool m_warmStarting;
+ bool m_continuousPhysics;
+ bool m_subStepping;
+
+ bool m_stepComplete;
+
+ b2Profile m_profile;
+};
+
+inline b2Body* b2World::GetBodyList()
+{
+ return m_bodyList;
+}
+
+inline const b2Body* b2World::GetBodyList() const
+{
+ return m_bodyList;
+}
+
+inline b2Joint* b2World::GetJointList()
+{
+ return m_jointList;
+}
+
+inline const b2Joint* b2World::GetJointList() const
+{
+ return m_jointList;
+}
+
+inline b2Contact* b2World::GetContactList()
+{
+ return m_contactManager.m_contactList;
+}
+
+inline const b2Contact* b2World::GetContactList() const
+{
+ return m_contactManager.m_contactList;
+}
+
+inline int32 b2World::GetBodyCount() const
+{
+ return m_bodyCount;
+}
+
+inline int32 b2World::GetJointCount() const
+{
+ return m_jointCount;
+}
+
+inline int32 b2World::GetContactCount() const
+{
+ return m_contactManager.m_contactCount;
+}
+
+inline void b2World::SetGravity(const b2Vec2& gravity)
+{
+ m_gravity = gravity;
+}
+
+inline b2Vec2 b2World::GetGravity() const
+{
+ return m_gravity;
+}
+
+inline bool b2World::IsLocked() const
+{
+ return (m_flags & e_locked) == e_locked;
+}
+
+inline void b2World::SetAutoClearForces(bool flag)
+{
+ if (flag)
+ {
+ m_flags |= e_clearForces;
+ }
+ else
+ {
+ m_flags &= ~e_clearForces;
+ }
+}
+
+/// Get the flag that controls automatic clearing of forces after each time step.
+inline bool b2World::GetAutoClearForces() const
+{
+ return (m_flags & e_clearForces) == e_clearForces;
+}
+
+inline const b2ContactManager& b2World::GetContactManager() const
+{
+ return m_contactManager;
+}
+
+inline const b2Profile& b2World::GetProfile() const
+{
+ return m_profile;
+}
+
+#endif
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp b/games/hillclimb/src/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp
new file mode 100644
index 00000000..82b28cc0
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2WorldCallbacks.cpp
@@ -0,0 +1,36 @@
+/*
+* Copyright (c) 2006-2009 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/b2WorldCallbacks.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+
+// Return true if contact calculations should be performed between these two shapes.
+// If you implement your own collision filter you may want to build from this implementation.
+bool b2ContactFilter::ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB)
+{
+ const b2Filter& filterA = fixtureA->GetFilterData();
+ const b2Filter& filterB = fixtureB->GetFilterData();
+
+ if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0)
+ {
+ return filterA.groupIndex > 0;
+ }
+
+ bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0;
+ return collide;
+}
diff --git a/games/hillclimb/src/box2d/Box2D/Dynamics/b2WorldCallbacks.h b/games/hillclimb/src/box2d/Box2D/Dynamics/b2WorldCallbacks.h
new file mode 100644
index 00000000..9b937e81
--- /dev/null
+++ b/games/hillclimb/src/box2d/Box2D/Dynamics/b2WorldCallbacks.h
@@ -0,0 +1,155 @@
+/*
+* Copyright (c) 2006-2009 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_WORLD_CALLBACKS_H
+#define B2_WORLD_CALLBACKS_H
+
+#include <Box2D/Common/b2Settings.h>
+
+struct b2Vec2;
+struct b2Transform;
+class b2Fixture;
+class b2Body;
+class b2Joint;
+class b2Contact;
+struct b2ContactResult;
+struct b2Manifold;
+
+/// Joints and fixtures are destroyed when their associated
+/// body is destroyed. Implement this listener so that you
+/// may nullify references to these joints and shapes.
+class b2DestructionListener
+{
+public:
+ virtual ~b2DestructionListener() {}
+
+ /// Called when any joint is about to be destroyed due
+ /// to the destruction of one of its attached bodies.
+ virtual void SayGoodbye(b2Joint* joint) = 0;
+
+ /// Called when any fixture is about to be destroyed due
+ /// to the destruction of its parent body.
+ virtual void SayGoodbye(b2Fixture* fixture) = 0;
+};
+
+/// Implement this class to provide collision filtering. In other words, you can implement
+/// this class if you want finer control over contact creation.
+class b2ContactFilter
+{
+public:
+ virtual ~b2ContactFilter() {}
+
+ /// Return true if contact calculations should be performed between these two shapes.
+ /// @warning for performance reasons this is only called when the AABBs begin to overlap.
+ virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB);
+};
+
+/// Contact impulses for reporting. Impulses are used instead of forces because
+/// sub-step forces may approach infinity for rigid body collisions. These
+/// match up one-to-one with the contact points in b2Manifold.
+struct b2ContactImpulse
+{
+ float32 normalImpulses[b2_maxManifoldPoints];
+ float32 tangentImpulses[b2_maxManifoldPoints];
+ int32 count;
+};
+
+/// Implement this class to get contact information. You can use these results for
+/// things like sounds and game logic. You can also get contact results by
+/// traversing the contact lists after the time step. However, you might miss
+/// some contacts because continuous physics leads to sub-stepping.
+/// Additionally you may receive multiple callbacks for the same contact in a
+/// single time step.
+/// You should strive to make your callbacks efficient because there may be
+/// many callbacks per time step.
+/// @warning You cannot create/destroy Box2D entities inside these callbacks.
+class b2ContactListener
+{
+public:
+ virtual ~b2ContactListener() {}
+
+ /// Called when two fixtures begin to touch.
+ virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); }
+
+ /// Called when two fixtures cease to touch.
+ virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); }
+
+ /// This is called after a contact is updated. This allows you to inspect a
+ /// contact before it goes to the solver. If you are careful, you can modify the
+ /// contact manifold (e.g. disable contact).
+ /// A copy of the old manifold is provided so that you can detect changes.
+ /// Note: this is called only for awake bodies.
+ /// Note: this is called even when the number of contact points is zero.
+ /// Note: this is not called for sensors.
+ /// Note: if you set the number of contact points to zero, you will not
+ /// get an EndContact callback. However, you may get a BeginContact callback
+ /// the next step.
+ virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
+ {
+ B2_NOT_USED(contact);
+ B2_NOT_USED(oldManifold);
+ }
+
+ /// This lets you inspect a contact after the solver is finished. This is useful
+ /// for inspecting impulses.
+ /// Note: the contact manifold does not include time of impact impulses, which can be
+ /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly
+ /// in a separate data structure.
+ /// Note: this is only called for contacts that are touching, solid, and awake.
+ virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
+ {
+ B2_NOT_USED(contact);
+ B2_NOT_USED(impulse);
+ }
+};
+
+/// Callback class for AABB queries.
+/// See b2World::Query
+class b2QueryCallback
+{
+public:
+ virtual ~b2QueryCallback() {}
+
+ /// Called for each fixture found in the query AABB.
+ /// @return false to terminate the query.
+ virtual bool ReportFixture(b2Fixture* fixture) = 0;
+};
+
+/// Callback class for ray casts.
+/// See b2World::RayCast
+class b2RayCastCallback
+{
+public:
+ virtual ~b2RayCastCallback() {}
+
+ /// Called for each fixture found in the query. You control how the ray cast
+ /// proceeds by returning a float:
+ /// return -1: ignore this fixture and continue
+ /// return 0: terminate the ray cast
+ /// return fraction: clip the ray to this point
+ /// return 1: don't clip the ray and continue
+ /// @param fixture the fixture hit by the ray
+ /// @param point the point of initial intersection
+ /// @param normal the normal vector at the point of intersection
+ /// @return -1 to filter, 0 to terminate, fraction to clip the ray for
+ /// closest hit, 1 to continue
+ virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point,
+ const b2Vec2& normal, float32 fraction) = 0;
+};
+
+#endif
diff --git a/games/hillclimb/src/box2d/License.txt b/games/hillclimb/src/box2d/License.txt
new file mode 100644
index 00000000..622772e5
--- /dev/null
+++ b/games/hillclimb/src/box2d/License.txt
@@ -0,0 +1,18 @@
+Copyright (c) 2006-2010 Erin Catto http://www.gphysics.com
+
+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.
+
diff --git a/games/hillclimb/src/car.c b/games/hillclimb/src/car.c
deleted file mode 100644
index 77e811e1..00000000
--- a/games/hillclimb/src/car.c
+++ /dev/null
@@ -1,461 +0,0 @@
-/* A vehicle's physics (car.h). */
-#include <math.h>
-#include <string.h>
-#include "art.h"
-#include "car.h"
-#include "stage.h"
-#include "vehicle.h"
-
-#define SUB 4 /* steps a frame */
-#define DT (1.0f / (CAR_HZ * SUB))
-#define ITER 10
-#define BETA 0.2f /* how much of an overlap is pushed out each step */
-#define SLOP 0.004f
-#define MAXC 64
-#define SEG 0.2f /* the ground is straight between points this far apart */
-#define HULL_R 0.05f
-#define REACT 0.4f /* how much of the engine's twist the chassis feels (Bill leans into it) */
-
-typedef struct {
- Body *b;
- float rx, ry, nx, ny, depth, mu, mn, mt, jn, jt, bias;
- int tree; /* a tree's index, or -1 */
- int wheel; /* the wheel's index, or -1 */
-} Contact;
-
-static Contact con[MAXC];
-static int ncon;
-
-static float cross(float ax, float ay, float bx, float by) { return ax * by - ay * bx; }
-static void rot(float a, float x, float y, float *ox, float *oy) {
- float c = cosf(a), s = sinf(a);
- *ox = c * x - s * y, *oy = s * x + c * y;
-}
-
-float car_fuel_seconds(int veh, const uint8_t lv[4]) {
- const VehDef *d = &vehicles[veh];
- float f = d->fuel;
- for (int u = 0; u < 4; u++)
- if (d->up[u] == UP_FUEL) f *= 1 + 1.6f * (float)(lv[u] - 1) / (float)(d->max[u] - 1);
- return f;
-}
-
-void car_init(Car *c, int veh, const uint8_t lv[4], float x) {
- const VehDef *d = &vehicles[veh];
- const VehArt *a = &veh_art[veh];
- memset(c, 0, sizeof *c);
- c->veh = veh, c->nw = a->naxles, c->tree_broken = -1, c->tree_hurt_id = -1;
- float eng = 0, sus = 0, tir = 0, awd = d->awd, air = d->air, down = 0;
- for (int u = 0; u < 4; u++) {
- float f = (float)(lv[u] - 1) / (float)(d->max[u] - 1);
- switch (d->up[u]) {
- case UP_ENGINE: eng = f; break;
- case UP_SUSPENSION: sus = f; break;
- case UP_TIRES: case UP_TRACKS: tir = f; break;
- case UP_AWD: awd = f; break;
- case UP_AIR: air *= 1 + 1.5f * f; break;
- case UP_DOWNFORCE: down = d->downforce * f; break;
- }
- }
- c->torque = d->torque * (1 + 1.5f * eng);
- c->wmax = d->speed * (1 + 0.6f * eng) / a->wheel_r[0];
- c->brake = d->torque * 1.6f;
- c->grip = d->grip * (1 + 0.55f * tir);
- c->air = air, c->down = down;
- c->com[0] = d->com[0], c->com[1] = d->com[1] - 0.07f * sus;
- /* bodies */
- c->ch.im = 1 / d->mass;
- c->ch.ii = 1 / (d->mass * d->radius * d->radius);
- float wsum = 0;
- for (int i = 0; i < c->nw; i++) {
- float r = a->wheel_r[i];
- c->wr[i] = r;
- c->wh[i].im = 1 / d->wmass;
- c->wh[i].ii = 1 / (0.6f * d->wmass * r * r);
- /* the rear wheel always driven; the others by the 4WD's share */
- c->drive[i] = i == 0 ? 1 : awd;
- wsum += c->drive[i];
- }
- for (int i = 0; i < c->nw; i++) c->drive[i] *= (float)c->nw / (wsum > 0 ? wsum : 1) * 0.5f;
- if (c->nw > 2) /* (the tank's five wheels share the engine) */
- for (int i = 0; i < c->nw; i++) c->drive[i] = 2.0f / (float)c->nw;
- /* springs: settled at `sag` under the chassis' share of the weight */
- float load = d->mass / (float)c->nw;
- float sag = d->sag * (1 - 0.25f * sus);
- c->k = load * 9.8f / sag;
- c->c = 2 * (d->zeta * (1 + 0.6f * sus)) * sqrtf(c->k * load);
- c->s0 = 2 * sag;
- c->smax = 2 * sag + d->droop;
- for (int i = 0; i < c->nw; i++) {
- c->anc[i][0] = a->axle[i][0] - c->com[0];
- c->anc[i][1] = a->axle[i][1] + sag - c->com[1];
- }
- c->nhull = a->nhull;
- for (int i = 0; i < a->nhull; i++) c->hull[i][0] = a->hull[i][0] - c->com[0], c->hull[i][1] = a->hull[i][1] - c->com[1];
- /* Bill's head over his hips, leaning */
- float nx, ny, hx, hy;
- rot(a->lean, BILL_NECK_X, BILL_NECK_Y, &nx, &ny);
- rot(a->lean, BILL_HEAD_X, BILL_HEAD_Y, &hx, &hy);
- c->head[0] = a->hips[0] + nx + hx - c->com[0];
- c->head[1] = a->hips[1] + ny + hy - c->com[1];
- /* on the ground at x, level */
- float gy = stage_floor(x);
- float lowest = 0;
- for (int i = 0; i < c->nw; i++)
- if (a->axle[i][1] - a->wheel_r[i] < lowest) lowest = a->axle[i][1] - a->wheel_r[i];
- c->ch.x = x + c->com[0], c->ch.y = gy - lowest + c->com[1] + 0.02f;
- for (int i = 0; i < c->nw; i++) {
- c->wh[i].x = c->ch.x + c->anc[i][0];
- c->wh[i].y = c->ch.y + c->anc[i][1] - sag;
- }
-}
-
-/* ------------------------------------------------------------------ the ground's contacts */
-static Contact *new_contact(Body *b, float px, float py, float nx, float ny, float depth, float mu, int wheel) {
- if (ncon >= MAXC) return NULL;
- Contact *k = &con[ncon++];
- k->b = b, k->rx = px - b->x, k->ry = py - b->y, k->nx = nx, k->ny = ny, k->depth = depth, k->mu = mu;
- k->jn = k->jt = 0, k->tree = -1, k->wheel = wheel;
- return k;
-}
-
-/* a circle against a line through points of f, all of them above (floor) or below (ceiling) it: its deepest touch */
-static bool circle_line(float cx, float cy, float r, bool ceiling, float *px, float *py, float *nx, float *ny, float *depth) {
- float best = 1e9f, bx = 0, by = 0;
- int i0 = (int)floorf((cx - r) / SEG) - 1, i1 = (int)ceilf((cx + r) / SEG) + 1;
- float ya = 0, yb;
- for (int i = i0; i <= i1; i++) {
- float xb = (float)i * SEG;
- if (ceiling) {
- if (!stage_ceiling(xb, &yb)) {
- if (i == i0) ya = 1e9f;
- else ya = 1e9f;
- continue;
- }
- } else {
- yb = stage_floor(xb);
- }
- if (i > i0 && ya < 1e8f) {
- float xa = xb - SEG, dx = SEG, dy = yb - ya;
- float t = ((cx - xa) * dx + (cy - ya) * dy) / (dx * dx + dy * dy);
- t = t < 0 ? 0 : t > 1 ? 1 : t;
- float qx = xa + t * dx, qy = ya + t * dy;
- float ex = cx - qx, ey = cy - qy, d = sqrtf(ex * ex + ey * ey);
- /* inside the ground: the distance counts as negative */
- float side = cross(dx, dy, cx - xa, cy - ya);
- if (ceiling ? side > 0 : side < 0) d = -d;
- if (d < best) best = d, bx = qx, by = qy;
- }
- ya = yb;
- }
- if (best >= r) return false;
- *px = bx, *py = by;
- float ex = cx - bx, ey = cy - by, l = sqrtf(ex * ex + ey * ey);
- if (l > 1e-5f && best > 0) {
- *nx = ex / l, *ny = ey / l;
- } else { /* deep inside: straight out of the ground's slope */
- float x0 = cx - 0.1f, x1 = cx + 0.1f, y0, y1;
- if (ceiling) {
- stage_ceiling(x0, &y0), stage_ceiling(x1, &y1);
- } else {
- y0 = stage_floor(x0), y1 = stage_floor(x1);
- }
- float tx = x1 - x0, ty = y1 - y0, tl = sqrtf(tx * tx + ty * ty);
- *nx = -ty / tl, *ny = tx / tl;
- if (ceiling) *nx = -*nx, *ny = -*ny;
- }
- *depth = r - best;
- return true;
-}
-
-static void touch_circle(Body *b, float cx, float cy, float r, float mu, int wheel) {
- float px, py, nx, ny, d;
- if (circle_line(cx, cy, r, false, &px, &py, &nx, &ny, &d)) new_contact(b, cx - nx * r, cy - ny * r, nx, ny, d, mu, wheel);
- if (stage->ceiling && circle_line(cx, cy, r, true, &px, &py, &nx, &ny, &d))
- new_contact(b, cx - nx * r, cy - ny * r, nx, ny, d, mu, wheel);
- if (cx - r < STAGE_WALL) new_contact(b, cx - r, cy, 1, 0, STAGE_WALL - (cx - r), mu * 0.3f, wheel);
- if (stage->feature == FEAT_TREES) {
- for (int k = stage_tree_first(cx - 4);; k++) {
- float tx;
- if (!stage_tree(k, &tx)) {
- if (k % 6 == 0) break;
- continue;
- }
- if (tx > cx + 4) break;
- if (!stage_tree_standing(k) || tx < cx - 4) continue;
- float ty0 = stage_floor(tx), ty1 = ty0 + TREE_H;
- float qy = cy < ty0 ? ty0 : cy > ty1 ? ty1 : cy, ex = cx - tx, ey = cy - qy, l = sqrtf(ex * ex + ey * ey);
- if (l >= r + TREE_R || l < 1e-5f) continue;
- Contact *k2 = new_contact(b, cx - ex / l * r, cy - ey / l * r, ex / l, ey / l, r + TREE_R - l, 0.3f, wheel);
- if (k2) k2->tree = k;
- }
- }
-}
-
-static void find_contacts(Car *c) {
- ncon = 0;
- float mu = c->grip * stage->friction;
- for (int i = 0; i < c->nw; i++) {
- int before = ncon;
- touch_circle(&c->wh[i], c->wh[i].x, c->wh[i].y, c->wr[i], mu, i);
- c->ground[i] = c->ground[i] || ncon > before;
- }
- int before = ncon;
- float ca = cosf(c->ch.a), sa = sinf(c->ch.a);
- for (int i = 0; i < c->nhull; i++) {
- float px = c->ch.x + ca * c->hull[i][0] - sa * c->hull[i][1];
- float py = c->ch.y + sa * c->hull[i][0] + ca * c->hull[i][1];
- touch_circle(&c->ch, px, py, HULL_R, 0.6f * stage->friction, -1);
- }
- if (c->head_hit) { /* (Bill down: his head lies on the ground too) */
- float hx = c->ch.x + ca * c->head[0] - sa * c->head[1], hy = c->ch.y + sa * c->head[0] + ca * c->head[1];
- touch_circle(&c->ch, hx, hy, BILL_HEAD_R, 0.6f, -1);
- }
- c->touch = c->touch || ncon > before;
-}
-
-/* ------------------------------------------------------------------ solving */
-static void push(Body *b, float px, float py, float rx, float ry) {
- b->vx += b->im * px, b->vy += b->im * py;
- b->w += b->ii * cross(rx, ry, px, py);
-}
-
-static void prepare_contacts(void) {
- for (int i = 0; i < ncon; i++) {
- Contact *k = &con[i];
- float rn = cross(k->rx, k->ry, k->nx, k->ny), rt = cross(k->rx, k->ry, -k->ny, k->nx);
- k->mn = 1 / (k->b->im + k->b->ii * rn * rn);
- k->mt = 1 / (k->b->im + k->b->ii * rt * rt);
- float pen = k->depth - SLOP;
- k->bias = pen > 0 ? BETA / DT * pen : 0;
- if (k->bias > 4) k->bias = 4;
- }
-}
-
-static void solve_contacts(void) {
- for (int i = 0; i < ncon; i++) {
- Contact *k = &con[i];
- Body *b = k->b;
- float vx = b->vx - b->w * k->ry, vy = b->vy + b->w * k->rx;
- /* along the normal: no going in */
- float vn = vx * k->nx + vy * k->ny;
- float j = k->mn * (k->bias - vn), old = k->jn;
- k->jn = old + j > 0 ? old + j : 0;
- j = k->jn - old;
- push(b, j * k->nx, j * k->ny, k->rx, k->ry);
- /* friction along the ground, up to mu times the push */
- vx = b->vx - b->w * k->ry, vy = b->vy + b->w * k->rx;
- float tx = -k->ny, ty = k->nx, vt = vx * tx + vy * ty;
- float jt = -k->mt * vt, lim = k->mu * k->jn;
- old = k->jt;
- k->jt = old + jt;
- if (k->jt > lim) k->jt = lim;
- if (k->jt < -lim) k->jt = -lim;
- jt = k->jt - old;
- push(b, jt * tx, jt * ty, k->rx, k->ry);
- }
-}
-
-/* the wheel joints: across the axis held, along it the bump stops; and the engine */
-typedef struct {
- float px, py, sAy, my, bias; /* across the axis, and the error there pushed out */
- float dx, dy, sAx, mx, s; /* along it (down the chassis) */
- float jlo, jm, mmax, speed; /* the stops' and the engine's impulses; the engine's most, its target */
-} Joint;
-static Joint jo[CAR_MAXW];
-
-static void prepare_joints(Car *c, float gas, float brake, bool fuel) {
- Body *A = &c->ch;
- float ca = cosf(A->a), sa = sinf(A->a);
- /* the engine: forward is the wheels turning clockwise */
- float spin = 0;
- for (int i = 0; i < c->nw; i++) spin += c->wh[i].w - A->w;
- spin /= (float)c->nw;
- float speed = 0, tmax = 0;
- bool shared = true;
- if (gas > 0 && fuel) {
- speed = -c->wmax, tmax = c->torque * gas;
- } else if (brake > 0) {
- if (spin < -1.5f || !fuel) speed = 0, tmax = c->brake * brake, shared = false; /* rolling forward: brake */
- else speed = c->wmax * 0.45f, tmax = c->torque * 0.7f * brake; /* stopped: reverse */
- } else {
- speed = 0, tmax = c->torque * 0.015f, shared = false; /* coasting: the engine's own drag */
- }
- c->rpm = 0;
- for (int i = 0; i < c->nw; i++) {
- Joint *J = &jo[i];
- Body *B = &c->wh[i];
- float rax = ca * c->anc[i][0] - sa * c->anc[i][1], ray = sa * c->anc[i][0] + ca * c->anc[i][1];
- float dx = B->x - (A->x + rax), dy = B->y - (A->y + ray);
- J->dx = sa, J->dy = -ca; /* down the chassis */
- J->px = ca, J->py = sa; /* across */
- J->s = dx * J->dx + dy * J->dy;
- J->bias = -BETA / DT * (dx * J->px + dy * J->py);
- J->sAy = cross(dx + rax, dy + ray, J->px, J->py);
- J->sAx = cross(dx + rax, dy + ray, J->dx, J->dy);
- J->my = 1 / (A->im + B->im + A->ii * J->sAy * J->sAy);
- J->mx = 1 / (A->im + B->im + A->ii * J->sAx * J->sAx);
- J->jlo = J->jm = 0;
- J->speed = speed;
- J->mmax = (shared ? tmax * c->drive[i] : tmax) * DT;
- /* the spring and damper: once a step, as an impulse */
- float vs = (B->vx - A->vx) * J->dx + (B->vy - A->vy) * J->dy - J->sAx * A->w;
- float f = c->k * (c->s0 - J->s) - c->c * vs;
- c->wheel_load[i] = f > 0 ? f : 0;
- float j = f * DT;
- B->vx += B->im * j * J->dx, B->vy += B->im * j * J->dy;
- A->vx -= A->im * j * J->dx, A->vy -= A->im * j * J->dy, A->w -= A->ii * j * J->sAx;
- float r = -(B->w - A->w) / c->wmax;
- if (r > c->rpm) c->rpm = r;
- }
- if (c->rpm > 1) c->rpm = 1;
-}
-
-static void solve_joints(Car *c) {
- Body *A = &c->ch;
- for (int i = 0; i < c->nw; i++) {
- Joint *J = &jo[i];
- Body *B = &c->wh[i];
- /* the engine (or brake) between chassis and wheel */
- if (J->mmax > 0) {
- float rel = B->w - A->w - J->speed;
- float j = -rel / (REACT * A->ii + B->ii), old = J->jm;
- J->jm = old + j;
- if (J->jm > J->mmax) J->jm = J->mmax;
- if (J->jm < -J->mmax) J->jm = -J->mmax;
- j = J->jm - old;
- A->w -= REACT * A->ii * j, B->w += B->ii * j;
- }
- /* across the axis: the wheel stays on it */
- float v = (B->vx - A->vx) * J->px + (B->vy - A->vy) * J->py - J->sAy * A->w;
- float j = J->my * (J->bias - v);
- B->vx += B->im * j * J->px, B->vy += B->im * j * J->py;
- A->vx -= A->im * j * J->px, A->vy -= A->im * j * J->py, A->w -= A->ii * j * J->sAy;
- /* along it: the bump stop (s >= 0) and the end of its travel (s <= smax) */
- float vs = (B->vx - A->vx) * J->dx + (B->vy - A->vy) * J->dy - J->sAx * A->w;
- if (J->s < 0.02f) {
- float bias = J->s < 0 ? -BETA / DT * J->s : 0;
- float jl = J->mx * (bias - vs), old = J->jlo;
- J->jlo = old + jl > 0 ? old + jl : 0;
- jl = J->jlo - old;
- B->vx += B->im * jl * J->dx, B->vy += B->im * jl * J->dy;
- A->vx -= A->im * jl * J->dx, A->vy -= A->im * jl * J->dy, A->w -= A->ii * jl * J->sAx;
- } else if (J->s > c->smax - 0.02f) {
- float bias = J->s > c->smax ? -BETA / DT * (J->s - c->smax) : 0;
- float jl = J->mx * (bias - vs), old = J->jlo;
- J->jlo = old + jl < 0 ? old + jl : 0;
- jl = J->jlo - old;
- B->vx += B->im * jl * J->dx, B->vy += B->im * jl * J->dy;
- A->vx -= A->im * jl * J->dx, A->vy -= A->im * jl * J->dy, A->w -= A->ii * jl * J->sAx;
- }
- }
-}
-
-static void integrate(Body *b) {
- b->x += b->vx * DT, b->y += b->vy * DT, b->a += b->w * DT;
-}
-
-void car_step(Car *c, float gas, float brake, bool fuel) {
- float g = stage->gravity;
- for (int i = 0; i < c->nw; i++) c->ground[i] = false;
- c->touch = false;
- c->tree_broken = -1;
- c->last_vx = c->ch.vx, c->last_vy = c->ch.vy;
- for (int sub = 0; sub < SUB; sub++) {
- /* forces: gravity, downforce, turning in the air */
- c->ch.vy -= g * DT;
- for (int i = 0; i < c->nw; i++) c->wh[i].vy -= g * DT;
- bool air = true;
- for (int i = 0; i < c->nw; i++) air = air && !c->ground[i];
- if (c->down > 0) {
- float v2 = c->ch.vx * c->ch.vx + c->ch.vy * c->ch.vy, f = c->down * v2 * c->ch.im * DT;
- if (f > g * 1.2f * DT) f = g * 1.2f * DT;
- c->ch.vx += sinf(c->ch.a) * f, c->ch.vy -= cosf(c->ch.a) * f;
- }
- if (air && !c->touch && !c->head_hit) c->ch.w += c->air * (gas - brake) * c->ch.ii * DT;
- /* a little air: nothing spins forever */
- c->ch.w *= 1 - 0.3f * DT;
- find_contacts(c);
- /* a tree hit fast snaps at once: the vehicle goes through, a little slower */
- for (int i = 0; i < ncon; i++) {
- Contact *k = &con[i];
- if (k->tree < 0 || !stage_tree_standing(k->tree)) continue;
- float vn = (k->b->vx - k->b->w * k->ry) * k->nx + (k->b->vy + k->b->w * k->rx) * k->ny;
- if (vn > -3.5f) continue;
- stage_tree_fall(k->tree);
- c->tree_broken = k->tree;
- c->ch.vx *= 0.85f;
- for (int w = 0; w < c->nw; w++) c->wh[w].vx *= 0.85f;
- }
- for (int i = 0; i < ncon;) { /* (the pushes of trees that fell are gone) */
- if (con[i].tree >= 0 && !stage_tree_standing(con[i].tree)) con[i] = con[--ncon];
- else i++;
- }
- prepare_contacts();
- prepare_joints(c, gas, brake, fuel);
- for (int it = 0; it < ITER; it++) {
- solve_joints(c);
- solve_contacts();
- }
- /* trees that took too hard a knock fall */
- for (int i = 0; i < ncon; i++) {
- if (con[i].tree < 0) continue;
- float knock = 0; /* (all the pushes on that tree this step) */
- for (int j = 0; j < ncon; j++)
- if (con[j].tree == con[i].tree) knock += con[j].jn, con[j].jn = 0;
- /* a hard knock, or pushing on it a while */
- if (c->tree_hurt_id != con[i].tree) c->tree_hurt_id = con[i].tree, c->tree_hurt = 0;
- c->tree_hurt += knock;
- if (knock > 300.0f || c->tree_hurt > 700.0f) {
- stage_tree_fall(con[i].tree);
- c->tree_broken = con[i].tree;
- }
- }
- integrate(&c->ch);
- for (int i = 0; i < c->nw; i++) {
- integrate(&c->wh[i]);
- c->spin[i] += c->wh[i].w * DT;
- }
- }
- /* Bill's head: does it touch the ground (or a cave's roof)? */
- if (!c->head_hit) {
- float hx, hy, px, py, nx, ny, d;
- float ca = cosf(c->ch.a), sa = sinf(c->ch.a);
- hx = c->ch.x + ca * c->head[0] - sa * c->head[1], hy = c->ch.y + sa * c->head[0] + ca * c->head[1];
- if (circle_line(hx, hy, BILL_HEAD_R * 0.92f, false, &px, &py, &nx, &ny, &d) ||
- (stage->ceiling && circle_line(hx, hy, BILL_HEAD_R * 0.92f, true, &px, &py, &nx, &ny, &d)))
- c->head_hit = true;
- }
- /* his head nods on its neck: a spring pulled by how the chassis speeds up */
- float ax = (c->ch.vx - c->last_vx) * CAR_HZ, ay = (c->ch.vy - c->last_vy) * CAR_HZ + g;
- float ca = cosf(-c->ch.a), sa = sinf(-c->ch.a), lx = ca * ax - sa * ay, ly = sa * ax + ca * ay;
- for (int k = 0; k < 2; k++) {
- float f = -160 * c->wob[k] - 14 * c->wobv[k] - (k ? ly - g : lx) * 0.6f;
- c->wobv[k] += f / CAR_HZ;
- c->wob[k] += c->wobv[k] / CAR_HZ;
- if (c->wob[k] > 0.12f) c->wob[k] = 0.12f, c->wobv[k] = 0;
- if (c->wob[k] < -0.12f) c->wob[k] = -0.12f, c->wobv[k] = 0;
- }
-}
-
-void car_origin(const Car *c, float *x, float *y) { car_point(c, 0, 0, x, y); }
-
-void car_point(const Car *c, float lx, float ly, float *wx, float *wy) {
- float ox, oy;
- rot(c->ch.a, lx - c->com[0], ly - c->com[1], &ox, &oy);
- *wx = c->ch.x + ox, *wy = c->ch.y + oy;
-}
-
-void car_head(const Car *c, float *x, float *y) {
- float ox, oy;
- rot(c->ch.a, c->head[0] + c->wob[0], c->head[1] + c->wob[1], &ox, &oy);
- *x = c->ch.x + ox, *y = c->ch.y + oy;
-}
-
-float car_speed(const Car *c) { return sqrtf(c->ch.vx * c->ch.vx + c->ch.vy * c->ch.vy); }
-
-bool car_airborne(const Car *c) {
- for (int i = 0; i < c->nw; i++)
- if (c->ground[i]) return false;
- return !c->touch;
-}
diff --git a/games/hillclimb/src/car.cpp b/games/hillclimb/src/car.cpp
new file mode 100644
index 00000000..c38b0404
--- /dev/null
+++ b/games/hillclimb/src/car.cpp
@@ -0,0 +1,798 @@
+/* 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). */
+#include <math.h>
+#include <new>
+#include <string.h>
+#include <Box2D/Collision/Shapes/b2CircleShape.h>
+#include <Box2D/Collision/Shapes/b2EdgeShape.h>
+#include <Box2D/Collision/Shapes/b2PolygonShape.h>
+#include <Box2D/Collision/b2Collision.h>
+#include <Box2D/Dynamics/Contacts/b2Contact.h>
+#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>
+#include <Box2D/Dynamics/Joints/b2RevoluteJoint.h>
+#include <Box2D/Dynamics/Joints/b2WheelJoint.h>
+#include <Box2D/Dynamics/b2Body.h>
+#include <Box2D/Dynamics/b2Fixture.h>
+#include <Box2D/Dynamics/b2World.h>
+#include "car.h"
+#include "stage.h"
+#include "vehicle.h"
+
+#ifndef HOST
+/* (no C++ runtime on the calculator: the few things Box2D's classes refer to; nothing is deleted) */
+void operator delete(void *) noexcept {}
+void operator delete(void *, unsigned int) noexcept {}
+extern "C" void __cxa_pure_virtual(void) {
+ for (;;) {
+ }
+}
+#endif
+
+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 };
+/* 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) */
+
+/* ------------------------------------------------------------------ the vehicles' numbers (PlayerCar*) */
+struct Spec {
+ float hz, damp0, damp_k; /* suspension: spring frequency; damping ratio damp0 x damp_k^L */
+ int damp_cap; /* the damping's level counts up to this (0: no cap) */
+ float speed0, speed_k, speed_m; /* top wheel speed speed0 x speed_k^L x speed_m (rad/s) */
+ float turbo0, turbo_k; /* the turbo's cap turbo0 x turbo_k^L */
+ float rate0; /* the turbo's build rate rate0 x 1.1^(L-1) */
+ float torque; /* the engine's torque (N m) */
+ float tire0, tire_k; /* the tires' friction tire0 x tire_k^L */
+ float awd; /* the front wheel's share of the torque with no 4WD upgrade */
+ float wy, r, rr, hwb; /* wheels: below the spawn point (-), radius, rear radius, half wheelbase */
+ float cdens, cfric, wdens; /* chassis density and friction, wheels' density */
+ float com_k; /* the centre of mass lowered by com_k a suspension level */
+ float front_fric; /* the front tyre's friction share */
+ bool fork; /* a raked front fork (bikes) */
+ float seat[2]; /* Bill's seat from the spawn point */
+ float neck_limit, driver_fric; /* his joints' bend, his friction */
+ float air; /* the air control's torque */
+ int nv;
+ float poly[8][2]; /* the chassis */
+ float down0, down_k; /* downforce coefficient down0 + down_k x L (0, 0: none) */
+};
+
+/* indexes match vehicle.h (V_JEEP...) */
+const Spec SPECS[NVEHICLES] = {
+ /* 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}},
+ 0, 0},
+ /* Motocross Bike */
+ {3.5f, 0.2f, 1.11f, 14, 28, 1.05f, 1, 0.5f, 1.15f, 2.0f, 15, 1.85f, 1.115f, 0, -0.2f, 0.5f, 0.5f, 1.25f, 1, 1.5f, 0.6f,
+ 0.045f, 0.15f, true, {-0.3f, 1.35f}, 0.4f, 0.75f, 20, 6,
+ {{-1.3f, 0.2f}, {-1.3f, -0.1f}, {-0.5f, -0.4f}, {0.5f, -0.4f}, {1.45f, -0.1f}, {1.45f, 0.2f}}, 0, 0},
+ /* Monster Truck */
+ {3, 0.2f, 1.11f, 0, 28, 1.05f, 0.55f, 0.5f, 1.15f, 2.5f, 20, 0.65f, 1.115f, 0, 0, 0.7f, 0.7f, 1.45f, 0.5f, 0.2f, 0.2f,
+ 0.05f, 1, false, {-0.1f, 0.8f}, 0.3f, 0.5f, 20, 6,
+ {{-1.275f, -0.5f}, {1.275f, -0.5f}, {1.7f, 0}, {0, 0.5f}, {-1.3175f, 0.5f}, {-1.7f, 0.2f}}, 0, 0},
+ /* Quad Bike */
+ {3.25f, 0.2f, 1.11f, 14, 25, 1.05f, 1, 0.5f, 1.15f, 2.0f, 15, 1.85f, 1.115f, 0, -0.2f, 0.6f, 0.6f, 1.25f, 1, 1.5f, 0.3f,
+ 0.045f, 0.15f, true, {-0.3f, 1.35f}, 0.4f, 0.75f, 20, 6,
+ {{-1.4f, 0.3f}, {-1.4f, -0.1f}, {-0.5f, -0.4f}, {0.5f, -0.4f}, {1.55f, -0.1f}, {1.55f, 0.3f}}, 0, 0},
+ /* Race Car */
+ {5.5f, 0.2f, 1.11f, 0, 28, 1.05f, 1, 0.5f, 1.15f, 2.5f, 20, 1.25f, 1.115f, 0, -0.4f, 0.5f, 0.625f, 1.45f, 1, 0.2f, 0.2f,
+ 0.045f, 1, false, {0.15f, 0.65f}, 0.3f, 0.5f, 20, 6,
+ {{-1.875f, -0.5f}, {1.6875f, -0.4f}, {1.6875f, 0}, {0, 0.4f}, {-1.9375f, 0.55f}, {-2, 0.55f}}, 0.25f, 0.4f},
+ /* Rally Car */
+ {5, 0.2f, 1.11f, 0, 33, 1.05f, 1, 0.5f, 1.15f, 2.5f, 20, 1.25f, 1.115f, 0.5f, -0.25f, 0.5f, 0.5f, 1.3f, 1, 0.2f, 0.2f,
+ 0.045f, 1, false, {-0.25f, 0.9f}, 0.3f, 0.5f, 30, 6,
+ {{-1.875f, -0.5f}, {1.6875f, -0.4f}, {1.6875f, 0}, {0, 0.4f}, {-1.9375f, 0.55f}, {-2, 0.55f}}, 0.25f, 0.3f},
+ /* Dune Buggy */
+ {4.5f, 0.2f, 1.11f, 0, 21, 1.05f, 1, 0.5f, 1.15f, 2.5f, 22, 1.35f, 1.115f, 0.5f, -0.35f, 0.5f, 0.625f, 1.6f, 1, 0.2f, 0.2f,
+ 0.045f, 1, false, {-0.15f, 0.85f}, 0.3f, 0.5f, 20, 6,
+ {{-1.875f, -0.5f}, {1.6875f, -0.4f}, {1.6875f, 0}, {0, 0.4f}, {-1.9375f, 0.55f}, {-2, 0.55f}}, 0.25f, 0},
+ /* Tank */
+ {3, 0.3f, 1.0875f, 0, 34, 1.048f, 0.55f, 0.87f, 1.14f, 3.33f, 6, 0.5f, 1.1612f, 0.5f, 0, 0.35f, 0.35f, 1.45f, 0.5f, 0.2f,
+ 0.2f, 0.0707142857f, 1, false, {-0.2f, 1.4f}, 0.3f, 0.5f, 3.5f, 6,
+ {{-1.275f, -0.4f}, {1.275f, -0.4f}, {2.04f, 0.5f}, {0, 1}, {-2.1675f, 0.5f}, {-2.04f, 0.2f}}, 0, 0},
+};
+/* the Tank's six wheels, rear to front: place from the spawn point, the joint's axis (not normalised, as in the
+ * game), spring frequency (x the suspension's for 1 and 1.5), damping ratio */
+const float TANK_WHEELS[6][6] = {
+ {-2.2f, 1.0f, 0.8f, 0.2f, 10.1f, 1}, {-1.5f, 0.1f, 0, 1, -1, 1}, {-0.5f, -1.5e-17f, 0, 1, -1.5f, 1},
+ {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},
+};
+
+float powi(float b, int n) {
+ float r = 1;
+ for (int i = 0; i < n; i++) r *= b;
+ return r;
+}
+float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; }
+
+/* ------------------------------------------------------------------ the world */
+alignas(8) unsigned char world_mem[sizeof(b2World)];
+b2World *W;
+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 */
+};
+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};
+
+/* ------------------------------------------------------------------ the vehicle (PlayerCar) */
+struct Vehicle {
+ const Spec *s;
+ int veh, nw;
+ b2Body *chassis, *wheel[CAR_MAXW], *torso, *head;
+ b2WheelJoint *joint[CAR_MAXW];
+ b2RevoluteJoint *neck; /* torso to head */
+ b2DistanceJoint *spring[2]; /* chassis to torso, torso to head */
+ float wr[CAR_MAXW], share[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];
+ bool decel_air;
+ bool dead, head_hit;
+ int flips_k; /* the turn handleFlips counts from */
+ bool alive_at_turn;
+ bool accelerating;
+} V;
+
+/* the level of the vehicle's upgrade of a kind, or -1 */
+int level_of(int veh, const uint8_t lv[4], int kind) {
+ for (int u = 0; u < 4; u++)
+ if (vehicles[veh].up[u] == kind) return lv[u];
+ return -1;
+}
+
+b2Body *make_body(float x, float y, float angle, bool bullet, Tag *tag) {
+ b2BodyDef bd;
+ bd.type = b2_dynamicBody;
+ bd.position.Set(x, y);
+ bd.angle = angle;
+ bd.bullet = bullet;
+ bd.userData = tag;
+ return W->CreateBody(&bd);
+}
+
+void add_fixture(b2Body *b, const b2Shape *sh, float friction, float density, uint16 cat, uint16 mask, int16 group) {
+ b2FixtureDef fd;
+ fd.shape = sh;
+ fd.friction = friction;
+ fd.density = density;
+ fd.restitution = 0;
+ fd.filter.categoryBits = cat;
+ fd.filter.maskBits = mask;
+ fd.filter.groupIndex = group;
+ 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;
+ 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);
+ b2RevoluteJointDef rj;
+ rj.bodyA = prev;
+ rj.bodyB = b;
+ rj.localAnchorA = i ? b2Vec2(0, -0.3f) : prev->GetLocalPoint(b2Vec2(x, 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;
+ b2RevoluteJoint *rev = (b2RevoluteJoint *)W->CreateJoint(&rj);
+ if (i) V.neck = rev;
+ /* a zero-length spring beside the joint keeps him upright */
+ b2DistanceJointDef dj;
+ dj.bodyA = prev;
+ dj.bodyB = b;
+ b2Vec2 side = b->GetWorldPoint(b2Vec2(-0.15f, 0.3f));
+ dj.localAnchorA = i ? b2Vec2(-0.15f, -0.3f) : prev->GetLocalPoint(side);
+ dj.localAnchorB.Set(-0.15f, 0.3f);
+ dj.length = (prev->GetWorldPoint(dj.localAnchorA) - b->GetWorldPoint(dj.localAnchorB)).Length();
+ 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;
+ prev = b;
+ }
+}
+
+b2WheelJoint *wheel_joint(b2Body *wheel, b2Vec2 axis, float hz, float damp) {
+ b2WheelJointDef jd;
+ jd.Initialize(V.chassis, wheel, wheel->GetPosition(), axis);
+ jd.enableMotor = true;
+ jd.maxMotorTorque = 500;
+ jd.motorSpeed = 0;
+ jd.frequencyHz = hz;
+ jd.dampingRatio = damp;
+ return (b2WheelJoint *)W->CreateJoint(&jd);
+}
+
+/* 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;
+ 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);
+ if (le < 1) le = 1;
+ if (ls < 1) ls = 1;
+ if (lt < 1) lt = 1;
+ V.hz = s->hz;
+ V.damp = s->damp0 * powi(s->damp_k, s->damp_cap && ls > s->damp_cap ? s->damp_cap : ls);
+ V.speed = s->speed0 * powi(s->speed_k, le) * s->speed_m;
+ V.turbo_cap = s->turbo0 * powi(s->turbo_k, le);
+ V.rate = s->rate0 * powi(1.1f, le - 1);
+ V.tires = s->tire0 * powi(s->tire_k, lt);
+ V.awd = la > 0 ? (float)(la - 1) / 18.0f : s->awd;
+ V.air = s->air;
+ if (veh == V_BIKE) V.air = 0.8f * powi(1.15f, (lair > 0 ? lair : 1) - 1);
+ if (veh == V_QUAD) V.air = 0.8f * powi(1.15f, 4); /* (the Quad's own, fixed) */
+ V.down = s->down0 + s->down_k * (float)(ld > 0 ? ld : 0);
+ /* the chassis */
+ b2PolygonShape poly;
+ b2Vec2 vs[8];
+ for (int i = 0; i < s->nv; i++) vs[i].Set(s->poly[i][0], s->poly[i][1]);
+ poly.Set(vs, s->nv);
+ tag_car[0] = {T_CAR, 0};
+ V.chassis = make_body(x, y + 1, 0, true, &tag_car[0]);
+ add_fixture(V.chassis, &poly, s->cfric, s->cdens, T_CAR, CAR_MASK, veh == V_TANK ? 1 : 0);
+ /* the suspension lowers the centre of mass */
+ b2MassData md;
+ V.chassis->GetMassData(&md);
+ md.center.y -= (float)(ls - 1) * s->com_k;
+ V.chassis->SetMassData(&md);
+ /* the wheels */
+ if (veh == V_TANK) {
+ V.nw = 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);
+ 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);
+ }
+ } else {
+ V.nw = 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);
+ 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;
+ }
+ create_driver(x + s->seat[0], y + s->seat[1]);
+ V.alive_at_turn = true;
+}
+
+/* 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;
+}
+
+struct Listener : b2ContactListener {
+ void PreSolve(b2Contact *contact, const b2Manifold *old) override {
+ (void)old;
+ Tag *a = (Tag *)contact->GetFixtureA()->GetBody()->GetUserData();
+ Tag *b = (Tag *)contact->GetFixtureB()->GetBody()->GetUserData();
+ if (!a || !b) return;
+ if (a->type == T_CAR && b->type != T_CAR) report_touch(b->type, a);
+ else if (b->type == T_CAR && a->type != T_CAR) report_touch(a->type, b);
+ }
+} listener;
+
+/* ------------------------------------------------------------------ the ground: 0.5 m edges, as the game's Terrain */
+const float SEG = 0.5f, X0 = -40.0f;
+const int RING = 64; /* the edges kept around the car (the game keeps 200; only these near it can be touched) */
+struct Ring {
+ b2Fixture *f[RING];
+ int k0, k1; /* edges k0..k1-1 exist; edge k from vertex k to k + 1 */
+ bool ceiling;
+};
+Ring floor_ring, ceil_ring;
+int game_end; /* the game's last vertex: 40 m ahead of the farthest the car got */
+b2Fixture *wall;
+float wall_x;
+
+float vertex_y(int k, bool ceiling) {
+ /* the game's Terrain::addSegment: vertex k at X0 + 0.5 k has the height of the x before it */
+ return ceiling ? stage_roof_vertex(k) : stage_vertex(k);
+}
+
+b2Fixture *edge(float xa, float ya, float xb, float yb) {
+ b2EdgeShape e;
+ e.Set(b2Vec2(xa, ya), b2Vec2(xb, yb));
+ b2FixtureDef fd;
+ fd.shape = &e;
+ fd.friction = stage->friction;
+ fd.restitution = 0;
+ fd.density = 0;
+ fd.filter.categoryBits = T_GROUND;
+ fd.filter.maskBits = GROUND_MASK;
+ return ground->CreateFixture(&fd);
+}
+
+void ring_set(Ring *r, int lo, int hi) {
+ if (hi - lo > RING) lo = hi - RING;
+ /* drop what left the window */
+ while (r->k0 < r->k1 && r->k0 < lo) ground->DestroyFixture(r->f[r->k0++ % RING]);
+ while (r->k1 > r->k0 && r->k1 > hi) ground->DestroyFixture(r->f[--r->k1 % RING]);
+ if (r->k0 >= r->k1) r->k0 = r->k1 = lo;
+ /* and add what entered it, on both sides */
+ while (r->k0 > lo) {
+ int k = --r->k0;
+ r->f[k % RING] = edge(X0 + SEG * (float)k, vertex_y(k, r->ceiling), X0 + SEG * (float)(k + 1),
+ vertex_y(k + 1, r->ceiling));
+ }
+ while (r->k1 < hi) {
+ int k = r->k1++;
+ r->f[k % RING] = edge(X0 + SEG * (float)k, vertex_y(k, r->ceiling), X0 + SEG * (float)(k + 1),
+ vertex_y(k + 1, r->ceiling));
+ }
+}
+
+/* the ground's edges around the car; the game's wall behind (Terrain::updateBackWall: 20 edges into its ring of 200) */
+void update_ground(float cx) {
+ int want = (int)ceilf((cx + 40 - X0) / SEG);
+ if (want > game_end) game_end = want;
+ int start = game_end - 200 < 0 ? 0 : game_end - 200;
+ int wk = start + 20;
+ float wx = X0 + SEG * (float)wk;
+ if (game_end - start >= 21 && wx != wall_x) {
+ if (wall) ground->DestroyFixture(wall);
+ float wy = vertex_y(wk, false);
+ wall = edge(wx, wy - 100, wx, wy + 1000);
+ wall_x = wx;
+ }
+ /* (wider in the Forest: its fallen trees roll on ahead of the car) */
+ float back = stage->feature == FEAT_TREES ? 12 : 8, ahead = stage->feature == FEAT_TREES ? 18 : 10;
+ int lo = (int)floorf((cx - back - X0) / SEG), hi = (int)ceilf((cx + ahead - X0) / SEG);
+ if (lo < start) lo = start;
+ if (hi > game_end) hi = game_end;
+ ring_set(&floor_ring, lo, hi);
+ if (stage->ceiling) ring_set(&ceil_ring, lo, hi);
+}
+
+/* ------------------------------------------------------------------ rope bridges (Bridge::create) */
+const int MAXPLANK = 20;
+struct Bridge {
+ int k; /* which bridge, or -1 */
+ int n;
+ b2Body *plank[MAXPLANK];
+} bridges[2];
+
+void bridge_free(Bridge *br) {
+ for (int i = 0; i < br->n; i++) W->DestroyBody(br->plank[i]); /* (its joints go with it) */
+ br->n = 0, br->k = -1;
+}
+
+void bridge_make(Bridge *br, int k) {
+ float x0, len, y0;
+ if (!stage_bridge_k(k, &x0, &len, &y0)) return;
+ int n = (int)len;
+ if (n > MAXPLANK) n = MAXPLANK;
+ float x1 = x0 + len, t = 0.3f;
+ float w = (x1 - x0) / (float)(n - 1), dx = (x1 - x0) / (float)n;
+ b2PolygonShape box;
+ box.SetAsBox(w * 0.5f, t * 0.5f);
+ b2Body *prev = ground;
+ float cx = x0 + w, cy = y0 - t * 0.5f;
+ br->k = k, br->n = n;
+ for (int i = 0; i < n; i++) {
+ b2BodyDef bd;
+ bd.type = b2_dynamicBody;
+ bd.position.Set(cx, cy);
+ bd.userData = &tag_bridge;
+ b2Body *p = W->CreateBody(&bd);
+ b2FixtureDef fd;
+ fd.shape = &box;
+ fd.friction = 0.5f;
+ fd.density = 1;
+ fd.filter.categoryBits = T_BRIDGE;
+ fd.filter.maskBits = BRIDGE_MASK;
+ p->CreateFixture(&fd);
+ b2RevoluteJointDef rj;
+ rj.Initialize(prev, p, b2Vec2(cx - w * 0.5f, cy + t * 0.5f));
+ W->CreateJoint(&rj);
+ br->plank[i] = prev = p;
+ cx += dx;
+ }
+ b2RevoluteJointDef rj;
+ rj.Initialize(prev, ground, b2Vec2(cx - w * 0.5f, cy + t * 0.5f));
+ W->CreateJoint(&rj);
+}
+
+/* the bridges near the car exist, the others not */
+void update_bridges(float cx) {
+ if (!stage->bridges) return;
+ int near = -1;
+ for (int k = stage_bridge_first(cx - 40);; k++) {
+ float x0, len, y0;
+ if (!stage_bridge_k(k, &x0, &len, &y0) || x0 > cx + 45) break;
+ if (x0 + len < cx - 30) continue;
+ near = k;
+ break;
+ }
+ for (int i = 0; i < 2; i++)
+ if (bridges[i].k >= 0 && bridges[i].k != near) bridge_free(&bridges[i]);
+ if (near < 0) return;
+ for (int i = 0; i < 2; i++)
+ if (bridges[i].k == near) return;
+ for (int i = 0; i < 2; i++)
+ if (bridges[i].k < 0) {
+ bridge_make(&bridges[i], near);
+ return;
+ }
+}
+
+/* ------------------------------------------------------------------ trees (the Forest's: Tree::create) */
+const int MAXTREE = 10;
+struct TreeBody {
+ int k; /* the tree's index, or -1 */
+ b2Body *b;
+ b2RevoluteJoint *j;
+ float t; /* seconds since it broke */
+ float held; /* seconds pushed against its stop */
+} trees[MAXTREE];
+int tree_broken;
+
+void tree_free(TreeBody *t) {
+ if (t->b) W->DestroyBody(t->b);
+ t->b = NULL, t->j = NULL, t->k = -1;
+}
+
+/* a tree is four parts 0.45 x 0.85 m (density 0.2 x the vehicle's obstacle weight, friction 0.8), each held to the
+ * one under it by a joint that bends +-0.05 rad and a spring; here the four are one trunk on one such joint */
+void tree_make(TreeBody *t, int k, float weight) {
+ float x, y;
+ if (!stage_tree(k, &x, &y)) return;
+ b2PolygonShape box;
+ box.SetAsBox(0.225f, 0.425f * 4, b2Vec2(0, 0.425f * 4), 0);
+ b2BodyDef bd;
+ bd.type = b2_dynamicBody;
+ bd.position.Set(x, y);
+ bd.userData = &tag_tree;
+ t->b = W->CreateBody(&bd);
+ b2FixtureDef fd;
+ fd.shape = &box;
+ fd.friction = 0.8f;
+ fd.density = 0.2f * weight;
+ fd.filter.categoryBits = T_TREE;
+ fd.filter.maskBits = TREE_MASK;
+ t->b->CreateFixture(&fd);
+ b2RevoluteJointDef rj;
+ rj.Initialize(ground, t->b, b2Vec2(x, y));
+ rj.enableLimit = true;
+ rj.lowerAngle = -0.05f;
+ rj.upperAngle = 0.05f;
+ t->j = (b2RevoluteJoint *)W->CreateJoint(&rj);
+ 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};
+
+void update_trees(float cx) {
+ tree_broken = -1;
+ if (stage->feature != FEAT_TREES) return;
+ for (int i = 0; i < MAXTREE; i++) {
+ TreeBody *t = &trees[i];
+ if (t->k < 0) continue;
+ float x = t->b->GetPosition().x;
+ /* Tree::onSimulate: a part bent past 0.3 rad breaks off. The game's four light parts give way to a knock or
+ * a push; the one trunk here breaks on a knock or when held at its stop for 0.75 s */
+ if (t->j) {
+ bool stop = fabsf(t->j->GetJointAngle()) > 0.045f;
+ t->held = stop ? t->held + DT : 0;
+ }
+ if (t->j && (fabsf(t->j->GetJointAngle()) > 0.3f || fabsf(t->j->GetReactionTorque(CAR_HZ)) > 40 || t->held > 0.75f)) {
+ W->DestroyJoint(t->j);
+ t->j = NULL;
+ stage_tree_fall(t->k);
+ tree_broken = t->k;
+ }
+ if (!t->j) {
+ t->t += DT;
+ if (t->t > 1) { /* fallen: passes through after a second, gone after four */
+ b2Filter f;
+ f.categoryBits = 0, f.maskBits = 0;
+ t->b->GetFixtureList()->SetFilterData(f);
+ }
+ if (t->t > 4) tree_free(t);
+ continue;
+ }
+ if (x < cx - 12 || x > cx + 24) tree_free(t);
+ }
+ for (int k = stage_tree_first(cx - 10);; k++) {
+ float x, y;
+ if (!stage_tree(k, &x, &y) || x > cx + 20) break;
+ if (x < cx - 10 || !stage_tree_standing(k)) continue;
+ bool have = false;
+ for (int i = 0; i < MAXTREE; i++) have = have || trees[i].k == k;
+ if (have) continue;
+ for (int i = 0; i < MAXTREE; i++)
+ if (trees[i].k < 0) {
+ tree_make(&trees[i], k, OBSTACLE_WEIGHT[V.veh]);
+ break;
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ driving (accelerate, decelerate, idleEngine) */
+float wheel_w(int i) { return V.wheel[i]->GetAngularVelocity(); }
+
+/* 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) */
+ for (int r = 0; r < reps; r++) {
+ if (bike) {
+ float a = clampf((float)(V.air_frames - 5) / 15.0f, 0, 1) * V.air;
+ if (pedal > 0) ch->ApplyTorque(20 * a * clampf(a - w, 0, 1));
+ else ch->ApplyTorque(20 * a * clampf(-a - w, -1, 0));
+ } else if (pedal > 0 && V.air_frames > 5) {
+ ch->ApplyTorque(V.air * clampf(1 - w, 0, 1));
+ } else if (pedal < 0 && V.air_frames > 0) {
+ ch->ApplyTorque(V.air * clampf(-1 - w, -1, 0));
+ }
+ }
+}
+
+void idle_engine(void) {
+ for (int i = 0; i < V.nw; i++) V.joint[i]->SetMaxMotorTorque(0);
+ V.accelerating = false;
+}
+
+void accelerate(void) {
+ air_control(1);
+ if (V.veh == V_TANK) {
+ for (int i = 0; i < V.nw; 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);
+ if (V.air_frames > 0) t *= 0.25f;
+ V.joint[i]->SetMaxMotorTorque(t);
+ V.joint[i]->SetMotorSpeed(-V.speed);
+ }
+ } 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);
+ }
+ }
+ V.accelerating = true;
+}
+
+void decelerate(void) {
+ V.decel_air = true;
+ air_control(-1);
+ bool tank = V.veh == V_TANK;
+ 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);
+ }
+ 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 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);
+ }
+ V.accelerating = true;
+}
+
+/* ------------------------------------------------------------------ after each step (PlayerCar*::update) */
+void handle_head_hit(void) {
+ if (!V.head_hit) return;
+ V.head_hit = false;
+ V.dead = true;
+ for (int i = 0; i < 2; i++)
+ if (V.spring[i]) W->DestroyJoint(V.spring[i]), V.spring[i] = NULL;
+ V.neck->SetLimits(-1.22173f, 1.047198f);
+}
+
+/* PlayerCar::handleFlips: a turn counts once the chassis is back within 90 degrees of upright */
+int handle_flips(void) {
+ float deg = V.chassis->GetAngle() * 57.29578f;
+ int id = (int)deg;
+ int k = (deg > 0 ? id + 90 : id - 90) / 360 * 360;
+ float d = deg - (float)k;
+ if (!(d > -90 && d < 90)) return FLIP_NONE;
+ int r = FLIP_NONE;
+ if (k != V.flips_k) {
+ if (V.alive_at_turn && V.dead) r = FLIP_NECK;
+ else if (k < V.flips_k) r = FLIP_FRONT;
+ else r = FLIP_BACK;
+ }
+ V.flips_k = k;
+ V.alive_at_turn = !V.dead;
+ return r;
+}
+
+void downforce(void) {
+ if (V.down <= 0) return;
+ b2Body *ch = V.chassis;
+ b2Vec2 v = ch->GetLinearVelocity();
+ float sp = v.Length();
+ if (sp < 1.1920929e-7f) return;
+ float a = ch->GetAngle();
+ float f = clampf(sp - 3, 0, 150) * clampf((cosf(a) * v.x / sp + sinf(a) * v.y / sp - 0.75f) * 3, 0, 1) * V.down;
+ ch->ApplyForceToCenter(b2Vec2(sinf(a) * f, -cosf(a) * f));
+}
+
+int update(void) {
+ /* 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);
+ else V.rev += DT * 3 * (1 - V.rev);
+ unsigned any = V.touch_chassis;
+ for (int i = 0; i < V.nw; i++) any |= V.touch_wheel[i];
+ if (any) V.air_frames = 0, V.decel_air = false;
+ else V.air_frames++;
+ handle_head_hit();
+ int flip = handle_flips();
+ downforce();
+ /* the turbo builds while the gas is down */
+ if (V.accelerating) V.turbo += (0.35f + 0.75f * V.turbo) * V.rate / 60.0f;
+ else V.turbo -= DT * (1 + 4 * V.turbo);
+ V.turbo = clampf(V.turbo, 0, V.turbo_cap);
+ return flip;
+}
+
+void snapshot(Car *c, int flip) {
+ b2Body *b[3] = {V.chassis, V.torso, V.head};
+ CarBody *o[3] = {&c->ch, &c->torso, &c->head};
+ for (int i = 0; i < 3; i++) o[i]->x = b[i]->GetPosition().x, o[i]->y = b[i]->GetPosition().y, o[i]->a = b[i]->GetAngle();
+ for (int i = 0; i < V.nw; i++) {
+ c->wh[i].x = V.wheel[i]->GetPosition().x, c->wh[i].y = V.wheel[i]->GetPosition().y;
+ c->wh[i].a = V.wheel[i]->GetAngle();
+ c->ground[i] = V.touch_wheel[i] != 0;
+ }
+ c->vx = V.chassis->GetLinearVelocity().x, c->vy = V.chassis->GetLinearVelocity().y;
+ c->w = V.chassis->GetAngularVelocity();
+ c->air = V.air_frames;
+ c->dead = V.dead;
+ c->flip = flip;
+ c->rev = V.rev, c->turbo = V.turbo;
+ c->tree_broken = tree_broken;
+}
+
+} // namespace
+
+/* ------------------------------------------------------------------ the C side */
+extern "C" void car_init(Car *c, int veh, const uint8_t levels[4]) {
+ car_free();
+ W = new (world_mem) b2World(b2Vec2(0, -stage->gravity));
+ W->SetContactListener(&listener);
+ b2BodyDef bd;
+ bd.userData = &tag_ground;
+ ground = W->CreateBody(&bd);
+ memset(&floor_ring, 0, sizeof floor_ring);
+ 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 < 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;
+ update_ground(0);
+ create_vehicle(veh, levels, 0, y);
+ memset(c, 0, sizeof *c);
+ c->veh = veh, c->nw = V.nw;
+ for (int i = 0; i < V.nw; i++) c->wr[i] = V.wr[i];
+ snapshot(c, FLIP_NONE);
+}
+
+extern "C" void car_free(void) {
+ if (W) W->~b2World();
+ W = NULL;
+}
+
+extern "C" void car_step(Car *c, int pedal, bool engine) {
+ if (!W) return;
+ /* GameContentLayer::preFrameUpdate: the controls */
+ if (V.dead || !engine || pedal == 0) idle_engine();
+ else if (pedal < 0) decelerate();
+ else accelerate();
+ /* PhysicsSimulation::simulate */
+ float cx = V.chassis->GetPosition().x;
+ update_ground(cx);
+ update_bridges(cx);
+ update_trees(cx);
+ V.touch_chassis = 0;
+ for (int i = 0; i < V.nw; i++) V.touch_wheel[i] = 0;
+ W->Step(DT, 8, 3);
+ snapshot(c, update());
+}
+
+extern "C" void car_point(const Car *c, float lx, float ly, float *wx, float *wy) {
+ float s = sinf(c->ch.a), co = cosf(c->ch.a);
+ *wx = c->ch.x + co * lx - s * ly;
+ *wy = c->ch.y + s * lx + co * ly;
+}
+
+extern "C" float car_speed(const Car *c) { return sqrtf(c->vx * c->vx + c->vy * c->vy); }
+
+extern "C" bool car_airborne(const Car *c) { return c->air > 0; }
+
+extern "C" bool car_touches_box(const Car *c, float x, float y, float half) {
+ (void)c;
+ if (!W) return false;
+ b2PolygonShape box;
+ box.SetAsBox(half, half);
+ b2Transform bx;
+ bx.Set(b2Vec2(x, y), 0);
+ b2Body *parts[CAR_MAXW + 3] = {V.chassis, V.torso, V.head};
+ int n = 3;
+ for (int i = 0; i < V.nw; i++) parts[n++] = V.wheel[i];
+ 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;
+ for (b2Fixture *f = parts[i]->GetFixtureList(); f; f = f->GetNext())
+ if (b2TestOverlap(&box, 0, f->GetShape(), 0, bx, parts[i]->GetTransform())) return true;
+ }
+ return false;
+}
+
+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;
+}
+
+extern "C" int car_planks(CarBody *out, int most) {
+ int n = 0;
+ for (int i = 0; i < 2; i++)
+ for (int j = 0; j < bridges[i].n && n < most; j++, n++) {
+ b2Body *p = bridges[i].plank[j];
+ out[n].x = p->GetPosition().x, out[n].y = p->GetPosition().y, out[n].a = p->GetAngle();
+ }
+ return n;
+}
+
+extern "C" int car_trees(CarBody *out, int *which, int most) {
+ int n = 0;
+ for (int i = 0; i < MAXTREE && n < most; i++) {
+ if (trees[i].k < 0) continue;
+ which[n] = trees[i].k;
+ out[n].x = trees[i].b->GetPosition().x, out[n].y = trees[i].b->GetPosition().y, out[n].a = trees[i].b->GetAngle();
+ n++;
+ }
+ return n;
+}
diff --git a/games/hillclimb/src/car.h b/games/hillclimb/src/car.h
index 94849384..17c0fd6d 100644
--- a/games/hillclimb/src/car.h
+++ b/games/hillclimb/src/car.h
@@ -1,53 +1,58 @@
-/* Hill Climb Racing: a vehicle's physics.
+/* Hill Climb Racing: a vehicle and its world, as the game builds them (car.cpp).
*
- * The chassis (with Bill) and each wheel are rigid bodies in the plane. A wheel hangs from the chassis on a
- * spring and damper along the chassis' own up and down, held there by a joint; the engine turns the driven wheels
- * against the chassis, so it rears up when you floor it and turns in the air. The ground pushes on the wheels,
- * on the chassis' outline and, at the end, on Bill's head. Impulses are solved in turn (sequential impulses) at
- * 240 steps a second. Meters, seconds, kilograms; y up. */
+ * 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. */
#ifndef HC_CAR_H
#define HC_CAR_H
#include <stdbool.h>
#include <stdint.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
#define CAR_MAXW 6
#define CAR_HZ 60 /* car_step's rate */
-typedef struct { float x, y, a, vx, vy, w, im, ii; } Body; /* centre of mass, angle; inverse mass and inertia */
+typedef struct { float x, y, a; } CarBody; /* a body's origin and angle */
+
+enum { FLIP_NONE, FLIP_FRONT, FLIP_BACK, FLIP_NECK };
typedef struct {
int veh, nw;
- Body ch, wh[CAR_MAXW];
- float wr[CAR_MAXW], spin[CAR_MAXW];
- float anc[CAR_MAXW][2]; /* the tops of the springs, from the centre of mass (chassis frame) */
- float s0, smax; /* the springs' length at rest unloaded, the most they let a wheel hang */
- float k, c; /* stiffness, damping */
- float torque, wmax, brake, drive[CAR_MAXW];
- float grip, air, down;
- float com[2]; /* the centre of mass from the picture's origin */
- float hull[16][2];
- int nhull;
- float head[2]; /* Bill's head's centre, from the centre of mass */
- bool ground[CAR_MAXW], touch, head_hit;
- float wheel_load[CAR_MAXW];
- float rpm; /* 0 to 1, for the meter */
- float wob[2], wobv[2]; /* Bill's head nodding on its neck (chassis frame) */
- float last_vx, last_vy;
- int tree_broken; /* a tree knocked down this step, or -1 */
- int tree_hurt_id; /* the tree being pushed on, and how hard so far (N s) */
- float tree_hurt;
+ CarBody ch, wh[CAR_MAXW], torso, head, cannon;
+ float wr[CAR_MAXW]; /* the wheels' radii */
+ float vx, vy, w; /* the chassis' velocity and spin (rad/s, counterclockwise) */
+ int air; /* steps since a wheel or the chassis last touched anything */
+ bool dead; /* Bill's head touched the ground: driver down */
+ int flip; /* a flip completed this step (FLIP_*) */
+ 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 */
} Car;
-/* levels: the vehicle's four upgrades (1 and up) */
-void car_init(Car *c, int veh, const uint8_t levels[4], float x);
-/* one 1/60 s: gas and brake from 0 to 1; no fuel left: the engine is off */
-void car_step(Car *c, float gas, float brake, bool fuel);
-/* the picture's origin and angle: where to draw it */
-void car_origin(const Car *c, float *x, float *y);
-/* a point of the picture's frame (meters, y up) in the world */
+/* a new world for the stage being driven (stage.h), and the vehicle in it at the start */
+void car_init(Car *c, int veh, const uint8_t levels[4]);
+/* one 1/60 s: gas (1), brake (-1) or neither (0); engine: there is fuel and Bill is alive */
+void car_step(Car *c, int pedal, bool engine);
+/* the world's memory back (a run ends) */
+void car_free(void);
+/* a picture frame point (meters, the chassis' frame) in the world */
void car_point(const Car *c, float lx, float ly, float *wx, float *wy);
-void car_head(const Car *c, float *x, float *y); /* Bill's head's centre in the world (nodding) */
-float car_speed(const Car *c); /* along the ground, m/s */
+float car_speed(const Car *c);
bool car_airborne(const Car *c);
-float car_fuel_seconds(int veh, const uint8_t levels[4]);
+/* does a square (centre, half its side) touch the vehicle or Bill: coins and fuel cans */
+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]);
+/* 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 __cplusplus
+}
+#endif
#endif
diff --git a/games/hillclimb/src/data.bin b/games/hillclimb/src/data.bin
index 4b3f39b0..772ad8dc 100644
Binary files a/games/hillclimb/src/data.bin and b/games/hillclimb/src/data.bin differ
diff --git a/games/hillclimb/src/game.c b/games/hillclimb/src/game.c
index d20610cb..dc8cc31e 100644
--- a/games/hillclimb/src/game.c
+++ b/games/hillclimb/src/game.c
@@ -127,7 +127,7 @@ void game_frame(uint32_t keys) {
break;
}
run_frame(keys);
- if (run.over && run.over_t > 75) {
+ if (run.over && run.over_t > 1) {
run_finish();
g_mode = MODE_END, end_t = 0;
}
diff --git a/games/hillclimb/src/game.h b/games/hillclimb/src/game.h
index 886d5490..99ddf483 100644
--- a/games/hillclimb/src/game.h
+++ b/games/hillclimb/src/game.h
@@ -17,7 +17,10 @@ typedef struct {
uint16_t best[NSTAGES][NVEHICLES]; /* meters */
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];
} 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 };
@@ -26,7 +29,8 @@ typedef struct {
char text[24];
uint32_t value;
uint16_t t; /* frames shown so far */
- uint8_t big;
+ uint16_t seq; /* the order they came in */
+ uint8_t big, wait; /* (frames before it shows) */
} Popup;
typedef struct {
@@ -34,30 +38,33 @@ typedef struct {
uint8_t kind; /* 0 the stage's dirt, 1 smoke, 2 a coin's sparkle */
} Particle;
-#define NPOPUPS 4
+#define NPOPUPS 5
#define NPARTICLES 40
typedef struct {
Car car;
int vehicle, stage;
- float fuel, fuel_max; /* seconds */
+ float fuel, burn; /* the game's fuel: 100 full, burning `burn` a second */
uint32_t coins, bonus; /* collected, and from tricks and levels */
float start_x, dist, best; /* meters: the farthest reached this run, the best before it */
- int level; /* levels done */
- float air_t, air_rot; /* in the air: for how long, turned how far (radians) */
- int air_flips, neck_ready;
- uint32_t air_value; /* what the air time is worth so far */
+ int level; /* the stage's level (from 0), and how many this run completed */
+ int levels_done;
+ float t; /* seconds since the start */
+ float air_best; /* this time in the air: the longest it has been (seconds) */
+ int air_step; /* the air time's step paid so far */
+ uint32_t air_value; /* what this air time has paid so far */
+ float down_t, empty_t; /* seconds since Bill went down, since the fuel ran out */
bool over;
int end; /* END_* */
int over_t; /* frames since */
- int empty_t; /* frames stopped without fuel */
bool new_best;
- float cam_x, cam_y, cam_s;
+ float cam_x, cam_y, cam_s, zoom;
uint32_t frame;
- float gas, brake; /* the pedals, eased */
+ float gas, brake; /* the pedals (drawn pressed) */
uint16_t got[COIN_GROUPS]; /* coins taken: a bit each */
- uint8_t fuel_got[512]; /* fuel cans taken */
+ uint8_t fuel_got[64]; /* fuel cans taken */
Popup pop[NPOPUPS];
+ uint16_t pop_seq;
Particle part[NPARTICLES];
int npart;
uint32_t flips;
diff --git a/games/hillclimb/src/main.c b/games/hillclimb/src/main.c
index 33dddda8..a638dd91 100644
--- a/games/hillclimb/src/main.c
+++ b/games/hillclimb/src/main.c
@@ -12,9 +12,10 @@ const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level")))
uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */
uint32_t perf_max __attribute__((used));
-static uint16_t band[SCREEN_W * GFX_BAND];
int main(void) {
+ /* the band drawn into lives on main's stack, leaving the app's RAM to the physics */
+ uint16_t band[SCREEN_W * GFX_BAND];
gfx_init(band);
plat_begin();
game_init();
diff --git a/games/hillclimb/src/run.c b/games/hillclimb/src/run.c
index a46c1192..b508f38e 100644
--- a/games/hillclimb/src/run.c
+++ b/games/hillclimb/src/run.c
@@ -1,4 +1,5 @@
-/* The run being driven: pedals, fuel, coins, tricks, levels, the end; the camera and the picture of it all. */
+/* The run being driven, by the game's rules (its GameLayer and GameContentLayer): pedals, fuel, coins, flips, air
+ * time, levels, the end; the camera and the picture of it all. */
#include <math.h>
#include <stdio.h>
#include <string.h>
@@ -11,12 +12,10 @@ Run run;
#define SX 124 /* where the camera's point is on the screen */
#define SY 138
#define PI 3.14159265f
-#define FLIP_TURN (1.5f * PI) /* a flip counts once upside down and the other wheel on top: 270 degrees */
-
-static const uint32_t air_values[] = {25, 50, 75, 100, 200, 300, 400, 500};
+#define DT (1.0f / CAR_HZ)
/* ------------------------------------------------------------------ popups and particles */
-static void popup(const char *text, uint32_t value, int big) {
+static void popup_later(const char *text, uint32_t value, int big, int wait) {
int slot = 0;
for (int i = 0; i < NPOPUPS; i++)
if (run.pop[i].t > run.pop[slot].t) slot = i;
@@ -27,7 +26,21 @@ static void popup(const char *text, uint32_t value, int big) {
}
Popup *p = &run.pop[slot];
snprintf(p->text, sizeof p->text, "%s", text);
- p->value = value, p->t = 0, p->big = (uint8_t)big;
+ p->value = value, p->t = 0, p->big = (uint8_t)big, p->seq = ++run.pop_seq, p->wait = (uint8_t)wait;
+}
+static void popup(const char *text, uint32_t value, int big) { popup_later(text, value, big, 0); }
+
+/* the same popup again (air time going up): its value and its time renewed */
+static void popup_update(const char *text, uint32_t value, int big) {
+ for (int i = 0; i < NPOPUPS; i++)
+ if (run.pop[i].text[0] && (!strcmp(run.pop[i].text, "AIR TIME") || !strcmp(run.pop[i].text, "BIG AIR TIME") ||
+ !strcmp(run.pop[i].text, "INSANE AIR TIME"))) {
+ snprintf(run.pop[i].text, sizeof run.pop[i].text, "%s", text);
+ run.pop[i].value = value, run.pop[i].big = (uint8_t)big;
+ if (run.pop[i].t > 8) run.pop[i].t = 8;
+ return;
+ }
+ popup(text, value, big);
}
static void particle(float x, float y, float vx, float vy, float life, float size, int kind) {
@@ -49,12 +62,18 @@ void run_start(int vehicle, int stg) {
stage_set(stg);
stage_trees_reset();
run.vehicle = vehicle, run.stage = stg;
- car_init(&run.car, vehicle, sv.level[vehicle], 0);
- run.fuel = run.fuel_max = car_fuel_seconds(vehicle, sv.level[vehicle]);
- run.start_x = run.car.ch.x;
+ car_init(&run.car, vehicle, sv.level[vehicle]);
+ run.fuel = 100;
+ run.burn = 2.5f * car_fuel_rate(vehicle, sv.level[vehicle]);
+ run.start_x = 0;
run.best = sv.best[stg][vehicle];
- run.cam_x = run.car.ch.x, run.cam_y = run.car.ch.y + 0.4f, run.cam_s = 22;
+ run.cam_x = run.car.ch.x, run.cam_y = run.car.ch.y, run.zoom = 40, run.cam_s = 22;
rnd_state = 12345u + (uint32_t)stg;
+ /* the stage's level goes on from the last run (StageInfo's level), and the run opens with its goal */
+ run.level = sv.stage_level[stg];
+ char t[32];
+ snprintf(t, sizeof t, "LEVEL %d: REACH %um", run.level + 1, (unsigned)stage_level_goal(run.level));
+ popup(t, 0, 0);
}
uint32_t run_total(void) { return run.coins + run.bonus; }
@@ -65,6 +84,7 @@ static void end_run(int why) {
}
void run_finish(void) {
+ car_free();
if (run.dist > (float)sv.best[run.stage][run.vehicle]) {
sv.best[run.stage][run.vehicle] = (uint16_t)(run.dist < 65535 ? run.dist : 65535);
run.new_best = true;
@@ -79,87 +99,65 @@ void run_finish(void) {
save_write();
}
-/* the air time's worth after t seconds in the air: from a second on, a step every quarter second */
-static uint32_t air_worth(float t) {
- if (t < 1.0f) return 0;
- int n = (int)((t - 1.0f) / 0.25f);
- if (n < 8) return air_values[n];
- uint32_t v = 1000 + 500 * (uint32_t)(n - 8);
- return v > 25000 ? 25000 : v;
-}
-
+/* flips (PlayerCar::handleFlips, GameLayer::onFlip...) and air time (GameLayer's frame): paid as they happen */
static void tricks(void) {
Car *c = &run.car;
- bool air = car_airborne(c) && !c->head_hit;
- static float last_a;
- float da = c->ch.a - last_a;
- last_a = c->ch.a;
- if (air) {
- run.air_t += 1.0f / CAR_HZ;
- run.air_rot += da;
- run.air_value = air_worth(run.air_t);
- /* a flip each time it has turned 270 degrees more (and 360 for each next one) */
- float turn = fabsf(run.air_rot) - FLIP_TURN - 2 * PI * (float)run.air_flips;
- if (turn >= 0) {
- run.air_flips++;
- run.flips++;
- run.bonus += 1000;
- popup(run.air_rot > 0 ? "BACK FLIP" : "FLIP", 1000, 1);
- }
- } else if (run.air_t > 0) {
- if (!c->head_hit && run.air_value) {
- run.bonus += run.air_value;
- popup(run.air_value >= 1000 ? "INSANE AIR TIME" : run.air_value >= 200 ? "BIG AIR TIME" : "AIR TIME",
- run.air_value, run.air_value >= 1000);
- uint32_t ms = (uint32_t)(run.air_t * 1000);
+ if (c->flip == FLIP_FRONT || c->flip == FLIP_BACK) {
+ run.flips++;
+ run.bonus += 1000;
+ popup(c->flip == FLIP_BACK ? "BACK FLIP" : "FLIP", 1000, 1);
+ } else if (c->flip == FLIP_NECK) {
+ run.bonus += 2500;
+ popup("NECK FLIP", 2500, 1);
+ }
+ /* air time counts from 0.75 s up, a step every 0.2 s: 25 each up to the 4th, 100 to the 8th, then 500;
+ * not in the run's first 3 seconds */
+ if (run.t < 3) return;
+ float t = (float)c->air / CAR_HZ;
+ if (t < 0.75f) {
+ if (run.air_value) {
+ uint32_t ms = (uint32_t)(run.air_best * 1000);
if (ms > run.air_best_ms) run.air_best_ms = ms;
}
- run.air_t = 0, run.air_rot = 0, run.air_flips = 0, run.air_value = 0;
- }
+ run.air_best = 0, run.air_step = 0, run.air_value = 0;
+ return;
+ }
+ if (t > run.air_best) run.air_best = t;
+ int n = (int)floorf(1 + (run.air_best - 0.75f) * 5);
+ if (n == run.air_step) return;
+ uint32_t v = n > 8 ? 500 : n > 4 ? 100 : 25;
+ run.bonus += v;
+ run.air_value += v;
+ run.air_step = n;
+ popup_update(n > 8 ? "INSANE AIR TIME" : n > 4 ? "BIG AIR TIME" : "AIR TIME", run.air_value, n > 4);
}
+/* coins and fuel cans are picked up by touching them (GameContentLayer::PreSolve) */
static void pickups(void) {
Car *c = &run.car;
- /* the points of the vehicle that take things: its middle, wheels and Bill */
- float px[CAR_MAXW + 2], py[CAR_MAXW + 2];
- int n = 0;
- px[n] = c->ch.x, py[n] = c->ch.y, n++;
- car_head(c, &px[n], &py[n]), n++;
- for (int i = 0; i < c->nw; i++) px[n] = c->wh[i].x, py[n] = c->wh[i].y, n++;
- float xmin = c->ch.x - 3, xmax = c->ch.x + 3;
- /* coins */
- int k0 = (int)((xmin - 8) / COIN_SPACING), k1 = (int)((xmax + 8) / COIN_SPACING) + 1;
+ float half = COIN_SIZE * 0.5f, xmin = c->ch.x - 5, xmax = c->ch.x + 5;
+ int k0 = (int)((xmin - 30) / COIN_SPACING), k1 = (int)(xmax / COIN_SPACING) + 1;
for (int k = k0 < 1 ? 1 : k0; k <= k1 && k < COIN_GROUPS; k++) {
float cx[14], cy[14];
int val[14];
int m = stage_coin_group(k, cx, cy, val);
for (int i = 0; i < m; i++) {
- if (run.got[k] >> i & 1) continue;
- for (int j = 0; j < n; j++) {
- float dx = cx[i] - px[j], dy = cy[i] - py[j], r = j >= 2 ? c->wr[j - 2] + 0.35f : 1.1f;
- if (dx * dx + dy * dy < r * r) {
- run.got[k] |= (uint16_t)(1 << i);
- run.coins += (uint32_t)val[i];
- for (int s = 0; s < 3; s++) particle(cx[i], cy[i], rndf() * 2 - 1, rndf() * 2 + 1, 0.4f, 0.3f, 2);
- break;
- }
+ if (run.got[k] >> i & 1 || cx[i] < xmin || cx[i] > xmax) continue;
+ 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);
}
}
}
- /* fuel */
- for (int k = 0; k < 4096; k++) {
- float fx;
- if (!stage_fuel(k, &fx) || fx > xmax + 2) break;
- if (fx < xmin - 2 || (k < 4096 && run.fuel_got[k >> 3] >> (k & 7) & 1)) continue;
- float fy = stage_floor(fx) + 0.45f;
- for (int j = 0; j < n; j++) {
- float dx = fx - px[j], dy = fy - py[j], r = j >= 2 ? c->wr[j - 2] + 0.45f : 1.2f;
- if (dx * dx + dy * dy < r * r) {
- run.fuel_got[k >> 3] |= (uint8_t)(1 << (k & 7));
- run.fuel = run.fuel_max;
- popup("FUEL", 0, 0);
- break;
- }
+ for (int k = 0; k < 512; k++) {
+ float fx, fy;
+ if (!stage_fuel(k, &fx, &fy) || fx > xmax) break;
+ if (fx < xmin || run.fuel_got[k >> 3] >> (k & 7) & 1) continue;
+ if (car_touches_box(c, fx, fy, half)) {
+ run.fuel_got[k >> 3] |= (uint8_t)(1 << (k & 7));
+ run.fuel = 100;
+ popup("FUEL", 0, 0);
}
}
}
@@ -167,89 +165,83 @@ static void pickups(void) {
void run_frame(uint32_t keys) {
Car *c = &run.car;
run.frame++;
- bool gas = !run.over && (keys & (K_RIGHT | K_OK)), brake = !run.over && (keys & K_LEFT);
- /* the pedals go down quickly and come up a little slower, as feet do */
- run.gas += ((gas ? 1.0f : 0.0f) - run.gas) * (gas ? 0.5f : 0.35f);
- run.brake += ((brake ? 1.0f : 0.0f) - run.brake) * (brake ? 0.5f : 0.35f);
- if (run.over) run.gas = run.brake = 0;
- bool fuel = run.fuel > 0;
- /* the bridge under the vehicle sags with its weight */
- stage_bridge_load(c->ch.x, 0.35f * (vehicles[run.vehicle].mass / 300.0f));
- car_step(c, run.gas, run.brake, fuel && !c->head_hit);
+ run.t += DT;
+ /* the brake wins over the gas (GameContentLayer::preFrameUpdate) */
+ bool brake = !run.over && (keys & K_LEFT), gas = !run.over && !brake && (keys & (K_RIGHT | K_OK));
+ run.gas = gas, run.brake = brake;
+ car_step(c, gas ? 1 : brake ? -1 : 0, run.fuel > 0);
if (c->tree_broken >= 0) {
- float tx;
- if (stage_tree(c->tree_broken, &tx))
+ float tx, ty;
+ if (stage_tree(c->tree_broken, &tx, &ty))
for (int s = 0; s < 14; s++)
- particle(tx, stage_floor(tx) + 0.3f + rndf() * 2.0f, c->ch.vx * 0.5f + rndf() * 4 - 1, rndf() * 4, 0.9f,
- 0.3f + rndf() * 0.2f, 0);
- }
- /* fuel burns while the run goes on */
- if (!run.over && run.fuel > 0) {
- run.fuel -= 1.0f / CAR_HZ;
- if (run.fuel < 0) run.fuel = 0;
- }
- /* distance and levels */
+ 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);
+ }
+ /* fuel: 2.5 a second (and the vehicle's rate) out of 100; empty, the run ends 4 s later */
+ if (run.fuel > 0) {
+ run.fuel -= run.burn * DT;
+ if (run.fuel <= 0) run.fuel = 0;
+ run.empty_t = 0;
+ } else if (!run.over && (run.empty_t += DT) > 4) {
+ end_run(END_OUT_OF_FUEL);
+ }
+ /* Bill down: the run ends 4 s later */
+ if (c->dead && !run.over && (run.down_t += DT) > 4) end_run(END_DRIVER_DOWN);
+ /* distance and levels (GameLayer::setScore): reaching the goal completes the level and pays its bonus; the
+ * next one is kept for the next runs */
float d = c->ch.x - run.start_x;
if (d > run.dist) run.dist = d;
- if (!run.over)
- while (run.dist >= stage_level_end(run.level + 1)) {
- run.level++;
- uint32_t r = stage_level_reward(run.level);
- run.bonus += r;
- char t[24];
- snprintf(t, sizeof t, "LEVEL %d", run.level);
- popup(t, r, 1);
- }
+ if (!run.over && run.level < 255 && run.dist >= (float)stage_level_goal(run.level)) {
+ uint32_t r = stage_level_bonus(run.level);
+ run.bonus += r;
+ run.levels_done++;
+ char t[32];
+ snprintf(t, sizeof t, "LEVEL %d COMPLETE", run.level + 1);
+ popup(t, 0, 1);
+ popup_later("LEVEL BONUS", r, 1, 60); /* (the game's: a second later, then the next goal) */
+ run.level++;
+ sv.stage_level[run.stage] = (uint8_t)run.level;
+ snprintf(t, sizeof t, "LEVEL %d: REACH %um", run.level + 1, (unsigned)stage_level_goal(run.level));
+ popup_later(t, 0, 0, 120);
+ }
if (!run.over) {
tricks();
pickups();
}
- /* Bill's neck */
- if (c->head_hit && !run.over) {
- if (fabsf(run.air_rot) >= PI * 0.75f || run.air_flips) {
- run.bonus += 2500;
- popup("NECK FLIP", 2500, 1);
- }
- end_run(END_DRIVER_DOWN);
- }
- /* out of fuel: when the vehicle has stopped */
- if (!run.over && run.fuel <= 0) {
- if (car_speed(c) < 0.6f) run.empty_t++;
- else run.empty_t = 0;
- if (run.empty_t > 90) end_run(END_OUT_OF_FUEL);
- }
if (run.over) run.over_t++;
/* dust from the wheels that spin on the ground, smoke from the exhaust */
for (int i = 0; i < c->nw; i++) {
- float slip = fabsf(c->wh[i].w * c->wr[i] - (c->wh[i].vx)), sp = fabsf(c->wh[i].vx);
- if (c->ground[i] && (slip > 2.0f || (sp > 9 && run.frame % 2)) && (run.frame + (uint32_t)i) % 4 == 0)
- particle(c->wh[i].x - c->wr[i] * 0.6f, c->wh[i].y - c->wr[i] * 0.8f, -c->wh[i].vx * 0.2f - rndf() * 2,
+ 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 (run.gas > 0.5f && fuel && run.frame % 9 == 0 && car_speed(c) < 6) {
+ if (gas && run.fuel > 0 && !c->dead && run.frame % 9 == 0 && car_speed(c) < 6) {
float ex, ey;
- car_point(c, -1.4f, 0.2f, &ex, &ey);
- particle(ex, ey, -1.0f + c->ch.vx * 0.5f, 0.5f, 0.6f, 0.16f, 1);
+ car_point(c, -1.5f, 0.1f, &ex, &ey);
+ particle(ex, ey, -1.0f + c->vx * 0.5f, 0.5f, 0.6f, 0.16f, 1);
}
for (int i = 0; i < run.npart; i++) {
Particle *p = &run.part[i];
if (p->life <= 0) continue;
- p->life -= 1.0f / CAR_HZ;
- p->x += p->vx / CAR_HZ, p->y += p->vy / CAR_HZ;
- if (p->kind == 0) p->vy -= 6.0f / CAR_HZ;
- else if (p->kind == 1) p->size += 0.5f / CAR_HZ;
+ p->life -= DT;
+ p->x += p->vx * DT, p->y += p->vy * DT;
+ if (p->kind == 0) p->vy -= 6.0f * DT;
+ else if (p->kind == 1) p->size += 0.5f * DT;
}
for (int i = 0; i < NPOPUPS; i++)
- if (run.pop[i].text[0] && ++run.pop[i].t > 110) run.pop[i].text[0] = 0;
- /* the camera: ahead of the vehicle as it goes, zooming out with speed */
- float sp = car_speed(c), lead = c->ch.vx * 0.2f;
- if (lead > 3.5f) lead = 3.5f;
- if (lead < -1.5f) lead = -1.5f;
- float tx = c->ch.x + lead, ty = c->ch.y + 0.4f;
- run.cam_x += (tx - run.cam_x) * 0.12f;
- run.cam_y += (ty - run.cam_y) * 0.12f;
- float ts = 22 - (sp > 20 ? 20 : sp) * 0.3f;
- run.cam_s += (ts - run.cam_s) * 0.03f;
+ if (run.pop[i].text[0] && !(run.pop[i].wait ? run.pop[i].wait-- : 0) && ++run.pop[i].t > 110)
+ run.pop[i].text[0] = 0;
+ /* the camera (GameContentLayer::updateCamera): half a second ahead of the vehicle, zooming out with its speed,
+ * a quarter second once Bill is down */
+ float sp = car_speed(c);
+ if (sp > 20) sp = 20;
+ if (c->dead) sp *= 0.5f;
+ float z = 40 - 0.75f * sp;
+ if (c->dead) z *= 1.5f;
+ run.zoom += (z - run.zoom) * 0.05f;
+ run.cam_x += (c->ch.x + (c->dead ? 0.25f : 0.5f) * c->vx - run.cam_x) * (3 * DT);
+ run.cam_y += (c->ch.y - run.cam_y) * (3 * DT);
+ run.cam_s = 22 * run.zoom / 40;
}
/* ------------------------------------------------------------------ drawing */
@@ -331,7 +323,7 @@ static void draw_ground(void) {
float wx = wld_x((float)(i * 2));
fl[i] = scr_y(stage_ground(wx));
float c;
- ce[i] = g->ceiling && stage_ceiling(wx, &c) ? scr_y(c) : -4000;
+ ce[i] = g->ceiling && stage_roof(wx, &c) ? scr_y(c) : -4000;
}
for (int x = 0; x < SCREEN_W; x++) {
int i = x >> 1;
@@ -350,88 +342,107 @@ static void draw_ground(void) {
gfx_ground_draw();
}
+static void draw_icicles(void) {
+ if (stage->feature != FEAT_ICICLES) return;
+ float s = run.cam_s, x0 = floorf(wld_x(-20) / 3.0f) * 3.0f, x1 = wld_x(SCREEN_W + 20);
+ for (float x = x0; x < x1; x += 3.0f) {
+ uint32_t h = hash2((uint32_t)(int32_t)(x * 10) + 99u);
+ if (h % 3 == 0) continue;
+ float px = x + (float)(h >> 8 & 255) / 256.0f * 2.5f, c;
+ if (!stage_roof(px, &c)) continue;
+ gfx_image(IMG_ICICLE, scr_x(px), scr_y(c) - 2, s / (img(IMG_ICICLE)->ppm4 / 4.0f) * (0.6f + (float)(h >> 16 & 7) * 0.06f),
+ 0, 255);
+ }
+}
+
+/* the game's rope bridges: planks on joints (where the car is near, as they move) */
+static void plank(float x, float y, float a, float s) {
+ gfx_image(IMG_PLANK, scr_x(x), scr_y(y), s / (img(IMG_PLANK)->ppm4 / 4.0f), a, 255);
+}
+
static void draw_bridges(void) {
- if (stage->feature != FEAT_BRIDGES) return;
- float x0w = wld_x(-20), x1w = wld_x(SCREEN_W + 20);
- for (float x = x0w; x < x1w;) {
- float b0, b1;
- if (!stage_bridge(x, &b0, &b1)) {
- x += 2;
- continue;
- }
- float s = run.cam_s;
- /* the posts at each end, the ropes over the planks */
+ if (!stage->bridges) return;
+ float s = run.cam_s, x0w = wld_x(-30), x1w = wld_x(SCREEN_W + 30);
+ CarBody pl[40];
+ int np = car_planks(pl, 40);
+ for (int k = stage_bridge_first(x0w);; k++) {
+ float b0, len, by;
+ if (!stage_bridge_k(k, &b0, &len, &by) || b0 > x1w) break;
+ float b1 = b0 + len, w = len / (len - 1);
+ /* the posts at each end */
for (int e = 0; e < 2; e++) {
- float px = e ? b1 : b0, py = stage_floor(px);
- gfx_tube(scr_x(px), scr_y(py - 0.3f), scr_x(px), scr_y(py + 1.3f), 0.12f * s, rgb565(0x6B4423), 255);
+ float px = e ? b1 + w * 0.5f : b0 + w * 0.5f;
+ gfx_tube(scr_x(px), scr_y(by - 0.3f), scr_x(px), scr_y(by + 1.3f), 0.12f * s, rgb565(0x6B4423), 255);
}
- int n = (int)((b1 - b0) / 0.8f);
- float lx = 0, ly = 0;
- for (int i = 0; i <= n; i++) {
- float px = b0 + (b1 - b0) * (float)i / (float)n, py = stage_floor(px);
- float a = atan2f(stage_floor(px + 0.1f) - stage_floor(px - 0.1f), 0.2f);
- float sx = scr_x(px), sy = scr_y(py - 0.14f);
- gfx_image(IMG_PLANK, sx, sy, s / img(IMG_PLANK)->ppm4 * 4.0f * 0.8f, a, 255);
- float rx = scr_x(px), ry = scr_y(py + 1.0f);
- if (i) gfx_tube(lx, ly, rx, ry, 0.035f * s, rgb565(0x8A6A3A), 255);
+ bool moving = false;
+ for (int i = 0; i < np; i++) moving = moving || (pl[i].x > b0 && pl[i].x < b1 + 1);
+ float lx = scr_x(b0 + w * 0.5f), ly = scr_y(by + 1.0f);
+ int n = (int)len;
+ for (int i = 0; i < n; i++) {
+ float px = b0 + w + (float)i, py = by - 0.15f, a = 0;
+ if (moving) {
+ for (int j = 0; j < np; j++)
+ if (fabsf(pl[j].x - px) < 0.6f) px = pl[j].x, py = pl[j].y, a = pl[j].a;
+ }
+ plank(px, py, a, s);
+ /* the rope over the planks */
+ float rx = scr_x(px), ry = scr_y(py + 1.15f);
+ gfx_tube(lx, ly, rx, ry, 0.035f * s, rgb565(0x8A6A3A), 255);
lx = rx, ly = ry;
}
- x = b1 + 1;
+ gfx_tube(lx, ly, scr_x(b1 + w * 0.5f), scr_y(by + 1.0f), 0.035f * s, rgb565(0x8A6A3A), 255);
+ }
+}
+
+/* a pine: the trunk, then three tiers of branches, each smaller, from its foot turned by a */
+static void tree(float tx, float ty, float a, float s) {
+ float sc = s / (img(IMG_TREE_TOP)->ppm4 / 4.0f), ux = -sinf(a), uy = cosf(a);
+ gfx_image(IMG_TREE_TRUNK, scr_x(tx), scr_y(ty) + 2, sc, a, 255);
+ for (int i = 0; i < 3; i++) {
+ float h = 0.75f + 0.55f * (float)i;
+ gfx_image(IMG_TREE_TOP, scr_x(tx + ux * h), scr_y(ty + uy * h), sc * (1 - 0.18f * (float)i), a, 255);
}
}
static void draw_trees(void) {
if (stage->feature != FEAT_TREES) return;
float x0w = wld_x(-40), x1w = wld_x(SCREEN_W + 40), s = run.cam_s;
+ CarBody tb[12];
+ int which[12], nt = car_trees(tb, which, 12);
for (int k = stage_tree_first(x0w);; k++) {
- float tx;
- if (!stage_tree(k, &tx)) {
- if (k % 6 == 0 && k > stage_tree_first(x1w) + 6) break;
+ float tx, ty;
+ if (k >= TREES_MAX) break;
+ if (!stage_tree(k, &tx, &ty)) {
+ if (stage_tree_first(x1w) <= k) break;
continue;
}
if (tx > x1w) break;
- float ty = stage_floor(tx), sc = s / (img(IMG_TREE_TOP)->ppm4 / 4.0f);
- if (!stage_tree_standing(k)) continue; /* (knocked down: gone in a burst of needles and bark) */
- /* a pine: the trunk, then three tiers of branches, each smaller */
- gfx_image(IMG_TREE_TRUNK, scr_x(tx), scr_y(ty) + 2, sc, 0, 255);
- for (int i = 0; i < 3; i++)
- gfx_image(IMG_TREE_TOP, scr_x(tx), scr_y(ty + 0.75f + 0.55f * (float)i), sc * (1 - 0.18f * (float)i), 0, 255);
- }
-}
-
-static void draw_icicles(void) {
- if (stage->feature != FEAT_ICICLES) return;
- float s = run.cam_s, x0 = floorf(wld_x(-20) / 3.0f) * 3.0f, x1 = wld_x(SCREEN_W + 20);
- for (float x = x0; x < x1; x += 3.0f) {
- uint32_t h = hash2((uint32_t)(int32_t)(x * 10) + 99u);
- if (h % 3 == 0) continue;
- float px = x + (float)(h >> 8 & 255) / 256.0f * 2.5f, c;
- if (!stage_ceiling(px, &c)) continue;
- gfx_image(IMG_ICICLE, scr_x(px), scr_y(c) - 2, s / (img(IMG_ICICLE)->ppm4 / 4.0f) * (0.6f + (float)(h >> 16 & 7) * 0.06f),
- 0, 255);
+ bool body = false;
+ for (int i = 0; i < nt; i++) body = body || which[i] == k;
+ if (!body && stage_tree_standing(k)) tree(tx, ty, 0, s);
}
+ for (int i = 0; i < nt; i++) tree(tb[i].x, tb[i].y, tb[i].a, s);
}
static void draw_things(void) {
float s = run.cam_s, x0 = wld_x(-30), x1 = wld_x(SCREEN_W + 30);
/* the flag at the best distance */
if (run.best > 1) {
- float fx = run.start_x + run.best, fy = stage_floor(fx);
+ float fx = run.start_x + run.best, fy = stage_deck(fx);
if (fx > x0 && fx < x1) {
gfx_tube(scr_x(fx), scr_y(fy), scr_x(fx), scr_y(fy + 2.4f), 0.05f * s, rgb565(0x3A3A3A), 255);
gfx_image(IMG_FLAG, scr_x(fx), scr_y(fy + 2.4f), s / (img(IMG_FLAG)->ppm4 / 4.0f), 0, 255);
}
}
/* fuel cans */
- for (int k = 0; k < 4096; k++) {
- float fx;
- if (!stage_fuel(k, &fx) || fx > x1) break;
+ for (int k = 0; k < 512; k++) {
+ float fx, fy;
+ if (!stage_fuel(k, &fx, &fy) || fx > x1) break;
if (fx < x0 || run.fuel_got[k >> 3] >> (k & 7) & 1) continue;
- float bob = sinf((float)run.frame * 0.08f + fx) * 0.06f;
- gfx_image(IMG_FUELCAN, scr_x(fx), scr_y(stage_floor(fx) + bob), s / (img(IMG_FUELCAN)->ppm4 / 4.0f), 0, 255);
+ gfx_image(IMG_FUELCAN, scr_x(fx), scr_y(fy), s / (img(IMG_FUELCAN)->ppm4 / 4.0f), 0, 255);
}
/* coins */
- int k0 = (int)((x0 - 8) / COIN_SPACING), k1 = (int)((x1 + 8) / COIN_SPACING) + 1;
+ int k0 = (int)((x0 - 20) / COIN_SPACING), k1 = (int)(x1 / COIN_SPACING) + 1;
for (int k = k0 < 1 ? 1 : k0; k <= k1 && k < COIN_GROUPS; k++) {
float cx[14], cy[14];
int val[14];
@@ -444,23 +455,28 @@ static void draw_things(void) {
}
}
-/* a picture at a point of the vehicle's frame, turned with it */
+/* a picture on a body: at (x, y), turned by a */
+static void body_image(int id, float x, float y, float a) {
+ gfx_image(id, scr_x(x), scr_y(y), run.cam_s / (img(id)->ppm4 / 4.0f), a, 255);
+}
+
+/* a picture at a point of the chassis' frame, turned with it */
static void car_image(int id, float lx, float ly, float extra) {
const Car *c = &run.car;
float wx, wy;
car_point(c, lx, ly, &wx, &wy);
- gfx_image(id, scr_x(wx), scr_y(wy), run.cam_s / (img(id)->ppm4 / 4.0f), c->ch.a + extra, 255);
+ body_image(id, wx, wy, c->ch.a + extra);
}
+/* Bill: his torso and head are bodies of their own (upside down in the game's frame: their angle less pi) */
static void draw_bill(const VehArt *a) {
const Car *c = &run.car;
- if (a->legs) car_image(IMG_BILL_LEG, a->hips[0] + 0.05f, a->hips[1] + 0.02f, a->lean * 0.3f);
- car_image(IMG_BILL_BODY, a->hips[0], a->hips[1], a->lean);
- /* the head on the neck, nodding; dropped to the side once Bill is down */
- float nx = BILL_NECK_X, ny = BILL_NECK_Y, ca = cosf(a->lean), sa = sinf(a->lean);
- float lx = a->hips[0] + ca * nx - sa * ny + c->wob[0], ly = a->hips[1] + sa * nx + ca * ny + c->wob[1];
- float tilt = c->head_hit ? -0.9f : -c->wob[0] * 2.0f;
- car_image(IMG_BILL_HEAD, lx, ly, a->lean + tilt);
+ float ta = c->torso.a - PI, ha = c->head.a - PI;
+ /* his hips: the bottom of his torso */
+ float hx = c->torso.x + sinf(ta) * 0.3f, hy = c->torso.y - cosf(ta) * 0.3f;
+ if (a->legs) body_image(IMG_BILL_LEG, hx, hy, c->ch.a);
+ body_image(IMG_BILL_BODY, hx, hy, ta);
+ body_image(IMG_BILL_HEAD, c->head.x, c->head.y, ha);
}
static void draw_car(void) {
@@ -468,29 +484,30 @@ static void draw_car(void) {
const VehArt *a = &veh_art[run.vehicle];
float s = run.cam_s;
bool rider = a->legs;
- /* behind: the tank's tracks, and the bikes' swingarm */
for (int i = 0; i < a->nlayers; i++)
if (!a->layer[i][3]) car_image((int)a->layer[i][0], a->layer[i][1], a->layer[i][2], 0);
if (run.vehicle == V_TANK) { /* the track around the wheels */
- float x0 = scr_x(c->wh[0].x), y0 = scr_y(c->wh[0].y), x1 = scr_x(c->wh[c->nw - 1].x), y1 = scr_y(c->wh[c->nw - 1].y);
- gfx_tube(x0, y0, x1, y1, (c->wr[0] + 0.07f) * s, rgb565(0x2A2A2A), 255);
- gfx_tube(x0, y0, x1, y1, (c->wr[0] - 0.02f) * s, rgb565(0x4A4A4A), 255);
+ for (int pass = 0; pass < 2; pass++)
+ for (int i = 0; i < c->nw; i++) {
+ int j = (i + 1) % c->nw;
+ 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);
+ }
}
- if (a->ntubes) {
- int i = 0;
+ if (a->ntubes) { /* the swingarm, behind */
float tx, ty;
- car_point(c, a->tube[i][0], a->tube[i][1], &tx, &ty);
- int w = (int)a->tube[i][2];
- gfx_tube(scr_x(tx), scr_y(ty), scr_x(c->wh[w].x), scr_y(c->wh[w].y), a->tube[i][4] * s,
- rgb565((uint32_t)a->tube[i][3]), 255);
+ car_point(c, a->tube[0][0], a->tube[0][1], &tx, &ty);
+ int w = (int)a->tube[0][2];
+ 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 (!rider) draw_bill(a);
car_image(a->chassis, 0, 0, 0);
if (rider) draw_bill(a);
for (int i = 0; i < c->nw; i++)
- gfx_image(a->wheel, scr_x(c->wh[i].x), scr_y(c->wh[i].y), s / (img(a->wheel)->ppm4 / 4.0f) * c->wr[i] / a->wheel_r[0],
- c->spin[i], 255);
- for (int i = 1; i < a->ntubes; i++) {
+ 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);
+ 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);
int w = (int)a->tube[i][2];
@@ -524,7 +541,6 @@ void format_number(char *out, uint32_t n) {
}
out[j] = 0;
}
-
void draw_coins_counter(int x, int y, uint32_t n, int align) {
char t[20];
format_number(t, n);
@@ -534,11 +550,17 @@ void draw_coins_counter(int x, int y, uint32_t n, int align) {
gfx_text(FONT_M, x0 + 20, y, t, rgb565(0xFFE14A), C_BLACK, 0);
}
+/* the meters' needles: the game turns them 23 degrees a unit of revs and 87 of turbo pressure, from 135 */
+static float needle(float v, float per) {
+ v = v * per / 270;
+ return 2.2f - (v < 0 ? 0 : v > 1 ? 1 : v) * 4.4f;
+}
+
static void draw_hud(void) {
const Car *c = &run.car;
char t[40];
/* fuel: the can, then the gauge */
- float f = run.fuel / run.fuel_max;
+ float f = run.fuel / 100;
gfx_image(IMG_FUEL_ICON, 14, 13, 1, 0, 255);
gfx_rrect(26, 7, 64, 12, 3, C_BLACK, 200);
uint32_t col = f > 0.5f ? 0x5BE33A : f > 0.25f ? 0xF2C230 : 0xE8392E;
@@ -549,7 +571,7 @@ static void draw_hud(void) {
/* distance and the level */
snprintf(t, sizeof t, "%dm", (int)run.dist);
gfx_text(FONT_L, 160, 24, t, C_WHITE, C_BLACK, 1);
- float l0 = stage_level_end(run.level), l1 = stage_level_end(run.level + 1);
+ float l0 = run.level ? (float)stage_level_goal(run.level - 1) : 0, l1 = (float)stage_level_goal(run.level);
float p = (run.dist - l0) / (l1 - l0);
gfx_rrect(122, 30, 76, 6, 3, C_BLACK, 170);
if (p > 0) gfx_rrect(123, 31, (int)(74 * (p > 1 ? 1 : p)), 4, 2, rgb565(0xFFC21A), 255);
@@ -563,20 +585,27 @@ static void draw_hud(void) {
int pb = run.brake > 0.5f ? IMG_PEDAL_BRAKE_DOWN : IMG_PEDAL_BRAKE, pg = run.gas > 0.5f ? IMG_PEDAL_GAS_DOWN : IMG_PEDAL_GAS;
gfx_image(pb, 23, 218, 1, 0, 255);
gfx_image(pg, 297, 218, 1, 0, 255);
- float rpm = c->rpm * (run.fuel > 0 ? 1 : 0.1f), boost = car_speed(c) / (vehicles[run.vehicle].speed * 1.6f);
- if (boost > 1) boost = 1;
+ /* (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 boost = needle(c->turbo * tk, 87);
for (int m = 0; m < 2; m++) {
- float mx = m ? 186 : 134, my = 216, v = m ? rpm : boost;
+ float mx = m ? 186 : 134, my = 216;
gfx_image(m ? IMG_METER_RPM : IMG_METER_BOOST, mx, my, 1, 0, 255);
- gfx_image(IMG_NEEDLE, mx, my, 1, 2.2f - v * 4.4f, 255);
- }
- /* what was just earned */
- int row = 0;
- for (int i = 0; i < NPOPUPS; i++) {
- const Popup *q = &run.pop[i];
- if (!q->text[0]) continue;
+ gfx_image(IMG_NEEDLE, mx, my, 1, m ? rpm : boost, 255);
+ }
+ /* what was just earned, in the order it came, one under the other */
+ int y = 52;
+ uint16_t last = 0;
+ for (int n = 0; n < NPOPUPS; n++) {
+ const Popup *q = NULL;
+ for (int i = 0; i < NPOPUPS; i++)
+ if (run.pop[i].text[0] && run.pop[i].seq > last && (!q || run.pop[i].seq < q->seq)) q = &run.pop[i];
+ if (!q) break;
+ last = q->seq;
int a = q->t < 80 ? 255 : 255 - (q->t - 80) * 8;
- if (a <= 0) continue;
+ if (a <= 0 || q->wait) continue;
char v[16];
if (q->value) {
format_number(v, q->value);
@@ -584,14 +613,13 @@ static void draw_hud(void) {
} else {
snprintf(t, sizeof t, "%s", q->text);
}
- int y = 74 + row * 18 - (q->t < 8 ? 8 - q->t : 0);
- gfx_text(q->big ? FONT_L : FONT_M, 160, y, t, q->big ? rgb565(0xFFE14A) : C_WHITE, C_BLACK, 1);
- row++;
- }
- if (run.air_value && !run.over) {
- snprintf(t, sizeof t, "AIR TIME +%lu", (unsigned long)run.air_value);
- gfx_text(FONT_M, 160, 74 + row * 18, t, rgb565(0xBFF0FF), C_BLACK, 1);
+ int f = q->big && gfx_text_width(FONT_L, t) <= 300 ? FONT_L : FONT_M;
+ y += f == FONT_L ? 22 : 15; /* (down to its baseline) */
+ gfx_text(f, 160, y - (q->t < 8 ? 8 - q->t : 0), t, q->big ? rgb565(0xFFE14A) : C_WHITE, C_BLACK, 1);
+ y += 5;
}
+ if (c->dead && !run.over) gfx_text(FONT_XL, 160, 150, "DRIVER DOWN", rgb565(0xFF5A3C), C_BLACK, 1);
+ else if (run.fuel <= 0 && !run.over) gfx_text(FONT_XL, 160, 150, "OUT OF FUEL", rgb565(0xFFC21A), C_BLACK, 1);
}
void run_draw(bool hud) {
diff --git a/games/hillclimb/src/save.c b/games/hillclimb/src/save.c
index 21849fe8..10400987 100644
--- a/games/hillclimb/src/save.c
+++ b/games/hillclimb/src/save.c
@@ -1,6 +1,7 @@
/* Saves: hillclimb.sav (coins, vehicles, stages, upgrades, bests), and a copy of it in a Python script:
* installing apps from the NumWorks website keeps only Python scripts, so the save comes back from it when the
* file itself is gone. The copy is a comment line "#>name:base64" (the way NumPlay and its big games keep theirs). */
+#include <stddef.h>
#include <string.h>
#include "game.h"
#include "plat.h"
@@ -15,6 +16,7 @@ typedef struct {
uint32_t magic, size;
Save s;
} SaveFile;
+_Static_assert(offsetof(Save, stage_level) == SAVE_V1_SIZE, "the old saves' part comes first");
static const char copy_head[] =
"# Hill Climb Racing keeps a copy of your progress here, so\n"
@@ -107,10 +109,11 @@ void save_load(void) {
defaults();
uint32_t len;
const uint8_t *d = plat_load(SAVE_NAME, &len);
- if (!d || len != sizeof(SaveFile)) return;
+ if (!d || (len != sizeof(SaveFile) && len != 8 + SAVE_V1_SIZE)) return;
SaveFile f;
- memcpy(&f, d, sizeof f);
- if (f.magic != MAGIC || f.size != sizeof(Save)) return;
+ memset(&f, 0, sizeof f);
+ memcpy(&f, d, len);
+ if (f.magic != MAGIC || f.size != len - 8) return;
sv = f.s;
/* (whatever the file says, the first vehicle and stage are owned and levels stay in range) */
sv.vehicles |= 1, sv.stages |= 1;
diff --git a/games/hillclimb/src/stage.c b/games/hillclimb/src/stage.c
index 4cda6a74..8ce70672 100644
--- a/games/hillclimb/src/stage.c
+++ b/games/hillclimb/src/stage.c
@@ -1,188 +1,345 @@
-/* The stages (stage.h): their ground, ceilings, bridges, trees, coins, fuel and levels. */
+/* The stages (stage.h): the game's own ground, ceilings, bridges, trees, coins, fuel cans; the levels. */
#include <math.h>
#include "data.h"
#include "stage.h"
-/* name, price, gravity, friction; sky, surface, ground, ceiling's surface, icon, particle; ceiling, feature, clouds,
- * stars; seed; the four noises; a cave's height; fuel; coins; levels; the surface's colour. The prices, the
- * levels' lengths and rewards, fuel spacing and where the big coins start are the game's (Hill Climb Racing Wiki). */
+#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
+ * (StageManager::initialize). */
const Stage stages[NSTAGES] = {
- {"Countryside", 0, 9.8f, 1.0f, IMG_SKY, IMG_SURF_COUNTRY, IMG_GROUND_COUNTRY, IMG_SURF_CAVE, IMG_STAGE_COUNTRY,
- IMG_GRASS, 0, FEAT_NONE, 1, 0, 11,
- {90, 30, 9, 2.6f}, {6, 2.5f, 0.4f, 0}, {10, 5, 1.2f, 0.22f}, {18, 8, 2.1f, 0.42f}, 0, 0,
- 90, 90, 0, 90, 100, 200, 422, 5613, 200, 200, 5000, 3000, 0x7CC62B},
- {"Desert", 35000, 9.8f, 0.9f, IMG_SKY, IMG_SURF_DESERT, IMG_GROUND_DESERT, IMG_SURF_CAVE, IMG_STAGE_DESERT,
- IMG_DIRT, 0, FEAT_BRIDGES, 1, 0, 23,
- {70, 26, 9, 3.2f}, {3, 1.4f, 0.2f, 0}, {5, 3.2f, 0.8f, 0.12f}, {13, 7, 1.8f, 0.3f}, 0, 0,
- 90, 90, 0, 90, 100, 220, 480, 6695, 200, 0, 3000, 2000, 0xE8D99A},
- {"Arctic", 75000, 9.8f, 0.42f, IMG_SKY, IMG_SURF_ARCTIC, IMG_GROUND_ARCTIC, IMG_SURF_CAVE, IMG_STAGE_ARCTIC,
- IMG_SNOW, 0, FEAT_NONE, 1, 0, 11,
- {90, 30, 9, 2.6f}, {6, 2.5f, 0.4f, 0}, {10, 5, 1.2f, 0.22f}, {18, 8, 2.1f, 0.42f}, 0, 0,
- 90, 90, 4, 200, 90, 160, 270, 3604, 200, 0, 6000, 2000, 0xF2F6FA},
- {"Highway", 125000, 9.8f, 1.1f, IMG_SKY_HIGHWAY, IMG_SURF_HIGHWAY, IMG_GROUND_HIGHWAY, IMG_SURF_CAVE,
- IMG_STAGE_HIGHWAY, IMG_SMOKE, 0, FEAT_NONE, 1, 0, 37,
- {110, 40, 12, 3}, {0.4f, 0.2f, 0, 0}, {3.2f, 2, 0.35f, 0.05f}, {16, 8, 1.4f, 0.16f}, 0, 0,
- 150, 160, 18, 650, 120, 260, 600, 6090, 600, 300, 17000, 7500, 0x6E6E6E},
- {"Cave", 150000, 9.8f, 1.0f, IMG_SKY_CAVE, IMG_SURF_CAVE, IMG_GROUND_COUNTRY, IMG_SURF_CAVE, IMG_STAGE_CAVE,
- IMG_ROCKS, 1, FEAT_NONE, 0, 0, 41,
- {48, 18, 7, 2.4f}, {1.8f, 0.8f, 0.25f, 0.05f}, {3, 2.4f, 1, 0.2f}, {7, 4.4f, 1.8f, 0.4f}, 4.3f, 2.2f,
- 150, 120, 0, 150, 90, 180, 300, 4143, 300, 0, 11000, 9000, 0xB7B2A8},
- {"Moon", 175000, 3.6f, 0.9f, IMG_SKY_MOON, IMG_SURF_MOON, IMG_GROUND_MOON, IMG_SURF_CAVE, IMG_STAGE_MOON,
- IMG_SMOKE, 0, FEAT_NONE, 0, 1, 53,
- {56, 20, 7, 2.2f}, {3, 1.4f, 0.4f, 0.04f}, {4.5f, 3, 1.2f, 0.25f}, {12, 6.5f, 2.4f, 0.5f}, 0, 0,
- 90, 90, 0, 90, 80, 160, 272, 4500, 200, 300, 10000, 12000, 0xB9BAD8},
- {"Mars", 250000, 5.2f, 0.95f, IMG_SKY_MARS, IMG_SURF_MARS, IMG_GROUND_MARS, IMG_SURF_MARS, IMG_STAGE_MARS,
- IMG_ROCKS_MARS, 2, FEAT_NONE, 0, 0, 67,
- {60, 22, 8, 2.6f}, {2.4f, 1.2f, 0.3f, 0.04f}, {4, 2.6f, 1, 0.2f}, {10, 5.5f, 2, 0.42f}, 4.8f, 2.4f,
- 150, 150, 10, 420, 90, 180, 302, 4800, 200, 300, 10000, 12000, 0xC77B5A},
- {"Alien Planet", 750000, 9.8f, 0.85f, IMG_SKY_FOREST, IMG_SURF_ALIEN, IMG_GROUND_ALIEN, IMG_SURF_ALIEN,
- IMG_STAGE_ALIEN, IMG_SLIME, 0, FEAT_NONE, 0, 1, 71,
- {44, 19, 7, 2.2f}, {4, 1.8f, 0.4f, 0.05f}, {6, 3.5f, 1.3f, 0.25f}, {13, 7, 2.6f, 0.5f}, 0, 0,
- 120, 120, 8, 320, 90, 180, 300, 4000, 300, 0, 15000, 12000, 0x6FA34A},
- {"Arctic Cave", 800000, 9.8f, 0.45f, IMG_SKY_ARCTIC_CAVE, IMG_SURF_ARCTIC, IMG_GROUND_ARCTIC, IMG_SURF_ARCTIC,
- IMG_STAGE_ARCTIC_CAVE, IMG_SNOW, 1, FEAT_ICICLES, 0, 0, 83,
- {50, 19, 7, 2.4f}, {1.8f, 0.8f, 0.25f, 0.05f}, {3, 2.4f, 1, 0.2f}, {7, 4.4f, 1.8f, 0.4f}, 4.6f, 2.2f,
- 120, 120, 5, 260, 90, 180, 300, 4000, 300, 0, 15000, 12000, 0xEAF3F8},
- {"Forest", 850000, 9.8f, 1.0f, IMG_SKY_FOREST, IMG_SURF_FOREST, IMG_GROUND_FOREST, IMG_SURF_CAVE,
- IMG_STAGE_FOREST, IMG_GRASS, 0, FEAT_TREES, 1, 0, 97,
- {52, 20, 7.5f, 2.6f}, {3, 1.5f, 0.3f, 0.02f}, {5, 3, 1.1f, 0.22f}, {12, 6.5f, 2.2f, 0.42f}, 0, 0,
- 90, 90, 0, 90, 90, 180, 300, 4500, 200, 250, 10000, 10000, 0x4E9A2E},
+ {"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},
+ {"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},
+ {"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},
+ {"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},
+ {"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},
+ {"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},
+ {"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},
+ {"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},
+ {"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},
+ {"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},
};
const Stage *stage = &stages[0];
-static int stage_id;
-void stage_set(int s) { stage = &stages[s], stage_id = s; }
-
-/* ------------------------------------------------------------------ noise */
-static uint32_t hash(uint32_t a, uint32_t b) {
- uint32_t h = a * 0x9E3779B1u ^ (b + 0x7F4A7C15u) * 0x85EBCA77u;
- h ^= h >> 15;
- h *= 0x2C1B3C6Du;
- h ^= h >> 12;
- h *= 0x297A2D39u;
- h ^= h >> 15;
+int stage_id;
+
+static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; }
+/* the game's way to grow a stage's hills with the distance: a factor from lo, rising by d, at most hi + lo */
+static float grow(float d, float hi, float lo) { return d > hi ? hi + lo : d < 0 ? lo : d + lo; }
+
+/* ------------------------------------------------------------------ the ground: Stage*::getHeightAtX */
+static float h_countryside(float x) {
+ float u = 10 + 1.5f * x, k2 = clampf(0.00075f * u, 0, 1);
+ float h = 2 * cosf(u / 10) + 0.2f * cosf(u + sinf(u / 4)) * clampf(0.0015f * u, 0, 1) +
+ 2 * cosf(0.17f * u + sinf(u / 4)) * k2 + 2 * cosf(0.0952f * u + sinf(0.15f * u)) * clampf(0.00275f * u, 0, 1) +
+ 4 * sinf(u / 30 + cosf(u / 32.14f)) * k2 - 1;
+ return h * grow(u / 2000, 1.5f, 0.5f);
+}
+
+static float h_desert(float x) {
+ float u = 10 + 1.5f * x;
+ float h = 0.35f * cosf(u / 3 + sinf(u / 6.56f)) + 0.3f * cosf(u + sinf(0.175f * u)) * clampf(0.0015f * u, 0, 1) +
+ 2.5f * cosf(0.11f * u + sinf(0.0515f * u)) * clampf(0.00075f * u, 0, 1) +
+ 3.5f * sinf(0.132f * u + cosf(0.0151f * u)) * clampf(0.00275f * u, 0, 1) +
+ 2.5f * sinf(u / 30 + cosf(u / 64.14f)) * clampf(0.00175f * u, 0, 1) - 1;
+ return h * grow(u / 2000, 1.5f, 0.5f);
+}
+
+static float h_arctic(float x) {
+ float u = 10 + 1.5f * x;
+ if (u > 2190) u = 2190 + (u - 2190) * 0.875f;
+ float k = clampf(0.00145f * u, 0, 1);
+ float h = 2 * cosf(u / 10) + 0.1f * cosf(u + sinf(0.3215f * u)) * clampf(0.0015f * u, 0, 1) +
+ 1.5f * cosf(0.18f * u + sinf(0.165f * u)) * k +
+ 1.75f * cosf(0.0952f * u + sinf(0.115f * u)) * clampf(0.00275f * u, 0, 1) +
+ 4 * sinf(u / 11 + cosf(u / 32.14f)) * k;
+ return h * grow(u / 1600, 2.5f, 0.5f);
+}
+
+static float h_highway(float x) {
+ float a = (x + 3) * 6.7f, b = (x + 3) * 2.5f;
+ float h = 0.5f * cosf((a / 80 + PI) * 4) + 1.6f * cosf(a / 73 + PI) +
+ 1.6f * cosf((a / 57 + PI) * 0.5f) * clampf(b / 300, 0, 1) +
+ 1.6f * cosf((a / 78 + PI) / 3) * clampf(b / 600, 0, 1) +
+ 2.6f * cosf((a / 57 + PI) / 7) * clampf(b / 1200, 0, 1) +
+ 1.35f * cosf((a / 86 + PI) * 0.25f) * clampf(b / 1400, 0, 1) +
+ 1.25f * sinf((a / 67 + PI) * 0.25f) * clampf(b / 1500, 0, 1);
+ /* long flat stretches where this is near 1 */
+ float flat = clampf(powf(0.5f + 0.5f * sinf(b / 225), 8), 0, 1);
+ h = h + flat * (0.05f * h - h);
+ return h * grow(b / 1350, 2.25f, 1.35f);
+}
+
+/* the caves' ground (Cave, Mars, Arctic Cave share its shape) */
+typedef struct {
+ float ux, c1, c2, c3, s1, c4, c5, c6, c7, a2, c8, c9, a3, c10;
+} CaveShape;
+static float h_cave_shape(const CaveShape *c, float x) {
+ float u = 10 + c->ux * x;
+ float h = (sinf(u / 185) + c->s1) * cosf(u / c->c1 + sinf(u / c->c2)) +
+ c->c3 * cosf(u + sinf(c->c4 * u)) * sinf(u / 200) * clampf(x / 100, 0, 1) +
+ c->a2 * cosf(u / c->c5 + sinf(u / c->c6)) * clampf(x / 900, 0, 1) +
+ c->a3 * cosf(u / c->c7 + sinf(u / c->c8)) * clampf(x / 1900, 0, 1) +
+ 5 * sinf(u / c->c9 + cosf(u / c->c10)) * clampf(x / 2500, 0, 1) - 1;
return h;
}
-static float rnd(uint32_t a, uint32_t b) { return (float)(hash(a, b) >> 8) * (1.0f / 8388608.0f) - 1.0f; } /* -1..1 */
-static float frnd(uint32_t a, uint32_t b) { return (float)(hash(a, b) >> 8) * (1.0f / 16777216.0f); } /* 0..1 */
-
-/* a smooth curve through a hashed height at every whole t (Catmull-Rom) */
-static float noise(uint32_t seed, float t) {
- float f = floorf(t);
- int32_t i = (int32_t)f;
- float u = t - f;
- float p0 = rnd(seed, (uint32_t)(i - 1)), p1 = rnd(seed, (uint32_t)i), p2 = rnd(seed, (uint32_t)(i + 1)),
- p3 = rnd(seed, (uint32_t)(i + 2));
- return p1 + 0.5f * u * (p2 - p0 + u * (2 * p0 - 5 * p1 + 4 * p2 - p3 + u * (3 * (p1 - p2) + p3 - p0)));
-}
-
-static float smoothstep(float a, float b, float x) {
- float t = (x - a) / (b - a);
- t = t < 0 ? 0 : t > 1 ? 1 : t;
- return t * t * (3 - 2 * t);
-}
-
-/* the hills: the noises, growing with the distance, after a flat start; `from` leaves out the large ones */
-static float hills(float x, int from, int to) {
- if (x <= 12) return 0;
- float km = x * 0.001f, h = 0;
- for (int o = from; o < to; o++) {
- float a = stage->amp0[o] + stage->grow[o] * km;
- if (a > stage->amax[o]) a = stage->amax[o];
- if (a > 0) h += a * noise(stage->seed * 4 + (uint32_t)o, x / stage->len[o]);
- }
- return h * smoothstep(12, 70, x);
+static float cave_tail(float h, float x, float u, float wave) {
+ float flat = clampf(powf(0.5f + 0.5f * sinf(x / wave), 8), 0, 1);
+ h = h + flat * (0.05f * h - h);
+ return h * grow(u / 1200, 2.5f, 0.75f);
}
+static const CaveShape CAVE = {1.5f, 7.21f, 17, 0.2f, 1.5f, 0.1265f, 7.651f, 25.521f, 11.518f, 2, 15.412f, 35, 2, 42.14f};
+static const CaveShape MARS = {1.75f, 9.21f, 67, 0.2f, 1.95f, 0.1265f, 8.651f, 33.521f, 13.518f, 1.8f, 22.412f, 42.5f,
+ 2.2f, 64.14f};
+static float h_cave(float x) { return cave_tail(h_cave_shape(&CAVE, x), x, 10 + 1.5f * x, 95); }
+static float h_mars(float x) { return cave_tail(h_cave_shape(&MARS, x), x, 10 + 1.75f * x, 65); }
-/* Highway: the road starts flat and only now and then a hill */
-static float road(float x) {
- float h = hills(x, 0, 4);
- return x < 600 ? h * smoothstep(0, 600, x) * 0.7f : h;
+static float h_arctic_cave(float x) {
+ /* bumps of ice on the Arctic Cave's floor */
+ double s = sin((double)(10 * cosf(0.016f * x)) + (double)x * 0.2);
+ float k = x / 1000;
+ float bumps = (float)(s * (k > 2 ? 2.0 : k < 0.5f ? 0.5 : (double)k));
+ if (bumps < 0) bumps = -bumps;
+ float u = 10 + 1.5f * x;
+ if (u > 1569) u = 1569 + (u - 1569) * 0.875f;
+ float h = (sinf(u / 185) + 1.5f) * cosf(u / 7.21f + sinf(u / 17)) +
+ 0.25f * cosf(u + sinf(0.1565f * u)) * sinf(u / 200) * clampf(x / 100, 0, 1) +
+ 2 * cosf(u / 8.651f + sinf(u / 28.521f)) * clampf(x / 900, 0, 1) +
+ 2 * cosf(u / 13.518f + sinf(u / 14.412f)) * clampf(x / 1900, 0, 1) +
+ 5 * sinf(u / 37 + cosf(u / 62.14f)) * clampf(x / 2500, 0, 1) - 1;
+ return cave_tail(h + bumps, x, u, 95);
}
-/* ------------------------------------------------------------------ bridges */
-static float load_x = -1e9f, load_d;
-void stage_bridge_load(float x, float depth) { load_x = x, load_d = depth; }
+static float h_moon(float x) {
+ float u = 10 + 1.5f * x;
+ float h = 2 * cosf(0.125f * u) + 0.2f * cosf(u + sinf(1 + 0.25f * u)) * clampf(0.0015f * u, 0, 1) +
+ 2 * cosf(0.14f * u + sinf(0.45f * u)) * clampf(0.00075f * u, 0, 2) +
+ 2 * cosf(0.0752f * u + sinf(0.095f * u)) * clampf(0.00275f * u, 0, 1) +
+ 4 * sinf(u / 30 + cosf(u / 21.14f)) * clampf(0.00275f * u, 0, 2) - 1;
+ return h * grow(u / 1500, 1.5f, 0.5f);
+}
+
+static float h_alien(float x) {
+ /* two roads of waves, blended back and forth */
+ float a = (x + 3) * 22.7f, b = (x + 3) * 2.5f;
+ float c1 = clampf(b / 300, 0, 1), c2 = clampf(b / 600, 0, 1), c3 = clampf(b / 1200, 0, 1),
+ c4 = clampf(b / 1400, 0, 1), c5 = clampf(b / 1500, 0, 1);
+ float r1 = 0.5f * cosf((a / 80 + PI) * 0.45f) + 1.6f * cosf((a / 73 + PI) * 0.81f) +
+ 1.6f * cosf((a / 57 + PI) / 2.126f) * c1 + 1.6f * cosf((a / 78 + PI) / 2.895f) * c2 +
+ 2.6f * cosf((a / 57 + PI) / 4.721f) * c3 + 1.35f * cosf((a / 86 + PI) / 4.791f) * c4 +
+ 1.25f * sinf((a / 67 + PI) / 3.971f) * c5;
+ float r2 = 0.5f * cosf((a / 95.1f + PI) * 0.35f) + 1.6f * cosf((a / 33 + PI) * 0.51f) +
+ 1.6f * cosf((a / 87 + PI) / 3.126f) * c1 + 1.6f * cosf((a / 84.2f + PI) / 1.895f) * c2 +
+ 2.6f * cosf((a / 77.7f + PI) / 5.721f) * c3 + 1.35f * cosf((a / 84.35f + PI) / 4.791f) * c4 +
+ 1.25f * sinf((a / 96.7f + PI) / 3.971f) * c5;
+ float h = r1 + (0.5f + 0.5f * sinf(b / 100)) * (r2 - r1);
+ return h * grow(b / 2050, 2.25f, 0.95f);
+}
-/* bridge k: from x0 to x1 (k from 0) */
-static void bridge_k(int k, float *x0, float *x1) {
- *x0 = 340.0f + (float)k * 300.0f + frnd(stage->seed, 9000u + (uint32_t)k) * 120.0f;
- *x1 = *x0 + 14.0f + frnd(stage->seed, 9500u + (uint32_t)k) * 10.0f;
+static float h_forest(float x) {
+ float u = 10 + 1.5f * x, s = sinf(0.215f * u), k2 = clampf(0.00075f * u, 0, 1);
+ float h = 2 * cosf(u / 10) +
+ (0.2f * sinf(u + s) + 0.25f * cosf(0.25f * u + sinf(0.515f * u))) * clampf(0.0015f * u, 0, 1) +
+ 2 * cosf(0.16f * u + sinf(0.1515f * u) + 2.411f) * k2 +
+ 2 * cosf(0.0952f * u + s + 5.6f) * clampf(0.00275f * u, 0, 1) +
+ 4 * sinf(u / 32 + cosf(u / 31.14f)) * k2 - 1;
+ return h * grow(u / 2000, 1.5f, 0.5f);
}
-bool stage_bridge(float x, float *x0, float *x1) {
- if (stage->feature != FEAT_BRIDGES || x < 300) return false;
- int k = (int)((x - 340.0f) / 300.0f);
- for (int j = k - 1; j <= k; j++) {
- if (j < 0) continue;
- bridge_k(j, x0, x1);
- if (x >= *x0 && x <= *x1) return true;
+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};
+
+/* the caves' ceiling over the ground (StageCave::getCaveHeightAtX); Mars opens up now and then */
+static float cave_height(float x) {
+ float w = powf(clampf(fabsf(x) / 50, 0, 1), 0.15f);
+ float c = (cosf(x / 12.21f) + 1) * 0.175f + (cosf(0.0952f * x + sinf(0.421f * x)) + 1) * 0.25f;
+ float k = x / 1700;
+ c += (cosf(0.127f * x + sinf(0.751f * x)) + 1) * (k > 0.75f ? 0.25f : k < 0 ? 1 : 1 - k);
+ k = x / 1900;
+ c += (cosf(0.1952f * x + sinf(0.21f * x)) + 1) * (k > 0.85f ? 0.15f : k < 0 ? 1 : 1 - k);
+ k = x / 1000;
+ c += (sinf(x / 25 + cosf(x / 19.14f)) + 1) * 0.75f * (k > 1 ? 0 : k < 0 ? 1 : 1 - k);
+ float top = 3;
+ if (stage_id == ST_ARCTIC_CAVE) top = 4;
+ if (stage_id == ST_MARS) top = clampf(50 * sinf(x / 100), 0, 50) + 3;
+ 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 */
+
+/* the stage's own height with the bridges 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++;
}
- return false;
}
-static float base_floor(float x) { return stage_id == ST_HIGHWAY ? road(x) : hills(x, 0, 4); }
+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];
+ return true;
+}
-/* the bridge's planks: a rope's sag between its ends, and a dip under the vehicle */
-static float bridge_y(float x, float x0, float x1) {
- float t = (x - x0) / (x1 - x0), y0 = base_floor(x0), y1 = base_floor(x1);
- float sag = (x1 - x0) * 0.045f * sinf(3.14159265f * t);
- float d = (x - load_x) / 2.5f;
- float dip = d > -3 && d < 3 ? load_d * expf(-d * d) * sinf(3.14159265f * t) : 0;
- return y0 + (y1 - y0) * t - sag - dip;
+/* the last bridge starting before x, or -1 */
+static int bridge_before(float x) {
+ if (!stage->bridges || x <= 120) return -1;
+ int k = 0;
+ for (;; k++) {
+ bridges_upto(k + 1);
+ if (k + 1 >= MAXBRIDGE - 1 || br_x0[k + 1] >= x) break;
+ }
+ return k;
+}
+
+int stage_bridge_first(float x) {
+ int k = bridge_before(x);
+ if (k < 0) return 0;
+ return br_x0[k] + br_len[k] < x ? k + 1 : k;
}
float stage_floor(float x) {
- float x0, x1;
- if (stage_bridge(x, &x0, &x1)) return bridge_y(x, x0, x1);
- return base_floor(x);
+ int k = bridge_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 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 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;
+ }
+ return h;
}
-float stage_ground(float x) {
- float x0, x1, h = base_floor(x);
- if (!stage_bridge(x, &x0, &x1)) return h;
- float t = (x - x0) / (x1 - x0), b = bridge_y(x, x0, x1) - 0.4f;
- if (h > b) h = b;
- return h - 4.5f * powf(sinf(3.14159265f * t), 0.35f);
+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);
}
-/* ------------------------------------------------------------------ ceilings */
-#define TUNNEL_START 260.0f
-#define TUNNEL_EVERY 520.0f
-#define TUNNEL_LEN 170.0f
+/* ------------------------------------------------------------------ the ground as built: 0.5 m apart */
+#define VCACHE 256
+static int vkey[VCACHE], rkey[VCACHE];
+static float vval[VCACHE], rval[VCACHE];
+
+float stage_vertex(int k) {
+ int i = k & (VCACHE - 1);
+ if (vkey[i] != k) vkey[i] = k, vval[i] = stage_floor(-40.0f + 0.5f * (float)(k > 0 ? k - 1 : 0));
+ return vval[i];
+}
+
+float stage_ground(float x) {
+ float f = (x + 40) * 2, k = floorf(f);
+ float a = stage_vertex((int)k), b = stage_vertex((int)k + 1);
+ return a + (b - a) * (f - k);
+}
bool stage_ceiling(float x, float *y) {
if (!stage->ceiling) return false;
- float lift = 0;
- if (stage->ceiling == 2) { /* Mars: tunnels now and then, their roof coming down over 30 m at each end */
- float p = x - TUNNEL_START;
- if (p < -30) return false;
- p = fmodf(p + 30, TUNNEL_EVERY) - 30;
- if (p > TUNNEL_LEN + 30) return false;
- float in = p < 0 ? (p + 30) / 30 : p > TUNNEL_LEN ? (TUNNEL_LEN + 30 - p) / 30 : 1;
- lift = (1 - smoothstep(0, 1, in)) * 40;
- } else if (x < 8) {
- lift = (8 - x) * 0.4f; /* (the cave's mouth over the start) */
- }
- /* over the large hills (the small bumps come closer to it), with its own unevenness */
- float c = hills(x, 0, 2) + stage->clear + stage->clear_var * (0.5f + 0.5f * noise(stage->seed * 7 + 1, x / 13.0f)) +
- 0.35f * noise(stage->seed * 7 + 2, x / 3.1f);
- float f = hills(x, 0, 4) + 2.7f; /* never lower than a vehicle needs */
- *y = (c > f ? c : f) + lift;
+ /* over the highest ground near x (GameContentLayer::getCeilingHeightAt) */
+ float m = stage_deck(x - 2), v;
+ if ((v = stage_deck(x - 0.5f)) > m) m = v;
+ if ((v = stage_deck(x + 0.5f)) > m) m = v;
+ if ((v = stage_deck(x + 2)) > m) m = v;
+ *y = m + cave_height(x);
return true;
}
-/* ------------------------------------------------------------------ trees: in bunches */
-#define TREE_BUNCH 70.0f
-bool stage_tree(int k, float *x) {
- if (stage->feature != FEAT_TREES || k < 0) return false;
- int b = k / 6, i = k % 6;
- int n = 2 + (int)(frnd(stage->seed, 7000u + (uint32_t)b) * 5); /* 2 to 6 trees in a bunch */
- if (i >= n) return false;
- *x = 120.0f + (float)b * TREE_BUNCH + frnd(stage->seed, 7500u + (uint32_t)b) * 20.0f + (float)i * 2.2f;
+float stage_roof_vertex(int k) {
+ int i = k & (VCACHE - 1);
+ if (rkey[i] != k) {
+ float y = 0;
+ stage_ceiling(-40.0f + 0.5f * (float)(k > 0 ? k - 1 : 0), &y);
+ rkey[i] = k, rval[i] = y;
+ }
+ return rval[i];
+}
+
+bool stage_roof(float x, float *y) {
+ if (!stage->ceiling) return false;
+ float f = (x + 40) * 2, k = floorf(f);
+ float a = stage_roof_vertex((int)k), b = stage_roof_vertex((int)k + 1);
+ *y = a + (b - a) * (f - k);
return true;
}
+
+/* ------------------------------------------------------------------ trees: in bunches of 11, 16, 21... */
+static float tr_x[TREES_MAX];
+static int tr_n, tr_count, tr_group;
+static float tr_next;
static uint8_t fallen[TREES_MAX / 8];
+
+static void trees_upto(int k) {
+ while (tr_n <= k && tr_n < TREES_MAX) {
+ float x = tr_next;
+ tr_x[tr_n++] = x;
+ /* the next one: closer and closer within a bunch, 35 m after one */
+ float after = x;
+ if (++tr_count > tr_group * 5 + 10) tr_group++, tr_count = 0, after += 35;
+ float g = (float)tr_group / 15;
+ float gap = (g > 1 ? 1.75f : 2.75f - g) + 0.6f * cosf(1.7521f * x) + 0.6f * sinf(2.157f * x) + 0.75f * cosf(0.56f * x);
+ tr_next = after + (gap < 1 ? 1 : gap);
+ }
+}
+
+bool stage_tree(int k, float *x, float *y) {
+ if (stage->feature != FEAT_TREES || k < 0 || k >= TREES_MAX) return false;
+ trees_upto(k);
+ float tx = tr_x[k];
+ /* none on a bridge */
+ for (int b = stage_bridge_first(tx - 3); stage->bridges; b++) {
+ float x0, len, by;
+ if (!stage_bridge_k(b, &x0, &len, &by) || x0 > tx + 1) break;
+ if (tx + 1 >= x0 && tx - 2 <= x0 + len) return false;
+ }
+ float h = stage_floor(tx), v;
+ if ((v = stage_floor(tx - 0.35f)) < h) h = v;
+ if ((v = stage_floor(tx + 0.35f)) < h) h = v;
+ *x = tx, *y = h - 0.15f;
+ return true;
+}
+
+int stage_tree_first(float x) {
+ if (stage->feature != FEAT_TREES) return 0;
+ int lo = 0, hi = TREES_MAX - 1;
+ trees_upto(hi < 64 ? hi : 64);
+ while (tr_x[tr_n - 1] < x && tr_n < TREES_MAX) trees_upto(tr_n);
+ hi = tr_n - 1;
+ while (lo < hi) {
+ int m = (lo + hi) / 2;
+ if (tr_x[m] < x) lo = m + 1;
+ else hi = m;
+ }
+ return lo;
+}
+
void stage_trees_reset(void) {
for (unsigned i = 0; i < sizeof fallen; i++) fallen[i] = 0;
}
@@ -190,61 +347,75 @@ bool stage_tree_standing(int k) { return k < 0 || k >= TREES_MAX || !(fallen[k >
void stage_tree_fall(int k) {
if (k >= 0 && k < TREES_MAX) fallen[k >> 3] |= (uint8_t)(1 << (k & 7));
}
-int stage_tree_first(float x) {
- int b = (int)((x - 120.0f - 30.0f) / TREE_BUNCH);
- return b < 0 ? 0 : b * 6;
+
+/* ------------------------------------------------------------------ coins 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;
+ if ((v = stage_floor(x + 0.75f)) > h) h = v;
+ if ((v = stage_floor(x - 0.75f)) > h) h = v;
+ return h;
}
-/* ------------------------------------------------------------------ coins */
int stage_coin_group(int k, float *xs, float *ys, int *vals) {
if (k < 1 || k >= COIN_GROUPS) return 0;
- float x = (float)k * COIN_SPACING + 8.0f, d = x;
- int n = 4 + (k > 48 ? 4 : k / 12);
- uint32_t h = hash(stage->seed + 3u, (uint32_t)k);
- int value = d < stage->coin25 ? 5 : d < stage->coin100 ? 25 : d < stage->coin500 ? 100 : 500;
- if (value == 500 && d < stage->all500) {
- float share = (d - stage->coin500) / (stage->all500 - stage->coin500);
- if ((float)(h & 1023) / 1024.0f > share * 0.9f + 0.06f) value = 100;
+ float X = (float)k * COIN_SPACING;
+ int left = (int)(X * stage->coin_mult), n = 0, cols = 0, row = 1;
+ while (left > 0) {
+ int v = left > 500 ? 500 : left > 100 ? 100 : left > 25 ? 25 : left > 5 ? 5 : 0;
+ if (!v) break;
+ int col;
+ if (cols <= 6) col = cols++;
+ else if (row == 1) cols = 1, col = 0, row = 2;
+ else break;
+ float x = X + 4.5f + (float)col * 1.5f;
+ xs[n] = x, ys[n] = coin_floor(x) + ((float)row + stage->coin_off) * 1.5f, vals[n] = v, n++;
+ left -= v;
}
- int rows = (h >> 12) % 5 == 0 && k > 10 ? 2 : 1;
- if (n > 7 && rows == 2) n = 7;
- float cx = x - (n - 1) * 0.42f;
- int m = 0;
- for (int r = 0; r < rows; r++)
- for (int i = 0; i < n; i++) {
- float px = cx + (float)i * 0.84f;
- float g = stage_floor(px), cy = 1.05f + (float)r * 0.84f;
- float top;
- if (stage_ceiling(px, &top) && g + cy > top - 0.5f) cy = (top - g) * 0.5f;
- xs[m] = px, ys[m] = g + cy, vals[m] = value, m++;
+ return n;
+}
+
+/* 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_HIGHWAY: return 5 * n / 4 + 5;
+ case ST_CAVE: return 5 - n % 3;
+ case ST_MARS: return n / 3 + 5;
+ case ST_ALIEN: return 3 * n / 4 + 2;
+ default: return 3;
+ }
+}
+
+#define MAXCAN 512
+static int can_chunk[MAXCAN], can_n, can_scan, can_count, can_dens;
+
+bool stage_fuel(int k, float *x, float *y) {
+ if (k < 0 || k >= MAXCAN) return false;
+ while (can_n <= k && can_scan < COIN_GROUPS) {
+ can_scan++; /* the chunk at 30 can_scan m */
+ can_count = (can_count + 1) % can_dens;
+ if (can_count == 0) {
+ can_chunk[can_n++] = can_scan;
+ can_dens = fuel_density(can_n);
}
- return m;
-}
-
-/* ------------------------------------------------------------------ fuel */
-bool stage_fuel(int k, float *x) {
- if (k < 0 || k > 4000) return false;
- if (stage_id == ST_CAVE) { /* 150 m, 120 m, 90 m, again */
- static const float gaps[3] = {150, 120, 90};
- float p = 0;
- for (int i = 0; i <= k; i++) p += gaps[i % 3];
- *x = p;
- return true;
}
- /* the gaps grow by fuel_grow a can, up to fuel_max: a sum in closed form */
- float g0 = stage->fuel_gap, dg = stage->fuel_grow, gmax = stage->fuel_max;
- int ramp = dg > 0 ? (int)((gmax - g0) / dg) : 0;
- if (ramp < 0) ramp = 0;
- float p;
- if (k <= ramp) p = (float)k * g0 + dg * (float)k * (float)(k + 1) * 0.5f;
- else p = (float)ramp * g0 + dg * (float)ramp * (float)(ramp + 1) * 0.5f + (float)(k - ramp) * gmax;
- *x = stage->fuel_first + p;
+ if (k >= can_n) return false;
+ float cx = (float)can_chunk[k] * COIN_SPACING + 1.5f;
+ *x = cx, *y = coin_floor(cx) + (1 + stage->coin_off) * 1.5f;
return true;
}
/* ------------------------------------------------------------------ levels */
-float stage_level_end(int n) {
- /* each one lvl_inc longer than the last */
- return (float)n * stage->lvl_len + stage->lvl_inc * (float)n * (float)(n - 1) * 0.5f;
+uint32_t stage_level_goal(int n) { return stage->lvl_base + stage->lvl_step * (uint32_t)n; }
+uint32_t stage_level_bonus(int n) { return stage->lvl_mult * stage_level_goal(n) + 2500; }
+
+void stage_set(int s) {
+ stage = &stages[s], stage_id = s;
+ br_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;
}
-uint32_t stage_level_reward(int n) { return stage->lvl_reward + stage->lvl_reward_inc * (uint32_t)(n - 1); }
diff --git a/games/hillclimb/src/stage.h b/games/hillclimb/src/stage.h
index 538a25ac..3d8f9912 100644
--- a/games/hillclimb/src/stage.h
+++ b/games/hillclimb/src/stage.h
@@ -1,13 +1,17 @@
-/* Hill Climb Racing: the stages, their ground and what lies along it.
+/* Hill Climb Racing: the stages, their ground and what lies along it, as the game makes them.
*
- * A stage's ground is the same on every run: a sum of smooth noises (each a Catmull-Rom curve through hashed
- * heights) whose size grows with the distance, so the hills get steeper and bumpier the further you go. Caves
- * have a ceiling; the Desert has rope bridges over canyons, the Forest trees to break through. Coins come every
- * 30 m, fuel cans at the stage's own spacing, and each stretch of the road is a level with its reward. */
+ * 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.
+ * 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
#define HC_STAGE_H
#include <stdbool.h>
#include <stdint.h>
+#ifdef __cplusplus
+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 };
@@ -16,55 +20,60 @@ enum { FEAT_NONE, FEAT_BRIDGES, FEAT_TREES, FEAT_ICICLES };
typedef struct {
const char *name;
uint32_t price;
- float gravity, friction;
+ float gravity, friction; /* the game's: g (m/s2), the ground's friction */
+ float coin_mult, coin_off; /* a coin chunk at x is worth x * coin_mult; coins' rows from coin_off */
uint8_t sky, surf, ground, csurf, icon, particle;
- uint8_t ceiling; /* 0 none, 1 all along (a cave), 2 tunnels now and then */
+ uint8_t ceiling; /* a cave: a ceiling all along */
uint8_t feature, clouds, stars;
- uint32_t seed;
- float len[4], amp0[4], grow[4], amax[4]; /* the noises: wavelength, size at the start, + per km, at most */
- float clear, clear_var; /* a cave's height over its floor */
- float fuel_first, fuel_gap, fuel_grow, fuel_max; /* the first can, the gap, its growth per can, at most */
- float coin25, coin100, coin500, all500; /* where coins of each value start */
- float lvl_len, lvl_inc; /* a level's length and how much longer each next one is */
- uint32_t lvl_reward, lvl_reward_inc;
+ uint8_t bridges; /* rope bridges */
+ float bridge_k, bridge_d; /* the next bridge comes bridge_d (2 + sin(n / bridge_k)) m later */
+ 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) */
} Stage;
extern const Stage stages[NSTAGES];
extern const Stage *stage; /* the stage being driven */
-void stage_set(int s);
+extern int stage_id;
+void stage_set(int s); /* (also forgets what was worked out for the last one) */
-/* the ground under x (meters), what wheels drive on: bridges count */
+/* the ground under x (the game's GameContentLayer::getTerrainHeightAt): under a bridge, the canyon */
float stage_floor(float x);
-/* the ground drawn under x: below a bridge, the canyon's floor */
+/* 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 ceiling over x, if there is one there */
+/* the ground or a bridge's deck 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);
-/* the start: a wall behind it */
-#define STAGE_WALL -6.0f
+float stage_roof_vertex(int k);
+bool stage_roof(float x, float *y);
-/* bridges: the one over x (its ends), or false */
-bool stage_bridge(float x, float *x0, float *x1);
-/* how the bridge under the vehicle gives way: its weight at x (set each frame) */
-void stage_bridge_load(float x, float depth);
+/* bridges: the k-th one (from 0) starts at x0, is len meters long, at height y; false if none */
+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 */
-/* trees: the k-th tree's place (false past the stage's end); broken ones are kept in a bit set */
-bool stage_tree(int k, float *x);
-int stage_tree_first(float x); /* the first tree at or after x */
-#define TREES_MAX 4800
-void stage_trees_reset(void); /* all standing again (a new run) */
+/* 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 */
+#define TREES_MAX 3200
+void stage_trees_reset(void); /* all standing again (a new run) */
bool stage_tree_standing(int k);
void stage_tree_fall(int k);
-#define TREE_H 2.4f
-#define TREE_R 0.16f
+#define TREE_H 3.4f
-/* coins: group k's coins (at most 14); value of a coin; positions */
+/* coins: chunk k (from 1, at 30 k m): at most 14 coins, their places and values; how many */
#define COIN_GROUPS 2048
#define COIN_SPACING 30.0f
-int stage_coin_group(int k, float *x, float *y, int *value); /* how many, their places and values */
-/* fuel cans: the k-th one's x, k from 0; false past the last */
-bool stage_fuel(int k, float *x);
-/* levels: where level n (1, 2...) ends and its reward */
-float stage_level_end(int n);
-uint32_t stage_level_reward(int n);
+#define COIN_SIZE 1.5f /* a coin's side (and a fuel can's): the car picks it up by touching it */
+int stage_coin_group(int k, float *x, float *y, int *value);
+/* fuel cans: the k-th one's place, k from 0; false past the last */
+bool stage_fuel(int k, float *x, float *y);
+/* levels (StageInfo::getLevelGoal, getLevelBonus): where level n (0, 1...) ends, and its bonus */
+uint32_t stage_level_goal(int n);
+uint32_t stage_level_bonus(int n);
+
+#ifdef __cplusplus
+}
+#endif
#endif
diff --git a/games/hillclimb/src/vehicle.c b/games/hillclimb/src/vehicle.c
index ba3eee24..1a7af6b0 100644
--- a/games/hillclimb/src/vehicle.c
+++ b/games/hillclimb/src/vehicle.c
@@ -1,7 +1,6 @@
/* The vehicles (vehicle.h). Their prices, upgrades, the upgrades' last levels and prices are the game's (Hill
- * Climb Racing Wiki); how they drive is tuned to match it: the Hill Climber light and tippy, rear-wheel driven
- * until its 4WD is upgraded; the bike quick to flip; the Monster Truck's big soft wheels; the Race Car fast and low;
- * the Tank slow, heavy and gripping everything. */
+ * 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. */
#include "data.h"
#include "vehicle.h"
@@ -12,32 +11,24 @@ const uint8_t upgrade_icons[NUPKINDS] = {IMG_UP_ENGINE, IMG_UP_SUSPENSION, IMG_U
const VehDef vehicles[NVEHICLES] = {
{"Hill Climber", "Bill's trusty jeep. Upgrade its 4WD to climb anything.", 0, IMG_ICON_JEEP,
- {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AWD}, {13, 14, 16, 10}, {1000, 1000, 1000, 1000},
- 300, 24, {0.02f, 0.38f}, 0.95f, 0.14f, 0.16f, 0.55f, 430, 11.0f, 0, 0.95f, 760, 40, 0},
+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AWD}, {13, 14, 16, 10}, {1000, 1000, 1000, 1000}},
{"Motocross Bike", "Race the hills with this impressive turboed motocross bike.", 75000, IMG_ICON_BIKE,
- {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AIR}, {12, 14, 16, 10}, {1500, 1000, 1000, 3000},
- 150, 14, {-0.05f, 0.55f}, 0.62f, 0.13f, 0.18f, 0.5f, 230, 13.0f, 0, 1.0f, 160, 40, 0},
+ {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},
- 340, 48, {0.0f, 0.45f}, 1.05f, 0.26f, 0.3f, 0.45f, 820, 11.5f, 0, 1.0f, 1100, 40, 0},
+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AWD}, {13, 14, 15, 10}, {1500, 1200, 1200, 1500}},
{"Quad Bike", "4x4 quad bike with almost the same agility as the bike offers you a different ride.", 175000,
- IMG_ICON_QUAD, {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AIR}, {13, 14, 16, 10}, {1500, 1200, 1200, 2500},
- 190, 20, {0.0f, 0.5f}, 0.7f, 0.18f, 0.22f, 0.5f, 300, 12, 1.0f, 1.0f, 260, 40, 0},
+ IMG_ICON_QUAD, {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_AWD}, {13, 14, 16, 10}, {1500, 1200, 1200, 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},
- 270, 18, {0.05f, 0.18f}, 1.05f, 0.06f, 0.08f, 0.6f, 430, 17, 0, 1.05f, 900, 40, 9.0f},
+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_DOWNFORCE}, {12, 14, 16, 12}, {1500, 1500, 1500, 2500}},
{"Rally Car", "Powerful engine and downforce upgraded provide the most ultimate combination for hill climbing.",
750000, IMG_ICON_RALLY, {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_DOWNFORCE}, {14, 14, 17, 10},
- {2000, 2000, 2000, 3000},
- 320, 22, {0.05f, 0.3f}, 1.0f, 0.11f, 0.13f, 0.6f, 560, 16, 0.6f, 1.05f, 1000, 40, 8.0f},
+ {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},
- 260, 22, {0.1f, 0.32f}, 0.95f, 0.17f, 0.22f, 0.5f, 520, 15, 0.8f, 1.15f, 700, 52, 0},
+ {UP_ENGINE, UP_SUSPENSION, UP_TIRES, UP_FUEL}, {15, 15, 15, 20}, {3000, 3000, 3000, 3000}},
{"Tank", "It's a tank!", 1000000, IMG_ICON_TANK,
- {UP_ENGINE, UP_SUSPENSION, UP_TRACKS, UP_FUEL}, {15, 15, 15, 20}, {3000, 3000, 3000, 3000},
- 900, 30, {0.0f, 0.42f}, 1.15f, 0.08f, 0.1f, 0.7f, 520, 8.0f, 1.0f, 1.45f, 2600, 40, 0},
+ {UP_ENGINE, UP_SUSPENSION, UP_TRACKS, UP_FUEL}, {15, 15, 15, 20}, {3000, 3000, 3000, 3000}},
};
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 c13f54ab..13bb2d26 100644
--- a/games/hillclimb/src/vehicle.h
+++ b/games/hillclimb/src/vehicle.h
@@ -1,8 +1,11 @@
-/* Hill Climb Racing: the vehicles, their upgrades and how they drive (car.c). */
+/* Hill Climb Racing: the vehicles and their upgrades (how they drive: car.cpp). */
#ifndef HC_VEHICLE_H
#define HC_VEHICLE_H
#include <stdbool.h>
#include <stdint.h>
+#ifdef __cplusplus
+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 };
@@ -13,18 +16,13 @@ typedef struct {
uint8_t icon;
uint8_t up[4], max[4]; /* its four upgrades and their last levels */
uint16_t cost[4]; /* level L costs cost x L x L coins */
- float mass, wmass; /* the chassis with Bill, each wheel (kg) */
- float com[2]; /* the centre of mass, from the picture's origin (meters) */
- float radius; /* the chassis' radius of gyration (meters) */
- float sag, droop, zeta; /* the springs: how far they settle, how far wheels hang, damping ratio */
- float torque, speed; /* the engine at level 1: the most torque on a wheel (N m), top speed (m/s) */
- float awd; /* torque on the other wheels than the rear (0 to 1) at level 1 */
- float grip, air, fuel; /* tyre grip; turning in the air (N m); seconds of fuel */
- float downforce; /* with the upgrade at its last level: N for 1 (m/s)^2 */
} VehDef;
extern const VehDef vehicles[NVEHICLES];
extern const char *const upgrade_names[NUPKINDS];
extern const uint8_t upgrade_icons[NUPKINDS];
uint32_t upgrade_cost(int v, int u, int level); /* the price of reaching `level` (2 and up) */
+#ifdef __cplusplus
+}
+#endif
#endif
diff --git a/games/hillclimb/tests/play.c b/games/hillclimb/tests/play.c
index ca651311..257eaff3 100644
--- a/games/hillclimb/tests/play.c
+++ b/games/hillclimb/tests/play.c
@@ -46,26 +46,38 @@ static void parse_keys(const char *spec) {
/* a driver: gas, and in the air the pedals to land level with the ground ahead */
static bool flipper; /* --flips: backflips in the air when there is time */
+static float air_rot, last_a, best_x;
+static int stuck, backing, tries;
static uint32_t autopilot(void) {
const Car *c = &run.car;
if (run.over) return 0;
- float x = c->ch.x, slope = atan2f(stage_floor(x + 1.5f) - stage_floor(x - 1.5f), 3.0f);
+ /* stuck at the foot of a hill: back up the last one and take a run at it, as a player would */
+ if (backing && c->ch.x > best_x - 4 - 3 * tries) return backing--, K_LEFT;
+ backing = 0;
+ if (c->ch.x > best_x + 1) best_x = c->ch.x, stuck = 0, tries = 0;
+ else if (++stuck > 90 && run.fuel > 0) { /* (further back each time) */
+ stuck = 0, backing = 45 + 40 * (tries < 4 ? tries++ : tries);
+ return K_LEFT;
+ }
+ air_rot = car_airborne(c) ? air_rot + (c->ch.a - last_a) : 0;
+ last_a = c->ch.a;
+ float x = c->ch.x, slope = atan2f(stage_deck(x + 1.5f) - stage_deck(x - 1.5f), 3.0f);
float a = c->ch.a;
while (a > 3.14159f) a -= 6.28318f;
while (a < -3.14159f) a += 6.28318f;
float d = a - slope;
if (car_airborne(c)) {
- if (flipper && run.air_rot < 2.4f) { /* time left in the air against the turn still to make */
- float h = c->ch.y - stage_floor(c->ch.x), g = stage->gravity, vy = c->ch.vy;
- float left = (vy + sqrtf(vy * vy + 2 * g * (h > 0 ? h : 0))) / g, w = c->ch.w > 2 ? c->ch.w : 2;
- if (left > (6.28f - run.air_rot) / w + 0.25f) return K_RIGHT;
+ if (flipper && air_rot < 2.4f) { /* time left in the air against the turn still to make */
+ float h = c->ch.y - stage_deck(c->ch.x), g = stage->gravity, vy = c->vy;
+ float left = (vy + sqrtf(vy * vy + 2 * g * (h > 0 ? h : 0))) / g, w = c->w > 2 ? c->w : 2;
+ if (left > (6.28f - air_rot) / w + 0.25f) return K_RIGHT;
}
- if (d > 0.25f || (c->ch.w > 1.2f && d > -0.9f)) return K_LEFT;
- if (d < -0.35f) return K_RIGHT;
+ if (d > 0.25f || (c->w > 1.2f && d > -0.9f)) return K_LEFT;
+ if (d < -0.35f || (c->w < -1.2f && d < 0.9f)) return K_RIGHT;
return 0;
}
if (d > 0.6f) return K_LEFT; /* rearing up: a touch of brake brings the nose down */
- if (d > 0.3f && c->ch.w > 0.6f) return 0; /* coming up fast: ease off */
+ if (d > 0.3f && c->w > 0.6f) return 0; /* coming up fast: ease off */
if (car_speed(c) < 0.3f && run.fuel <= 0) return 0;
return K_RIGHT;
}
@@ -100,14 +112,10 @@ int main(int argc, char **argv) {
else if (!strcmp(argv[i], "--trace")) trace = 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, b1, c, f;
- for (float x = 0; x < 2000; x += 1) {
- if (stage_bridge(x, &b0, &b1)) printf("bridge %.0f to %.0f\n", b0, b1), x = b1;
- }
- bool in = false;
- for (float x = 0; x < 2000; x += 1)
- if (stage_ceiling(x, &c) != in) in = !in, printf("ceiling %s at %.0f\n", in ? "starts" : "ends", x);
- for (int k = 0; k < 8 && stage_fuel(k, &f); k++) printf("fuel %.0f\n", f);
+ float b0, len, by, f, fy;
+ for (int k = 0; stage_bridge_k(k, &b0, &len, &by) && b0 < 2000; k++)
+ printf("bridge %.0f to %.0f at %.1f\n", b0, b0 + len, by);
+ for (int k = 0; k < 8 && stage_fuel(k, &f, &fy); k++) printf("fuel %.1f %.1f\n", f, fy);
return 0;
} else if (!strcmp(argv[i], "--slopes")) { /* the steepest slope of each 100 m of a stage, in degrees */
stage_set(atoi(argv[++i]));
@@ -154,8 +162,8 @@ int main(int argc, char **argv) {
host_shot(p);
}
if (trace && f % trace == 0 && (g_mode == MODE_RUN || g_mode == MODE_END))
- printf("f %d x %.1f y %.1f a %.2f v %.1f fuel %.1f air %d head %d dist %.0f coins %u\n", f, run.car.ch.x,
- run.car.ch.y, run.car.ch.a, car_speed(&run.car), run.fuel, car_airborne(&run.car), run.car.head_hit,
+ printf("f %d x %.2f y %.2f a %.3f v %.2f fuel %.1f air %d dead %d dist %.0f coins %u\n", f, run.car.ch.x,
+ run.car.ch.y, run.car.ch.a, car_speed(&run.car), run.fuel, run.car.air, run.car.dead,
run.dist, (unsigned)run_total());
}
printf("END mode %d dist %d coins %u total %u over %d end %d level %d flips %u saved %u running %d\n", g_mode,
diff --git a/games/hillclimb/tools/art.py b/games/hillclimb/tools/art.py
index 47291bbe..68c0c538 100644
--- a/games/hillclimb/tools/art.py
+++ b/games/hillclimb/tools/art.py
@@ -1,47 +1,38 @@
-"""Where everything sits: the vehicles' pictures over their bodies, and how big every picture is kept.
+"""How the vehicles and Bill are drawn over their bodies, as the game draws them.
-Vehicles are measured in the pixels of their chassis picture (x right, y down), as the wiki keeps it; meters come
-from the distance between their first and last axles (`wheelbase`). tools/pack.py turns this into src/art.h, and
-tools/preview.py draws each vehicle put together, to check the numbers."""
+The game puts each picture on its physics body, centred and stretched to a size in meters (its PlayerCar*::create
+and PlayerCar::createDriver call PhysicsSimulation::createSprite(picture, body, width, height)): the chassis'
+picture on the chassis, a wheel's on the wheel (2.15 times its radius square), Bill's head on his head (0.96 m).
+The wiki keeps the same pictures (the same 256 x 128 chassis canvases). tools/pack.py turns this into src/art.h
+(pictures at VPPM pixels a meter, pivots at their centres) and tools/preview.py draws each vehicle put together."""
-# Each vehicle: its chassis picture; its axles (the wheels' centres at rest, in the chassis' pixels); the wheel's
-# picture, the radius of its tyre in that picture and in meters (one per axle when they differ); the distance
-# between the first and last axles in meters; where Bill's hips go (chassis pixels), how he leans (degrees, back)
+# 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)
VEHICLES = [
- dict(id="jeep", name="Hill Climber", chassis="Chassis-hillclimber-red.png",
- axles=[(50, 108), (205, 108)], wheelbase=2.15, wheel="Common_Wheel_-_Type_1.png", wheel_px=31,
- wheel_m=[0.43, 0.43], driver=dict(hips=(120, 62), lean=4)),
- dict(id="bike", name="Motocross Bike", chassis="Bike-motocross.png",
- axles=[(42, 126), (218, 126)], wheelbase=1.85, wheel="Bike-motocross-tire.png", wheel_px=31,
- wheel_m=[0.44, 0.44], driver=dict(hips=(104, 40), lean=-16, legs=True),
- # the swingarm (engine -> rear axle) and fork (handlebar -> front axle), drawn as tubes
- tubes=[((128, 104), 0, 0x5A5E66, 0.09), ((176, 30), 1, 0x30343A, 0.07)]),
- dict(id="monster", name="Monster Truck", chassis="Car-monster.png",
- axles=[(50, 99), (210, 99)], wheelbase=2.55, wheel="Car-monster-tire.png", wheel_px=31,
- wheel_m=[0.62, 0.62], driver=dict(hips=(120, 56), lean=4)),
- dict(id="quad", name="Quad Bike", chassis="Car-quadbike.png",
- axles=[(54, 106), (204, 106)], wheelbase=1.75, wheel="Common_Wheel_-_Type_4.png", wheel_px=62,
- wheel_m=[0.5, 0.5], driver=dict(hips=(116, 32), lean=-12, legs=True)),
- dict(id="race", name="Race Car", chassis="Car-racecar.png",
- axles=[(62, 86), (204, 86)], wheelbase=2.45, wheel="Common_Wheel_-_Type_2.png", wheel_px=31,
- wheel_m=[0.4, 0.4], driver=dict(hips=(126, 68), lean=22)),
- dict(id="rally", name="Rally Car", chassis="Car-rallycar.png",
- axles=[(53, 92), (211, 92)], wheelbase=2.35, wheel="Common_Wheel_-_Type_8.png", wheel_px=31,
- wheel_m=[0.42, 0.42], driver=dict(hips=(130, 62), lean=6)),
- dict(id="buggy", name="Dune Buggy", chassis="Dune_Buggy_Chassis_(Sprite).png",
- axles=[(48, 88), (206, 84)], wheelbase=2.3, wheel="buggy-tire", wheel_px=39,
- wheel_m=[0.52, 0.4], driver=dict(hips=(86, 66), lean=10)),
- dict(id="tank", name="Tank", chassis="Car-tank-fg.png",
- axles=[(40, 96), (84, 102), (128, 102), (172, 102), (216, 96)], wheelbase=3.2, wheel="Car-tank-tire.png",
- wheel_px=31, wheel_m=[0.3] * 5, driver=dict(hips=(130, 44), lean=0),
- # the tracks' base under the hull and the cannon over it: (picture, its pixel on the chassis' (0, 0),
- # its scale to the chassis, in front)
- layers=[("Car-tank-bg.png", (14, 18), 0.92, False), ("Car-tank-cannon.png", (140, -26), 0.42, True)]),
+ 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),
+ dict(id="bike", name="Motocross Bike", chassis="Bike-motocross.png", size=(3.2, 1.6),
+ wheel="Bike-motocross-tire.png", wheel_r=0.5, legs=True,
+ tubes=[((0.0, -0.5), 0, 0x5A5E66, 0.09), ((0.6, 0.425), 1, 0x30343A, 0.07)]),
+ dict(id="monster", name="Monster Truck", chassis="Car-monster.png", size=(4.267, 2.133),
+ wheel="Car-monster-tire.png", wheel_r=0.7),
+ dict(id="quad", name="Quad Bike", chassis="Car-quadbike.png", size=(3.413, 1.707),
+ wheel="Common_Wheel_-_Type_4.png", wheel_r=0.6, legs=True),
+ dict(id="race", name="Race Car", chassis="Car-racecar.png", size=(5.689, 2.844),
+ wheel="Common_Wheel_-_Type_2.png", wheel_r=0.5),
+ dict(id="rally", name="Rally Car", chassis="Car-rallycar.png", size=(4.376, 2.188),
+ wheel="Common_Wheel_-_Type_8.png", wheel_r=0.5),
+ dict(id="buggy", name="Dune Buggy", chassis="Dune_Buggy_Chassis_(Sprite).png", size=(5.12, 2.56),
+ wheel="buggy-tire", wheel_r=0.5, wheel_px=39),
+ 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)]),
]
-# Bill: his head and body pictures and where they join (picture pixels): the base of the neck on the body, the
-# neck under the chin on the head, his hips at the bottom of the body; how big they are (meters, the pictures'
-# heights); his legs on bikes (the leg picture, its hip and its size)
-BILL = dict(head="Driver-head.png", body="Driver-body.png", head_neck=(52, 104), body_neck=(34, 10),
- body_hips=(36, 110), body_m=0.98, head_m=0.84, leg="Bike-driver-leg-full.png", leg_hip=(12, 28),
- leg_m=0.78)
+# 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
+# 0.96 m square picture of 64); his body from his hips (the bottom of his torso, a 0.6 m box) to his neck (its top):
+# the body picture's hips and neck pixels; his legs on bikes (the leg picture, its hip, its height)
+BILL = dict(head="Driver-head.png", head_m=0.855, body="Driver-body.png", body_neck=(34, 10), body_hips=(36, 110),
+ torso_m=0.6, leg="Bike-driver-leg-full.png", leg_hip=(12, 28), leg_m=0.78)
diff --git a/games/hillclimb/tools/pack.py b/games/hillclimb/tools/pack.py
index 4a9f7b76..bf9094ee 100644
--- a/games/hillclimb/tools/pack.py
+++ b/games/hillclimb/tools/pack.py
@@ -11,7 +11,8 @@ data.bin: "HCRD", the number of pictures and fonts, then a table of their offset
from the pen, advance, 3 bytes of 0, offset of its bitmap: u8 u8 s8 s8 u8, u32) and the bitmaps, a byte a pixel: the
letter's coverage in the high 4 bits, its dark outline's in the low 4
-data.h names them (IMG_*, FONT_*); art.h is tools/art.py's vehicles in meters, for src/vehicle.c."""
+data.h names them (IMG_*, FONT_*); art.h is tools/art.py's vehicles in meters, for src/run.c.
+icon(REF) drew src/icon.png once (it is kept as it is now, with NumPlay's corners: tools/round_icons.py)."""
import math
import os
import struct
@@ -32,15 +33,16 @@ VPPM = 44 # pixels a meter the vehicles, Bill and the things on the way are ke
# name, wiki file, crop box or None, how it is sized: ("ppm", source pixels a meter) keeps VPPM pixels a meter;
# ("w", width) or ("h", height) or ("size", w, h) for the menus; pivot ("c": centre, or (x, y) source pixels)
PICTURES = [
- ("COIN5", "Coin5.png", None, ("ppm", 64 / 0.72), "c"),
- ("COIN25", "Coin25.png", None, ("ppm", 64 / 0.72), "c"),
- ("COIN100", "Coin100.png", None, ("ppm", 64 / 0.72), "c"),
- ("COIN500", "Coin500.png", None, ("ppm", 64 / 0.72), "c"),
- ("FUELCAN", "Fuel-canister.png", None, ("ppm", 64 / 0.95), (32, 60)),
+ # coins and fuel cans: 1.5 m squares in the game (Coin::create, FuelCanister::create)
+ ("COIN5", "Coin5.png", None, ("ppm", 64 / 1.5), "c"),
+ ("COIN25", "Coin25.png", None, ("ppm", 64 / 1.5), "c"),
+ ("COIN100", "Coin100.png", None, ("ppm", 64 / 1.5), "c"),
+ ("COIN500", "Coin500.png", None, ("ppm", 64 / 1.5), "c"),
+ ("FUELCAN", "Fuel-canister.png", None, ("ppm", 64 / 1.5), "c"),
("CLOUD", "Sky-cloud.png", None, ("w", 76), "c"),
("TREE_TRUNK", "Lowres-tree-part1.png", None, ("ppm", 64 / 1.3), (32, 31)),
("TREE_TOP", "Lowres-tree-part2.png", None, ("ppm", 64 / 1.9), (32, 31)),
- ("PLANK", "BridgeWoodBlock.png", None, ("ppm", 64 / 1.1), "c"),
+ ("PLANK", "BridgeWoodBlock.png", None, ("ppm", 64 / 1.08), "c"), # (a plank: 1.08 x 0.3 m, its picture 0.59 m high)
("FLAG", "Flag.png", None, ("ppm", 128 / 1.6), (4, 62)),
("ROCKS", "Rocks.png", None, ("ppm", 64 / 1.2), "c"),
("ROCKS_MARS", "Rocks-mars.png", None, ("ppm", 64 / 1.2), "c"),
@@ -220,126 +222,67 @@ def sized(im, how, crop):
def vehicle_pictures(ref):
"""The vehicles' pictures, kept at VPPM pixels a meter, and art.h's tables."""
pics = []
- lines = ["/* Generated by tools/pack.py from tools/art.py: the vehicles put together, in meters. */",
+ lines = ["/* Generated by tools/pack.py from tools/art.py: how the vehicles and Bill are drawn, in meters. */",
"#ifndef HC_ART_H", "#define HC_ART_H", '#include "data.h"', ""]
B = art.BILL
body, head, leg = load(ref, B["body"]), load(ref, B["head"]), load(ref, B["leg"])
- bppm, hppm, lppm = body.height / B["body_m"], head.height / B["head_m"], leg.height / B["leg_m"]
- for name, im, ppm, piv in (("BILL_BODY", body, bppm, B["body_hips"]), ("BILL_HEAD", head, hppm, B["head_neck"]),
+ bppm = math.dist(B["body_neck"], B["body_hips"]) / B["torso_m"]
+ hb = head.getbbox()
+ hppm = (hb[2] - hb[0]) / B["head_m"]
+ lppm = leg.height / B["leg_m"]
+ for name, im, ppm, piv in (("BILL_BODY", body, bppm, B["body_hips"]),
+ ("BILL_HEAD", head, hppm, ((hb[0] + hb[2]) / 2, (hb[1] + hb[3]) / 2)),
("BILL_LEG", leg, lppm, B["leg_hip"])):
k = VPPM / ppm
pics.append((name, premul_resize(im, round(im.width * k), round(im.height * k)), VPPM,
(piv[0] * k, piv[1] * k), False))
- # the neck from the hips (meters, Bill upright, y up); the head's circle from the neck
- neck = ((B["body_neck"][0] - B["body_hips"][0]) / bppm, -(B["body_neck"][1] - B["body_hips"][1]) / bppm)
- hb = np.asarray(head)[..., 3] > 128
- ys, xs = np.nonzero(hb)
- hcx, hcy = (xs.min() + xs.max()) / 2, (ys.min() + ys.max()) / 2
- hr = min(xs.max() - xs.min(), ys.max() - ys.min()) / 2 * 0.86 / hppm
- lines.append(f"#define BILL_NECK_X {neck[0]:.3f}f")
- lines.append(f"#define BILL_NECK_Y {neck[1]:.3f}f")
- lines.append(f"#define BILL_HEAD_X {(hcx - B['head_neck'][0]) / hppm:.3f}f /* the head's centre from the neck */")
- lines.append(f"#define BILL_HEAD_Y {-(hcy - B['head_neck'][1]) / hppm:.3f}f")
- lines.append(f"#define BILL_HEAD_R {hr:.3f}f")
+ # the body picture's neck from its hips, Bill upright (meters, y up)
+ lines.append(f"#define BILL_NECK_X {(B['body_neck'][0] - B['body_hips'][0]) / bppm:.3f}f")
+ lines.append(f"#define BILL_NECK_Y {-(B['body_neck'][1] - B['body_hips'][1]) / bppm:.3f}f")
lines.append("")
lines.append("typedef struct {")
- lines.append(" uint8_t chassis, wheel, naxles, legs, ntubes, nlayers, nhull;")
- lines.append(" float axle[6][2], wheel_r[6]; /* from the chassis' origin: halfway between the first and last axles */")
- lines.append(" float hips[2], lean; /* Bill's hips, and how far he leans back (radians) */")
+ lines.append(" uint8_t chassis, wheel, legs, ntubes, nlayers;")
+ lines.append(" float wheel_r; /* the radius the wheel's picture is drawn for */")
lines.append(" float tube[2][5]; /* from (x, y) to axle (index), colour 0xRRGGBB, radius */")
- lines.append(" float layer[2][4]; /* picture, its pivot's place (x, y), in front (1) or behind */")
- lines.append(" float hull[16][2]; /* the chassis' outline, for the ground to push on */")
+ lines.append(" float layer[2][4]; /* picture, its centre (x, y), in front (1) or behind */")
lines.append("} VehArt;")
lines.append(f"#define NVEH {len(art.VEHICLES)}")
lines.append("static const VehArt veh_art[NVEH] = {")
+ f = lambda x: f"{x:.3f}f" # noqa: E731
+
+ def sized_on(im, size):
+ """A picture stretched to size (meters), at VPPM pixels a meter, pivot at its centre."""
+ w, h = max(1, round(size[0] * VPPM)), max(1, round(size[1] * VPPM))
+ return premul_resize(im, w, h), (w / 2, h / 2)
+
for v in art.VEHICLES:
- ch = load(ref, v["chassis"])
- ax = v["axles"]
- cppm = (ax[-1][0] - ax[0][0]) / v["wheelbase"]
- ox, oy = (ax[0][0] + ax[-1][0]) / 2, ax[0][1]
- k = VPPM / cppm
- cname = "CH_" + v["id"].upper()
- pics.append((cname, premul_resize(ch, round(ch.width * k), round(ch.height * k)), VPPM, (ox * k, oy * k), False))
- m = lambda p: ((p[0] - ox) / cppm, -(p[1] - oy) / cppm) # noqa: E731
- wname = "WHEEL_" + v["id"].upper()
+ cname, wname = "CH_" + v["id"].upper(), "WHEEL_" + v["id"].upper()
+ im, piv = sized_on(load(ref, v["chassis"]), v["size"])
+ pics.append((cname, im, VPPM, piv, False))
wim = load(ref, v["wheel"])
- wppm = v["wheel_px"] / max(v["wheel_m"])
- wk = VPPM / wppm
- pics.append((wname, premul_resize(wim, round(wim.width * wk), round(wim.height * wk)), VPPM,
- (wim.width * wk / 2, wim.height * wk / 2), False))
- # the outline: the convex hull of the chassis' opaque pixels, points along it every 0.35 m
- a = np.asarray(ch)[..., 3] > 140
- pts = np.argwhere(a)[:, ::-1].astype(float)
- hull = convex_hull(pts)
- ring = resample_ring([m(p) for p in hull], 0.4, 16)
+ 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 = 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, at, scale, front) in v.get("layers", []):
- lim = load(ref, lpic)
- lk = k * scale
+ for (lpic, size, at, front) in v.get("layers", []):
lname = "LAYER_" + lpic.split(".")[0].upper().replace("-", "_")
- pics.append((lname, premul_resize(lim, round(lim.width * lk), round(lim.height * lk)), VPPM, (0, 0), False))
- layers.append((lname, m(at), front))
- tubes = []
- for (frm, axi, col, r) in v.get("tubes", []):
- p = m(frm)
- tubes.append((p[0], p[1], axi, col, r))
- d = v["driver"]
- hips = m(d["hips"])
- f = lambda x: f"{x:.3f}f" # noqa: E731
- axs = ", ".join("{" + f(m(p)[0]) + ", " + f(m(p)[1]) + "}" for p in ax)
- rs = ", ".join(f(r) for r in v["wheel_m"])
+ im, piv = sized_on(load(ref, lpic), size)
+ 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", [])]
tb = ", ".join("{" + ", ".join([f(t[0]), f(t[1]), f(t[2]), f"{float(t[3])}f", f(t[4])]) + "}" for t in tubes) or "{0}"
ly = ", ".join("{IMG_" + n + ", " + f(p[0]) + ", " + f(p[1]) + ", " + ("1" if fr else "0") + "}"
for n, p, fr in layers) or "{0}"
- hl = ", ".join("{" + f(x) + ", " + f(y) + "}" for x, y in ring)
- lines.append(f" {{IMG_{cname}, IMG_{wname}, {len(ax)}, {1 if d.get('legs') else 0}, {len(tubes)}, "
- f"{len(layers)}, {len(ring)},")
- lines.append(f" {{{axs}}}, {{{rs}}},")
- lines.append(f" {{{f(hips[0])}, {f(hips[1])}}}, {f(math.radians(d['lean']))}, {{{tb}}}, {{{ly}}},")
- lines.append(f" {{{hl}}}}}, /* {v['name']} */")
+ lines.append(f" {{IMG_{cname}, IMG_{wname}, {1 if v.get('legs') else 0}, {len(tubes)}, {len(layers)}, "
+ f"{f(v['wheel_r'])}, {{{tb}}}, {{{ly}}}}}, /* {v['name']} */")
lines.append("};")
lines.append("#endif")
return pics, lines
-def convex_hull(pts):
- pts = sorted(set(map(tuple, pts)))
- if len(pts) < 3:
- return pts
-
- def cross(o, a, b):
- return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
- lower, upper = [], []
- for p in pts:
- while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
- lower.pop()
- lower.append(p)
- for p in reversed(pts):
- while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
- upper.pop()
- upper.append(p)
- return lower[:-1] + upper[:-1]
-
-
-def resample_ring(ring, step, most):
- """Points along a closed outline about `step` apart, at most `most`, the corners kept first."""
- n = len(ring)
- per = sum(math.dist(ring[i], ring[(i + 1) % n]) for i in range(n))
- count = max(6, min(most, int(per / step)))
- out = []
- for j in range(count):
- t = per * j / count
- for i in range(n):
- seg = math.dist(ring[i], ring[(i + 1) % n])
- if t <= seg:
- a, b = ring[i], ring[(i + 1) % n]
- u = t / seg if seg else 0
- out.append((a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u))
- break
- t -= seg
- return out
-
-
def font_data(ttf, cap, weight, outline):
up = 4
for size in range(6, 400):
@@ -423,7 +366,6 @@ def icon(ref):
def main():
ref = sys.argv[1]
- icon(ref)
pics = []
for name, file, crop, how, pivot in PICTURES:
im, k, ppm = sized(load(ref, file), how, crop)