1
0
mirror of https://github.com/rwengine/openrw.git synced 2024-11-25 20:02:40 +01:00

clang-format files in rwgame/states

This commit is contained in:
Daniel Evans 2016-09-09 21:13:20 +01:00
parent e39ee21ca8
commit a403cc87b7
12 changed files with 1144 additions and 1200 deletions

View File

@ -1,116 +1,102 @@
#include "BenchmarkState.hpp" #include "BenchmarkState.hpp"
#include "RWGame.hpp"
#include <engine/GameState.hpp> #include <engine/GameState.hpp>
#include <fstream> #include <fstream>
#include "RWGame.hpp"
BenchmarkState::BenchmarkState(RWGame* game, const std::string& benchfile) BenchmarkState::BenchmarkState(RWGame* game, const std::string& benchfile)
: State(game) : State(game), benchfile(benchfile), benchmarkTime(0.f), frameCounter(0) {
, benchfile(benchfile)
, benchmarkTime(0.f)
, frameCounter(0)
{
} }
void BenchmarkState::enter() void BenchmarkState::enter() {
{ getWindow().hideCursor();
getWindow().hideCursor();
std::ifstream benchstream(benchfile); std::ifstream benchstream(benchfile);
unsigned int clockHour; unsigned int clockHour;
unsigned int clockMinute; unsigned int clockMinute;
benchstream >> clockHour; benchstream >> clockHour;
benchstream.seekg(1,std::ios_base::cur); benchstream.seekg(1, std::ios_base::cur);
benchstream >> clockMinute; benchstream >> clockMinute;
game->getWorld()->state->basic.gameHour = clockHour; game->getWorld()->state->basic.gameHour = clockHour;
game->getWorld()->state->basic.gameMinute = clockMinute; game->getWorld()->state->basic.gameMinute = clockMinute;
float time = 0.f; float time = 0.f;
glm::vec3 tmpPos; glm::vec3 tmpPos;
while (benchstream) while (benchstream) {
{ TrackPoint point;
TrackPoint point; benchstream >> point.time;
benchstream >> point.time; if (!benchstream) break;
if (!benchstream) break; benchstream >> point.position.x;
benchstream >> point.position.x; if (!benchstream) break;
if (!benchstream) break; benchstream >> point.position.y;
benchstream >> point.position.y; if (!benchstream) break;
if (!benchstream) break; benchstream >> point.position.z;
benchstream >> point.position.z; if (!benchstream) break;
if (!benchstream) break; benchstream >> point.angle.x;
benchstream >> point.angle.x; if (!benchstream) break;
if (!benchstream) break; benchstream >> point.angle.y;
benchstream >> point.angle.y; if (!benchstream) break;
if (!benchstream) break; benchstream >> point.angle.z;
benchstream >> point.angle.z; if (!benchstream) break;
if (!benchstream) break; benchstream >> point.angle.w;
benchstream >> point.angle.w; if (!benchstream) break;
if (!benchstream) break; if (track.size() == 0) {
if (track.size() == 0) { tmpPos = point.position;
tmpPos = point.position; }
} float pointDist = glm::distance(tmpPos, point.position);
float pointDist = glm::distance(tmpPos, point.position); tmpPos = point.position;
tmpPos = point.position; point.time = time + pointDist / 50.f;
point.time = time + pointDist / 50.f; time = point.time;
time = point.time; duration = std::max(duration, point.time);
duration = std::max(duration, point.time); track.push_back(point);
track.push_back(point); }
}
std::cout << "Loaded " << track.size() << " points" << std::endl; std::cout << "Loaded " << track.size() << " points" << std::endl;
} }
void BenchmarkState::exit() void BenchmarkState::exit() {
{ std::cout << "Results =============\n"
std::cout << "Results =============\n" << "Benchmark: " << benchfile << "\n"
<< "Benchmark: " << benchfile << "\n" << "Frames: " << frameCounter << "\n"
<< "Frames: " << frameCounter << "\n" << "Duration: " << duration << " seconds\n"
<< "Duration: " << duration << " seconds\n" << "Avg frametime: " << std::setprecision(3)
<< "Avg frametime: " << std::setprecision(3) << (duration/frameCounter) << (duration / frameCounter) << " (" << (frameCounter / duration)
<< " (" << (frameCounter/duration) << " fps)" << std::endl; << " fps)" << std::endl;
} }
void BenchmarkState::tick(float dt) void BenchmarkState::tick(float dt) {
{ if (track.size() > 0) {
if (track.size() > 0) TrackPoint& a = track.front();
{ TrackPoint& b = track.back();
TrackPoint& a = track.front(); for (TrackPoint& p : track) {
TrackPoint& b = track.back(); if (benchmarkTime < p.time) {
for (TrackPoint& p : track) b = p;
{ break;
if (benchmarkTime < p.time) }
{ a = p;
b = p; }
break; if (benchmarkTime > duration) {
} StateManager::get().exit();
a = p; }
} if (b.time != a.time) {
if (benchmarkTime > duration) { float alpha = (benchmarkTime - a.time) / (b.time - a.time);
StateManager::get().exit(); trackCam.position = glm::mix(a.position, b.position, alpha);
} trackCam.rotation = glm::slerp(a.angle, b.angle, alpha);
if (b.time != a.time) }
{ benchmarkTime += dt;
float alpha = (benchmarkTime - a.time) / (b.time - a.time); }
trackCam.position = glm::mix(a.position, b.position, alpha);
trackCam.rotation = glm::slerp(a.angle, b.angle, alpha);
}
benchmarkTime += dt;
}
} }
void BenchmarkState::draw(GameRenderer* r) void BenchmarkState::draw(GameRenderer* r) {
{ frameCounter++;
frameCounter++; State::draw(r);
State::draw(r);
} }
void BenchmarkState::handleEvent(const SDL_Event& e) void BenchmarkState::handleEvent(const SDL_Event& e) {
{ State::handleEvent(e);
State::handleEvent(e);
} }
const ViewCamera &BenchmarkState::getCamera() const ViewCamera& BenchmarkState::getCamera() {
{ return trackCam;
return trackCam;
} }

View File

@ -3,34 +3,34 @@
#include "State.hpp" #include "State.hpp"
class BenchmarkState : public State class BenchmarkState : public State {
{ struct TrackPoint {
struct TrackPoint { float time;
float time; glm::vec3 position;
glm::vec3 position; glm::quat angle;
glm::quat angle; };
}; std::vector<TrackPoint> track;
std::vector<TrackPoint> track;
ViewCamera trackCam; ViewCamera trackCam;
std::string benchfile; std::string benchfile;
float benchmarkTime;
float duration;
uint32_t frameCounter;
float benchmarkTime;
float duration;
uint32_t frameCounter;
public: public:
BenchmarkState(RWGame* game, const std::string& benchfile); BenchmarkState(RWGame* game, const std::string& benchfile);
virtual void enter(); virtual void enter();
virtual void exit(); virtual void exit();
virtual void tick(float dt); virtual void tick(float dt);
virtual void draw(GameRenderer* r); virtual void draw(GameRenderer* r);
virtual void handleEvent(const SDL_Event& event); virtual void handleEvent(const SDL_Event& event);
const ViewCamera& getCamera(); const ViewCamera& getCamera();
}; };
#endif #endif

View File

@ -1,47 +1,43 @@
#include "DebugState.hpp" #include "DebugState.hpp"
#include "RWGame.hpp"
#include <ai/PlayerController.hpp> #include <ai/PlayerController.hpp>
#include <data/WeaponData.hpp>
#include <engine/GameState.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/string_cast.hpp>
#include <items/InventoryItem.hpp>
#include <objects/CharacterObject.hpp> #include <objects/CharacterObject.hpp>
#include <objects/InstanceObject.hpp> #include <objects/InstanceObject.hpp>
#include <objects/VehicleObject.hpp> #include <objects/VehicleObject.hpp>
#include <engine/GameState.hpp>
#include <items/InventoryItem.hpp>
#include <data/WeaponData.hpp>
#include <sstream> #include <sstream>
#include <glm/gtc/quaternion.hpp> #include "RWGame.hpp"
#include <glm/gtx/string_cast.hpp>
constexpr float kDebugEntryHeight = 14.f; constexpr float kDebugEntryHeight = 14.f;
const glm::vec2 kDebugMenuOffset = glm::vec2(10.f, 50.f); const glm::vec2 kDebugMenuOffset = glm::vec2(10.f, 50.f);
static void jumpCharacter(RWGame* game, CharacterObject* player, const glm::vec3& target, bool ground = true) static void jumpCharacter(RWGame* game, CharacterObject* player,
{ const glm::vec3& target, bool ground = true) {
glm::vec3 newPosition = target; glm::vec3 newPosition = target;
if (ground) { if (ground) {
newPosition = game->getWorld()->getGroundAtPosition(newPosition) + glm::vec3(0.f, 0.f, 1.f); newPosition = game->getWorld()->getGroundAtPosition(newPosition) +
} glm::vec3(0.f, 0.f, 1.f);
if( player ) }
{ if (player) {
if( player->getCurrentVehicle() ) if (player->getCurrentVehicle()) {
{ player->getCurrentVehicle()->setPosition(newPosition);
player->getCurrentVehicle()->setPosition(newPosition); } else {
} player->setPosition(newPosition);
else }
{ }
player->setPosition(newPosition);
}
}
} }
Menu* DebugState::createDebugMenu() Menu* DebugState::createDebugMenu() {
{ CharacterObject* player = nullptr;
CharacterObject* player = nullptr; if (game->getPlayer()) {
if (game->getPlayer()) { player = game->getPlayer()->getCharacter();
player = game->getPlayer()->getCharacter(); }
}
Menu* m = new Menu(2); Menu* m = new Menu(2);
m->offset = kDebugMenuOffset; m->offset = kDebugMenuOffset;
#if 0 #if 0
m->addEntry(Menu::lambda("Random Vehicle", [this] { m->addEntry(Menu::lambda("Random Vehicle", [this] {
auto it = getWorld()->vehicleTypes.begin(); auto it = getWorld()->vehicleTypes.begin();
@ -84,432 +80,414 @@ Menu* DebugState::createDebugMenu()
}, entryHeight)); }, entryHeight));
} }
#endif #endif
m->addEntry(Menu::lambda("Jump to Debug Camera", [=] { m->addEntry(Menu::lambda("Jump to Debug Camera",
jumpCharacter(game, player, _debugCam.position + _debugCam.rotation * glm::vec3(3.f, 0.f, 0.f), false); [=] {
}, kDebugEntryHeight)); jumpCharacter(game, player,
_debugCam.position +
_debugCam.rotation *
glm::vec3(3.f, 0.f, 0.f),
false);
},
kDebugEntryHeight));
m->addEntry(Menu::lambda("-Map", [=] { m->addEntry(Menu::lambda("-Map", [=] { this->enterMenu(createMapMenu()); },
this->enterMenu(createMapMenu()); kDebugEntryHeight));
}, kDebugEntryHeight)); m->addEntry(Menu::lambda("-Vehicles",
m->addEntry(Menu::lambda("-Vehicles", [=] { [=] { this->enterMenu(createVehicleMenu()); },
this->enterMenu(createVehicleMenu()); kDebugEntryHeight));
}, kDebugEntryHeight)); m->addEntry(Menu::lambda("-AI", [=] { this->enterMenu(createAIMenu()); },
m->addEntry(Menu::lambda("-AI", [=] { kDebugEntryHeight));
this->enterMenu(createAIMenu()); m->addEntry(Menu::lambda("-Weapons",
}, kDebugEntryHeight)); [=] { this->enterMenu(createWeaponMenu()); },
m->addEntry(Menu::lambda("-Weapons", [=] { kDebugEntryHeight));
this->enterMenu(createWeaponMenu());
}, kDebugEntryHeight));
m->addEntry(Menu::lambda("Set Super Jump", [=] { m->addEntry(Menu::lambda("Set Super Jump",
player->setJumpSpeed(20.f); [=] { player->setJumpSpeed(20.f); },
}, kDebugEntryHeight)); kDebugEntryHeight));
m->addEntry(Menu::lambda("Set Normal Jump", [=] { m->addEntry(Menu::lambda(
player->setJumpSpeed(CharacterObject::DefaultJumpSpeed); "Set Normal Jump",
}, kDebugEntryHeight)); [=] { player->setJumpSpeed(CharacterObject::DefaultJumpSpeed); },
m->addEntry(Menu::lambda("Full Health", [=] { kDebugEntryHeight));
player->getCurrentState().health = 100.f; m->addEntry(Menu::lambda("Full Health",
}, kDebugEntryHeight)); [=] { player->getCurrentState().health = 100.f; },
m->addEntry(Menu::lambda("Full Armour", [=] { kDebugEntryHeight));
player->getCurrentState().armour = 100.f; m->addEntry(Menu::lambda("Full Armour",
}, kDebugEntryHeight)); [=] { player->getCurrentState().armour = 100.f; },
m->addEntry(Menu::lambda("Cull Here", [=] { kDebugEntryHeight));
game->getRenderer()->setCullOverride(true, _debugCam); m->addEntry(Menu::lambda(
}, kDebugEntryHeight)); "Cull Here",
[=] { game->getRenderer()->setCullOverride(true, _debugCam); },
kDebugEntryHeight));
// Optional block if the player is in a vehicle
auto cv = player->getCurrentVehicle();
if (cv) {
m->addEntry(Menu::lambda(
"Flip vehicle",
[=] {
cv->setRotation(
cv->getRotation() *
glm::quat(glm::vec3(0.f, glm::pi<float>(), 0.f)));
},
kDebugEntryHeight));
}
// Optional block if the player is in a vehicle return m;
auto cv = player->getCurrentVehicle();
if(cv) {
m->addEntry(Menu::lambda("Flip vehicle", [=] {
cv->setRotation(cv->getRotation() * glm::quat(glm::vec3(0.f, glm::pi<float>(), 0.f)));
}, kDebugEntryHeight));
}
return m;
} }
Menu* DebugState::createMapMenu() Menu* DebugState::createMapMenu() {
{ CharacterObject* player = nullptr;
CharacterObject* player = nullptr; if (game->getPlayer()) {
if (game->getPlayer()) { player = game->getPlayer()->getCharacter();
player = game->getPlayer()->getCharacter(); }
}
Menu* m = new Menu(2); Menu* m = new Menu(2);
m->offset = kDebugMenuOffset; m->offset = kDebugMenuOffset;
m->addEntry(Menu::lambda("Back", [=] { m->addEntry(Menu::lambda("Back",
this->enterMenu(createDebugMenu()); [=] { this->enterMenu(createDebugMenu()); },
}, kDebugEntryHeight)); kDebugEntryHeight));
m->addEntry(Menu::lambda("Jump to Docks", [=] { m->addEntry(Menu::lambda(
jumpCharacter(game, player, glm::vec3(1390.f, -837.f, 100.f)); "Jump to Docks",
}, kDebugEntryHeight)); [=] { jumpCharacter(game, player, glm::vec3(1390.f, -837.f, 100.f)); },
m->addEntry(Menu::lambda("Jump to Garage", [=] { kDebugEntryHeight));
jumpCharacter(game, player, glm::vec3(270.f, -605.f, 40.f)); m->addEntry(Menu::lambda(
}, kDebugEntryHeight)); "Jump to Garage",
m->addEntry(Menu::lambda("Jump to Airport", [=] { [=] { jumpCharacter(game, player, glm::vec3(270.f, -605.f, 40.f)); },
jumpCharacter(game, player, glm::vec3(-950.f, -980.f, 12.f)); kDebugEntryHeight));
}, kDebugEntryHeight)); m->addEntry(Menu::lambda(
m->addEntry(Menu::lambda("Jump to Hideout", [=] { "Jump to Airport",
jumpCharacter(game, player, glm::vec3(875.0, -309.0, 100.0)); [=] { jumpCharacter(game, player, glm::vec3(-950.f, -980.f, 12.f)); },
}, kDebugEntryHeight)); kDebugEntryHeight));
m->addEntry(Menu::lambda("Jump to Luigi's", [=] { m->addEntry(Menu::lambda(
jumpCharacter(game, player, glm::vec3(902.75, -425.56, 100.0)); "Jump to Hideout",
}, kDebugEntryHeight)); [=] { jumpCharacter(game, player, glm::vec3(875.0, -309.0, 100.0)); },
m->addEntry(Menu::lambda("Jump to Hospital", [=] { kDebugEntryHeight));
jumpCharacter(game, player, glm::vec3(1123.77, -569.15, 100.0)); m->addEntry(Menu::lambda(
}, kDebugEntryHeight)); "Jump to Luigi's",
m->addEntry(Menu::lambda("Unsolid garage doors", [=] { [=] { jumpCharacter(game, player, glm::vec3(902.75, -425.56, 100.0)); },
kDebugEntryHeight));
m->addEntry(Menu::lambda(
"Jump to Hospital",
[=] {
jumpCharacter(game, player, glm::vec3(1123.77, -569.15, 100.0));
},
kDebugEntryHeight));
m->addEntry(Menu::lambda(
"Unsolid garage doors",
[=] {
std::vector<std::string> garageDoorModels { std::vector<std::string> garageDoorModels{
"8ballsuburbandoor", "8ballsuburbandoor", "amcogaragedoor",
"amcogaragedoor", "bankjobdoor", "bombdoor",
"bankjobdoor", "crushercrush", "crushertop",
"bombdoor", "door2_garage", "door3_garage",
"crushercrush", "door4_garage", "door_bombshop",
"crushertop", "door_col_compnd_01", "door_col_compnd_02",
"door2_garage", "door_col_compnd_03", "door_col_compnd_04",
"door3_garage", "door_col_compnd_05", "door_jmsgrage",
"door4_garage", "door_sfehousegrge", "double_garage_dr",
"door_bombshop", "impex_door", "impexpsubgrgdoor",
"door_col_compnd_01", "ind_plyrwoor", "ind_slidedoor",
"door_col_compnd_02", "jamesgrge_kb", "leveldoor2",
"door_col_compnd_03", "oddjgaragdoor", "plysve_gragedoor",
"door_col_compnd_04", "SalvGarage", "shedgaragedoor",
"door_col_compnd_05", "Sub_sprayshopdoor", "towergaragedoor1",
"door_jmsgrage", "towergaragedoor2", "towergaragedoor3",
"door_sfehousegrge", "vheistlocdoor"};
"double_garage_dr",
"impex_door",
"impexpsubgrgdoor",
"ind_plyrwoor",
"ind_slidedoor",
"jamesgrge_kb",
"leveldoor2",
"oddjgaragdoor",
"plysve_gragedoor",
"SalvGarage",
"shedgaragedoor",
"Sub_sprayshopdoor",
"towergaragedoor1",
"towergaragedoor2",
"towergaragedoor3",
"vheistlocdoor"
};
auto gw = game->getWorld(); auto gw = game->getWorld();
for(auto& i : gw->instancePool.objects) { for (auto& i : gw->instancePool.objects) {
auto obj = static_cast<InstanceObject*>(i.second); auto obj = static_cast<InstanceObject*>(i.second);
if (std::find(garageDoorModels.begin(), garageDoorModels.end(), obj->model->name) != garageDoorModels.end()) { if (std::find(garageDoorModels.begin(), garageDoorModels.end(),
obj->setSolid(false); obj->model->name) != garageDoorModels.end()) {
} obj->setSolid(false);
} }
}, kDebugEntryHeight)); }
},
kDebugEntryHeight));
return m; return m;
} }
Menu* DebugState::createVehicleMenu() Menu* DebugState::createVehicleMenu() {
{ Menu* m = new Menu(2);
Menu* m = new Menu(2); m->offset = kDebugMenuOffset;
m->offset = kDebugMenuOffset;
m->addEntry(Menu::lambda("Back", [=] { m->addEntry(Menu::lambda("Back",
this->enterMenu(createDebugMenu()); [=] { this->enterMenu(createDebugMenu()); },
}, kDebugEntryHeight)); kDebugEntryHeight));
const std::map<std::string, int> kVehicleTypes = { const std::map<std::string, int> kVehicleTypes = {
{"Landstalker", 90}, {"Landstalker", 90}, {"Taxi", 110}, {"Firetruck", 97},
{"Taxi", 110}, {"Police", 116}, {"Ambulance", 106}, {"Bobcat", 112},
{"Firetruck", 97}, {"Banshee", 119}, {"Rhino", 122}, {"Barracks", 123},
{"Police", 116}, {"Rumpo", 130}, {"Columbian", 138}, {"Dodo", 126},
{"Ambulance", 106}, {"Speeder", 142}, {"Yakuza", 136},
{"Bobcat", 112}, };
{"Banshee", 119},
{"Rhino", 122},
{"Barracks", 123},
{"Rumpo", 130},
{"Columbian", 138},
{"Dodo", 126},
{"Speeder", 142},
{"Yakuza", 136},
};
for (auto& e : kVehicleTypes) { for (auto& e : kVehicleTypes) {
m->addEntry(Menu::lambda(e.first, [=] { spawnVehicle(e.second); }, m->addEntry(Menu::lambda(e.first, [=] { spawnVehicle(e.second); },
kDebugEntryHeight)); kDebugEntryHeight));
} }
return m; return m;
} }
Menu* DebugState::createAIMenu() Menu* DebugState::createAIMenu() {
{ Menu* m = new Menu(2);
Menu* m = new Menu(2); m->offset = kDebugMenuOffset;
m->offset = kDebugMenuOffset;
m->addEntry(Menu::lambda("Back", [=] { m->addEntry(Menu::lambda("Back",
this->enterMenu(createDebugMenu()); [=] { this->enterMenu(createDebugMenu()); },
}, kDebugEntryHeight)); kDebugEntryHeight));
const std::map<std::string, int> kPedTypes = { const std::map<std::string, int> kPedTypes = {
{"Triad", 12}, {"Triad", 12}, {"Cop", 1}, {"SWAT", 2},
{"Cop", 1}, {"FBI", 3}, {"Fireman", 6}, {"Construction", 74},
{"SWAT", 2}, };
{"FBI", 3},
{"Fireman", 6},
{"Construction", 74},
};
for (auto& e : kPedTypes) { for (auto& e : kPedTypes) {
m->addEntry(Menu::lambda(e.first + " Follower", [=] { m->addEntry(Menu::lambda(e.first + " Follower",
spawnFollower(e.second); [=] { spawnFollower(e.second); },
}, kDebugEntryHeight)); kDebugEntryHeight));
} }
m->addEntry(Menu::lambda("Kill All Peds", [=] { m->addEntry(Menu::lambda(
for (auto& p : game->getWorld()->pedestrianPool.objects) { "Kill All Peds",
if (p.second->getLifetime() == GameObject::PlayerLifetime) { [=] {
continue; for (auto& p : game->getWorld()->pedestrianPool.objects) {
} if (p.second->getLifetime() == GameObject::PlayerLifetime) {
p.second->takeDamage({p.second->getPosition(), continue;
p.second->getPosition(), 100.f, }
GameObject::DamageInfo::Explosion, 0.f}); p.second->takeDamage({p.second->getPosition(),
} p.second->getPosition(), 100.f,
}, kDebugEntryHeight)); GameObject::DamageInfo::Explosion, 0.f});
return m; }
},
kDebugEntryHeight));
return m;
} }
Menu*DebugState::createWeaponMenu() Menu* DebugState::createWeaponMenu() {
{ Menu* m = new Menu(2);
Menu* m = new Menu(2); m->offset = kDebugMenuOffset;
m->offset = kDebugMenuOffset;
m->addEntry(Menu::lambda("Back", [=] { m->addEntry(Menu::lambda("Back",
this->enterMenu(createDebugMenu()); [=] { this->enterMenu(createDebugMenu()); },
}, kDebugEntryHeight)); kDebugEntryHeight));
for (int i = 1; i < maxInventorySlots; ++i) { for (int i = 1; i < maxInventorySlots; ++i) {
auto item = getWorld()->getInventoryItem(i); auto item = getWorld()->getInventoryItem(i);
auto& name = getWorld()->data->weaponData[i]->name; auto& name = getWorld()->data->weaponData[i]->name;
m->addEntry(Menu::lambda(name, [=] { m->addEntry(
giveItem(item); Menu::lambda(name, [=] { giveItem(item); }, kDebugEntryHeight));
}, kDebugEntryHeight)); }
}
return m; return m;
} }
DebugState::DebugState(RWGame* game, const glm::vec3& vp, const glm::quat& vd) DebugState::DebugState(RWGame* game, const glm::vec3& vp, const glm::quat& vd)
: State(game) : State(game), _invertedY(game->getConfig().getInputInvertY()) {
, _invertedY(game->getConfig().getInputInvertY()) this->enterMenu(createDebugMenu());
{
this->enterMenu(createDebugMenu());
_debugCam.position = vp; _debugCam.position = vp;
_debugCam.rotation = vd; _debugCam.rotation = vd;
} }
void DebugState::enter() void DebugState::enter() {
{ getWindow().showCursor();
getWindow().showCursor();
} }
void DebugState::exit() void DebugState::exit() {
{
} }
void DebugState::tick(float dt) void DebugState::tick(float dt) {
{ /*if(debugObject) {
/*if(debugObject) { auto p = debugObject->getPosition();
auto p = debugObject->getPosition(); ss << "Position: " << p.x << " " << p.y << " " << p.z << std::endl;
ss << "Position: " << p.x << " " << p.y << " " << p.z << std::endl; ss << "Health: " << debugObject->mHealth << std::endl;
ss << "Health: " << debugObject->mHealth << std::endl; if(debugObject->model) {
if(debugObject->model) { auto m = debugObject->model;
auto m = debugObject->model; ss << "Textures: " << std::endl;
ss << "Textures: " << std::endl; for(auto it = m->geometries.begin(); it != m->geometries.end();
for(auto it = m->geometries.begin(); it != m->geometries.end(); ++it )
++it ) {
{ auto g = *it;
auto g = *it; for(auto itt = g->materials.begin(); itt != g->materials.end();
for(auto itt = g->materials.begin(); itt != g->materials.end(); ++itt)
++itt) {
{ for(auto tit = itt->textures.begin(); tit !=
for(auto tit = itt->textures.begin(); tit != itt->textures.end(); itt->textures.end();
++tit) ++tit)
{ {
ss << " " << tit->name << std::endl; ss << " " << tit->name << std::endl;
} }
} }
} }
} }
if(debugObject->type() == GameObject::Vehicle) { if(debugObject->type() == GameObject::Vehicle) {
GTAVehicle* vehicle = static_cast<GTAVehicle*>(debugObject); GTAVehicle* vehicle = static_cast<GTAVehicle*>(debugObject);
ss << "ID: " << vehicle->info->handling.ID << std::endl; ss << "ID: " << vehicle->info->handling.ID << std::endl;
} }
}*/ }*/
if (_freeLook) { if (_freeLook) {
_debugCam.rotation = glm::angleAxis(_debugLook.x, glm::vec3(0.f, 0.f, 1.f)) _debugCam.rotation =
* glm::angleAxis(_debugLook.y, glm::vec3(0.f, 1.f, 0.f)); glm::angleAxis(_debugLook.x, glm::vec3(0.f, 0.f, 1.f)) *
glm::angleAxis(_debugLook.y, glm::vec3(0.f, 1.f, 0.f));
_debugCam.position += _debugCam.rotation * _movement * dt * (_sonicMode ? 500.f : 50.f); _debugCam.position +=
} _debugCam.rotation * _movement * dt * (_sonicMode ? 500.f : 50.f);
}
} }
void DebugState::draw(GameRenderer* r) void DebugState::draw(GameRenderer* r) {
{ // Draw useful information like camera position.
// Draw useful information like camera position. std::stringstream ss;
std::stringstream ss; ss << "Camera Position: " << glm::to_string(_debugCam.position);
ss << "Camera Position: " << glm::to_string(_debugCam.position);
TextRenderer::TextInfo ti; TextRenderer::TextInfo ti;
ti.text = GameStringUtil::fromString(ss.str()); ti.text = GameStringUtil::fromString(ss.str());
ti.font = 2; ti.font = 2;
ti.screenPosition = glm::vec2( 10.f, 10.f ); ti.screenPosition = glm::vec2(10.f, 10.f);
ti.size = 15.f; ti.size = 15.f;
ti.baseColour = glm::u8vec3(255); ti.baseColour = glm::u8vec3(255);
r->text.renderText(ti); r->text.renderText(ti);
State::draw(r); State::draw(r);
} }
void DebugState::handleEvent(const SDL_Event& event) void DebugState::handleEvent(const SDL_Event& event) {
{ switch (event.type) {
switch(event.type) { case SDL_KEYDOWN:
case SDL_KEYDOWN: switch (event.key.keysym.sym) {
switch(event.key.keysym.sym) { case SDLK_ESCAPE:
case SDLK_ESCAPE: StateManager::get().exit();
StateManager::get().exit(); break;
break; case SDLK_w:
case SDLK_w: _movement.x = 1.f;
_movement.x = 1.f; break;
break; case SDLK_s:
case SDLK_s: _movement.x = -1.f;
_movement.x =-1.f; break;
break; case SDLK_a:
case SDLK_a: _movement.y = 1.f;
_movement.y = 1.f; break;
break; case SDLK_d:
case SDLK_d: _movement.y = -1.f;
_movement.y =-1.f; break;
break; case SDLK_f:
case SDLK_f: _freeLook = !_freeLook;
_freeLook = !_freeLook; if (_freeLook)
if (_freeLook) getWindow().hideCursor();
getWindow().hideCursor(); else
else getWindow().showCursor();
getWindow().showCursor(); break;
break; case SDLK_p:
case SDLK_p: printCameraDetails();
printCameraDetails(); break;
break; case SDLK_LSHIFT:
case SDLK_LSHIFT: _sonicMode = true;
_sonicMode = true; break;
break; default:
default: break; break;
} }
break; break;
case SDL_KEYUP: case SDL_KEYUP:
switch(event.key.keysym.sym) { switch (event.key.keysym.sym) {
case SDLK_w: case SDLK_w:
case SDLK_s: case SDLK_s:
_movement.x = 0.f; _movement.x = 0.f;
break; break;
case SDLK_a: case SDLK_a:
case SDLK_d: case SDLK_d:
_movement.y = 0.f; _movement.y = 0.f;
break; break;
case SDLK_LSHIFT: case SDLK_LSHIFT:
_sonicMode = false; _sonicMode = false;
break; break;
default: break; default:
} break;
}
break; break;
case SDL_MOUSEMOTION: case SDL_MOUSEMOTION:
if (game->hasFocus()) if (game->hasFocus()) {
{ glm::ivec2 screenSize = getWindow().getSize();
glm::ivec2 screenSize = getWindow().getSize(); glm::vec2 mouseMove(
glm::vec2 mouseMove(event.motion.xrel / static_cast<float>(screenSize.x), event.motion.xrel / static_cast<float>(screenSize.x),
event.motion.yrel / static_cast<float>(screenSize.y)); event.motion.yrel / static_cast<float>(screenSize.y));
if (!_invertedY) if (!_invertedY) mouseMove.y = -mouseMove.y;
mouseMove.y = -mouseMove.y;
_debugLook.x -= mouseMove.x; _debugLook.x -= mouseMove.x;
float qpi = glm::half_pi<float>(); float qpi = glm::half_pi<float>();
_debugLook.y -= glm::clamp(mouseMove.y, -qpi, qpi); _debugLook.y -= glm::clamp(mouseMove.y, -qpi, qpi);
} }
break; break;
default: break; default:
} break;
State::handleEvent(event); }
State::handleEvent(event);
} }
void DebugState::printCameraDetails() void DebugState::printCameraDetails() {
{ std::cout << " " << _debugCam.position.x << " " << _debugCam.position.y
std::cout << " " << _debugCam.position.x << " " << _debugCam.position.y << " " << _debugCam.position.z << " " << _debugCam.position.z << " " << _debugCam.rotation.x
<< " " << _debugCam.rotation.x << " " << _debugCam.rotation.y << " " << _debugCam.rotation.z << " " << _debugCam.rotation.y << " " << _debugCam.rotation.z
<< " " << _debugCam.rotation.w << std::endl; << " " << _debugCam.rotation.w << std::endl;
} }
void DebugState::spawnVehicle(unsigned int id) void DebugState::spawnVehicle(unsigned int id) {
{ auto ch = game->getPlayer()->getCharacter();
auto ch = game->getPlayer()->getCharacter(); if (!ch) return;
if (!ch)
return;
auto playerRot = ch->getRotation(); auto playerRot = ch->getRotation();
auto spawnPos = ch->getPosition(); auto spawnPos = ch->getPosition();
spawnPos += playerRot * glm::vec3(0.f, 3.f, 0.f); spawnPos += playerRot * glm::vec3(0.f, 3.f, 0.f);
auto spawnRot = glm::quat( auto spawnRot = glm::quat(
glm::vec3(0.f, 0.f, glm::roll(playerRot) + glm::half_pi<float>())); glm::vec3(0.f, 0.f, glm::roll(playerRot) + glm::half_pi<float>()));
getWorld()->createVehicle(id, spawnPos, spawnRot); getWorld()->createVehicle(id, spawnPos, spawnRot);
} }
void DebugState::spawnFollower(unsigned int id) void DebugState::spawnFollower(unsigned int id) {
{ auto ch = game->getPlayer()->getCharacter();
auto ch = game->getPlayer()->getCharacter(); if (!ch) return;
if(! ch) return;
glm::vec3 fwd = ch->rotation * glm::vec3(0.f, 1.f, 0.f); glm::vec3 fwd = ch->rotation * glm::vec3(0.f, 1.f, 0.f);
glm::vec3 hit, normal; glm::vec3 hit, normal;
if(game->hitWorldRay(ch->position + (fwd * 10.f), {0.f, 0.f, -2.f}, hit, normal)) { if (game->hitWorldRay(ch->position + (fwd * 10.f), {0.f, 0.f, -2.f}, hit,
auto spawnPos = hit + normal; normal)) {
auto follower = game->getWorld()->createPedestrian(id, spawnPos); auto spawnPos = hit + normal;
jumpCharacter(game, follower, spawnPos); auto follower = game->getWorld()->createPedestrian(id, spawnPos);
follower->controller->setGoal(CharacterController::FollowLeader); jumpCharacter(game, follower, spawnPos);
follower->controller->setTargetCharacter(ch); follower->controller->setGoal(CharacterController::FollowLeader);
} follower->controller->setTargetCharacter(ch);
}
} }
void DebugState::giveItem(InventoryItem* item) void DebugState::giveItem(InventoryItem* item) {
{ CharacterObject* player = nullptr;
CharacterObject* player = nullptr; if (game->getPlayer()) {
if (game->getPlayer()) { player = game->getPlayer()->getCharacter();
player = game->getPlayer()->getCharacter(); }
}
if (player) { if (player) {
player->addToInventory(item); player->addToInventory(item);
auto& wep = auto& wep = player->getCurrentState().weapons[item->getInventorySlot()];
player->getCurrentState().weapons[item->getInventorySlot()]; wep.bulletsTotal = 100;
wep.bulletsTotal = 100; wep.bulletsClip = 0;
wep.bulletsClip = 0; }
}
} }
const ViewCamera &DebugState::getCamera() const ViewCamera& DebugState::getCamera() {
{ return _debugCam;
return _debugCam;
} }

View File

@ -3,39 +3,39 @@
#include "State.hpp" #include "State.hpp"
class DebugState : public State class DebugState : public State {
{ ViewCamera _debugCam;
ViewCamera _debugCam; glm::vec3 _movement;
glm::vec3 _movement; glm::vec2 _debugLook;
glm::vec2 _debugLook; bool _freeLook = false;
bool _freeLook = false; bool _sonicMode = false;
bool _sonicMode = false; bool _invertedY;
bool _invertedY;
Menu* createDebugMenu(); Menu* createDebugMenu();
Menu* createMapMenu(); Menu* createMapMenu();
Menu* createVehicleMenu(); Menu* createVehicleMenu();
Menu* createAIMenu(); Menu* createAIMenu();
Menu* createWeaponMenu(); Menu* createWeaponMenu();
public: public:
DebugState(RWGame* game, const glm::vec3& vp = {}, const glm::quat& vd = {}); DebugState(RWGame* game, const glm::vec3& vp = {},
const glm::quat& vd = {});
virtual void enter(); virtual void enter();
virtual void exit(); virtual void exit();
virtual void tick(float dt); virtual void tick(float dt);
virtual void draw(GameRenderer* r); virtual void draw(GameRenderer* r);
virtual void handleEvent(const SDL_Event& event); virtual void handleEvent(const SDL_Event& event);
void printCameraDetails(); void printCameraDetails();
void spawnVehicle(unsigned int id); void spawnVehicle(unsigned int id);
void spawnFollower(unsigned int id); void spawnFollower(unsigned int id);
void giveItem(InventoryItem* item); void giveItem(InventoryItem* item);
const ViewCamera& getCamera(); const ViewCamera& getCamera();
}; };
#endif // DEBUGSTATE_HPP #endif // DEBUGSTATE_HPP

View File

@ -1,20 +1,20 @@
#include "IngameState.hpp" #include "IngameState.hpp"
#include "RWGame.hpp"
#include "PauseState.hpp"
#include "DebugState.hpp" #include "DebugState.hpp"
#include "DrawUI.hpp" #include "DrawUI.hpp"
#include "PauseState.hpp"
#include "RWGame.hpp"
#include <ai/PlayerController.hpp> #include <ai/PlayerController.hpp>
#include <objects/CharacterObject.hpp>
#include <objects/VehicleObject.hpp>
#include <objects/ItemPickup.hpp>
#include <dynamics/CollisionInstance.hpp>
#include <data/Model.hpp> #include <data/Model.hpp>
#include <items/WeaponItem.hpp> #include <dynamics/CollisionInstance.hpp>
#include <engine/GameWorld.hpp>
#include <engine/GameState.hpp>
#include <script/ScriptMachine.hpp>
#include <dynamics/RaycastCallbacks.hpp> #include <dynamics/RaycastCallbacks.hpp>
#include <engine/GameState.hpp>
#include <engine/GameWorld.hpp>
#include <items/WeaponItem.hpp>
#include <objects/CharacterObject.hpp>
#include <objects/ItemPickup.hpp>
#include <objects/VehicleObject.hpp>
#include <script/ScriptMachine.hpp>
#include <glm/gtc/constants.hpp> #include <glm/gtc/constants.hpp>
#include <unordered_map> #include <unordered_map>
@ -23,517 +23,507 @@ constexpr float kAutoLookTime = 2.f;
constexpr float kAutolookMinVelocity = 0.2f; constexpr float kAutolookMinVelocity = 0.2f;
const float kMaxRotationRate = glm::half_pi<float>(); const float kMaxRotationRate = glm::half_pi<float>();
const float kCameraPitchLimit = glm::quarter_pi<float>() * 0.5f; const float kCameraPitchLimit = glm::quarter_pi<float>() * 0.5f;
const float kVehicleCameraPitch = glm::half_pi<float>() - glm::quarter_pi<float>() * 0.25f; const float kVehicleCameraPitch =
glm::half_pi<float>() - glm::quarter_pi<float>() * 0.25f;
// Hardcoded Controls SDLK_* -> GameInputState::Control // Hardcoded Controls SDLK_* -> GameInputState::Control
const std::unordered_multimap<int, GameInputState::Control> kDefaultControls = { const std::unordered_multimap<int, GameInputState::Control> kDefaultControls = {
/* On Foot */ /* On Foot */
{ SDLK_LCTRL, GameInputState::FireWeapon }, {SDLK_LCTRL, GameInputState::FireWeapon},
{ SDLK_KP_0, GameInputState::FireWeapon }, {SDLK_KP_0, GameInputState::FireWeapon},
{ SDLK_KP_ENTER, GameInputState::NextWeapon }, {SDLK_KP_ENTER, GameInputState::NextWeapon},
{ SDLK_KP_PERIOD, GameInputState::LastWeapon }, {SDLK_KP_PERIOD, GameInputState::LastWeapon},
{ SDLK_w, GameInputState::GoForward }, {SDLK_w, GameInputState::GoForward},
{ SDLK_UP, GameInputState::GoForward }, {SDLK_UP, GameInputState::GoForward},
{ SDLK_s, GameInputState::GoBackwards }, {SDLK_s, GameInputState::GoBackwards},
{ SDLK_DOWN, GameInputState::GoBackwards }, {SDLK_DOWN, GameInputState::GoBackwards},
{ SDLK_a, GameInputState::GoLeft }, {SDLK_a, GameInputState::GoLeft},
{ SDLK_LEFT, GameInputState::GoLeft }, {SDLK_LEFT, GameInputState::GoLeft},
{ SDLK_d, GameInputState::GoRight }, {SDLK_d, GameInputState::GoRight},
{ SDLK_RIGHT, GameInputState::GoRight }, {SDLK_RIGHT, GameInputState::GoRight},
{ SDLK_PAGEUP, GameInputState::ZoomIn }, {SDLK_PAGEUP, GameInputState::ZoomIn},
{ SDLK_z, GameInputState::ZoomIn }, {SDLK_z, GameInputState::ZoomIn},
{ SDLK_PAGEDOWN, GameInputState::ZoomOut }, {SDLK_PAGEDOWN, GameInputState::ZoomOut},
{ SDLK_x, GameInputState::ZoomOut }, {SDLK_x, GameInputState::ZoomOut},
{ SDLK_f, GameInputState::EnterExitVehicle }, {SDLK_f, GameInputState::EnterExitVehicle},
{ SDLK_RETURN, GameInputState::EnterExitVehicle }, {SDLK_RETURN, GameInputState::EnterExitVehicle},
{ SDLK_c, GameInputState::ChangeCamera }, {SDLK_c, GameInputState::ChangeCamera},
{ SDLK_HOME, GameInputState::ChangeCamera }, {SDLK_HOME, GameInputState::ChangeCamera},
{ SDLK_RCTRL, GameInputState::Jump }, {SDLK_RCTRL, GameInputState::Jump},
{ SDLK_SPACE, GameInputState::Jump }, {SDLK_SPACE, GameInputState::Jump},
{ SDLK_LSHIFT, GameInputState::Sprint }, {SDLK_LSHIFT, GameInputState::Sprint},
{ SDLK_RSHIFT, GameInputState::Sprint }, {SDLK_RSHIFT, GameInputState::Sprint},
{ SDLK_LALT, GameInputState::Walk }, {SDLK_LALT, GameInputState::Walk},
{ SDLK_DELETE, GameInputState::AimWeapon }, {SDLK_DELETE, GameInputState::AimWeapon},
{ SDLK_CAPSLOCK, GameInputState::LookBehind }, {SDLK_CAPSLOCK, GameInputState::LookBehind},
/* In Vehicle */ /* In Vehicle */
{ SDLK_LCTRL, GameInputState::VehicleFireWeapon }, {SDLK_LCTRL, GameInputState::VehicleFireWeapon},
{ SDLK_a, GameInputState::VehicleLeft }, {SDLK_a, GameInputState::VehicleLeft},
{ SDLK_LEFT, GameInputState::VehicleLeft }, {SDLK_LEFT, GameInputState::VehicleLeft},
{ SDLK_d, GameInputState::VehicleRight }, {SDLK_d, GameInputState::VehicleRight},
{ SDLK_RIGHT, GameInputState::VehicleRight }, {SDLK_RIGHT, GameInputState::VehicleRight},
{ SDLK_w, GameInputState::VehicleAccelerate }, {SDLK_w, GameInputState::VehicleAccelerate},
{ SDLK_UP, GameInputState::VehicleAccelerate }, {SDLK_UP, GameInputState::VehicleAccelerate},
{ SDLK_d, GameInputState::VehicleBrake }, {SDLK_d, GameInputState::VehicleBrake},
{ SDLK_DOWN, GameInputState::VehicleBrake }, {SDLK_DOWN, GameInputState::VehicleBrake},
{ SDLK_INSERT, GameInputState::ChangeRadio }, {SDLK_INSERT, GameInputState::ChangeRadio},
{ SDLK_r, GameInputState::ChangeRadio }, {SDLK_r, GameInputState::ChangeRadio},
{ SDLK_LSHIFT, GameInputState::Horn }, {SDLK_LSHIFT, GameInputState::Horn},
{ SDLK_RSHIFT, GameInputState::Horn }, {SDLK_RSHIFT, GameInputState::Horn},
{ SDLK_KP_PLUS, GameInputState::Submission }, {SDLK_KP_PLUS, GameInputState::Submission},
{ SDLK_CAPSLOCK, GameInputState::Submission }, {SDLK_CAPSLOCK, GameInputState::Submission},
{ SDLK_RCTRL, GameInputState::Handbrake }, {SDLK_RCTRL, GameInputState::Handbrake},
{ SDLK_SPACE, GameInputState::Handbrake }, {SDLK_SPACE, GameInputState::Handbrake},
{ SDLK_KP_9, GameInputState::VehicleAimUp }, {SDLK_KP_9, GameInputState::VehicleAimUp},
{ SDLK_KP_2, GameInputState::VehicleAimDown }, {SDLK_KP_2, GameInputState::VehicleAimDown},
{ SDLK_KP_4, GameInputState::VehicleAimLeft }, {SDLK_KP_4, GameInputState::VehicleAimLeft},
{ SDLK_KP_6, GameInputState::VehicleAimRight }, {SDLK_KP_6, GameInputState::VehicleAimRight},
{ SDLK_KP_9, GameInputState::VehicleDown }, {SDLK_KP_9, GameInputState::VehicleDown},
{ SDLK_KP_2, GameInputState::VehicleUp }, {SDLK_KP_2, GameInputState::VehicleUp},
{ SDLK_KP_1, GameInputState::LookLeft }, {SDLK_KP_1, GameInputState::LookLeft},
{ SDLK_q, GameInputState::LookLeft }, {SDLK_q, GameInputState::LookLeft},
{ SDLK_KP_2, GameInputState::LookRight }, {SDLK_KP_2, GameInputState::LookRight},
{ SDLK_e, GameInputState::LookRight }, {SDLK_e, GameInputState::LookRight},
}; };
IngameState::IngameState(RWGame* game, bool newgame, const std::string& save) IngameState::IngameState(RWGame* game, bool newgame, const std::string& save)
: State(game) : State(game)
, started(false) , started(false)
, save(save) , save(save)
, newgame(newgame) , newgame(newgame)
, autolookTimer(0.f) , autolookTimer(0.f)
, camMode(IngameState::CAMERA_NORMAL) , camMode(IngameState::CAMERA_NORMAL)
, m_cameraAngles { 0.f, glm::half_pi<float>() } , m_cameraAngles{0.f, glm::half_pi<float>()}
, m_invertedY(game->getConfig().getInputInvertY()) , m_invertedY(game->getConfig().getInputInvertY())
, m_vehicleFreeLook(true) , m_vehicleFreeLook(true) {
{
} }
void IngameState::startTest() void IngameState::startTest() {
{ auto playerChar = getWorld()->createPlayer({270.f, -605.f, 40.f});
auto playerChar = getWorld()->createPlayer({270.f, -605.f, 40.f});
getWorld()->state->playerObject = playerChar->getGameObjectID(); getWorld()->state->playerObject = playerChar->getGameObjectID();
glm::vec3 itemspawn(276.5f, -609.f, 36.5f); glm::vec3 itemspawn(276.5f, -609.f, 36.5f);
for (int i = 1; i < maxInventorySlots; ++i) { for (int i = 1; i < maxInventorySlots; ++i) {
auto item = getWorld()->getInventoryItem(i); auto item = getWorld()->getInventoryItem(i);
getWorld()->createPickup(itemspawn, item->getModelID(), getWorld()->createPickup(itemspawn, item->getModelID(),
PickupObject::OnStreet); PickupObject::OnStreet);
itemspawn.x += 2.5f; itemspawn.x += 2.5f;
} }
auto carPos = glm::vec3( 286.f, -591.f, 37.f ); auto carPos = glm::vec3(286.f, -591.f, 37.f);
auto carRot = glm::angleAxis(glm::radians(90.f), glm::vec3(0.f, 0.f, 1.f)); auto carRot = glm::angleAxis(glm::radians(90.f), glm::vec3(0.f, 0.f, 1.f));
//auto boatPos = glm::vec3( -1000.f, -1040.f, 5.f ); // auto boatPos = glm::vec3( -1000.f, -1040.f, 5.f );
int i = 0; int i = 0;
for( auto& vi : getWorld()->data->objectTypes ) { for (auto& vi : getWorld()->data->objectTypes) {
switch( vi.first ) { switch (vi.first) {
case 140: continue; case 140:
case 141: continue; continue;
} case 141:
if( vi.second->class_type == ObjectInformation::_class("CARS") ) continue;
{ }
if ( i++ > 20 ) break; if (vi.second->class_type == ObjectInformation::_class("CARS")) {
auto vehicle = std::static_pointer_cast<VehicleData>(vi.second); if (i++ > 20) break;
auto vehicle = std::static_pointer_cast<VehicleData>(vi.second);
auto& sp = carPos; auto& sp = carPos;
auto& sr = carRot; auto& sr = carRot;
auto v = getWorld()->createVehicle(vi.first, sp, sr); auto v = getWorld()->createVehicle(vi.first, sp, sr);
sp += sr * glm::vec3( 2.f + v->info->handling.dimensions.x, 0.f, 0.f); sp +=
} sr * glm::vec3(2.f + v->info->handling.dimensions.x, 0.f, 0.f);
} }
}
} }
void IngameState::startGame() void IngameState::startGame() {
{ game->startScript("data/main.scm");
game->startScript("data/main.scm"); game->getScript()->startThread(0);
game->getScript()->startThread(0); getWorld()->sound.playBackground(getWorld()->data->getDataPath() +
getWorld()->sound.playBackground( getWorld()->data->getDataPath() + "/audio/City.wav" ); "/audio/City.wav");
} }
void IngameState::enter() void IngameState::enter() {
{ if (!started) {
if( ! started ) if (newgame) {
{ if (save.empty()) {
if( newgame )
{
if( save.empty() )
{
startGame(); startGame();
} else if (save == "test") {
startTest();
} else {
game->loadGame(save);
} }
else if( save == "test" ) }
{ started = true;
startTest(); }
}
else {
game->loadGame( save );
}
}
started = true;
}
getWindow().hideCursor(); getWindow().hideCursor();
} }
void IngameState::exit() void IngameState::exit() {
{
} }
void IngameState::tick(float dt) void IngameState::tick(float dt) {
{ auto world = getWorld();
auto world = getWorld(); autolookTimer = std::max(autolookTimer - dt, 0.f);
autolookTimer = std::max(autolookTimer - dt, 0.f);
// Update displayed money value // Update displayed money value
// @todo the game uses another algorithm which is non-linear // @todo the game uses another algorithm which is non-linear
{ {
float moneyFrequency = 1.0f / 30.0f; float moneyFrequency = 1.0f / 30.0f;
moneyTimer += dt; moneyTimer += dt;
while (moneyTimer >= moneyFrequency) { while (moneyTimer >= moneyFrequency) {
int32_t difference = world->state->playerInfo.money - world->state->playerInfo.displayedMoney; int32_t difference = world->state->playerInfo.money -
world->state->playerInfo.displayedMoney;
// Generates 0, 1 (difference < 100), 12 (difference < 1000), 123 (difference < 10000), .. etc. // Generates 0, 1 (difference < 100), 12 (difference < 1000), 123
// Negative input will result in negative output // (difference < 10000), .. etc.
auto GetIncrement = [](int32_t difference) -> int32_t { // Negative input will result in negative output
// @todo is this correct for difference >= 1000000000 ? auto GetIncrement = [](int32_t difference) -> int32_t {
int32_t r = 1; // @todo is this correct for difference >= 1000000000 ?
int32_t i = 2; int32_t r = 1;
if (difference == 0) { return 0; } int32_t i = 2;
while (std::abs(difference) >= 100) { if (difference == 0) {
difference /= 10; return 0;
r = r * 10 + i; }
i++; while (std::abs(difference) >= 100) {
} difference /= 10;
return (difference < 0) ? -r : r; r = r * 10 + i;
}; i++;
world->state->playerInfo.displayedMoney += GetIncrement(difference); }
return (difference < 0) ? -r : r;
};
world->state->playerInfo.displayedMoney += GetIncrement(difference);
moneyTimer -= moneyFrequency; moneyTimer -= moneyFrequency;
} }
} }
auto player = game->getPlayer(); auto player = game->getPlayer();
const auto& input = world->state->input; const auto& input = world->state->input;
if( player && player->isInputEnabled() ) if (player && player->isInputEnabled()) {
{ float viewDistance = 4.f;
float viewDistance = 4.f; switch (camMode) {
switch( camMode ) case IngameState::CAMERA_CLOSE:
{ viewDistance = 2.f;
case IngameState::CAMERA_CLOSE: break;
viewDistance = 2.f; case IngameState::CAMERA_NORMAL:
break; viewDistance = 4.0f;
case IngameState::CAMERA_NORMAL: break;
viewDistance = 4.0f; case IngameState::CAMERA_FAR:
break; viewDistance = 6.f;
case IngameState::CAMERA_FAR: break;
viewDistance = 6.f; case IngameState::CAMERA_TOPDOWN:
break; viewDistance = 15.f;
case IngameState::CAMERA_TOPDOWN: break;
viewDistance = 15.f; default:
break; viewDistance = 4.f;
default: }
viewDistance = 4.f;
}
auto target = world->pedestrianPool.find(world->state->cameraTarget);
if( target == nullptr ) auto target = world->pedestrianPool.find(world->state->cameraTarget);
{
target = player->getCharacter();
}
glm::vec3 targetPosition = target->getPosition(); if (target == nullptr) {
glm::vec3 lookTargetPosition = targetPosition; target = player->getCharacter();
targetPosition += glm::vec3(0.f, 0.f, 1.f); }
lookTargetPosition += glm::vec3(0.f, 0.f, 0.5f);
btCollisionObject* physTarget = player->getCharacter()->physObject; glm::vec3 targetPosition = target->getPosition();
glm::vec3 lookTargetPosition = targetPosition;
targetPosition += glm::vec3(0.f, 0.f, 1.f);
lookTargetPosition += glm::vec3(0.f, 0.f, 0.5f);
auto vehicle = ( target->type() == GameObject::Character ) ? static_cast<CharacterObject*>(target)->getCurrentVehicle() : nullptr; btCollisionObject* physTarget = player->getCharacter()->physObject;
if( vehicle ) {
auto model = vehicle->model;
float maxDist = 0.f;
for(auto& g : model->resource->geometries) {
float partSize = glm::length(g->geometryBounds.center) + g->geometryBounds.radius;
maxDist = std::max(partSize, maxDist);
}
viewDistance = viewDistance + maxDist;
targetPosition = vehicle->getPosition();
lookTargetPosition = targetPosition;
lookTargetPosition.z += (vehicle->info->handling.dimensions.z * 0.5f);
targetPosition.z += (vehicle->info->handling.dimensions.z * 0.5f);
physTarget = vehicle->collision->getBulletBody();
if (!m_vehicleFreeLook) auto vehicle =
{ (target->type() == GameObject::Character)
m_cameraAngles.y = kVehicleCameraPitch; ? static_cast<CharacterObject*>(target)->getCurrentVehicle()
} : nullptr;
if (vehicle) {
auto model = vehicle->model;
float maxDist = 0.f;
for (auto& g : model->resource->geometries) {
float partSize = glm::length(g->geometryBounds.center) +
g->geometryBounds.radius;
maxDist = std::max(partSize, maxDist);
}
viewDistance = viewDistance + maxDist;
targetPosition = vehicle->getPosition();
lookTargetPosition = targetPosition;
lookTargetPosition.z +=
(vehicle->info->handling.dimensions.z * 0.5f);
targetPosition.z += (vehicle->info->handling.dimensions.z * 0.5f);
physTarget = vehicle->collision->getBulletBody();
// Rotate the camera to the ideal angle if the player isn't moving it if (!m_vehicleFreeLook) {
float velocity = vehicle->getVelocity(); m_cameraAngles.y = kVehicleCameraPitch;
if (autolookTimer <= 0.f && glm::abs(velocity) > kAutolookMinVelocity) }
{
auto idealYaw = -glm::roll(vehicle->getRotation()) + glm::half_pi<float>();
const auto idealPitch = kVehicleCameraPitch;
if (velocity < 0.f) {
idealYaw = glm::mod(idealYaw - glm::pi<float>(), glm::pi<float>() * 2.f);
}
float currentYaw = glm::mod(m_cameraAngles.x, glm::pi<float>()*2);
float currentPitch = m_cameraAngles.y;
float deltaYaw = idealYaw - currentYaw;
float deltaPitch = idealPitch - currentPitch;
if (glm::abs(deltaYaw) > glm::pi<float>()) {
deltaYaw -= glm::sign(deltaYaw) * glm::pi<float>()*2.f;
}
m_cameraAngles.x += glm::sign(deltaYaw) * std::min(kMaxRotationRate * dt, glm::abs(deltaYaw));
m_cameraAngles.y += glm::sign(deltaPitch) * std::min(kMaxRotationRate * dt, glm::abs(deltaPitch));
}
}
// Non-topdown camera can orbit // Rotate the camera to the ideal angle if the player isn't moving
if( camMode != IngameState::CAMERA_TOPDOWN ) // it
{ float velocity = vehicle->getVelocity();
bool lookleft = input.pressed(GameInputState::LookLeft); if (autolookTimer <= 0.f &&
bool lookright = input.pressed(GameInputState::LookRight); glm::abs(velocity) > kAutolookMinVelocity) {
if ((lookleft || lookright) && vehicle != nullptr) { auto idealYaw =
auto rotation = vehicle->getRotation(); -glm::roll(vehicle->getRotation()) + glm::half_pi<float>();
if (! lookright) { const auto idealPitch = kVehicleCameraPitch;
rotation *= glm::angleAxis(glm::half_pi<float>(), glm::vec3(0.f, 0.f,-1.f)); if (velocity < 0.f) {
} idealYaw = glm::mod(idealYaw - glm::pi<float>(),
else if (! lookleft) { glm::pi<float>() * 2.f);
rotation *= glm::angleAxis(glm::half_pi<float>(), glm::vec3(0.f, 0.f, 1.f)); }
} float currentYaw =
cameraPosition = targetPosition + rotation * glm::vec3(0.f, viewDistance, 0.f); glm::mod(m_cameraAngles.x, glm::pi<float>() * 2);
} float currentPitch = m_cameraAngles.y;
else { float deltaYaw = idealYaw - currentYaw;
// Determine the "ideal" camera position for the current view float deltaPitch = idealPitch - currentPitch;
// angles if (glm::abs(deltaYaw) > glm::pi<float>()) {
auto yaw = deltaYaw -= glm::sign(deltaYaw) * glm::pi<float>() * 2.f;
glm::angleAxis(m_cameraAngles.x, glm::vec3(0.f, 0.f, -1.f)); }
auto pitch = m_cameraAngles.x +=
glm::angleAxis(m_cameraAngles.y, glm::vec3(0.f, 1.f, 0.f)); glm::sign(deltaYaw) *
auto cameraOffset = std::min(kMaxRotationRate * dt, glm::abs(deltaYaw));
yaw * pitch * glm::vec3(0.f, 0.f, viewDistance); m_cameraAngles.y +=
cameraPosition = targetPosition + cameraOffset; glm::sign(deltaPitch) *
} std::min(kMaxRotationRate * dt, glm::abs(deltaPitch));
} }
else }
{
cameraPosition = targetPosition + glm::vec3(0.f, 0.f, viewDistance);
}
glm::quat angle; // Non-topdown camera can orbit
if (camMode != IngameState::CAMERA_TOPDOWN) {
bool lookleft = input.pressed(GameInputState::LookLeft);
bool lookright = input.pressed(GameInputState::LookRight);
if ((lookleft || lookright) && vehicle != nullptr) {
auto rotation = vehicle->getRotation();
if (!lookright) {
rotation *= glm::angleAxis(glm::half_pi<float>(),
glm::vec3(0.f, 0.f, -1.f));
} else if (!lookleft) {
rotation *= glm::angleAxis(glm::half_pi<float>(),
glm::vec3(0.f, 0.f, 1.f));
}
cameraPosition = targetPosition +
rotation * glm::vec3(0.f, viewDistance, 0.f);
} else {
// Determine the "ideal" camera position for the current view
// angles
auto yaw =
glm::angleAxis(m_cameraAngles.x, glm::vec3(0.f, 0.f, -1.f));
auto pitch =
glm::angleAxis(m_cameraAngles.y, glm::vec3(0.f, 1.f, 0.f));
auto cameraOffset =
yaw * pitch * glm::vec3(0.f, 0.f, viewDistance);
cameraPosition = targetPosition + cameraOffset;
}
} else {
cameraPosition = targetPosition + glm::vec3(0.f, 0.f, viewDistance);
}
auto camtotarget = targetPosition - cameraPosition; glm::quat angle;
auto dir = glm::normalize(camtotarget);
float correction = glm::length(camtotarget) - viewDistance;
if( correction < 0.f )
{
float innerDist = viewDistance * 0.1f;
correction = glm::min(0.f, correction + innerDist);
}
cameraPosition += dir * 10.f * correction * dt;
auto lookdir = glm::normalize(lookTargetPosition - cameraPosition); auto camtotarget = targetPosition - cameraPosition;
// Calculate the yaw to look at the target. auto dir = glm::normalize(camtotarget);
float angleYaw = glm::atan(lookdir.y, lookdir.x); float correction = glm::length(camtotarget) - viewDistance;
angle = glm::quat( glm::vec3(0.f, 0.f, angleYaw) ); if (correction < 0.f) {
glm::vec3 movement; float innerDist = viewDistance * 0.1f;
correction = glm::min(0.f, correction + innerDist);
}
cameraPosition += dir * 10.f * correction * dt;
movement.x = input[GameInputState::GoForward] - input[GameInputState::GoBackwards]; auto lookdir = glm::normalize(lookTargetPosition - cameraPosition);
movement.y = input[GameInputState::GoLeft] - input[GameInputState::GoRight]; // Calculate the yaw to look at the target.
/// @todo replace with correct sprint behaviour float angleYaw = glm::atan(lookdir.y, lookdir.x);
float speed = input.pressed(GameInputState::Sprint) ? 2.f : 1.f; angle = glm::quat(glm::vec3(0.f, 0.f, angleYaw));
glm::vec3 movement;
if( player->isInputEnabled() ) movement.x = input[GameInputState::GoForward] -
{ input[GameInputState::GoBackwards];
player->setRunning(!input.pressed(GameInputState::Walk)); movement.y =
/// @todo find the correct behaviour for entering & exiting input[GameInputState::GoLeft] - input[GameInputState::GoRight];
if (input.pressed(GameInputState::EnterExitVehicle)) { /// @todo replace with correct sprint behaviour
/// @todo move me float speed = input.pressed(GameInputState::Sprint) ? 2.f : 1.f;
if (player->getCharacter()->getCurrentVehicle()) {
player->exitVehicle();
}
else if (!player->isCurrentActivity(
Activities::EnterVehicle::ActivityName)) {
player->enterNearestVehicle();
}
}
else if (glm::length2(movement) > 0.001f) {
if (player->isCurrentActivity(
Activities::EnterVehicle::ActivityName)) {
// Give up entering a vehicle if we're alreadying doing so
player->skipActivity();
}
}
if (player->getCharacter()->getCurrentVehicle()) if (player->isInputEnabled()) {
{ player->setRunning(!input.pressed(GameInputState::Walk));
auto vehicle = player->getCharacter()->getCurrentVehicle(); /// @todo find the correct behaviour for entering & exiting
vehicle->setHandbraking(input.pressed(GameInputState::Handbrake)); if (input.pressed(GameInputState::EnterExitVehicle)) {
player->setMoveDirection(movement); /// @todo move me
} if (player->getCharacter()->getCurrentVehicle()) {
else player->exitVehicle();
{ } else if (!player->isCurrentActivity(
if (input.pressed(GameInputState::Jump)) { Activities::EnterVehicle::ActivityName)) {
player->jump(); player->enterNearestVehicle();
} }
} else if (glm::length2(movement) > 0.001f) {
if (player->isCurrentActivity(
Activities::EnterVehicle::ActivityName)) {
// Give up entering a vehicle if we're alreadying doing so
player->skipActivity();
}
}
float length = glm::length(movement); if (player->getCharacter()->getCurrentVehicle()) {
float movementAngle = angleYaw - glm::half_pi<float>(); auto vehicle = player->getCharacter()->getCurrentVehicle();
if (length > 0.1f) vehicle->setHandbraking(
{ input.pressed(GameInputState::Handbrake));
glm::vec3 direction = glm::normalize(movement); player->setMoveDirection(movement);
movementAngle += atan2(direction.y, direction.x); } else {
player->setMoveDirection(glm::vec3(speed, 0.f, 0.f)); if (input.pressed(GameInputState::Jump)) {
} player->jump();
else }
{
player->setMoveDirection(glm::vec3(0.f));
}
player->setLookDirection({movementAngle, 0.f});
}
}
else
{
player->setMoveDirection(glm::vec3(0.f));
}
float len2d = glm::length(glm::vec2(lookdir)); float length = glm::length(movement);
float anglePitch = glm::atan(lookdir.z, len2d); float movementAngle = angleYaw - glm::half_pi<float>();
angle *= glm::quat( glm::vec3(0.f, -anglePitch, 0.f) ); if (length > 0.1f) {
glm::vec3 direction = glm::normalize(movement);
movementAngle += atan2(direction.y, direction.x);
player->setMoveDirection(glm::vec3(speed, 0.f, 0.f));
} else {
player->setMoveDirection(glm::vec3(0.f));
}
player->setLookDirection({movementAngle, 0.f});
}
} else {
player->setMoveDirection(glm::vec3(0.f));
}
// Use rays to ensure target is visible from cameraPosition float len2d = glm::length(glm::vec2(lookdir));
auto rayEnd = cameraPosition; float anglePitch = glm::atan(lookdir.z, len2d);
auto rayStart = targetPosition; angle *= glm::quat(glm::vec3(0.f, -anglePitch, 0.f));
auto to = btVector3(rayEnd.x, rayEnd.y, rayEnd.z);
auto from = btVector3(rayStart.x, rayStart.y, rayStart.z);
ClosestNotMeRayResultCallback ray(physTarget, from, to);
world->dynamicsWorld->rayTest(from, to, ray); // Use rays to ensure target is visible from cameraPosition
if( ray.hasHit() && ray.m_closestHitFraction < 1.f ) auto rayEnd = cameraPosition;
{ auto rayStart = targetPosition;
cameraPosition = glm::vec3(ray.m_hitPointWorld.x(), ray.m_hitPointWorld.y(), auto to = btVector3(rayEnd.x, rayEnd.y, rayEnd.z);
ray.m_hitPointWorld.z()); auto from = btVector3(rayStart.x, rayStart.y, rayStart.z);
cameraPosition += glm::vec3(ray.m_hitNormalWorld.x(), ray.m_hitNormalWorld.y(), ClosestNotMeRayResultCallback ray(physTarget, from, to);
ray.m_hitNormalWorld.z()) * 0.1f;
}
_look.position = cameraPosition; world->dynamicsWorld->rayTest(from, to, ray);
_look.rotation = angle; if (ray.hasHit() && ray.m_closestHitFraction < 1.f) {
} cameraPosition =
glm::vec3(ray.m_hitPointWorld.x(), ray.m_hitPointWorld.y(),
ray.m_hitPointWorld.z());
cameraPosition +=
glm::vec3(ray.m_hitNormalWorld.x(), ray.m_hitNormalWorld.y(),
ray.m_hitNormalWorld.z()) *
0.1f;
}
_look.position = cameraPosition;
_look.rotation = angle;
}
} }
void IngameState::draw(GameRenderer* r) void IngameState::draw(GameRenderer* r) {
{ if (!getWorld()->state->isCinematic && getWorld()->isCutsceneDone()) {
if( !getWorld()->state->isCinematic && getWorld()->isCutsceneDone() ) drawHUD(_look, game->getPlayer(), getWorld(), r);
{ }
drawHUD(_look, game->getPlayer(), getWorld(), r);
}
State::draw(r); State::draw(r);
} }
void IngameState::handleEvent(const SDL_Event& event) void IngameState::handleEvent(const SDL_Event& event) {
{ auto player = game->getPlayer();
auto player = game->getPlayer();
switch(event.type) { switch (event.type) {
case SDL_KEYDOWN: case SDL_KEYDOWN:
switch(event.key.keysym.sym) { switch (event.key.keysym.sym) {
case SDLK_ESCAPE: case SDLK_ESCAPE:
StateManager::get().enter(new PauseState(game)); StateManager::get().enter(new PauseState(game));
break; break;
case SDLK_m: case SDLK_m:
StateManager::get().enter(new DebugState(game, _look.position, _look.rotation)); StateManager::get().enter(
break; new DebugState(game, _look.position, _look.rotation));
case SDLK_SPACE: break;
if( getWorld()->state->currentCutscene ) case SDLK_SPACE:
{ if (getWorld()->state->currentCutscene) {
getWorld()->state->skipCutscene = true; getWorld()->state->skipCutscene = true;
} }
break; break;
case SDLK_c: case SDLK_c:
camMode = CameraMode((camMode+(CameraMode)1)%CAMERA_MAX); camMode =
break; CameraMode((camMode + (CameraMode)1) % CAMERA_MAX);
default: break; break;
} default:
break; break;
default: break; }
} break;
default:
break;
}
updateInputState(event); updateInputState(event);
if( player && player->isInputEnabled() ) if (player && player->isInputEnabled()) {
{ handlePlayerInput(event);
handlePlayerInput(event); }
} State::handleEvent(event);
State::handleEvent(event);
} }
void IngameState::handlePlayerInput(const SDL_Event& event) void IngameState::handlePlayerInput(const SDL_Event& event) {
{ auto player = game->getPlayer();
auto player = game->getPlayer(); switch (event.type) {
switch(event.type) { case SDL_MOUSEBUTTONDOWN:
switch (event.button.button) {
case SDL_BUTTON_LEFT:
player->getCharacter()->useItem(true, true);
break;
default:
break;
}
break;
case SDL_MOUSEBUTTONUP:
switch (event.button.button) {
case SDL_BUTTON_LEFT:
player->getCharacter()->useItem(false, true);
break;
default:
break;
}
break;
case SDL_MOUSEWHEEL:
player->getCharacter()->cycleInventory(event.wheel.y > 0);
break;
case SDL_MOUSEMOTION:
if (game->hasFocus()) {
glm::ivec2 screenSize = getWindow().getSize();
glm::vec2 mouseMove(
event.motion.xrel / static_cast<float>(screenSize.x),
event.motion.yrel / static_cast<float>(screenSize.y));
case SDL_MOUSEBUTTONDOWN: autolookTimer = kAutoLookTime;
switch(event.button.button) { if (!m_invertedY) {
case SDL_BUTTON_LEFT: mouseMove.y = -mouseMove.y;
player->getCharacter()->useItem(true, true); }
break; m_cameraAngles += glm::vec2(mouseMove.x, mouseMove.y);
default: break; m_cameraAngles.y =
} glm::clamp(m_cameraAngles.y, kCameraPitchLimit,
break; glm::pi<float>() - kCameraPitchLimit);
case SDL_MOUSEBUTTONUP: }
switch(event.button.button) { break;
case SDL_BUTTON_LEFT: default:
player->getCharacter()->useItem(false, true); break;
break; }
default: break;
}
break;
case SDL_MOUSEWHEEL:
player->getCharacter()->cycleInventory(event.wheel.y > 0);
break;
case SDL_MOUSEMOTION:
if (game->hasFocus())
{
glm::ivec2 screenSize = getWindow().getSize();
glm::vec2 mouseMove(event.motion.xrel / static_cast<float>(screenSize.x),
event.motion.yrel / static_cast<float>(screenSize.y));
autolookTimer = kAutoLookTime;
if (!m_invertedY) {
mouseMove.y = -mouseMove.y;
}
m_cameraAngles += glm::vec2(mouseMove.x, mouseMove.y);
m_cameraAngles.y = glm::clamp(m_cameraAngles.y, kCameraPitchLimit, glm::pi<float>() - kCameraPitchLimit);
}
break;
default:
break;
}
} }
void IngameState::updateInputState(const SDL_Event& event) void IngameState::updateInputState(const SDL_Event& event) {
{ switch (event.type) {
switch (event.type) { case SDL_KEYDOWN:
case SDL_KEYDOWN: case SDL_KEYUP: {
case SDL_KEYUP: { auto sym = event.key.keysym.sym;
auto sym = event.key.keysym.sym; auto level = event.type == SDL_KEYDOWN ? 1.f : 0.f;
auto level = event.type == SDL_KEYDOWN ? 1.f : 0.f; auto& levels = getWorld()->state->input.currentLevels;
auto& levels = getWorld()->state->input.currentLevels;
auto range = kDefaultControls.equal_range(sym); auto range = kDefaultControls.equal_range(sym);
for (auto it = range.first; it != range.second; ++it) { for (auto it = range.first; it != range.second; ++it) {
levels[it->second] = level; levels[it->second] = level;
} }
} break; } break;
} }
} }
bool IngameState::shouldWorldUpdate() {
bool IngameState::shouldWorldUpdate()
{
return true; return true;
} }
const ViewCamera &IngameState::getCamera() const ViewCamera& IngameState::getCamera() {
{ return _look;
return _look;
} }

View File

@ -5,35 +5,33 @@
class PlayerController; class PlayerController;
class IngameState : public State class IngameState : public State {
{ enum CameraMode {
enum CameraMode CAMERA_CLOSE = 0,
{ CAMERA_NORMAL = 1,
CAMERA_CLOSE = 0, CAMERA_FAR = 2,
CAMERA_NORMAL = 1, CAMERA_TOPDOWN = 3,
CAMERA_FAR = 2, /** Used for counting - not a valid camera mode */
CAMERA_TOPDOWN = 3, CAMERA_MAX
/** Used for counting - not a valid camera mode */ };
CAMERA_MAX
};
bool started; bool started;
std::string save; std::string save;
bool newgame; bool newgame;
ViewCamera _look; ViewCamera _look;
glm::vec3 cameraPosition; glm::vec3 cameraPosition;
/** Timer to hold user camera position */ /** Timer to hold user camera position */
float autolookTimer; float autolookTimer;
CameraMode camMode; CameraMode camMode;
/// Current camera yaw and pitch /// Current camera yaw and pitch
glm::vec2 m_cameraAngles; glm::vec2 m_cameraAngles;
/// Invert Y axis movement /// Invert Y axis movement
bool m_invertedY; bool m_invertedY;
/// Free look in vehicles. /// Free look in vehicles.
bool m_vehicleFreeLook; bool m_vehicleFreeLook;
float moneyTimer; // Timer used to updated displayed money value float moneyTimer; // Timer used to updated displayed money value
public: public:
/** /**
* @brief IngameState * @brief IngameState
@ -41,24 +39,25 @@ public:
* @param newgame * @param newgame
* @param game An empty string, a save game to load, or the string "test". * @param game An empty string, a save game to load, or the string "test".
*/ */
IngameState(RWGame* game, bool newgame = true, const std::string& save = ""); IngameState(RWGame* game, bool newgame = true,
const std::string& save = "");
void startTest(); void startTest();
void startGame(); void startGame();
virtual void enter(); virtual void enter();
virtual void exit(); virtual void exit();
virtual void tick(float dt); virtual void tick(float dt);
virtual void draw(GameRenderer* r); virtual void draw(GameRenderer* r);
virtual void handleEvent(const SDL_Event& event); virtual void handleEvent(const SDL_Event& event);
virtual void handlePlayerInput(const SDL_Event& event); virtual void handlePlayerInput(const SDL_Event& event);
void updateInputState(const SDL_Event& event); void updateInputState(const SDL_Event& event);
virtual bool shouldWorldUpdate(); virtual bool shouldWorldUpdate();
const ViewCamera& getCamera(); const ViewCamera& getCamera();
}; };
#endif // INGAMESTATE_HPP #endif // INGAMESTATE_HPP

View File

@ -1,57 +1,47 @@
#include "LoadingState.hpp" #include "LoadingState.hpp"
#include "RWGame.hpp"
#include <render/OpenGLRenderer.hpp> #include <render/OpenGLRenderer.hpp>
#include "RWGame.hpp"
LoadingState::LoadingState(RWGame* game) LoadingState::LoadingState(RWGame* game) : State(game), next(nullptr) {
: State(game), next(nullptr)
{
} }
void LoadingState::enter() void LoadingState::enter() {
{ game->newGame();
game->newGame();
} }
void LoadingState::exit() void LoadingState::exit() {
{
} }
void LoadingState::tick(float dt) void LoadingState::tick(float dt) {
{ RW_UNUSED(dt);
RW_UNUSED(dt);
// If background work is completed, switch to the next state // If background work is completed, switch to the next state
if( getWorld()->_work->isEmpty() ) { if (getWorld()->_work->isEmpty()) {
StateManager::get().exec(next); StateManager::get().exec(next);
} }
} }
bool LoadingState::shouldWorldUpdate() bool LoadingState::shouldWorldUpdate() {
{ return false;
return false;
} }
void LoadingState::setNextState(State* nextState) void LoadingState::setNextState(State* nextState) {
{ next = nextState;
next = nextState;
} }
void LoadingState::handleEvent(const SDL_Event& e) void LoadingState::handleEvent(const SDL_Event& e) {
{ State::handleEvent(e);
State::handleEvent(e);
} }
void LoadingState::draw(GameRenderer* r) void LoadingState::draw(GameRenderer* r) {
{ static auto kLoadingString = GameStringUtil::fromString("Loading...");
static auto kLoadingString = GameStringUtil::fromString("Loading..."); // Display some manner of loading screen.
// Display some manner of loading screen. TextRenderer::TextInfo ti;
TextRenderer::TextInfo ti; ti.text = kLoadingString;
ti.text = kLoadingString; auto size = r->getRenderer()->getViewport();
auto size = r->getRenderer()->getViewport(); ti.size = 25.f;
ti.size = 25.f; ti.screenPosition = glm::vec2(50.f, size.y - ti.size - 50.f);
ti.screenPosition = glm::vec2( 50.f, size.y - ti.size - 50.f ); ti.font = 2;
ti.font = 2; ti.baseColour = glm::u8vec3(255);
ti.baseColour = glm::u8vec3(255); r->text.renderText(ti);
r->text.renderText(ti);
} }

View File

@ -3,24 +3,24 @@
#include "State.hpp" #include "State.hpp"
class LoadingState : public State class LoadingState : public State {
{ State* next;
State* next;
public: public:
LoadingState(RWGame* game); LoadingState(RWGame* game);
virtual void enter(); virtual void enter();
virtual void exit(); virtual void exit();
virtual void tick(float dt); virtual void tick(float dt);
virtual void draw(GameRenderer* r); virtual void draw(GameRenderer* r);
void setNextState(State* nextState);
void setNextState(State* nextState);
virtual bool shouldWorldUpdate(); virtual bool shouldWorldUpdate();
virtual void handleEvent(const SDL_Event& event); virtual void handleEvent(const SDL_Event& event);
}; };
#endif // LOADINGSTATE_HPP #endif // LOADINGSTATE_HPP

View File

@ -1,83 +1,88 @@
#include "MenuState.hpp" #include "MenuState.hpp"
#include "game.hpp"
#include "IngameState.hpp" #include "IngameState.hpp"
#include "game.hpp"
#include "RWGame.hpp"
#include <engine/SaveGame.hpp> #include <engine/SaveGame.hpp>
#include <rw/defines.hpp> #include <rw/defines.hpp>
#include "RWGame.hpp"
MenuState::MenuState(RWGame* game) MenuState::MenuState(RWGame* game) : State(game) {
: State(game) enterMainMenu();
{
enterMainMenu();
} }
void MenuState::enterMainMenu() void MenuState::enterMainMenu() {
{ auto data = game->getGameData();
auto data = game->getGameData(); auto& t = data->texts;
auto& t = data->texts;
Menu *m = new Menu; Menu* m = new Menu;
m->offset = glm::vec2(200.f, 200.f); m->offset = glm::vec2(200.f, 200.f);
m->addEntry(Menu::lambda(t.text(MenuDefaults::kStartGameId), [=] { StateManager::get().enter(new IngameState(game)); })); m->addEntry(Menu::lambda(t.text(MenuDefaults::kStartGameId), [=] {
m->addEntry(Menu::lambda(t.text(MenuDefaults::kLoadGameId), [=] { enterLoadMenu(); })); StateManager::get().enter(new IngameState(game));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kDebugId), [=] { StateManager::get().enter(new IngameState(game, true, "test")); })); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kOptionsId), [] { RW_UNIMPLEMENTED("Options Menu"); })); m->addEntry(Menu::lambda(t.text(MenuDefaults::kLoadGameId),
m->addEntry(Menu::lambda(t.text(MenuDefaults::kQuitGameId), [] { StateManager::get().clear(); })); [=] { enterLoadMenu(); }));
this->enterMenu(m); m->addEntry(Menu::lambda(t.text(MenuDefaults::kDebugId), [=] {
StateManager::get().enter(new IngameState(game, true, "test"));
}));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kOptionsId),
[] { RW_UNIMPLEMENTED("Options Menu"); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kQuitGameId),
[] { StateManager::get().clear(); }));
this->enterMenu(m);
} }
void MenuState::enterLoadMenu() void MenuState::enterLoadMenu() {
{ Menu* m = new Menu;
Menu *m = new Menu; m->offset = glm::vec2(20.f, 30.f);
m->offset = glm::vec2(20.f, 30.f); m->addEntry(Menu::lambda("BACK", [=] { enterMainMenu(); }));
m->addEntry(Menu::lambda("BACK", [=] { enterMainMenu(); })); auto saves = SaveGame::getAllSaveGameInfo();
auto saves = SaveGame::getAllSaveGameInfo(); for (SaveGameInfo& save : saves) {
for(SaveGameInfo& save : saves) { if (save.valid) {
if (save.valid) { std::stringstream ss;
std::stringstream ss; ss << save.basicState.saveTime.year << " "
ss << save.basicState.saveTime.year << " " << save.basicState.saveTime.month << " " << save.basicState.saveTime.day << save.basicState.saveTime.month << " "
<< " " << save.basicState.saveTime.hour << ":" << save.basicState.saveTime.minute << " "; << save.basicState.saveTime.day << " "
auto name = GameStringUtil::fromString(ss.str()); << save.basicState.saveTime.hour << ":"
name += save.basicState.saveName; << save.basicState.saveTime.minute << " ";
m->addEntry(Menu::lambda(name, [=] { auto name = GameStringUtil::fromString(ss.str());
StateManager::get().enter(new IngameState(game, false)); name += save.basicState.saveName;
game->loadGame(save.savePath); m->addEntry(Menu::lambda(name,
}, 20.f)); [=] {
} StateManager::get().enter(
else { new IngameState(game, false));
m->addEntry(Menu::lambda("CORRUPT", [=] { })); game->loadGame(save.savePath);
} },
} 20.f));
this->enterMenu(m); } else {
m->addEntry(Menu::lambda("CORRUPT", [=] {}));
}
}
this->enterMenu(m);
} }
void MenuState::enter() void MenuState::enter() {
{ getWindow().showCursor();
getWindow().showCursor();
} }
void MenuState::exit() void MenuState::exit() {
{
} }
void MenuState::tick(float dt) void MenuState::tick(float dt) {
{ RW_UNUSED(dt);
RW_UNUSED(dt);
} }
void MenuState::handleEvent(const SDL_Event& e) void MenuState::handleEvent(const SDL_Event& e) {
{ switch (e.type) {
switch(e.type) { case SDL_KEYUP:
case SDL_KEYUP: switch (e.key.keysym.sym) {
switch(e.key.keysym.sym) { case SDLK_ESCAPE:
case SDLK_ESCAPE: StateManager::get().exit();
StateManager::get().exit(); default:
default: break; break;
} }
break; break;
default: break; default:
} break;
State::handleEvent(e); }
State::handleEvent(e);
} }

View File

@ -3,20 +3,19 @@
#include "State.hpp" #include "State.hpp"
class MenuState : public State class MenuState : public State {
{
public: public:
MenuState(RWGame* game); MenuState(RWGame* game);
virtual void enter(); virtual void enter();
virtual void exit(); virtual void exit();
virtual void tick(float dt); virtual void tick(float dt);
virtual void enterMainMenu(); virtual void enterMainMenu();
virtual void enterLoadMenu(); virtual void enterLoadMenu();
virtual void handleEvent(const SDL_Event& event); virtual void handleEvent(const SDL_Event& event);
}; };
#endif // MENUSTATE_HPP #endif // MENUSTATE_HPP

View File

@ -1,67 +1,65 @@
#include "PauseState.hpp" #include "PauseState.hpp"
#include "RWGame.hpp"
#include <ai/PlayerController.hpp> #include <ai/PlayerController.hpp>
#include <objects/CharacterObject.hpp> #include <objects/CharacterObject.hpp>
#include "RWGame.hpp"
PauseState::PauseState(RWGame* game) PauseState::PauseState(RWGame* game) : State(game) {
: State(game) auto data = game->getGameData();
{ auto& t = data->texts;
auto data = game->getGameData();
auto& t = data->texts;
Menu *m = new Menu; Menu* m = new Menu;
m->offset = glm::vec2( 200.f, 200.f ); m->offset = glm::vec2(200.f, 200.f);
m->addEntry(Menu::lambda(t.text(MenuDefaults::kResumeGameId), [] { StateManager::get().exit(); })); m->addEntry(Menu::lambda(t.text(MenuDefaults::kResumeGameId),
m->addEntry(Menu::lambda(t.text(MenuDefaults::kOptionsId), [] { std::cout << "Options" << std::endl; })); [] { StateManager::get().exit(); }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kQuitGameId), [] { StateManager::get().clear(); })); m->addEntry(Menu::lambda(t.text(MenuDefaults::kOptionsId),
this->enterMenu(m); [] { std::cout << "Options" << std::endl; }));
m->addEntry(Menu::lambda(t.text(MenuDefaults::kQuitGameId),
[] { StateManager::get().clear(); }));
this->enterMenu(m);
} }
void PauseState::enter() void PauseState::enter() {
{ getWorld()->setPaused(true);
getWorld()->setPaused(true);
getWindow().showCursor(); getWindow().showCursor();
} }
void PauseState::exit() void PauseState::exit() {
{ getWorld()->setPaused(false);
getWorld()->setPaused(false);
} }
void PauseState::tick(float dt) void PauseState::tick(float dt) {
{ RW_UNUSED(dt);
RW_UNUSED(dt);
} }
void PauseState::draw(GameRenderer* r) void PauseState::draw(GameRenderer* r) {
{ MapRenderer::MapInfo map;
MapRenderer::MapInfo map;
auto& vp = r->getRenderer()->getViewport(); auto& vp = r->getRenderer()->getViewport();
map.worldSize = 4000.f; map.worldSize = 4000.f;
map.clipToSize = false; map.clipToSize = false;
map.screenPosition = glm::vec2(vp.x/2, vp.y/2); map.screenPosition = glm::vec2(vp.x / 2, vp.y / 2);
map.screenSize = std::max(vp.x, vp.y); map.screenSize = std::max(vp.x, vp.y);
game->getRenderer()->map.draw(getWorld(), map); game->getRenderer()->map.draw(getWorld(), map);
State::draw(r); State::draw(r);
} }
void PauseState::handleEvent(const SDL_Event& e) void PauseState::handleEvent(const SDL_Event& e) {
{ switch (e.type) {
switch(e.type) { case SDL_KEYDOWN:
case SDL_KEYDOWN: switch (e.key.keysym.sym) {
switch(e.key.keysym.sym) { case SDLK_ESCAPE:
case SDLK_ESCAPE: StateManager::get().exit();
StateManager::get().exit(); break;
break; default:
default: break; break;
} }
break; break;
default: break; default:
} break;
State::handleEvent(e); }
State::handleEvent(e);
} }

View File

@ -3,19 +3,18 @@
#include "State.hpp" #include "State.hpp"
class PauseState : public State class PauseState : public State {
{
public: public:
PauseState(RWGame* game); PauseState(RWGame* game);
virtual void enter(); virtual void enter();
virtual void exit(); virtual void exit();
virtual void tick(float dt);
virtual void tick(float dt);
virtual void draw(GameRenderer* r); virtual void draw(GameRenderer* r);
virtual void handleEvent(const SDL_Event& event); virtual void handleEvent(const SDL_Event& event);
}; };
#endif // PAUSESTATE_HPP #endif // PAUSESTATE_HPP