1
0
mirror of https://github.com/rwengine/openrw.git synced 2024-09-15 06:52:34 +02:00

clang-format files in rwgame

This commit is contained in:
Daniel Evans 2016-09-09 21:13:20 +01:00
parent e888d04303
commit e39ee21ca8
13 changed files with 1512 additions and 1602 deletions

View File

@ -1,9 +1,9 @@
#include "DrawUI.hpp"
#include <render/GameRenderer.hpp>
#include <ai/PlayerController.hpp>
#include <objects/CharacterObject.hpp>
#include <engine/GameState.hpp>
#include <items/WeaponItem.hpp>
#include <objects/CharacterObject.hpp>
#include <render/GameRenderer.hpp>
#include <glm/gtc/constants.hpp>
#include <iomanip>
@ -26,8 +26,8 @@ const float ui_mapSize = 150.f;
const float ui_worldSizeMin = 200.f;
const float ui_worldSizeMax = 300.f;
void drawMap(ViewCamera& currentView, PlayerController* player, GameWorld* world, GameRenderer* render)
{
void drawMap(ViewCamera& currentView, PlayerController* player,
GameWorld* world, GameRenderer* render) {
MapRenderer::MapInfo map;
glm::quat camRot = currentView.rotation;
@ -35,15 +35,16 @@ void drawMap(ViewCamera& currentView, PlayerController* player, GameWorld* worl
map.rotation = glm::roll(camRot) - glm::half_pi<float>();
map.worldSize = ui_worldSizeMin;
map.worldSize = ui_worldSizeMax;
if( player )
{
if (player) {
map.worldCenter = glm::vec2(player->getCharacter()->getPosition());
}
const glm::ivec2& vp = render->getRenderer()->getViewport();
glm::vec2 mapTop = glm::vec2(ui_outerMargin, vp.y - (ui_outerMargin + ui_mapSize));
glm::vec2 mapBottom = glm::vec2(ui_outerMargin + ui_mapSize, vp.y - ui_outerMargin);
glm::vec2 mapTop =
glm::vec2(ui_outerMargin, vp.y - (ui_outerMargin + ui_mapSize));
glm::vec2 mapBottom =
glm::vec2(ui_outerMargin + ui_mapSize, vp.y - ui_outerMargin);
map.screenPosition = (mapTop + mapBottom) / 2.f;
map.screenSize = ui_mapSize * 0.95;
@ -51,16 +52,15 @@ void drawMap(ViewCamera& currentView, PlayerController* player, GameWorld* worl
render->map.draw(world, map);
}
void drawPlayerInfo(PlayerController* player, GameWorld* world, GameRenderer* render)
{
void drawPlayerInfo(PlayerController* player, GameWorld* world,
GameRenderer* render) {
float infoTextX = render->getRenderer()->getViewport().x -
(ui_outerMargin + ui_weaponSize + ui_infoMargin);
float infoTextY = 0.f + ui_outerMargin;
float iconX = render->getRenderer()->getViewport().x -
(ui_outerMargin + ui_weaponSize);
float iconY = ui_outerMargin;
float wantedX = render->getRenderer()->getViewport().x -
(ui_outerMargin);
float wantedX = render->getRenderer()->getViewport().x - (ui_outerMargin);
float wantedY = ui_outerMargin + ui_weaponSize + 3.f;
TextRenderer::TextInfo ti;
@ -71,8 +71,7 @@ void drawPlayerInfo(PlayerController* player, GameWorld* world, GameRenderer* re
{
std::stringstream ss;
ss << std::setw(2) << std::setfill('0') << world->getHour()
<< std::setw(0) << ":"
<< std::setw(2) << world->getMinute();
<< std::setw(0) << ":" << std::setw(2) << world->getMinute();
ti.text = GameStringUtil::fromString(ss.str());
}
@ -88,7 +87,8 @@ void drawPlayerInfo(PlayerController* player, GameWorld* world, GameRenderer* re
{
std::stringstream ss;
ss << std::setw(8) << std::setfill('0') << world->state->playerInfo.displayedMoney;
ss << std::setw(8) << std::setfill('0')
<< world->state->playerInfo.displayedMoney;
ti.text = GameSymbols::Money + GameStringUtil::fromString(ss.str());
}
@ -116,14 +116,14 @@ void drawPlayerInfo(PlayerController* player, GameWorld* world, GameRenderer* re
ti.screenPosition = glm::vec2(infoTextX, infoTextY);
render->text.renderText(ti);
if (player->getCharacter()->getCurrentState().armour > 0)
{
if (player->getCharacter()->getCurrentState().armour > 0) {
std::stringstream ss;
ss << std::setw(3) << std::setfill('0')
<< (int)player->getCharacter()->getCurrentState().armour;
ti.text = GameSymbols::Armour + GameStringUtil::fromString(ss.str());
ti.baseColour = ui_shadowColour;
ti.screenPosition = glm::vec2(infoTextX + 1.f - ui_armourOffset, infoTextY+1.f);
ti.screenPosition =
glm::vec2(infoTextX + 1.f - ui_armourOffset, infoTextY + 1.f);
render->text.renderText(ti);
ti.baseColour = ui_armourColour;
@ -157,9 +157,8 @@ void drawPlayerInfo(PlayerController* player, GameWorld* world, GameRenderer* re
if (current) {
uint16_t model = current->getModelID();
if (model > 0) {
ObjectDataPtr weaponData = world
->data
->findObjectType<ObjectData>(model);
ObjectDataPtr weaponData =
world->data->findObjectType<ObjectData>(model);
if (weaponData != nullptr) {
itemTextureName = weaponData->modelName;
}
@ -170,47 +169,47 @@ void drawPlayerInfo(PlayerController* player, GameWorld* world, GameRenderer* re
itemTextureName = "pistol";
}
TextureData::Handle itemTexture = render->getData()->findTexture(itemTextureName);
TextureData::Handle itemTexture =
render->getData()->findTexture(itemTextureName);
RW_CHECK(itemTexture != nullptr, "Item has 0 texture");
if (itemTexture != nullptr) {
RW_CHECK(itemTexture->getName() != 0, "Item has 0 texture");
render->drawTexture(itemTexture.get(),
glm::vec4(iconX,
iconY,
ui_weaponSize,
ui_weaponSize));
render->drawTexture(
itemTexture.get(),
glm::vec4(iconX, iconY, ui_weaponSize, ui_weaponSize));
}
if (current) {
WeaponItem* wep = static_cast<WeaponItem*>(current);
if (wep->getWeaponData()->fireType != WeaponData::MELEE) {
const CharacterState& cs = player->getCharacter()->getCurrentState();
const CharacterState& cs =
player->getCharacter()->getCurrentState();
const CharacterWeaponSlot& slotInfo = cs.weapons[cs.currentWeapon];
ti.text = GameStringUtil::fromString(
std::to_string(slotInfo.bulletsClip) + "-"
+ std::to_string(slotInfo.bulletsTotal));
std::to_string(slotInfo.bulletsClip) + "-" +
std::to_string(slotInfo.bulletsTotal));
ti.baseColour = ui_shadowColour;
ti.font = 2;
ti.size = ui_ammoSize;
ti.align = TextRenderer::TextInfo::Center;
ti.screenPosition = glm::vec2(iconX + ui_weaponSize / 2.f,
ti.screenPosition =
glm::vec2(iconX + ui_weaponSize / 2.f,
iconY + ui_weaponSize - ui_ammoHeight);
render->text.renderText(ti);
}
}
}
void drawHUD(ViewCamera& currentView, PlayerController* player, GameWorld* world, GameRenderer* render)
{
void drawHUD(ViewCamera& currentView, PlayerController* player,
GameWorld* world, GameRenderer* render) {
if (player && player->getCharacter()) {
drawMap(currentView, player, world, render);
drawPlayerInfo(player, world, render);
}
}
void drawOnScreenText(GameWorld* world, GameRenderer* renderer)
{
void drawOnScreenText(GameWorld* world, GameRenderer* renderer) {
const auto vp = glm::vec2(renderer->getRenderer()->getViewport());
TextRenderer::TextInfo ti;
@ -220,10 +219,8 @@ void drawOnScreenText(GameWorld* world, GameRenderer* renderer)
auto& alltext = world->state->text.getAllText();
for(auto& l : alltext)
{
for (auto& t : l)
{
for (auto& l : alltext) {
for (auto& t : l) {
ti.size = t.size;
ti.font = t.font;
ti.text = t.text;
@ -242,9 +239,9 @@ void drawOnScreenText(GameWorld* world, GameRenderer* renderer)
}
// Check for the background type
if (t.colourBG.a == 0)
{
glm::vec2 shadowPosition((int8_t)t.colourBG.x, (int8_t)t.colourBG.y);
if (t.colourBG.a == 0) {
glm::vec2 shadowPosition((int8_t)t.colourBG.x,
(int8_t)t.colourBG.y);
ti.baseColour = glm::vec3(0.f);
ti.screenPosition += shadowPosition;
@ -253,9 +250,7 @@ void drawOnScreenText(GameWorld* world, GameRenderer* renderer)
renderer->text.renderText(ti, true);
ti.screenPosition -= shadowPosition;
}
else if(t.colourBG.a > 0)
{
} else if (t.colourBG.a > 0) {
ti.backgroundColour = t.colourBG;
}

View File

@ -4,6 +4,7 @@
class PlayerController;
void drawHUD(ViewCamera& currentView, PlayerController* player, GameWorld* world, GameRenderer* render);
void drawHUD(ViewCamera& currentView, PlayerController* player,
GameWorld* world, GameRenderer* render);
void drawOnScreenText(GameWorld* world, GameRenderer* renderer);

View File

@ -1,49 +1,43 @@
#include "GameConfig.hpp"
#include <rw/defines.hpp>
#include <cstring>
#include <cstdlib>
#include <cstring>
#include <rw/defines.hpp>
#include <ini.h>
const std::string kConfigDirectoryName("OpenRW");
GameConfig::GameConfig(const std::string& configName, const std::string& configPath)
GameConfig::GameConfig(const std::string& configName,
const std::string& configPath)
: m_configName(configName)
, m_configPath(configPath)
, m_valid(false)
, m_inputInvertY(false)
{
if (m_configPath.empty())
{
, m_inputInvertY(false) {
if (m_configPath.empty()) {
m_configPath = getDefaultConfigPath();
}
// Look up the path to use
auto configFile = getConfigFile();
if (ini_parse(configFile.c_str(), handler, this) < 0)
{
if (ini_parse(configFile.c_str(), handler, this) < 0) {
m_valid = false;
}
else
{
} else {
m_valid = true;
}
}
std::string GameConfig::getConfigFile()
{
std::string GameConfig::getConfigFile() {
return m_configPath + "/" + m_configName;
}
bool GameConfig::isValid()
{
bool GameConfig::isValid() {
return m_valid;
}
std::string GameConfig::getDefaultConfigPath()
{
#if defined(RW_LINUX) || defined(RW_FREEBSD) || defined(RW_NETBSD) || defined(RW_OPENBSD)
std::string GameConfig::getDefaultConfigPath() {
#if defined(RW_LINUX) || defined(RW_FREEBSD) || defined(RW_NETBSD) || \
defined(RW_OPENBSD)
char* config_home = getenv("XDG_CONFIG_HOME");
if (config_home != nullptr) {
return std::string(config_home) + "/" + kConfigDirectoryName;
@ -56,7 +50,8 @@ std::string GameConfig::getDefaultConfigPath()
#elif defined(RW_OSX)
char* home = getenv("HOME");
if (home)
return std::string(home) + "/Library/Preferences/" + kConfigDirectoryName;
return std::string(home) + "/Library/Preferences/" +
kConfigDirectoryName;
#else
return ".";
@ -67,30 +62,21 @@ std::string GameConfig::getDefaultConfigPath()
return ".";
}
int GameConfig::handler(void* user,
const char* section,
const char* name,
const char* value)
{
int GameConfig::handler(void* user, const char* section, const char* name,
const char* value) {
auto self = static_cast<GameConfig*>(user);
#define MATCH(_s, _n) (strcmp(_s, section) == 0 && strcmp(_n, name) == 0)
if (MATCH("game", "path"))
{
if (MATCH("game", "path")) {
self->m_gamePath = value;
}
else if (MATCH("game", "language"))
{
} else if (MATCH("game", "language")) {
// @todo Don't allow path seperators and relative directories
self->m_gameLanguage = value;
}
else if (MATCH("input", "invert_y"))
{
} else if (MATCH("input", "invert_y")) {
self->m_inputInvertY = atoi(value) > 0;
}
else
{
RW_MESSAGE("Unhandled config entry [" << section << "] " << name << " = " << value);
} else {
RW_MESSAGE("Unhandled config entry [" << section << "] " << name
<< " = " << value);
return 0;
}

View File

@ -2,15 +2,15 @@
#define RWGAME_GAMECONFIG_HPP
#include <string>
class GameConfig
{
class GameConfig {
public:
/**
* @brief GameConfig Loads a game configuration
* @param configName The configuration filename to load
* @param configPath Where to look.
*/
GameConfig(const std::string& configName, const std::string& configPath = getDefaultConfigPath());
GameConfig(const std::string& configName,
const std::string& configPath = getDefaultConfigPath());
/**
* @brief getFilePath Returns the system file path for the configuration
@ -23,9 +23,15 @@ public:
*/
bool isValid();
const std::string& getGameDataPath() const { return m_gamePath; }
const std::string& getGameLanguage() const { return m_gameLanguage; }
bool getInputInvertY() const { return m_inputInvertY; }
const std::string& getGameDataPath() const {
return m_gamePath;
}
const std::string& getGameLanguage() const {
return m_gameLanguage;
}
bool getInputInvertY() const {
return m_inputInvertY;
}
private:
static std::string getDefaultConfigPath();

View File

@ -1,27 +1,24 @@
#include <core/Logger.hpp>
#include "GameWindow.hpp"
#include <core/Logger.hpp>
GameWindow::GameWindow() :
window(nullptr), glcontext(nullptr)
{
GameWindow::GameWindow() : window(nullptr), glcontext(nullptr) {
}
void GameWindow::create(const std::string& title, size_t w, size_t h, bool fullscreen)
{
void GameWindow::create(const std::string& title, size_t w, size_t h,
bool fullscreen) {
Uint32 style = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN;
if (fullscreen)
style |= SDL_WINDOW_FULLSCREEN;
if (fullscreen) style |= SDL_WINDOW_FULLSCREEN;
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, style);
window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, w, h, style);
if (window == nullptr) {
// Window creation failure is fatal
std::string sdlErrorStr = SDL_GetError();
@ -37,30 +34,22 @@ void GameWindow::create(const std::string& title, size_t w, size_t h, bool fulls
SDL_ShowWindow(window);
}
void GameWindow::close()
{
void GameWindow::close() {
SDL_GL_DeleteContext(glcontext);
SDL_DestroyWindow(window);
window = nullptr;
}
void GameWindow::showCursor()
{
void GameWindow::showCursor() {
SDL_SetRelativeMouseMode(SDL_FALSE);
}
void GameWindow::hideCursor()
{
void GameWindow::hideCursor() {
SDL_SetRelativeMouseMode(SDL_TRUE);
}
glm::ivec2 GameWindow::getSize() const
{
glm::ivec2 GameWindow::getSize() const {
int x, y;
SDL_GL_GetDrawableSize(window, &x, &y);

View File

@ -1,15 +1,13 @@
#ifndef GAMEWINDOW_HPP
#define GAMEWINDOW_HPP
#include <glm/vec2.hpp>
#include <string>
#include "SDL.h"
#include <glm/vec2.hpp>
#include <render/GameRenderer.hpp>
class GameWindow
{
class GameWindow {
SDL_Window* window;
SDL_GLContext glcontext;
@ -24,13 +22,11 @@ public:
glm::ivec2 getSize() const;
void swap() const
{
void swap() const {
SDL_GL_SwapWindow(window);
}
bool isOpen() const
{
bool isOpen() const {
return !!window;
}
};

View File

@ -1,17 +1,16 @@
#ifndef _GAME_MENUSYSTEM_HPP_
#define _GAME_MENUSYSTEM_HPP_
#include <string>
#include <memory>
#include <glm/glm.hpp>
#include <render/GameRenderer.hpp>
#include <functional>
#include <algorithm>
#include <functional>
#include <glm/glm.hpp>
#include <memory>
#include <render/GameRenderer.hpp>
#include <string>
/**
* Default values for menus that should match the look and feel of the original
*/
namespace MenuDefaults
{
namespace MenuDefaults {
constexpr int kFont = 1;
constexpr const char* kStartGameId = "FET_SAN";
@ -22,40 +21,35 @@ constexpr const char* kOptionsId = "FET_OPT";
constexpr const char* kQuitGameId = "FET_QG";
}
class Menu
{
class Menu {
int font;
public:
Menu(int font = MenuDefaults::kFont) : font(font), activeEntry(-1) {
}
Menu(int font = MenuDefaults::kFont)
: font(font), activeEntry(-1) {}
struct MenuEntry
{
struct MenuEntry {
GameString text;
float _size;
MenuEntry(const GameString& n, float size = 30.f)
: text(n)
, _size(size)
{
: text(n), _size(size) {
}
float getHeight() { return _size; }
float getHeight() {
return _size;
}
virtual void draw(int font, bool active, GameRenderer* r, glm::vec2& basis)
{
virtual void draw(int font, bool active, GameRenderer* r,
glm::vec2& basis) {
TextRenderer::TextInfo ti;
ti.font = font;
ti.screenPosition = basis;
ti.text = text;
ti.size = getHeight();
if( ! active )
{
if (!active) {
ti.baseColour = glm::u8vec3(255);
}
else
{
} else {
ti.baseColour = glm::u8vec3(255, 255, 0);
}
r->text.renderText(ti);
@ -65,33 +59,29 @@ public:
virtual void activate(float clickX, float clickY) = 0;
};
struct Entry : public MenuEntry
{
struct Entry : public MenuEntry {
std::function<void(void)> callback;
Entry(const GameString& title,
std::function<void(void)> cb,
float size)
: MenuEntry(title, size)
, callback(cb)
{
Entry(const GameString& title, std::function<void(void)> cb, float size)
: MenuEntry(title, size), callback(cb) {
}
void activate(float clickX, float clickY)
{
void activate(float clickX, float clickY) {
RW_UNUSED(clickX);
RW_UNUSED(clickY);
callback();
}
};
static std::shared_ptr<MenuEntry> lambda(const GameString& n, std::function<void (void)> callback, float size = 30.f)
{
static std::shared_ptr<MenuEntry> lambda(const GameString& n,
std::function<void(void)> callback,
float size = 30.f) {
return std::shared_ptr<MenuEntry>(new Entry(n, callback, size));
}
static std::shared_ptr<MenuEntry> lambda(const std::string& n, std::function<void (void)> callback, float size = 30.f)
{
static std::shared_ptr<MenuEntry> lambda(const std::string& n,
std::function<void(void)> callback,
float size = 30.f) {
return lambda(GameStringUtil::fromString(n), callback, size);
}
@ -104,76 +94,57 @@ public:
glm::vec2 offset;
void addEntry(std::shared_ptr<MenuEntry> entry)
{
void addEntry(std::shared_ptr<MenuEntry> entry) {
entries.push_back(entry);
}
void draw(GameRenderer* r)
{
void draw(GameRenderer* r) {
glm::vec2 basis(offset);
for(size_t i = 0;
i < entries.size();
++i)
{
for (size_t i = 0; i < entries.size(); ++i) {
bool active = false;
if(activeEntry >= 0 && i == (unsigned) activeEntry)
{
if (activeEntry >= 0 && i == (unsigned)activeEntry) {
active = true;
}
entries[i]->draw(font, active, r, basis);
}
}
void hover(const float x, const float y)
{
void hover(const float x, const float y) {
glm::vec2 c(x - offset.x, y - offset.y);
for(size_t i = 0;
i < entries.size();
++i)
{
for (size_t i = 0; i < entries.size(); ++i) {
if (c.y > 0.f && c.y < entries[i]->getHeight()) {
activeEntry = i;
return;
}
else {
} else {
c.y -= entries[i]->getHeight();
}
}
}
void click(const float x, const float y)
{
void click(const float x, const float y) {
glm::vec2 c(x - offset.x, y - offset.y);
for(auto it = entries.begin();
it != entries.end();
++it)
{
for (auto it = entries.begin(); it != entries.end(); ++it) {
if (c.y > 0.f && c.y < (*it)->getHeight()) {
(*it)->activate(c.x, c.y);
return;
}
else {
} else {
c.y -= (*it)->getHeight();
}
}
}
// Activates the menu entry at the current active index.
void activate()
{
void activate() {
if (activeEntry >= 0 && (unsigned)activeEntry < entries.size()) {
entries[activeEntry]->activate(0.f, 0.f);
}
}
void move(int movement)
{
void move(int movement) {
activeEntry += movement;
if (activeEntry >= int(entries.size())) {
activeEntry = 0;
}
else if (activeEntry < 0) {
} else if (activeEntry < 0) {
activeEntry = entries.size() - 1;
}
}

View File

@ -1,25 +1,25 @@
#include "RWGame.hpp"
#include "State.hpp"
#include "states/LoadingState.hpp"
#include "states/IngameState.hpp"
#include "states/MenuState.hpp"
#include "states/BenchmarkState.hpp"
#include "DrawUI.hpp"
#include "State.hpp"
#include "states/BenchmarkState.hpp"
#include "states/IngameState.hpp"
#include "states/LoadingState.hpp"
#include "states/MenuState.hpp"
#include <core/Profiler.hpp>
#include <objects/GameObject.hpp>
#include <engine/GameState.hpp>
#include <engine/SaveGame.hpp>
#include <engine/GameWorld.hpp>
#include <render/GameRenderer.hpp>
#include <engine/SaveGame.hpp>
#include <objects/GameObject.hpp>
#include <render/DebugDraw.hpp>
#include <render/GameRenderer.hpp>
#include <script/ScriptMachine.hpp>
#include <script/modules/GTA3Module.hpp>
#include <data/CutsceneData.hpp>
#include <ai/PlayerController.hpp>
#include <data/CutsceneData.hpp>
#include <objects/CharacterObject.hpp>
#include <objects/VehicleObject.hpp>
@ -39,11 +39,10 @@ DebugDraw* debug = nullptr;
StdOutReciever logPrinter;
RWGame::RWGame(int argc, char* argv[])
{
if (!config.isValid())
{
throw std::runtime_error("Invalid configuration file at: " + config.getConfigFile());
RWGame::RWGame(int argc, char* argv[]) {
if (!config.isValid()) {
throw std::runtime_error("Invalid configuration file at: " +
config.getConfigFile());
}
size_t w = GAME_WINDOW_WIDTH, h = GAME_WINDOW_HEIGHT;
@ -57,60 +56,47 @@ RWGame::RWGame(int argc, char* argv[])
// Define and parse command line options
namespace po = boost::program_options;
po::options_description desc("Available options");
desc.add_options()
("help", "Show this help message")
("width,w", po::value<size_t>(), "Game resolution width in pixel")
("height,h", po::value<size_t>(), "Game resolution height in pixel")
("fullscreen,f", "Enable fullscreen mode")
("newgame,n", "Directly start a new game")
("test,t", "Starts a new game in a test location")
("load,l", po::value<std::string>(), "Load save file")
("benchmark,b", po::value<std::string>(), "Run benchmark from file")
;
desc.add_options()("help", "Show this help message")(
"width,w", po::value<size_t>(), "Game resolution width in pixel")(
"height,h", po::value<size_t>(), "Game resolution height in pixel")(
"fullscreen,f", "Enable fullscreen mode")("newgame,n",
"Directly start a new game")(
"test,t", "Starts a new game in a test location")(
"load,l", po::value<std::string>(), "Load save file")(
"benchmark,b", po::value<std::string>(), "Run benchmark from file");
po::variables_map vm;
try
{
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
}
catch (po::error& ex)
{
} catch (po::error& ex) {
help = true;
std::cout << "Error parsing arguments: " << ex.what() << std::endl;
}
if( help || vm.count("help") )
{
if (help || vm.count("help")) {
std::cout << desc;
throw std::invalid_argument("");
}
if( vm.count("width") )
{
if (vm.count("width")) {
w = vm["width"].as<size_t>();
}
if( vm.count("height") )
{
if (vm.count("height")) {
h = vm["height"].as<size_t>();
}
if( vm.count("fullscreen") )
{
if (vm.count("fullscreen")) {
fullscreen = true;
}
if( vm.count("newgame") )
{
if (vm.count("newgame")) {
newgame = true;
}
if( vm.count("test") )
{
if (vm.count("test")) {
test = true;
}
if( vm.count("load") )
{
if (vm.count("load")) {
startSave = vm["load"].as<std::string>();
}
if( vm.count("benchmark") )
{
if (vm.count("benchmark")) {
benchFile = vm["benchmark"].as<std::string>();
}
@ -126,9 +112,9 @@ RWGame::RWGame(int argc, char* argv[])
log.info("Game", "Game directory: " + config.getGameDataPath());
log.info("Game", "Build: " + kBuildStr);
if(! GameData::isValidGameDirectory(config.getGameDataPath()) )
{
throw std::runtime_error("Invalid game directory path: " + config.getGameDataPath());
if (!GameData::isValidGameDirectory(config.getGameDataPath())) {
throw std::runtime_error("Invalid game directory path: " +
config.getGameDataPath());
}
data = new GameData(&log, work, config.getGameDataPath());
@ -144,41 +130,34 @@ RWGame::RWGame(int argc, char* argv[])
renderer->text.setFontTexture(2, "font2");
debug = new DebugDraw;
debug->setDebugMode(btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits);
debug->setDebugMode(btIDebugDraw::DBG_DrawWireframe |
btIDebugDraw::DBG_DrawConstraints |
btIDebugDraw::DBG_DrawConstraintLimits);
debug->setShaderProgram(renderer->worldProg);
data->loadDynamicObjects(config.getGameDataPath() + "/data/object.dat");
data->loadGXT("text/" + config.getGameLanguage() + ".gxt");
getRenderer()->water.setWaterTable(data->waterHeights, 48, data->realWater, 128*128);
getRenderer()->water.setWaterTable(data->waterHeights, 48, data->realWater,
128 * 128);
for(int m = 0; m < MAP_BLOCK_SIZE; ++m)
{
for (int m = 0; m < MAP_BLOCK_SIZE; ++m) {
std::string num = (m < 10 ? "0" : "");
std::string name = "radar" + num + std::to_string(m);
data->loadTXD(name + ".txd");
}
auto loading = new LoadingState(this);
if (! benchFile.empty())
{
if (!benchFile.empty()) {
loading->setNextState(new BenchmarkState(this, benchFile));
}
else if( test)
{
} else if (test) {
loading->setNextState(new IngameState(this, true, "test"));
}
else if( newgame )
{
} else if (newgame) {
loading->setNextState(new IngameState(this, true));
}
else if( ! startSave.empty() )
{
} else if (!startSave.empty()) {
loading->setNextState(new IngameState(this, true, startSave));
}
else
{
} else {
loading->setNextState(new MenuState(this));
}
@ -187,8 +166,7 @@ RWGame::RWGame(int argc, char* argv[])
log.info("Game", "Started");
}
RWGame::~RWGame()
{
RWGame::~RWGame() {
log.info("Game", "Beginning cleanup");
log.info("Game", "Stopping work queue");
@ -217,10 +195,8 @@ RWGame::~RWGame()
log.info("Game", "Done cleaning up");
}
void RWGame::newGame()
{
if( state != nullptr )
{
void RWGame::newGame() {
if (state != nullptr) {
log.error("Game", "Cannot start a new game: game is already running.");
return;
}
@ -233,22 +209,19 @@ void RWGame::newGame()
state->world = world;
world->state = state;
for(std::map<std::string, std::string>::iterator it = world->data->iplLocations.begin();
it != world->data->iplLocations.end();
++it) {
for (std::map<std::string, std::string>::iterator it =
world->data->iplLocations.begin();
it != world->data->iplLocations.end(); ++it) {
world->data->loadZone(it->second);
world->placeItems(it->second);
}
}
void RWGame::saveGame(const std::string& savename)
{
void RWGame::saveGame(const std::string& savename) {
RW_UNUSED(savename);
}
void RWGame::loadGame(const std::string& savename)
{
void RWGame::loadGame(const std::string& savename) {
delete state->world;
delete state->script;
state = nullptr;
@ -259,14 +232,12 @@ void RWGame::loadGame(const std::string& savename)
startScript("data/main.scm");
if(! SaveGame::loadGame(*state, savename) )
{
if (!SaveGame::loadGame(*state, savename)) {
log.error("Game", "Failed to load game");
}
}
void RWGame::startScript(const std::string& name)
{
void RWGame::startScript(const std::string& name) {
SCMFile* f = world->data->loadSCM(name);
if (f) {
if (script) delete script;
@ -277,17 +248,14 @@ void RWGame::startScript(const std::string& name)
script = new ScriptMachine(state, f, opcodes);
state->script = script;
}
else {
} else {
log.error("Game", "Failed to load SCM: " + name);
}
}
PlayerController *RWGame::getPlayer()
{
PlayerController* RWGame::getPlayer() {
auto object = world->pedestrianPool.find(state->playerObject);
if( object )
{
if (object) {
auto controller = static_cast<CharacterObject*>(object)->controller;
return static_cast<PlayerController*>(controller);
}
@ -303,7 +271,8 @@ void RWGame::handleCheatInput(char symbol) {
cheatInputWindow = cheatInputWindow.substr(1) + symbol;
// Helper to check for cheats
auto checkForCheat = [this](std::string cheat, std::function<void()> action) {
auto checkForCheat = [this](std::string cheat,
std::function<void()> action) {
RW_CHECK(cheatInputWindow.length() >= cheat.length(), "Cheat too long");
size_t offset = cheatInputWindow.length() - cheat.length();
if (cheat == cheatInputWindow.substr(offset)) {
@ -316,7 +285,8 @@ void RWGame::handleCheatInput(char symbol) {
// Player related cheats
{
auto player = static_cast<CharacterObject*>(world->pedestrianPool.find(state->playerObject));
auto player = static_cast<CharacterObject*>(
world->pedestrianPool.find(state->playerObject));
#ifdef RW_GAME_GTA3_GERMAN // Germans got their own cheat
std::string health_cheat = "GESUNDHEIT";
@ -325,7 +295,8 @@ void RWGame::handleCheatInput(char symbol) {
#endif
checkForCheat(health_cheat, [&] {
player->getCurrentState().health = 100.f;
// @todo ShowHelpMessage("CHEAT3"); // III / VC: Inputting health cheat.
// @todo ShowHelpMessage("CHEAT3"); // III / VC: Inputting health
// cheat.
});
#if RW_GAME_VERSION >= 1100 // Changed cheat name in version 1.1
@ -335,12 +306,14 @@ void RWGame::handleCheatInput(char symbol) {
#endif
checkForCheat(armor_cheat, [&] {
player->getCurrentState().armour = 100.f;
// @todo ShowHelpMessage("CHEAT4"); // III / VC: Inputting armor cheat.
// @todo ShowHelpMessage("CHEAT4"); // III / VC: Inputting armor
// cheat.
});
checkForCheat("GUNSGUNSGUNS", [&] {
// @todo give player weapons
// @todo ShowHelpMessage("CHEAT2"); // III / VC: Inputting weapon cheats.
// @todo ShowHelpMessage("CHEAT2"); // III / VC: Inputting weapon
// cheats.
});
checkForCheat("IFIWEREARICHMAN", [&] {
@ -350,12 +323,14 @@ void RWGame::handleCheatInput(char symbol) {
checkForCheat("MOREPOLICEPLEASE", [&] {
// @todo raise to next wanted level
// @todo ShowHelpMessage("CHEAT5"); // III / VC: Inputting wanted level cheats.
// @todo ShowHelpMessage("CHEAT5"); // III / VC: Inputting wanted
// level cheats.
});
checkForCheat("NOPOLICEPLEASE", [&] {
// @todo lower to next lower wanted level
// @todo ShowHelpMessage("CHEAT5"); // III / VC: Inputting wanted level cheats.
// @todo ShowHelpMessage("CHEAT5"); // III / VC: Inputting wanted
// level cheats.
});
}
@ -364,74 +339,90 @@ void RWGame::handleCheatInput(char symbol) {
checkForCheat("BANGBANGBANG", [&] {
// @todo Explode nearby vehicles
// @todo What radius?
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
checkForCheat("GIVEUSATANK", [&] {
// The iPod / Android version of the game (10th year anniversary) spawns random (?) vehicles instead of always rhino
// The iPod / Android version of the game (10th year anniversary) spawns random
// (?) vehicles instead of always rhino
#ifdef RW_GAME_GTA3_ANNIVERSARY
uint16_t vehicleModel = 110; // @todo Which cars are spawned?!
#else
uint16_t vehicleModel = 122;
#endif
// @todo Spawn rhino
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
checkForCheat("CORNERSLIKEMAD", [&] {
// @todo Weird car handling
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
checkForCheat("ANICESETOFWHEELS", [&] {
// @todo Hide car bodies
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
checkForCheat("CHITTYCHITTYBB", [&] {
// @todo Cars can fly
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
checkForCheat("NASTYLIMBCHEAT", [&] {
// @todo Makes it possible to shoot limbs off, iirc?
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
checkForCheat("ILIKEDRESSINGUP", [&] {
// @todo Which skins will be chosen?
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
}
// Pedestrian cheats
{
checkForCheat("WEAPONSFORALL", [&] {
// @todo Give all pedestrians weapons.. this is also saved in the savegame?!
// @todo Give all pedestrians weapons.. this is also saved in the
// savegame?!
// @todo Which weapons do they get?
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
checkForCheat("NOBODYLIKESME", [&] {
// @todo Set all pedestrians hostile towards player.. this is also saved in the savegame?!
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo Set all pedestrians hostile towards player.. this is also
// saved in the savegame?!
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
checkForCheat("ITSALLGOINGMAAAD", [&] {
// @todo Set all pedestrians to fighting each other.. this is also saved in the savegame?!
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo Set all pedestrians to fighting each other.. this is also
// saved in the savegame?!
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
// Game speed cheats
checkForCheat("TIMEFLIESWHENYOU", [&] {
// @todo Set fast gamespeed
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
checkForCheat("BOOOOORING", [&] {
// @todo Set slow gamespeed
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most cheats.
// @todo ShowHelpMessage("CHEAT1"); // III / VC: Inputting most
// cheats.
});
}
@ -439,33 +430,37 @@ void RWGame::handleCheatInput(char symbol) {
{
checkForCheat("ILIKESCOTLAND", [&] {
// @todo Set weather to cloudy
// @todo ShowHelpMessage("CHEAT7"); // III / VC: Inputting weather cheats.
// @todo ShowHelpMessage("CHEAT7"); // III / VC: Inputting weather
// cheats.
});
checkForCheat("SKINCANCERFORME", [&] {
// @todo Set sunny / normal weather
// @todo ShowHelpMessage("CHEAT7"); // III / VC: Inputting weather cheats.
// @todo ShowHelpMessage("CHEAT7"); // III / VC: Inputting weather
// cheats.
});
checkForCheat("MADWEATHER", [&] {
// @todo Set bad weather
// @todo ShowHelpMessage("CHEAT7"); // III / VC: Inputting weather cheats.
// @todo ShowHelpMessage("CHEAT7"); // III / VC: Inputting weather
// cheats.
});
checkForCheat("ILOVESCOTLAND", [&] {
// @todo Set weather to rainy
// @todo ShowHelpMessage("CHEAT7"); // III / VC: Inputting weather cheats.
// @todo ShowHelpMessage("CHEAT7"); // III / VC: Inputting weather
// cheats.
});
checkForCheat("PEASOUP", [&] {
// @todo Set weather to foggy
// @todo ShowHelpMessage("CHEAT7"); // III / VC: Inputting weather cheats.
// @todo ShowHelpMessage("CHEAT7"); // III / VC: Inputting weather
// cheats.
});
}
}
int RWGame::run()
{
int RWGame::run() {
last_clock_time = clock.now();
// Loop until we run out of states.
@ -511,7 +506,8 @@ int RWGame::run()
RW_PROFILE_END();
auto now = clock.now();
float timer = std::chrono::duration<float>(now - last_clock_time).count();
float timer =
std::chrono::duration<float>(now - last_clock_time).count();
last_clock_time = now;
accum += timer * timescale;
@ -532,16 +528,14 @@ int RWGame::run()
accum -= GAME_TIMESTEP;
// Throw away time if the accumulator reaches too high.
if ( accum > GAME_TIMESTEP * 5.f )
{
if (accum > GAME_TIMESTEP * 5.f) {
accum = 0.f;
}
}
RW_PROFILE_END();
float alpha = fmod(accum, GAME_TIMESTEP) / GAME_TIMESTEP;
if( ! state->shouldWorldUpdate() )
{
if (!state->shouldWorldUpdate()) {
alpha = 1.f;
}
@ -565,8 +559,7 @@ int RWGame::run()
return 0;
}
void RWGame::tick(float dt)
{
void RWGame::tick(float dt) {
// Process the Engine's background work.
world->_work->update();
@ -595,15 +588,12 @@ void RWGame::tick(float dt)
}
// Clean up old VisualFX
for( int i = 0; i < static_cast<int>(world->effects.size()); ++i )
{
for (int i = 0; i < static_cast<int>(world->effects.size()); ++i) {
VisualFX* effect = world->effects[i];
if( effect->getType() == VisualFX::Particle )
{
if (effect->getType() == VisualFX::Particle) {
auto& part = effect->particle;
if (part.lifetime < 0.f) continue;
if( world->getGameTime() >= part.starttime + part.lifetime )
{
if (world->getGameTime() >= part.starttime + part.lifetime) {
world->destroyEffect(effect);
--i;
}
@ -624,8 +614,7 @@ void RWGame::tick(float dt)
if (script) {
try {
script->execute(dt);
}
catch( SCMException& ex ) {
} catch (SCMException& ex) {
std::cerr << ex.what() << std::endl;
log.error("Script", ex.what());
throw;
@ -634,7 +623,8 @@ void RWGame::tick(float dt)
/// @todo this doesn't make sense as the condition
if (state->playerObject) {
nextCam.frustum.update(nextCam.frustum.projection() * nextCam.getView());
nextCam.frustum.update(nextCam.frustum.projection() *
nextCam.getView());
// Use the current camera position to spawn pedestrians.
world->cleanupTraffic(nextCam);
world->createTraffic(nextCam);
@ -646,8 +636,7 @@ void RWGame::tick(float dt)
nextCam = currState->getCamera();
}
void RWGame::render(float alpha, float time)
{
void RWGame::render(float alpha, float time) {
lastDraws = getRenderer()->getRenderer()->getDrawCount();
getRenderer()->getRenderer()->swap();
@ -657,10 +646,10 @@ void RWGame::render(float alpha, float time)
ViewCamera viewCam;
viewCam.frustum.fov = glm::radians(90.f);
if( state->currentCutscene != nullptr && state->cutsceneStartTime >= 0.f )
{
if (state->currentCutscene != nullptr && state->cutsceneStartTime >= 0.f) {
auto cutscene = state->currentCutscene;
float cutsceneTime = std::min(world->getGameTime() - state->cutsceneStartTime,
float cutsceneTime =
std::min(world->getGameTime() - state->cutsceneStartTime,
cutscene->tracks.duration);
cutsceneTime += GAME_TIMESTEP * alpha;
glm::vec3 cameraPos = cutscene->tracks.getPositionAt(cutsceneTime),
@ -670,7 +659,8 @@ void RWGame::render(float alpha, float time)
float tilt = cutscene->tracks.getRotationAt(cutsceneTime);
auto direction = glm::normalize(targetPos - cameraPos);
auto right = glm::normalize(glm::cross(glm::vec3(0.f, 0.f, 1.f), direction));
auto right =
glm::normalize(glm::cross(glm::vec3(0.f, 0.f, 1.f), direction));
auto up = glm::normalize(glm::cross(direction, right));
glm::mat3 m;
@ -693,23 +683,20 @@ void RWGame::render(float alpha, float time)
viewCam.position = cameraPos;
viewCam.rotation = glm::inverse(glm::quat_cast(m)) * qtilt;
}
else if( state->cameraFixed )
{
} else if (state->cameraFixed) {
viewCam.position = state->cameraPosition;
viewCam.rotation = state->cameraRotation;
}
else
{
} else {
// There's no cutscene playing - use the camera returned by the State.
viewCam.position = glm::mix(lastCam.position, nextCam.position, alpha);
viewCam.rotation = glm::slerp(lastCam.rotation, nextCam.rotation, alpha);
viewCam.rotation =
glm::slerp(lastCam.rotation, nextCam.rotation, alpha);
}
viewCam.frustum.aspectRatio = windowSize.x / static_cast<float>(windowSize.y);
viewCam.frustum.aspectRatio =
windowSize.x / static_cast<float>(windowSize.y);
if ( state->isCinematic )
{
if (state->isCinematic) {
viewCam.frustum.fov *= viewCam.frustum.aspectRatio;
}
@ -722,24 +709,19 @@ void RWGame::render(float alpha, float time)
renderer->renderWorld(world, viewCam, alpha);
RW_PROFILE_END();
auto rendertime = renderer->getRenderer()->popDebugGroup();
RW_PROFILE_BEGIN("debug");
if( showDebugPaths )
{
if (showDebugPaths) {
renderDebugPaths(time);
}
if ( showDebugStats )
{
if (showDebugStats) {
renderDebugStats(time, rendertime);
}
if( showDebugPhysics )
{
if( world )
{
if (showDebugPhysics) {
if (world) {
world->dynamicsWorld->debugDrawWorld();
debug->flush(renderer);
}
@ -749,8 +731,8 @@ void RWGame::render(float alpha, float time)
drawOnScreenText(world, renderer);
}
void RWGame::renderDebugStats(float time, Renderer::ProfileInfo& worldRenderTime)
{
void RWGame::renderDebugStats(float time,
Renderer::ProfileInfo& worldRenderTime) {
// Turn time into milliseconds
float time_ms = time * 1000.f;
constexpr size_t average_every_frame = 15;
@ -777,27 +759,33 @@ void RWGame::renderDebugStats(float time, Renderer::ProfileInfo& worldRenderTime
std::stringstream ss;
ss << "Frametime: " << time_ms << " (FPS " << (1.f / time) << ")\n";
ss << "Average (per " << average_every_frame << " frames); Frametime: " << time_average << " (FPS " << (1000.f/time_average) << ")\n";
ss << "Average (per " << average_every_frame
<< " frames); Frametime: " << time_average << " (FPS "
<< (1000.f / time_average) << ")\n";
ss << "Draws: " << lastDraws << " (" << renderer->culled << " Culls)\n";
ss << " Texture binds: " << renderer->getRenderer()->getTextureCount() << "\n";
ss << " Buffer binds: " << renderer->getRenderer()->getBufferCount() << "\n";
ss << " Texture binds: " << renderer->getRenderer()->getTextureCount()
<< "\n";
ss << " Buffer binds: " << renderer->getRenderer()->getBufferCount()
<< "\n";
ss << " World time: " << (worldRenderTime.duration / 1000000) << "ms\n";
for(auto& perf : profGroups)
{
ss << " " << perf.first << ": "
<< perf.second->draws << " draws " << perf.second->primitives << " prims "
for (auto& perf : profGroups) {
ss << " " << perf.first << ": " << perf.second->draws << " draws "
<< perf.second->primitives << " prims "
<< (perf.second->duration / 1000000) << "ms\n";
}
// Count the number of interesting objects.
int peds = 0, cars = 0;
for( auto& object : world->allObjects )
{
switch ( object->type() )
{
case GameObject::Character: peds++; break;
case GameObject::Vehicle: cars++; break;
default: break;
for (auto& object : world->allObjects) {
switch (object->type()) {
case GameObject::Character:
peds++;
break;
case GameObject::Vehicle:
cars++;
break;
default:
break;
}
}
@ -810,8 +798,7 @@ void RWGame::renderDebugStats(float time, Renderer::ProfileInfo& worldRenderTime
ss << "Player Activity: ";
if (player->getCurrentActivity()) {
ss << player->getCurrentActivity()->name();
}
else {
} else {
ss << "Idle";
}
ss << std::endl;
@ -825,7 +812,8 @@ void RWGame::renderDebugStats(float time, Renderer::ProfileInfo& worldRenderTime
ti.baseColour = glm::u8vec3(255);
renderer->text.renderText(ti);
/*while( engine->log.size() > 0 && engine->log.front().time + 10.f < engine->gameTime ) {
/*while( engine->log.size() > 0 && engine->log.front().time + 10.f <
engine->gameTime ) {
engine->log.pop_front();
}
@ -846,7 +834,8 @@ void RWGame::renderDebugStats(float time, Renderer::ProfileInfo& worldRenderTime
}
// Interpolate the color
// c.a = (engine->gameTime - it->time > 5.f) ? 255 - (((engine->gameTime - it->time) - 5.f)/5.f) * 255 : 255;
// c.a = (engine->gameTime - it->time > 5.f) ? 255 - (((engine->gameTime
- it->time) - 5.f)/5.f) * 255 : 255;
// text.setColor(c);
engine->renderer.text.renderText(ti);
@ -854,23 +843,23 @@ void RWGame::renderDebugStats(float time, Renderer::ProfileInfo& worldRenderTime
}*/
}
void RWGame::renderDebugPaths(float time)
{
void RWGame::renderDebugPaths(float time) {
RW_UNUSED(time);
btVector3 roadColour(1.f, 0.f, 0.f);
btVector3 pedColour(0.f, 0.f, 1.f);
for( AIGraphNode* n : world->aigraph.nodes )
{
for (AIGraphNode* n : world->aigraph.nodes) {
btVector3 p(n->position.x, n->position.y, n->position.z);
auto& col = n->type == AIGraphNode::Pedestrian ? pedColour : roadColour;
debug->drawLine( p - btVector3(0.f, 0.f, 1.f), p + btVector3(0.f, 0.f, 1.f), col);
debug->drawLine( p - btVector3(1.f, 0.f, 0.f), p + btVector3(1.f, 0.f, 0.f), col);
debug->drawLine( p - btVector3(0.f, 1.f, 0.f), p + btVector3(0.f, 1.f, 0.f), col);
debug->drawLine(p - btVector3(0.f, 0.f, 1.f),
p + btVector3(0.f, 0.f, 1.f), col);
debug->drawLine(p - btVector3(1.f, 0.f, 0.f),
p + btVector3(1.f, 0.f, 0.f), col);
debug->drawLine(p - btVector3(0.f, 1.f, 0.f),
p + btVector3(0.f, 1.f, 0.f), col);
for( AIGraphNode* c : n->connections )
{
for (AIGraphNode* c : n->connections) {
btVector3 f(c->position.x, c->position.y, c->position.z);
debug->drawLine(p, f, col);
}
@ -896,11 +885,15 @@ void RWGame::renderDebugPaths(float time)
for (size_t v = 0; v < state->vehicleGenerators.size(); ++v) {
auto& generator = state->vehicleGenerators[v];
btVector3 color(1.f, 0.f, 0.f);
btVector3 position(generator.position.x,generator.position.y,generator.position.z);
btVector3 position(generator.position.x, generator.position.y,
generator.position.z);
float heading = glm::radians(generator.heading);
auto back = btVector3(0.f,-1.f, 0.f).rotate(btVector3(0.f, 0.f, 1.f), heading);
auto right = btVector3(0.15f, -0.15f, 0.f).rotate(btVector3(0.f, 0.f, 1.f), heading);
auto left = btVector3(-0.15f,-0.15f, 0.f).rotate(btVector3(0.f, 0.f, 1.f), heading);
auto back =
btVector3(0.f, -1.f, 0.f).rotate(btVector3(0.f, 0.f, 1.f), heading);
auto right = btVector3(0.15f, -0.15f, 0.f)
.rotate(btVector3(0.f, 0.f, 1.f), heading);
auto left = btVector3(-0.15f, -0.15f, 0.f)
.rotate(btVector3(0.f, 0.f, 1.f), heading);
debug->drawLine(position, position + back, color);
debug->drawLine(position, position + right, color);
debug->drawLine(position, position + left, color);
@ -909,8 +902,7 @@ void RWGame::renderDebugPaths(float time)
debug->flush(renderer);
}
void RWGame::renderProfile()
{
void RWGame::renderProfile() {
#if RW_PROFILER
auto& frame = perf::Profiler::get().getFrame();
constexpr float upperlimit = 30000.f;
@ -921,35 +913,28 @@ void RWGame::renderProfile()
for (int r = 0; r < c; ++r) {
for (int g = 0; g < c; ++g) {
for (int b = 0; b < c; ++b) {
perf_colours.push_back({
r / c, g / c, b / c, 1.f
});
perf_colours.push_back({r / c, g / c, b / c, 1.f});
}
}
}
}
float xscale = renderer->getRenderer()->getViewport().x / upperlimit;
TextRenderer::TextInfo ti;
ti.align = TextRenderer::TextInfo::Left;
ti.font = 2;
ti.size = lineHeight - 2.f;
ti.baseColour = glm::u8vec3(255);
std::function<void(const perf::ProfileEntry&,int)> renderEntry = [&](const perf::ProfileEntry& entry, int depth)
{
std::function<void(const perf::ProfileEntry&, int)> renderEntry = [&](
const perf::ProfileEntry& entry, int depth) {
int g = 0;
for(auto& event : entry.childProfiles)
{
for (auto& event : entry.childProfiles) {
auto duration = event.end - event.start;
float y = 60.f + (depth * (lineHeight + 5.f));
renderer->drawColour(perf_colours[(std::hash<std::string>()(entry.label) * (g++))%perf_colours.size()],
{
xscale * event.start,
y,
xscale * duration,
lineHeight
});
renderer->drawColour(
perf_colours[(std::hash<std::string>()(entry.label) * (g++)) %
perf_colours.size()],
{xscale * event.start, y, xscale * duration, lineHeight});
ti.screenPosition.x = xscale * (event.start);
ti.screenPosition.y = y + 2.f;
ti.text = event.label + " " + std::to_string(duration) + " us ";
@ -964,8 +949,7 @@ void RWGame::renderProfile()
#endif
}
void RWGame::globalKeyEvent(const SDL_Event& event)
{
void RWGame::globalKeyEvent(const SDL_Event& event) {
switch (event.key.keysym.sym) {
case SDLK_LEFTBRACKET:
world->offsetGameTime(-30);
@ -988,7 +972,8 @@ void RWGame::globalKeyEvent(const SDL_Event& event)
case SDLK_F3:
showDebugPhysics = !showDebugPhysics;
break;
default: break;
default:
break;
}
std::string keyName = SDL_GetKeyName(event.key.keysym.sym);

View File

@ -1,12 +1,12 @@
#ifndef _RWGAME_HPP_
#define _RWGAME_HPP_
#include <chrono>
#include <core/Logger.hpp>
#include <engine/GameData.hpp>
#include <engine/GameWorld.hpp>
#include <render/GameRenderer.hpp>
#include <script/ScriptMachine.hpp>
#include <chrono>
#include "game.hpp"
#include "GameConfig.hpp"
@ -16,8 +16,7 @@
class PlayerController;
class RWGame
{
class RWGame {
Logger log;
GameConfig config{"openrw.ini"};
GameState* state = nullptr;
@ -43,8 +42,8 @@ class RWGame
float accum = 0.f;
float timescale = 1.f;
public:
public:
RWGame(int argc, char* argv[]);
~RWGame();
@ -55,43 +54,36 @@ public:
*/
void newGame();
GameState* getState() const
{
GameState* getState() const {
return state;
}
GameWorld* getWorld() const
{
GameWorld* getWorld() const {
return world;
}
GameData* getGameData() const
{
GameData* getGameData() const {
return data;
}
GameRenderer* getRenderer() const
{
GameRenderer* getRenderer() const {
return renderer;
}
GameWindow& getWindow()
{
GameWindow& getWindow() {
return *window;
}
ScriptMachine* getScript() const
{
ScriptMachine* getScript() const {
return script;
}
const GameConfig& getConfig() const
{
const GameConfig& getConfig() const {
return config;
}
bool hitWorldRay(glm::vec3 &hit, glm::vec3 &normal, GameObject** object = nullptr)
{
bool hitWorldRay(glm::vec3& hit, glm::vec3& normal,
GameObject** object = nullptr) {
auto vc = nextCam;
glm::vec3 from(vc.position.x, vc.position.y, vc.position.z);
glm::vec3 tmp = vc.rotation * glm::vec3(1000.f, 0.f, 0.f);
@ -99,21 +91,24 @@ public:
return hitWorldRay(from, tmp, hit, normal, object);
}
bool hitWorldRay(const glm::vec3 &start, const glm::vec3 &direction, glm::vec3 &hit, glm::vec3 &normal, GameObject **object = nullptr)
{
bool hitWorldRay(const glm::vec3& start, const glm::vec3& direction,
glm::vec3& hit, glm::vec3& normal,
GameObject** object = nullptr) {
auto from = btVector3(start.x, start.y, start.z);
auto to = btVector3(start.x+direction.x, start.y+direction.y, start.z+direction.z);
auto to = btVector3(start.x + direction.x, start.y + direction.y,
start.z + direction.z);
btCollisionWorld::ClosestRayResultCallback ray(from, to);
world->dynamicsWorld->rayTest(from, to, ray);
if( ray.hasHit() )
{
if (ray.hasHit()) {
hit = glm::vec3(ray.m_hitPointWorld.x(), ray.m_hitPointWorld.y(),
ray.m_hitPointWorld.z());
normal = glm::vec3(ray.m_hitNormalWorld.x(), ray.m_hitNormalWorld.y(),
normal =
glm::vec3(ray.m_hitNormalWorld.x(), ray.m_hitNormalWorld.y(),
ray.m_hitNormalWorld.z());
if (object) {
*object = static_cast<GameObject*>(ray.m_collisionObject->getUserPointer());
*object = static_cast<GameObject*>(
ray.m_collisionObject->getUserPointer());
}
return true;
}
@ -122,7 +117,9 @@ public:
void startScript(const std::string& name);
bool hasFocus() const { return inFocus; }
bool hasFocus() const {
return inFocus;
}
void saveGame(const std::string& savename);
void loadGame(const std::string& savename);

View File

@ -2,11 +2,11 @@
#include "RWGame.hpp"
// This serves as the "initial" camera position.
ViewCamera defaultView({-250.f, -550.f, 75.f}, glm::angleAxis(glm::radians(5.f), glm::vec3(0.f, 1.f, 0.f)));
ViewCamera defaultView({-250.f, -550.f, 75.f},
glm::angleAxis(glm::radians(5.f),
glm::vec3(0.f, 1.f, 0.f)));
void State::handleEvent(const SDL_Event& e)
{
void State::handleEvent(const SDL_Event& e) {
auto m = getCurrentMenu();
if (!m) return;
@ -37,22 +37,18 @@ void State::handleEvent(const SDL_Event& e)
}
}
const ViewCamera& State::getCamera()
{
const ViewCamera& State::getCamera() {
return defaultView;
}
bool State::shouldWorldUpdate()
{
bool State::shouldWorldUpdate() {
return false;
}
GameWorld* State::getWorld()
{
GameWorld* State::getWorld() {
return game->getWorld();
}
GameWindow& State::getWindow()
{
GameWindow& State::getWindow() {
return game->getWindow();
}

View File

@ -1,35 +1,33 @@
#ifndef _GAME_STATE_HPP_
#define _GAME_STATE_HPP_
#include <functional>
#include <glm/gtc/quaternion.hpp>
#include <queue>
#include <render/ViewCamera.hpp>
#include "GameWindow.hpp"
#include "MenuSystem.hpp"
#include <glm/gtc/quaternion.hpp>
#include "SDL.h"
#include "SDL_events.h"
#include "GameWindow.hpp"
class RWGame;
class GameWorld;
struct State
{
struct State {
// Helper for global menu behaviour
Menu* currentMenu;
Menu* nextMenu;
RWGame* game;
State(RWGame* game)
: currentMenu(nullptr), nextMenu(nullptr), game(game) {}
State(RWGame* game) : currentMenu(nullptr), nextMenu(nullptr), game(game) {
}
virtual void enter() = 0;
virtual void exit() = 0;
virtual void tick(float dt) = 0;
virtual void draw(GameRenderer* r)
{
virtual void draw(GameRenderer* r) {
if (getCurrentMenu()) {
getCurrentMenu()->draw(r);
}
@ -41,13 +39,11 @@ struct State
}
}
void enterMenu(Menu* menu)
{
void enterMenu(Menu* menu) {
nextMenu = menu;
}
Menu* getCurrentMenu()
{
Menu* getCurrentMenu() {
if (nextMenu) {
if (currentMenu) {
delete currentMenu;
@ -72,45 +68,37 @@ struct State
GameWindow& getWindow();
};
struct StateManager
{
static StateManager& get()
{
struct StateManager {
static StateManager& get() {
static StateManager m;
return m;
}
std::deque<State*> states;
void clear()
{
void clear() {
states.clear();
}
void enter(State* state)
{
void enter(State* state) {
states.push_back(state);
state->enter();
}
void exec(State* state)
{
void exec(State* state) {
exit();
enter(state);
}
void tick(float dt)
{
void tick(float dt) {
states.back()->tick(dt);
}
void draw(GameRenderer* r)
{
void draw(GameRenderer* r) {
states.back()->draw(r);
}
void exit()
{
void exit() {
// TODO: Resole states being leaked.
states.back()->exit();
states.pop_back();

View File

@ -1,20 +1,21 @@
#ifndef GAME_HPP
#define GAME_HPP
#include <objects/GameObject.hpp>
#include <engine/GameWorld.hpp>
#include <objects/GameObject.hpp>
constexpr double PiOver180 = 3.1415926535897932384626433832795028 / 180;
// TODO: Move all of this stuff so it's not just lying around.
bool hitWorldRay(glm::vec3& hit, glm::vec3& normal, GameObject** object = nullptr);
bool hitWorldRay(glm::vec3& hit, glm::vec3& normal,
GameObject** object = nullptr);
bool hitWorldRay(const glm::vec3& start, const glm::vec3& direction,
glm::vec3& hit, glm::vec3& normal, GameObject** object = nullptr);
glm::vec3& hit, glm::vec3& normal,
GameObject** object = nullptr);
#define GAME_TIMESTEP (1.f / 30.f)
#define GAME_WINDOW_WIDTH 800
#define GAME_WINDOW_HEIGHT 600
#endif // GAME_HPP

View File

@ -1,9 +1,8 @@
#include <iostream>
#include "RWGame.hpp"
#include "SDL.h"
#include <iostream>
int main(int argc, char* argv[])
{
int main(int argc, char* argv[]) {
try {
RWGame game(argc, argv);