Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
62 changes: 62 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Compilation/Formatting

- Read the README.md in the repository root for instructions on how to compile on Linux, Windows/Visual Studio, ...
- Compilation **MUST** finish without any warnings
- Formatting uses clang-format-10 and can be automatically done via `make clangFormat`
- `clang-tidy` is used for further static analysis, `tools/runClangTidy.sh` can be used to run it manually with a configured build tree

# Testing / Bug fixing

- For each Bug fixed/feature added, there should be a test (GUI excluded until this is possible too)
- Keep tests small, complete and descriptive
- Some tests may run differently based on the Random Generator (RNG), make sure they succeed in all cases but keep the constraints tight
- If a test fails suddenly, it may depend on the RNG. Make sure the behaviour is correct before e.g increasing max. GF amount to wait till the event is checked

# Naming

- Classes/Structs: UpperCamelCase
- Parameters, local variables, member functions: lowerCamelCase
- Member variables: Suffix "\_" (e.g. `myMember_`)
- Do not shadow variables (e.g. using the name of a member as a parameter)
- Use imperative for setters and question-style for getters e.g. `lieSomewhere`, `carry`, `burn` and `isLying`, `isValid`, `canChange`

# Locals / String encoding / Paths / UTF8

- All strings (`std::string`) used in the program **must** be encoded in UTF8. Conversion from different encodings must be done on reading/writing ONLY. Use the helper functions in libUtil (`ucString.h` or `utf8.h`)
- Filepaths/Folderpaths must be stored in `bfs::path` variables
- 'Filepath' means a complete path whereas 'Filename' is just the name itself
- Use `bfs` function for all file system operations
- Note: 'bfs::path::string()` returns an UTF8 encoded string already. No need to use conversions there (see https://github.com/Return-To-The-Roots/s25client/pull/645)

# General

- Small include files
- Use forward declarations instead of including headers
- Include what you use (e.g. when using `std::vector`, include `<vector>`)
- Once class/struct per file, avoid "collections" of structs even when they belong partly together
- Check STL/Boost before rolling your own implementations
- Implementing any of the **Big 3** (copy ctor, copy assignment, destructor) requires implementing the others as well. For classes, that should not be copied (e.g. having open handles) declare copy ctor **AND** copy assignment in private region and *do not* implement it. Put a comment there.
- Comment functions you write at least with a summary in the header. use JavaDoc syntax (Either `///` or `/** foo bar */`)
- Make sure assumptions are met ->
- Use `static_assert` to check what is possible during compile-time
- Use exceptions for enforcing stuff at runtime (e.g. parameter values, switch(enum) defaults)
- Use `assert`s for general conditions that should be met, but are less critical or performance-wise expensive to check
- Avoid unnecessary branches: No need for an `else` after a `return`. Additional branches require additional indentation which makes (especially) longer functions hard to read.
- Avoid code duplication: If you write the same or very similar thing twice (even in one function), factor it out into a new function. This eases maintainability if one ever needs to change or fix that.
- **Document your functions!**
- put at least a one-liner in the header describing what it does
- For more complex functions include also pre-/post-conditions, special cases, ...
- If you have problems understanding a function and finally figured it out: Help others and add that to the docu
- Do not describe trivial things like "this is a copy-ctor/sets foo/gets bar" as this should be obvious from the function name (`FooBar(const FooBar&)` / `void setFoo(foo)` / `Bar getBar()`)

# Safety

- Use RAII idiom
- Encapsulate all resources once they are acquired
- Use STL collections (`vector`, `list`, ...)
- Use smart pointers (`std::unique_ptr`, `boost::intrusive_shared_ptr`, `std::shared_pointer` in that order)
- `delete[]` should never be used. Use C++ structs (e.g. `vector`)
- Use `std::array`instead of plain C-arrays
- Do __NOT__ use magic constants. All constants should be made named consts (or defines). For iterations, use iterators or actual sizes
- Do not use printf/sprint/snprintf,fprintf,... They can easily cause buffer overflows. Use C++ streams instead

82 changes: 41 additions & 41 deletions extras/ai-battle/HeadlessGame.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,90 +35,90 @@ HeadlessGame::HeadlessGame(const GlobalGameSettings& ggs, const bfs::path& map,
mapInfo.type = MapType::OldMap;
mapInfo.filepath = map;
mapInfo.luaFilepath = luaPath;
SetupGameWorld(game_, mapInfo, localState_, nullptr);
setupGameWorld(game_, mapInfo, localState_, nullptr);

if(world_.HasLua())
if(world_.hasLua())
{
world_.GetLua().setSuppressStdout(true);
world_.getLua().setSuppressStdout(true);
luaPath_ = luaPath;
bnw::cout << "Lua script loaded: " << luaPath << '\n';
}

for(unsigned playerId = 0; playerId < world_.GetNumPlayers(); ++playerId)
players_.push_back(AIFactory::Create(world_.GetPlayer(playerId).aiInfo, playerId, world_));
for(unsigned playerId = 0; playerId < world_.getNumPlayers(); ++playerId)
players_.push_back(AIFactory::create(world_.getPlayer(playerId).aiInfo, playerId, world_));
}

HeadlessGame::~HeadlessGame()
{
Close();
close();
}

void HeadlessGame::Run(unsigned maxGF)
void HeadlessGame::run(unsigned maxGF)
{
AsyncChecksum checksum;
gameStartTime_ = std::chrono::steady_clock::now();
auto nextReport = gameStartTime_ + std::chrono::seconds(1);

game_.Start(false);
game_.start(false);

while(em_.GetCurrentGF() < maxGF && !game_.IsGameFinished())
while(em_.getCurrentGF() < maxGF && !game_.isGameFinished())
{
// In the actual game, the network frame intervall is based on ping (highest_ping < NFW-length < 20*gf_length).
bool isnfw = em_.GetCurrentGF() % 20 == 0;
bool isnfw = em_.getCurrentGF() % 20 == 0;

if(isnfw)
{
if(replay_.IsRecording())
if(replay_.isRecording())
checksum = AsyncChecksum::create(game_);
for(unsigned playerId = 0; playerId < world_.GetNumPlayers(); ++playerId)
for(unsigned playerId = 0; playerId < world_.getNumPlayers(); ++playerId)
{
world_.GetPlayer(playerId);
world_.getPlayer(playerId);
AIPlayer* player = players_[playerId].get();
PlayerGameCommands cmds;
cmds.gcs = player->FetchGameCommands();

if(replay_.IsRecording() && !cmds.gcs.empty())
if(replay_.isRecording() && !cmds.gcs.empty())
{
cmds.checksum = checksum;
replay_.AddGameCommand(em_.GetCurrentGF(), playerId, cmds);
replay_.addGameCommand(em_.getCurrentGF(), playerId, cmds);
}

for(const gc::GameCommandPtr& gc : cmds.gcs)
gc->Execute(world_, player->GetPlayerId());
gc->execute(world_, player->getPlayerId());
}
}

for(auto& player : players_)
player->RunGF(em_.GetCurrentGF(), isnfw);
player->runGF(em_.getCurrentGF(), isnfw);

game_.RunGF();
game_.runGF();

if(replay_.IsRecording())
replay_.UpdateLastGF(em_.GetCurrentGF());
if(replay_.isRecording())
replay_.updateLastGF(em_.getCurrentGF());

if(std::chrono::steady_clock::now() > nextReport)
{
nextReport += std::chrono::seconds(1);
PrintState();
printState();
}
}
PrintState();
printState();
}

void HeadlessGame::Close()
void HeadlessGame::close()
{
bnw::cout << '\n';

if(replay_.IsRecording())
if(replay_.isRecording())
{
replay_.StopRecording();
replay_.stopRecording();
bnw::cout << "Replay written to " << canonical(replayPath_) << '\n';
}

replay_.Close();
replay_.close();
}

void HeadlessGame::RecordReplay(const bfs::path& path, unsigned random_init)
void HeadlessGame::recordReplay(const bfs::path& path, unsigned random_init)
{
// Remove old replay
bfs::remove(path);
Expand All @@ -127,50 +127,50 @@ void HeadlessGame::RecordReplay(const bfs::path& path, unsigned random_init)

MapInfo mapInfo;
mapInfo.filepath = map_;
mapInfo.mapData.CompressFromFile(mapInfo.filepath, &mapInfo.mapChecksum);
mapInfo.mapData.compressFromFile(mapInfo.filepath, &mapInfo.mapChecksum);
mapInfo.type = MapType::OldMap;

if(!luaPath_.empty() && bfs::exists(luaPath_))
{
mapInfo.luaFilepath = luaPath_;
mapInfo.luaData.CompressFromFile(luaPath_, &mapInfo.luaChecksum);
mapInfo.luaData.compressFromFile(luaPath_, &mapInfo.luaChecksum);
}

for(auto& player : world_.getPlayers())
replay_.AddPlayer(player);
replay_.addPlayer(player);
replay_.ggs = game_.ggs_;
if(!replay_.StartRecording(path, mapInfo, random_init))
if(!replay_.startRecording(path, mapInfo, random_init))
throw std::runtime_error("Replayfile could not be opened!");
}

void HeadlessGame::SaveGame(const bfs::path& path) const
void HeadlessGame::saveGame(const bfs::path& path) const
{
// Remove old savegame
bfs::remove(path);

Savegame save;
for(auto& player : world_.getPlayers())
save.AddPlayer(player);
save.addPlayer(player);
save.ggs = game_.ggs_;
save.ggs.exploration = Exploration::Disabled; // no FOW
save.start_gf = em_.GetCurrentGF();
save.sgd.MakeSnapshot(game_);
save.Save(path, "AI Battle");
save.start_gf = em_.getCurrentGF();
save.sgd.makeSnapshot(game_);
save.save(path, "AI Battle");

bnw::cout << "Savegame written to " << canonical(path) << '\n';
}

void HeadlessGame::PrintState()
void HeadlessGame::printState()
{
HeadlessStats stats;
stats.currentGF = em_.GetCurrentGF();
stats.currentGF = em_.getCurrentGF();
stats.gameTime =
std::chrono::duration_cast<std::chrono::milliseconds>(SPEED_GF_LENGTHS[GameSpeed::Normal] * em_.GetCurrentGF());
std::chrono::duration_cast<std::chrono::milliseconds>(SPEED_GF_LENGTHS[GameSpeed::Normal] * em_.getCurrentGF());
stats.wallTime =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - gameStartTime_);
stats.gfPerSecond = em_.GetCurrentGF() - lastReportGf_;
stats.gfPerSecond = em_.getCurrentGF() - lastReportGf_;
statsPrinter_.print(stats, world_);
lastReportGf_ = em_.GetCurrentGF();
lastReportGf_ = em_.getCurrentGF();
}

std::vector<PlayerInfo> GeneratePlayerInfo(const std::vector<AI::Info>& ais, const std::vector<Team>& teams)
Expand Down
10 changes: 5 additions & 5 deletions extras/ai-battle/HeadlessGame.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ class HeadlessGame
const boost::filesystem::path& luaPath = {}, const std::vector<Team>& teams = {});
~HeadlessGame();

void Run(unsigned maxGF = std::numeric_limits<unsigned>::max());
void Close();
void run(unsigned maxGF = std::numeric_limits<unsigned>::max());
void close();

void RecordReplay(const boost::filesystem::path& path, unsigned random_init);
void SaveGame(const boost::filesystem::path& path) const;
void recordReplay(const boost::filesystem::path& path, unsigned random_init);
void saveGame(const boost::filesystem::path& path) const;

private:
void PrintState();
void printState();

NullLocalGameState localState_;
boost::filesystem::path map_;
Expand Down
12 changes: 6 additions & 6 deletions extras/ai-battle/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ int main(int argc, char** argv)
}
if(options.count("version"))
{
bnw::cout << rttr::version::GetTitle() << " v" << rttr::version::GetVersion() << "-"
<< rttr::version::GetRevision() << std::endl
bnw::cout << rttr::version::getTitle() << " v" << rttr::version::getVersion() << "-"
<< rttr::version::getRevision() << std::endl
<< "Compiled with " << System::getCompilerName() << " for " << System::getOSName() << std::endl;
return 0;
}
Expand Down Expand Up @@ -256,12 +256,12 @@ int main(int argc, char** argv)
HeadlessGame game(ggs, mapPath, ais, opts.lua_path ? RTTRCONFIG.ExpandPath(*opts.lua_path) : bfs::path{},
teams);
if(opts.replay_path)
game.RecordReplay(RTTRCONFIG.ExpandPath(*opts.replay_path), opts.random_init);
game.recordReplay(RTTRCONFIG.ExpandPath(*opts.replay_path), opts.random_init);

game.Run(opts.maxGF);
game.Close();
game.run(opts.maxGF);
game.close();
if(opts.savegame_path)
game.SaveGame(RTTRCONFIG.ExpandPath(*opts.savegame_path));
game.saveGame(RTTRCONFIG.ExpandPath(*opts.savegame_path));
} catch(const std::exception& e)
{
bnw::cerr << e.what() << std::endl;
Expand Down
Loading
Loading