code refactoring

master
Vectozavr 2021-11-10 02:54:20 +07:00
parent fd1573a77d
commit 5e069cef68
45 changed files with 483 additions and 495 deletions

View File

@ -102,7 +102,7 @@ add_executable(shooter
engine/animation/AAttractToPoint.h
engine/animation/ARotateRelativePoint.h
engine/animation/ARotateLeft.h
)
engine/animation/Interpolation.cpp engine/animation/Animations.h)
if(APPLE OR UNIX)
include_directories(/usr/local/include)

View File

@ -7,18 +7,14 @@
#include <utility>
#include "engine/Screen.h"
#include "engine/utils/Log.h"
#include "engine/animation/Animations.h"
#include "engine/animation/Timeline.h"
#include "engine/animation/ARotateLeft.h"
Player::Player(ObjectNameTag name, const std::string &filename, const Vec3D &scale) : RigidBody(std::move(name), filename,scale) {
Player::Player(ObjectNameTag name, const std::string &filename, const Vec3D &scale) : RigidBody(std::move(name), filename, scale) {
setAcceleration(Vec3D{0, -ShooterConsts::GRAVITY, 0});
setCollision(true);
setVisible(false);
setSimpleHitBox(true);
setCollisionCallBack(
[this](const ObjectNameTag &tag, std::shared_ptr<RigidBody> obj) { collisionWithObject(tag, obj); });
setCollisionCallBack([this](const ObjectNameTag &tag, std::shared_ptr<RigidBody> obj) { collisionWithObject(tag, obj); });
}
void Player::rotateWeaponsRelativePoint(const Vec3D &point4D, const Vec3D &v, double val) {
@ -68,7 +64,7 @@ void Player::addWeapon(std::shared_ptr<Weapon> weapon) {
for (auto &w : _weapons) {
if (w->name() == weapon->name()) {
w->addAmmo(w->initialPack());
w->addAPack();
return;
}
}
@ -82,12 +78,12 @@ void Player::addWeapon(std::shared_ptr<Weapon> weapon) {
// add animation of reloading
_weapons.back()->setReloadCallBack([this]() {
Timeline::animate(AnimationListTag("reload_weapon"),
std::make_shared<ARotateLeft>(_weapons[_selectedWeapon],
Timeline::addAnimation<ARotateLeft>(AnimationListTag("reload_weapon"),
_weapons[_selectedWeapon],
-4 * Consts::PI,
_weapons[_selectedWeapon]->reloadTime()/2,
_weapons[_selectedWeapon]->reloadTime() / 2,
Animation::LoopOut::None,
Animation::InterpolationType::Cos));
Animation::InterpolationType::Cos);
});
// add call back function to create fire traces

View File

@ -4,11 +4,8 @@
#include "PlayerController.h"
#include "engine/utils/Log.h"
#include "engine/animation/AWait.h"
#include "engine/animation/ATranslate.h"
#include "engine/animation/ATranslateToPoint.h"
#include "engine/animation/Timeline.h"
#include "ShooterConsts.h"
#include "engine/animation/Animations.h"
PlayerController::PlayerController(std::shared_ptr<Player> player,
std::shared_ptr<Keyboard> keyboard,
@ -46,43 +43,50 @@ void PlayerController::update() {
std::shared_ptr<Object> camera = _player->attached(ObjectNameTag("Camera"));
if (camera != nullptr && _inRunning && _player->inCollision()) {
if (!Timeline::isInAnimList(AnimationListTag("camera_hor_oscil"))) {
Timeline::animate(AnimationListTag("camera_hor_oscil"),
std::make_shared<ATranslate>(camera, -camera->left() / 6, 0.3, Animation::LoopOut::None,
Animation::InterpolationType::Cos));
Timeline::animate(AnimationListTag("camera_hor_oscil"), std::make_shared<AWait>(0));
Timeline::animate(AnimationListTag("camera_hor_oscil"),
std::make_shared<ATranslate>(camera, camera->left() / 6, 0.3, Animation::LoopOut::None,
Animation::InterpolationType::Cos));
Timeline::animate(AnimationListTag("camera_vert_oscil"),
std::make_shared<ATranslate>(camera, -Vec3D{0, 1, 0} / 12, 0.15, Animation::LoopOut::None,
Animation::InterpolationType::Cos));
Timeline::animate(AnimationListTag("camera_vert_oscil"), std::make_shared<AWait>(0));
Timeline::animate(AnimationListTag("camera_vert_oscil"),
std::make_shared<ATranslate>(camera, Vec3D{0, 1, 0} / 12, 0.15, Animation::LoopOut::None,
Animation::InterpolationType::Cos));
Timeline::animate(AnimationListTag("camera_vert_oscil"), std::make_shared<AWait>(0));
Timeline::animate(AnimationListTag("camera_vert_oscil"),
std::make_shared<ATranslate>(camera, -Vec3D{0, 1, 0} / 12, 0.15, Animation::LoopOut::None,
Animation::InterpolationType::Cos));
Timeline::animate(AnimationListTag("camera_vert_oscil"), std::make_shared<AWait>(0));
Timeline::animate(AnimationListTag("camera_vert_oscil"),
std::make_shared<ATranslate>(camera, Vec3D{0, 1, 0} / 12, 0.15, Animation::LoopOut::None,
Animation::InterpolationType::Cos));
Timeline::animate(AnimationListTag("camera_init"),
std::make_shared<ATranslateToPoint>(camera, _player->position() + Vec3D{0, 1.8, 0}, 0.3,
Timeline::addAnimation<ATranslate>(AnimationListTag("camera_hor_oscil"),
camera, -camera->left() / 6, 0.3,
Animation::LoopOut::None,
Animation::InterpolationType::Cos));
Animation::InterpolationType::Cos);
Timeline::addAnimation<AWait>(AnimationListTag("camera_hor_oscil"), 0);
Timeline::addAnimation<ATranslate>(AnimationListTag("camera_hor_oscil"),
camera, camera->left() / 6, 0.3,
Animation::LoopOut::None,
Animation::InterpolationType::Cos);
Timeline::addAnimation<ATranslate>(AnimationListTag("camera_vert_oscil"),
camera, -Vec3D{0, 1, 0} / 12, 0.15,
Animation::LoopOut::None,
Animation::InterpolationType::Cos);
Timeline::addAnimation<AWait>(AnimationListTag("camera_vert_oscil"), 0);
Timeline::addAnimation<ATranslate>(AnimationListTag("camera_vert_oscil"),
camera, Vec3D{0, 1, 0} / 12, 0.15,
Animation::LoopOut::None,
Animation::InterpolationType::Cos);
Timeline::addAnimation<AWait>(AnimationListTag("camera_vert_oscil"), 0);
Timeline::addAnimation<ATranslate>(AnimationListTag("camera_vert_oscil"),
camera, -Vec3D{0, 1, 0} / 12, 0.15,
Animation::LoopOut::None,
Animation::InterpolationType::Cos);
Timeline::addAnimation<AWait>(AnimationListTag("camera_vert_oscil"), 0);
Timeline::addAnimation<ATranslate>(AnimationListTag("camera_vert_oscil"),
camera, Vec3D{0, 1, 0} / 12, 0.15,
Animation::LoopOut::None,
Animation::InterpolationType::Cos);
Timeline::addAnimation<ATranslateToPoint>(AnimationListTag("camera_init"),
camera, _player->position() + Vec3D{0, 1.8, 0},
0.3,
Animation::LoopOut::None,
Animation::InterpolationType::Cos);
}
} else if (camera != nullptr && inRunning_old && !_inRunning) {
Timeline::deleteAnimationList(AnimationListTag("camera_hor_oscil"));
Timeline::deleteAnimationList(AnimationListTag("camera_vert_oscil"));
Timeline::deleteAnimationList(AnimationListTag("camera_init"));
Timeline::animate(AnimationListTag("camera_init"),
std::make_shared<ATranslateToPoint>(camera, _player->position() + Vec3D{0, 1.8, 0}, 0.15,
Timeline::addAnimation<ATranslateToPoint>(AnimationListTag("camera_init"),
camera, _player->position() + Vec3D{0, 1.8, 0}, 0.15,
Animation::LoopOut::None,
Animation::InterpolationType::Cos));
Animation::InterpolationType::Cos);
}
// Left and right

View File

@ -5,17 +5,9 @@
#include "Shooter.h"
#include <fstream>
#include <utility>
#include "engine/animation/AColor.h"
#include "engine/animation/AFunction.h"
#include "engine/animation/ARotate.h"
#include "engine/animation/Timeline.h"
#include "engine/animation/Animations.h"
#include "ShooterConsts.h"
#include "engine/SoundController.h"
#include "engine/animation/AAttractToPoint.h"
#include "engine/animation/ARotateRelativePoint.h"
#include "engine/animation/ATranslateToPoint.h"
#include "engine/animation/AWait.h"
#include "engine/animation/ATranslate.h"
using namespace std;
@ -199,7 +191,8 @@ void Shooter::drawStatsTable() {
screen->drawText(client->lastEvent(), Vec2D{10, 10}, 25, sf::Color(0, 0, 0, 100));
vector<shared_ptr<Player>> allPlayers;
vector<shared_ptr < Player>>
allPlayers;
allPlayers.push_back(player);
for (auto&[playerId, player] : client->players())
allPlayers.push_back(player);
@ -276,8 +269,8 @@ void Shooter::spawnPlayer(sf::Uint16 id) {
world->body(ObjectNameTag(name + "_foot_2"))->translate(Vec3D{0.25, 0, 0});
newPlayer->attach(world->body(ObjectNameTag(name + "_foot_2")));
int colorBodyNum = static_cast<int> (static_cast<double>((rand()-1)) / RAND_MAX * 5.0);
int colorFootNum = static_cast<int> (static_cast<double>((rand()-1)) / RAND_MAX * 5.0);
int colorBodyNum = static_cast<int> (static_cast<double>((rand() - 1)) / RAND_MAX * 5.0);
int colorFootNum = static_cast<int> (static_cast<double>((rand() - 1)) / RAND_MAX * 5.0);
newPlayer->setColor(ShooterConsts::WHITE_COLORS[colorBodyNum]);
world->body(ObjectNameTag(name + "_foot_1"))->setColor(ShooterConsts::DARK_COLORS[colorFootNum]);
@ -301,11 +294,11 @@ void Shooter::addFireTrace(const Vec3D &from, const Vec3D &to) {
world->addBody(std::make_shared<RigidBody>(Mesh::LineTo(ObjectNameTag(traceName), from, to, 0.05)));
world->body(ObjectNameTag(traceName))->setCollider(false);
Timeline::animate(AnimationListTag(traceName + "_fadeOut"),
std::make_shared<AColor>(world->body(ObjectNameTag(traceName)), sf::Color{150, 150, 150, 0}));
Timeline::animate(AnimationListTag(traceName + "_delete"),
std::make_shared<AFunction>([this, traceName]() { removeFireTrace(ObjectNameTag(traceName)); }, 1,
1));
Timeline::addAnimation<AColor>(AnimationListTag(traceName + "_fadeOut"), world->body(ObjectNameTag(traceName)),
sf::Color{150, 150, 150, 0});
Timeline::addAnimation<AFunction>(AnimationListTag(traceName + "_delete"),
[this, traceName]() { removeFireTrace(ObjectNameTag(traceName)); }, 1,
1);
}
void Shooter::removeFireTrace(const ObjectNameTag &traceName) {
@ -320,11 +313,12 @@ void Shooter::addBonus(const string &bonusName, const Vec3D &position) {
world->addBody(std::make_shared<RigidBody>(ObjectNameTag(bonusName), "obj/" + name + ".obj", Vec3D{3, 3, 3}));
world->body(ObjectNameTag(bonusName))->translateToPoint(position);
world->body(ObjectNameTag(bonusName))->setCollider(false);
world->body(ObjectNameTag(bonusName))->setSimpleHitBox(true);
world->body(ObjectNameTag(bonusName))->setTrigger(true);
Timeline::animate(AnimationListTag(bonusName + "_rotation"),
std::make_shared<ARotate>(world->body(ObjectNameTag(bonusName)), Vec3D{0, 2 * Consts::PI, 0}, 4,
Animation::LoopOut::Continue, Animation::InterpolationType::Linear));
Timeline::addAnimation<ARotate>(AnimationListTag(bonusName + "_rotation"),
world->body(ObjectNameTag(bonusName)),
Vec3D{0, 2 * Consts::PI, 0}, 4,
Animation::LoopOut::Continue,
Animation::InterpolationType::Linear);
}
void Shooter::removeBonus(const ObjectNameTag &bonusName) {

View File

@ -8,13 +8,7 @@
#include "engine/utils/Log.h"
#include "engine/animation/Timeline.h"
#include "ShooterMsgType.h"
#include "engine/animation/AAttractToPoint.h"
#include "engine/animation/ARotateRelativePoint.h"
#include "engine/animation/ATranslateToPoint.h"
#include "engine/animation/AWait.h"
#include "engine/animation/AFunction.h"
#include "engine/animation/ARotateLeft.h"
#include "engine/animation/Animations.h"
void ShooterClient::updatePacket() {
sf::Packet packet;
@ -74,19 +68,32 @@ void ShooterClient::processUpdate(sf::Packet &packet) {
weapon->rotateLeft(buf[5] - _players[targetId]->headAngle());
}
if(isAnimate) {
if(foot1 != nullptr && foot2 != nullptr && !Timeline::isInAnimList(AnimationListTag(name + "_foot1_rotation"))) {
Timeline::animate(AnimationListTag(name + "_foot1_rotation"), std::make_shared<ARotateLeft>(foot1, 0.6, 0.2, Animation::LoopOut::None, Animation::InterpolationType::Linear));
Timeline::animate(AnimationListTag(name + "_foot1_rotation"), std::make_shared<AWait>(0));
Timeline::animate(AnimationListTag(name + "_foot1_rotation"), std::make_shared<ARotateLeft>(foot1, -1.2, 0.2, Animation::LoopOut::None, Animation::InterpolationType::Linear));
Timeline::animate(AnimationListTag(name + "_foot1_rotation"), std::make_shared<AWait>(0));
Timeline::animate(AnimationListTag(name + "_foot1_rotation"), std::make_shared<ARotateLeft>(foot1, 0.6, 0.2, Animation::LoopOut::None, Animation::InterpolationType::Linear));
if (isAnimate) {
if (foot1 != nullptr && foot2 != nullptr &&
!Timeline::isInAnimList(AnimationListTag(name + "_foot1_rotation"))) {
Timeline::addAnimation<ARotateLeft>(AnimationListTag(name + "_foot1_rotation"),
foot1, 0.6, 0.2, Animation::LoopOut::None,
Animation::InterpolationType::Linear);
Timeline::addAnimation<AWait>(AnimationListTag(name + "_foot1_rotation"), 0);
Timeline::addAnimation<ARotateLeft>(AnimationListTag(name + "_foot1_rotation"),
foot1, -1.2, 0.2, Animation::LoopOut::None,
Animation::InterpolationType::Linear);
Timeline::addAnimation<AWait>(AnimationListTag(name + "_foot1_rotation"), 0);
Timeline::addAnimation<ARotateLeft>(AnimationListTag(name + "_foot1_rotation"),
foot1, 0.6, 0.2, Animation::LoopOut::None,
Animation::InterpolationType::Linear);
Timeline::animate(AnimationListTag(name + "_foot2_rotation"), std::make_shared<ARotateLeft>(foot2, -0.6, 0.2, Animation::LoopOut::None, Animation::InterpolationType::Linear));
Timeline::animate(AnimationListTag(name + "_foot2_rotation"), std::make_shared<AWait>(0));
Timeline::animate(AnimationListTag(name + "_foot2_rotation"), std::make_shared<ARotateLeft>(foot2, 1.2, 0.2, Animation::LoopOut::None, Animation::InterpolationType::Linear));
Timeline::animate(AnimationListTag(name + "_foot2_rotation"), std::make_shared<AWait>(0));
Timeline::animate(AnimationListTag(name + "_foot2_rotation"), std::make_shared<ARotateLeft>(foot2, -0.6, 0.2, Animation::LoopOut::None, Animation::InterpolationType::Linear));
Timeline::addAnimation<ARotateLeft>(AnimationListTag(name + "_foot2_rotation"),
foot2, -0.6, 0.2, Animation::LoopOut::None,
Animation::InterpolationType::Linear);
Timeline::addAnimation<AWait>(AnimationListTag(name + "_foot2_rotation"), 0);
Timeline::addAnimation<ARotateLeft>(AnimationListTag(name + "_foot2_rotation"),
foot2, 1.2, 0.2, Animation::LoopOut::None,
Animation::InterpolationType::Linear);
Timeline::addAnimation<AWait>(AnimationListTag(name + "_foot2_rotation"), 0);
Timeline::addAnimation<ARotateLeft>(AnimationListTag(name + "_foot2_rotation"),
foot2, -0.6, 0.2, Animation::LoopOut::None,
Animation::InterpolationType::Linear);
}
}
@ -141,7 +148,7 @@ void ShooterClient::processCustomPacket(sf::Packet &packet) {
_player->addDeath();
auto camera = _player->attached(ObjectNameTag("Camera"));
if(camera == nullptr) {
if (camera == nullptr) {
break;
}
@ -150,13 +157,18 @@ void ShooterClient::processCustomPacket(sf::Packet &packet) {
camera->rotateLeft(-camera->angleLeftUpLookAt().x());
camera->transform(Matrix4x4::Rotation(-_player->angle()));
Timeline::animate(AnimationListTag("camera_anim"), std::make_shared<ATranslateToPoint>(camera, Vec3D(0, 30, -100)));
Timeline::animate(AnimationListTag("camera_anim"), std::make_shared<AWait>(0));
Timeline::animate(AnimationListTag("camera_anim"), std::make_shared<ARotateRelativePoint>(camera, Vec3D(0), Vec3D{0, Consts::PI, 0}, 5, Animation::LoopOut::None, Animation::InterpolationType::Linear));
Timeline::animate(AnimationListTag("camera_anim"), std::make_shared<AWait>(0));
Timeline::animate(AnimationListTag("camera_anim"), std::make_shared<AFunction>([this, camera](){
Timeline::addAnimation<ATranslateToPoint>(AnimationListTag("camera_anim"),
camera, Vec3D(0, 30, -100));
Timeline::addAnimation<AWait>(AnimationListTag("camera_anim"), 0);
Timeline::addAnimation<ARotateRelativePoint>(AnimationListTag("camera_anim"),
camera, Vec3D(0), Vec3D{0, Consts::PI, 0},
5, Animation::LoopOut::None,
Animation::InterpolationType::Linear);
Timeline::addAnimation<AWait>(AnimationListTag("camera_anim"), 0);
Timeline::addAnimation<AFunction>(AnimationListTag("camera_anim"), [this, camera]() {
// respawn
_player->translateToPoint(Vec3D{50.0 * (-1 + 2.0 * (double) rand() / RAND_MAX), 30.0 * (double) rand() / RAND_MAX,
_player->translateToPoint(
Vec3D{50.0 * (-1 + 2.0 * (double) rand() / RAND_MAX), 30.0 * (double) rand() / RAND_MAX,
50.0 * (-1 + 2.0 * (double) rand() / RAND_MAX)});
_player->reInitWeapons();
_player->setFullAbility();
@ -167,7 +179,7 @@ void ShooterClient::processCustomPacket(sf::Packet &packet) {
camera->translateToPoint(_player->position() + Vec3D{0, 1.8, 0});
_player->attach(camera);
}, 1, 0.1));
}, 1, 0.1);
SoundController::playSound(SoundTag("death"), ShooterConsts::DEATH_SOUND);

View File

@ -11,7 +11,7 @@
namespace Consts {
const int STANDARD_SCREEN_WIDTH = 1920;
const int STANDARD_SCREEN_HEIGHT = 1920;
const int STANDARD_SCREEN_HEIGHT = 1080;
const sf::Color BACKGROUND_COLOR = sf::Color(255, 255, 255);
const std::string PROJECT_NAME = "engine";
const bool USE_LOG_FILE = true;

View File

@ -39,10 +39,6 @@ Mesh::Mesh(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scal
Mesh::Mesh(ObjectNameTag nameTag, const vector<Triangle> &tries) : Object(std::move(nameTag)), _tris(tries) {
}
Mesh Mesh::Obj(ObjectNameTag nameTag, const std::string &filename) {
return Mesh(std::move(nameTag), filename);
}
void Mesh::setColor(const sf::Color &c) {
_color = c;
@ -107,7 +103,6 @@ void Mesh::setTriangles(vector<Triangle>&& t) {
}
Mesh::~Mesh() {
_tris.clear();
delete[] _geometry;
}

View File

@ -54,8 +54,6 @@ public:
~Mesh() override;
Mesh static Obj(ObjectNameTag nameTag, const std::string &filename);
Mesh static LineTo(ObjectNameTag nameTag, const Vec3D &from, const Vec3D &to, double line_width = 0.1,
const sf::Color &color = {150, 150, 150, 100});

View File

@ -7,6 +7,13 @@
#include "Object.h"
#include "Matrix4x4.h"
bool ObjectNameTag::contains(const ObjectNameTag &nameTag) const {
if(_name.find(nameTag.str()) != std::string::npos) {
return true;
}
return false;
}
void Object::transform(const Matrix4x4 &t) {
_transformMatrix = t * _transformMatrix;

View File

@ -23,10 +23,10 @@ public:
[[nodiscard]] std::string str() const { return _name; }
bool operator==(const ObjectNameTag &tag) const { return _name == tag._name; }
bool operator!=(const ObjectNameTag &tag) const { return _name != tag._name; }
bool operator<(const ObjectNameTag &tag) const { return _name < tag._name; }
[[nodiscard]] bool contains(const ObjectNameTag& nameTag) const;
};
class Object {
@ -52,7 +52,7 @@ private:
public:
explicit Object(ObjectNameTag nameTag) : _nameTag(std::move(nameTag)) {};
Object(const Object &object) : _nameTag(object.name()), _transformMatrix(object.model()) {};
Object(const Object &object) = default;
// TODO: implement rotations using quaternions (?)
void transform(const Matrix4x4 &t);

View File

@ -11,78 +11,16 @@
#include "utils/Log.h"
ResourceManager *ResourceManager::_instance = nullptr;
bool ResourceManager::_validInstance = false;
void ResourceManager::init() {
delete _instance;
_instance = new ResourceManager();
_validInstance = true;
Log::log("ResourceManager::init(): resource manager was initialized");
}
void ResourceManager::unloadTextures() {
int texturesCounter = _instance->_textures.size();
for (auto &_texture : _instance->_textures) {
_texture.second.reset();
}
_instance->_textures.clear();
Log::log("ResourceManager::unloadTextures(): all " + std::to_string(texturesCounter) + " textures was unloaded");
}
void ResourceManager::unloadSoundBuffers() {
int soundBuffersCounter = _instance->_soundBuffers.size();
for (auto &_soundBuffer : _instance->_soundBuffers) {
_soundBuffer.second.reset();
}
_instance->_soundBuffers.clear();
Log::log("ResourceManager::unloadSoundBuffers(): all " + std::to_string(soundBuffersCounter) +
" soundBuffers was unloaded");
}
void ResourceManager::unloadFonts() {
int fontsCounter = _instance->_fonts.size();
for (auto &_font : _instance->_fonts) {
_font.second.reset();
}
_instance->_fonts.clear();
Log::log("ResourceManager::unloadFonts(): all " + std::to_string(fontsCounter) + " fonts was unloaded");
}
void ResourceManager::unloadObjects() {
int objCounter = _instance->_objects.size();
_instance->_objects.clear();
Log::log("ResourceManager::unloadObjects(): all " + std::to_string(objCounter) + " objects was unloaded");
}
void ResourceManager::unloadAllResources() {
if (!_validInstance) {
return;
}
unloadTextures();
unloadSoundBuffers();
unloadFonts();
unloadObjects();
Log::log("ResourceManager::unloadAllResources(): all resources was unloaded");
}
void ResourceManager::free() {
unloadAllResources();
_validInstance = false;
delete _instance;
Log::log("ResourceManager::free(): pointer to 'ResourceManager' was freed");
}
std::shared_ptr<sf::Texture> ResourceManager::loadTexture(const std::string &filename) {
if (!_validInstance) {
if (_instance == nullptr) {
return nullptr;
}
@ -109,7 +47,7 @@ std::shared_ptr<sf::Texture> ResourceManager::loadTexture(const std::string &fil
}
std::shared_ptr<sf::SoundBuffer> ResourceManager::loadSoundBuffer(const std::string &filename) {
if (!_validInstance) {
if (_instance == nullptr) {
return nullptr;
}
@ -135,7 +73,7 @@ std::shared_ptr<sf::SoundBuffer> ResourceManager::loadSoundBuffer(const std::str
}
std::shared_ptr<sf::Font> ResourceManager::loadFont(const std::string &filename) {
if (!_validInstance) {
if (_instance == nullptr) {
return nullptr;
}
@ -165,7 +103,7 @@ std::vector<std::shared_ptr<Mesh>> ResourceManager::loadObjects(const std::strin
std::vector<std::shared_ptr<Mesh>> objects{};
std::map<std::string, sf::Color> maters{};
if (!_validInstance) {
if (_instance == nullptr) {
return objects;
}
@ -241,3 +179,75 @@ std::vector<std::shared_ptr<Mesh>> ResourceManager::loadObjects(const std::strin
return objects;
}
void ResourceManager::unloadTextures() {
if (_instance == nullptr) {
return;
}
int texturesCounter = _instance->_textures.size();
for (auto &_texture : _instance->_textures) {
_texture.second.reset();
}
_instance->_textures.clear();
Log::log("ResourceManager::unloadTextures(): all " + std::to_string(texturesCounter) + " textures was unloaded");
}
void ResourceManager::unloadSoundBuffers() {
if (_instance == nullptr) {
return;
}
int soundBuffersCounter = _instance->_soundBuffers.size();
for (auto &_soundBuffer : _instance->_soundBuffers) {
_soundBuffer.second.reset();
}
_instance->_soundBuffers.clear();
Log::log("ResourceManager::unloadSoundBuffers(): all " + std::to_string(soundBuffersCounter) +
" soundBuffers was unloaded");
}
void ResourceManager::unloadFonts() {
if (_instance == nullptr) {
return;
}
int fontsCounter = _instance->_fonts.size();
for (auto &_font : _instance->_fonts) {
_font.second.reset();
}
_instance->_fonts.clear();
Log::log("ResourceManager::unloadFonts(): all " + std::to_string(fontsCounter) + " fonts was unloaded");
}
void ResourceManager::unloadObjects() {
if (_instance == nullptr) {
return;
}
int objCounter = _instance->_objects.size();
_instance->_objects.clear();
Log::log("ResourceManager::unloadObjects(): all " + std::to_string(objCounter) + " objects was unloaded");
}
void ResourceManager::unloadAllResources() {
unloadTextures();
unloadSoundBuffers();
unloadFonts();
unloadObjects();
Log::log("ResourceManager::unloadAllResources(): all resources was unloaded");
}
void ResourceManager::free() {
unloadAllResources();
delete _instance;
_instance = nullptr;
Log::log("ResourceManager::free(): pointer to 'ResourceManager' was freed");
}

View File

@ -20,7 +20,6 @@ private:
std::map<std::string, std::vector<std::shared_ptr<Mesh>>> _objects;
static ResourceManager *_instance;
static bool _validInstance;
ResourceManager() = default;

View File

@ -7,18 +7,17 @@
#include "utils/Log.h"
SoundController *SoundController::_instance = nullptr;
bool SoundController::_validInstance = false;
void SoundController::init() {
delete _instance;
_instance = new SoundController();
_validInstance = true;
Log::log("SoundController::init(): sound controller was initialized");
}
void SoundController::playSound(const SoundTag &soundTag, const std::string &filename) {
if (!_validInstance) {
if (_instance == nullptr) {
return;
}
@ -26,36 +25,30 @@ void SoundController::playSound(const SoundTag &soundTag, const std::string &fil
_instance->_sounds.emplace(soundTag, sf::Sound(*ResourceManager::loadSoundBuffer(filename)));
}
_instance->_sounds[soundTag].play();
Log::log("SoundController::playSound(): play sound '" + soundTag.str() + "'");
}
void SoundController::pauseSound(const SoundTag &soundTag) {
if (!_validInstance) {
if (_instance == nullptr) {
return;
}
if (_instance->_sounds.count(soundTag) > 0) {
_instance->_sounds[soundTag].pause();
}
Log::log("SoundController::pauseSound(): sound '" + soundTag.str() + "' was paused");
}
void SoundController::stopSound(const SoundTag &soundTag) {
if (!_validInstance) {
if (_instance == nullptr) {
return;
}
if (_instance->_sounds.count(soundTag) > 0) {
_instance->_sounds[soundTag].stop();
}
Log::log("SoundController::stopSound(): sound '" + soundTag.str() + "' was stopped");
}
sf::Sound::Status SoundController::getStatus(const SoundTag &soundTag) {
if (!_validInstance) {
if (_instance == nullptr) {
return sf::Sound::Status::Stopped;
}
@ -67,15 +60,15 @@ sf::Sound::Status SoundController::getStatus(const SoundTag &soundTag) {
}
void SoundController::free() {
if (_validInstance) {
if (_instance != nullptr) {
for (auto&[soundTag, sound] : _instance->_sounds) {
stopSound(soundTag);
}
_instance->_sounds.clear();
}
_validInstance = false;
delete _instance;
_instance = nullptr;
Log::log("SoundController::free(): pointer to 'SoundController' was freed");
}

View File

@ -30,7 +30,6 @@ private:
std::map<SoundTag, sf::Sound> _sounds;
static SoundController *_instance;
static bool _validInstance;
SoundController() = default;

View File

@ -19,7 +19,7 @@ void World::addBody(std::shared_ptr<RigidBody> body) {
}
void World::loadBody(const ObjectNameTag &tag, const string &filename, const Vec3D &scale) {
_objects.emplace(tag, std::make_shared<RigidBody>(Mesh(tag, filename, scale)));
_objects.emplace(tag, std::make_shared<RigidBody>(tag, filename, scale));
Log::log("World::loadBody(): inserted body from " + filename + " with title '" + tag.str() + "' with " +
std::to_string(_objects[tag]->triangles().size()) + " tris.");
}
@ -45,7 +45,7 @@ IntersectionInformation World::rayCast(const Vec3D &from, const Vec3D &to, const
bool escapeThisBody = false;
for (auto &escapeTag : tagsToSkip) {
if (name.str().find(escapeTag) != std::string::npos) {
if (name.contains(ObjectNameTag(escapeTag))) {
escapeThisBody = true;
break;
}
@ -78,7 +78,7 @@ IntersectionInformation World::rayCast(const Vec3D &from, const Vec3D &to, const
void World::loadMap(const std::string &filename, const Vec3D &scale) {
auto objs = ResourceManager::loadObjects(filename);
for (auto &i : objs) {
std::shared_ptr<RigidBody> obj = std::make_shared<RigidBody>(*i);
std::shared_ptr<RigidBody> obj = std::make_shared<RigidBody>(*i, false);
addBody(obj);
obj->scale(scale);
}
@ -122,9 +122,9 @@ void World::checkCollision(const ObjectNameTag &tag) {
}
void World::update() {
for (auto &m : _objects) {
m.second->updatePhysicsState();
checkCollision(m.first);
for (auto &[nameTag, obj] : _objects) {
obj->updatePhysicsState();
checkCollision(nameTag);
}
}

View File

@ -23,28 +23,23 @@ struct IntersectionInformation final {
class World final {
private:
std::map<ObjectNameTag, std::shared_ptr<RigidBody>> _objects;
public:
World() = default;
void checkCollision(const ObjectNameTag &tag);
public:
World() = default;
void update();
void addBody(std::shared_ptr<RigidBody> mesh);
std::shared_ptr<RigidBody> body(const ObjectNameTag &tag);
void removeBody(const ObjectNameTag &tag);
void loadBody(const ObjectNameTag &tag, const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1});
void loadMap(const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1});
// std::string skipTags is a string that consist of all objects we want to skip in ray casting
IntersectionInformation rayCast(const Vec3D &from, const Vec3D &to, const std::string &skipTags = "");
void loadMap(const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1});
std::map<ObjectNameTag, std::shared_ptr<RigidBody>>::iterator begin() { return _objects.begin(); }
std::map<ObjectNameTag, std::shared_ptr<RigidBody>>::iterator end() { return _objects.end(); }
};

View File

@ -15,12 +15,14 @@ private:
const double _valueToAttract;
void update() override {
if (_object.expired()) {
auto obj = _object.lock();
if (obj == nullptr) {
stop();
return;
}
_object.lock()->attractToPoint(_targetPoint, _valueToAttract * dprogress());
obj->attractToPoint(_targetPoint, _valueToAttract * dprogress());
}
public:

View File

@ -5,8 +5,6 @@
#ifndef ENGINE_ACOLOR_H
#define ENGINE_ACOLOR_H
#include <utility>
#include "Animation.h"
#include "../Mesh.h"
@ -19,21 +17,23 @@ private:
bool _started = false;
void update() override {
if (_mesh.expired()) {
auto mesh = _mesh.lock();
if (mesh == nullptr) {
stop();
return;
}
if (!_started) {
_started = true;
_startColor = _mesh.lock()->color();
_startColor = mesh->color();
}
Vec4D start(_startColor.r, _startColor.g, _startColor.b, _startColor.a);
Vec4D end(_newColor.r, _newColor.g, _newColor.b, _newColor.a);
Vec4D mid = start + (end - start) * progress();
_mesh.lock()->setColor(sf::Color(static_cast<sf::Uint8>(mid.x()), static_cast<sf::Uint8>(mid.y()),
mesh->setColor(sf::Color(static_cast<sf::Uint8>(mid.x()), static_cast<sf::Uint8>(mid.y()),
static_cast<sf::Uint8>(mid.z()), static_cast<sf::Uint8>(mid.w())));
}
@ -41,7 +41,7 @@ public:
AColor(std::weak_ptr<Mesh> mesh, const sf::Color &color, double duration = 1, LoopOut looped = LoopOut::None,
InterpolationType interpolationType = InterpolationType::Linear) : Animation(duration, looped,
interpolationType),
_mesh(std::move(mesh)), _newColor(color) {
_mesh(mesh), _newColor(color) {
}
};

View File

@ -5,8 +5,6 @@
#ifndef ENGINE_AFUNCTION_H
#define ENGINE_AFUNCTION_H
#include <utility>
#include "Animation.h"
class AFunction final : public Animation {

View File

@ -5,8 +5,6 @@
#ifndef ENGINE_AROTATE_H
#define ENGINE_AROTATE_H
#include <utility>
#include "Animation.h"
#include "../Object.h"
@ -16,12 +14,14 @@ private:
const Vec3D _rotationValue;
void update() override {
if (_object.expired()) {
auto obj = _object.lock();
if (obj == nullptr) {
stop();
return;
}
_object.lock()->rotate(_rotationValue * dprogress());
obj->rotate(_rotationValue * dprogress());
}
public:

View File

@ -5,8 +5,6 @@
#ifndef SHOOTER_AROTATELEFT_H
#define SHOOTER_AROTATELEFT_H
#include <utility>
#include "Animation.h"
#include "../Object.h"
@ -16,12 +14,14 @@ private:
const double _rotationValue;
void update() override {
if (_object.expired()) {
auto obj = _object.lock();
if (obj == nullptr) {
stop();
return;
}
_object.lock()->rotateLeft(_rotationValue*dprogress());
obj->rotateLeft(_rotationValue*dprogress());
}
public:

View File

@ -5,8 +5,6 @@
#ifndef SHOOTER_AROTATERELATIVEPOINT_H
#define SHOOTER_AROTATERELATIVEPOINT_H
#include <utility>
#include "Animation.h"
#include "../Object.h"
@ -17,13 +15,14 @@ private:
const Vec3D _rotationValue;
void update() override {
auto obj = _object.lock();
if (_object.expired()) {
if (obj == nullptr) {
stop();
return;
}
_object.lock()->rotateRelativePoint(_targetPoint, _rotationValue * dprogress());
obj->rotateRelativePoint(_targetPoint, _rotationValue * dprogress());
}
public:

View File

@ -5,8 +5,6 @@
#ifndef ENGINE_ASCALE_H
#define ENGINE_ASCALE_H
#include <utility>
#include "Animation.h"
#include "../physics/RigidBody.h"
@ -16,19 +14,21 @@ private:
const Vec3D _scalingValue;
void update() override {
if (_object.expired()) {
auto obj = _object.lock();
if (obj == nullptr) {
stop();
return;
}
auto object = _object.lock();
std::vector<Triangle> newTriangles;
newTriangles.reserve(object->triangles().size());
for (auto &t : object->triangles()) {
newTriangles.emplace_back(
t * Matrix4x4::Scale(Vec3D{1, 1, 1} + (_scalingValue - Vec3D{1, 1, 1}) * progress()));
newTriangles.reserve(obj->triangles().size());
for (auto &t : obj->triangles()) {
newTriangles.emplace_back(t * Matrix4x4::Scale(Vec3D{1, 1, 1} +
(_scalingValue - Vec3D{1, 1, 1}) * progress())
);
}
object.lock()->setTriangles(std::move(newTriangles));
obj->setTriangles(std::move(newTriangles));
}
public:

View File

@ -5,8 +5,6 @@
#ifndef ENGINE_ATRANSLATE_H
#define ENGINE_ATRANSLATE_H
#include <utility>
#include "Animation.h"
#include "../Object.h"
@ -16,19 +14,21 @@ private:
const Vec3D _translationValue;
void update() override {
if (_object.expired()) {
auto obj = _object.lock();
if (obj == nullptr) {
stop();
return;
}
_object.lock()->translate(_translationValue * dprogress());
obj->translate(_translationValue * dprogress());
}
public:
ATranslate(std::weak_ptr<Object> object, const Vec3D &t, double duration = 1, LoopOut looped = LoopOut::None,
InterpolationType interpolationType = InterpolationType::Bezier) : Animation(duration, looped,
interpolationType),
_object(std::move(object)),
_object(object),
_translationValue(t) {
}
};

View File

@ -5,8 +5,6 @@
#ifndef ENGINE_ATRANSLATETOPOINT_H
#define ENGINE_ATRANSLATETOPOINT_H
#include <utility>
#include "Animation.h"
#include "../Object.h"
@ -19,7 +17,9 @@ private:
bool _started = false;
void update() override {
if (_object.expired()) {
auto obj = _object.lock();
if (obj == nullptr) {
stop();
return;
}
@ -28,7 +28,7 @@ private:
_started = true;
_translationValue = _targetPoint - _object.lock()->position();
}
_object.lock()->translate(_translationValue * dprogress());
obj->translate(_translationValue * dprogress());
}
public:

View File

@ -3,9 +3,11 @@
//
#include "Animation.h"
#include "../Consts.h"
#include "../utils/Time.h"
Animation::Animation(double duration, Animation::LoopOut looped, Animation::InterpolationType intType, bool waitFor)
: _duration(duration), _looped(looped), _intType(intType), _waitFor(waitFor) {
Animation::Animation(double duration, Animation::LoopOut looped, Animation::InterpolationType intType, bool waitForFinish)
: _duration(duration), _looped(looped), _intType(intType), _waitForFinish(waitForFinish) {
}
bool Animation::updateState() {

View File

@ -5,10 +5,7 @@
#ifndef ENGINE_ANIMATION_H
#define ENGINE_ANIMATION_H
#include "../utils/Time.h"
#include "../Triangle.h"
#include "Interpolation.h"
#include "../Vec2D.h"
class Animation {
public:
@ -32,8 +29,9 @@ private:
double _progress = 0;
double _dprogress = 0;
// If '_waitFor' == true then we need to finish all animation before starting this one. (for example for a_wait() or a_scale())
const bool _waitFor = false;
// If '_waitForFinish' == true then we need to finish all animation before starting this one. (for example AWait)
// In addition new animations in particular animation list will be started only after finishing this animation.
const bool _waitForFinish = false;
const double _duration = 0;
const LoopOut _looped = LoopOut::None;
const InterpolationType _intType = InterpolationType::Bezier;
@ -41,22 +39,20 @@ private:
// You should override this method for your particular animation
virtual void update() = 0;
protected:
[[nodiscard]] double progress() const { return _progress; }
[[nodiscard]] double dprogress() const { return _dprogress; }
void stop() { _finished = true; }
public:
Animation(double duration, LoopOut looped, InterpolationType intType, bool _waitFor = false);
virtual ~Animation() = default;
[[nodiscard]] bool waitFor() const { return _waitFor; }
bool updateState();
[[nodiscard]] double progress() const { return _progress; }
[[nodiscard]] double dprogress() const { return _dprogress; }
void stop() { _finished = true; }
[[nodiscard]] bool isFinished() const { return _finished; }
[[nodiscard]] bool isWaitingForFinish() const { return _waitForFinish; }
};
#endif //INC_3DZAVR_ANIMATION_H

View File

@ -0,0 +1,21 @@
//
// Created by Иван Ильин on 09.11.2021.
//
#ifndef SHOOTER_ANIMATIONS_H
#define SHOOTER_ANIMATIONS_H
#include "Timeline.h"
#include "AAttractToPoint.h"
#include "AColor.h"
#include "AFunction.h"
#include "ARotate.h"
#include "ARotateLeft.h"
#include "ARotateRelativePoint.h"
#include "AScale.h"
#include "ATranslate.h"
#include "ATranslateToPoint.h"
#include "AWait.h"
#endif //SHOOTER_ANIMATIONS_H

View File

@ -0,0 +1,71 @@
//
// Created by Иван Ильин on 09.11.2021.
//
#include <cmath>
#include "Interpolation.h"
#include "../Consts.h"
double Interpolation::Linear(double t) {
if (t < 0) {
t = -t;
}
int integer = static_cast<int>(t);
return (integer % 2) ? 1.0 - (t - integer) : (t - integer);
}
double Interpolation::Bezier(const Vec2D &p1, const Vec2D &p2, double t) {
// TODO: implement bezier curve without finding the root of equation
t = Interpolation::Linear(t);
double h = Consts::EPS;
double eps = Consts::EPS;
// We are trying to find 's' when px = t
auto f = [=](double s) {
return 3.0 * (1.0 - s) * (1.0 - s) * s * p1.x() + 3.0 * (1.0 - s) * s * s * p2.x() + s * s * s - t;
};
// Using found 's' we will calculate resulting py
auto py = [=](double s) {
return 3.0 * (1.0 - s) * (1.0 - s) * s * p1.y() + 3.0 * (1.0 - s) * s * s * p2.y() + s * s * s;
};
auto df = [=](double s) {
return (f(s + h) - f(s - h)) / (2.0 * h);
};
// Newton method
double s1 = 0.0, s2 = 0.5;
int i = 0;
while (std::abs(s1 - s2) > eps) {
s1 = s2;
s2 = s1 - f(s1) / df(s1);
i++;
}
return py(s1);
}
double Interpolation::Bouncing(double t) {
t = Interpolation::Linear(t);
return 0.5 * (1.0 / (1.0 + exp(10.0 * (-4.0 * t + 0.8))) +
(1.0 + 2.5 * sin(50.0 * (t - 1.0 / 3.0)) * exp(-7.0 * t)) / (1.0 + exp(10.0 * (-15.0 * t + 3.1))));
}
double Interpolation::dLinear(double t, double dt) {
return ((int) trunc(t) % 2) ? -dt : dt;
}
double Interpolation::dCos(double t, double dt) {
return 0.5 * Consts::PI * sin(Consts::PI * t) * dt;
}
double Interpolation::dBezier(const Vec2D &p1, const Vec2D &p2, double t, double dt) {
return Interpolation::Bezier(p1, p2, t + dt) - Interpolation::Bezier(p1, p2, t);
}
double Interpolation::dBouncing(double t, double dt) {
return Bouncing(t + dt) - Bouncing(t);
}

View File

@ -5,95 +5,22 @@
#ifndef ENGINE_INTERPOLATION_H
#define ENGINE_INTERPOLATION_H
#include <cmath>
#include "../Vec2D.h"
#include "../Consts.h"
namespace Interpolation {
static double Linear(double t);
double Linear(double t);
static double Cos(double t);
double Bezier(const Vec2D &p1, const Vec2D &p2, double t);
static double Bezier(const Vec2D &p1, const Vec2D &p2, double t);
double Bouncing(double t);
static double Bouncing(double t);
double dLinear(double t, double dt);
static double dLinear(double t, double dt);
double dCos(double t, double dt);
static double dCos(double t, double dt);
double dBezier(const Vec2D &p1, const Vec2D &p2, double t, double dt);
static double dBezier(const Vec2D &p1, const Vec2D &p2, double t, double dt);
static double dBouncing(double t, double dt);
double dBouncing(double t, double dt);
};
double Interpolation::Linear(double t) {
if (t < 0) {
t = -t;
}
int integer = static_cast<int>(t);
return (integer % 2) ? 1.0 - (t - integer) : (t - integer);
}
double Interpolation::Cos(double t) {
return 0.5 * (1 - cos(Consts::PI * Interpolation::Linear(t)));
}
double Interpolation::Bezier(const Vec2D &p1, const Vec2D &p2, double t) {
// TODO: implement bezier curve without finding the root of equation
t = Interpolation::Linear(t);
double h = Consts::EPS;
double eps = Consts::EPS;
// We are trying to find 's' when px = t
auto f = [=](double s) {
return 3.0 * (1.0 - s) * (1.0 - s) * s * p1.x() + 3.0 * (1.0 - s) * s * s * p2.x() + s * s * s - t;
};
// Using found 's' we will calculate resulting py
auto py = [=](double s) {
return 3.0 * (1.0 - s) * (1.0 - s) * s * p1.y() + 3.0 * (1.0 - s) * s * s * p2.y() + s * s * s;
};
auto df = [=](double s) {
return (f(s + h) - f(s - h)) / (2.0 * h);
};
// Newton method
double s1 = 0.0, s2 = 0.5;
int i = 0;
while (std::abs(s1 - s2) > eps) {
s1 = s2;
s2 = s1 - f(s1) / df(s1);
i++;
}
return py(s1);
}
double Interpolation::Bouncing(double t) {
t = Interpolation::Linear(t);
return 0.5 * (1.0 / (1.0 + exp(10.0 * (-4.0 * t + 0.8))) +
(1.0 + 2.5 * sin(50.0 * (t - 1.0 / 3.0)) * exp(-7.0 * t)) / (1.0 + exp(10.0 * (-15.0 * t + 3.1))));
}
double Interpolation::dLinear(double t, double dt) {
return ((int) trunc(t) % 2) ? -dt : dt;
}
double Interpolation::dCos(double t, double dt) {
return 0.5 * Consts::PI * sin(Consts::PI * t) * dt;
}
double Interpolation::dBezier(const Vec2D &p1, const Vec2D &p2, double t, double dt) {
return Interpolation::Bezier(p1, p2, t + dt) - Interpolation::Bezier(p1, p2, t);
}
double Interpolation::dBouncing(double t, double dt) {
return Bouncing(t + dt) - Bouncing(t);
}
#endif //INC_3DZAVR_INTERPOLATION_H

View File

@ -9,64 +9,52 @@
#include "../utils/Log.h"
Timeline *Timeline::_instance = nullptr;
bool Timeline::_validInstance = false;
void Timeline::init() {
delete _instance;
_instance = new Timeline();
_validInstance = true;
Log::log("Timeline::init(): animation timeline was initialized");
}
void Timeline::animate(const AnimationListTag &listName, std::shared_ptr<Animation> anim) {
if (!_validInstance) {
return;
}
_instance->_animations[listName].emplace_back(anim);
Log::log("Timeline::animate(): add animation in '" + listName.str() + "' list");
}
void Timeline::deleteAllAnimations() {
if (!_validInstance) {
if (_instance == nullptr) {
return;
}
int animCounter = 0;
for (auto&[listName, animationList] : _instance->_animations) {
animCounter += animationList.size();
animationList.clear();
}
Log::log("Timeline::deleteAllAnimations(): all " + std::to_string(_instance->_animations.size()) + " list was deleted");
_instance->_animations.clear();
Log::log("Timeline::deleteAllAnimations(): all " + std::to_string(animCounter) + " animations was deleted");
}
void Timeline::deleteAnimationList(const AnimationListTag &listName) {
if (!_validInstance) {
if (_instance == nullptr) {
return;
}
int animCounter = _instance->_animations[listName].size();
_instance->_animations[listName].clear();
_instance->_animations.erase(listName);
auto it = _instance->_animations.find(listName);
Log::log("Timeline::deleteAnimationList(): list '" + listName.str() + "' with " + std::to_string(animCounter) +
" animations was deleted");
if(it != _instance->_animations.end()) {
_instance->_animations.erase(it);
} else {
Log::log("Timeline::deleteAnimationList(): list '" + listName.str() + "' does not exist");
}
}
[[nodiscard]] bool Timeline::isInAnimList(const AnimationListTag &listName) {
if (!_validInstance) {
if (_instance == nullptr) {
return false;
}
return !_instance->_animations[listName].empty();
auto it = _instance->_animations.find(listName);
if(it != _instance->_animations.end()) {
return !it->second.empty();
}
return false;
}
void Timeline::update() {
if (!_validInstance) {
if (_instance == nullptr) {
return;
}
@ -77,32 +65,33 @@ void Timeline::update() {
}
auto& animationList = iter->second;
auto it = animationList.begin();
// If it the front animation is 'a_wait()' we should wait until waiting time is over
if (it.operator*()->waitFor()) {
if (!it.operator*()->updateState()) {
if ((*it)->isWaitingForFinish()) {
if (!(*it)->updateState()) {
animationList.erase(it);
}
continue;
}
// Otherwise we iterate over all animation until we meet animations.end() or wait animation
while (!animationList.empty() && (it != animationList.end()) && (!it.operator*()->waitFor())) {
if (!it.operator*()->updateState()) {
while (!animationList.empty() && (it != animationList.end()) && (!(*it)->isWaitingForFinish())) {
if (!(*it)->updateState()) {
animationList.erase(it++);
} else {
it++;
++it;
}
}
iter++;
++iter;
}
}
void Timeline::free() {
Timeline::deleteAllAnimations();
_validInstance = false;
delete _instance;
_instance = nullptr;
Log::log("Timeline::free(): pointer to 'Timeline' was freed");
}

View File

@ -4,7 +4,10 @@
#ifndef SHOOTER_TIMELINE_H
#define SHOOTER_TIMELINE_H
#include <memory>
#include <string>
#include <map>
#include "Animation.h"
@ -28,7 +31,6 @@ private:
std::map<AnimationListTag, std::list<std::shared_ptr<Animation>>> _animations;
static Timeline *_instance;
static bool _validInstance;
Timeline() = default;
@ -39,8 +41,6 @@ public:
static void update();
static void animate(const AnimationListTag &listName, std::shared_ptr<Animation> anim);
static void deleteAllAnimations();
static void deleteAnimationList(const AnimationListTag &listName);
@ -50,6 +50,15 @@ public:
static void init();
static void free();
template <typename T, typename... Arguments>
static void addAnimation(const AnimationListTag &listName, Arguments... args) {
if (_instance == nullptr) {
return;
}
_instance->_animations[listName].emplace_back(std::make_shared<T>(args...));
}
};
#endif //SHOOTER_TIMELINE_H

View File

@ -5,10 +5,7 @@
#ifndef ENGINE_BUTTON_H
#define ENGINE_BUTTON_H
#include <functional>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
struct tPos final {
const int tx;

View File

@ -19,23 +19,15 @@ bool HitBox::Vec3DLess::operator()(const Vec3D& lhs, const Vec3D& rhs) const noe
return false;
}
HitBox::HitBox(const Mesh& mesh) {
// we dont need to add the same points in hit box
std::set<Vec3D, HitBox::Vec3DLess> points;
for (const auto& t : mesh.triangles())
for (int i = 0; i < 3; i++)
points.insert(Vec3D(t[i]));
_hitBox.reserve(points.size());
for (const auto& it : points)
_hitBox.push_back(it);
_hitBox.shrink_to_fit();
HitBox::HitBox(const Mesh& mesh, bool useSimpleBox) {
if (useSimpleBox) {
generateSimple(mesh);
} else {
generateDetailed(mesh);
}
}
HitBox HitBox::Box(const Mesh &mesh) {
HitBox result;
void HitBox::generateSimple(const Mesh &mesh) {
double maxX = -std::numeric_limits<double>::max();
double maxY = -std::numeric_limits<double>::max();
double maxZ = -std::numeric_limits<double>::max();
@ -69,15 +61,27 @@ HitBox HitBox::Box(const Mesh &mesh) {
}
}
result._hitBox.emplace_back(minX, minY, minZ);
result._hitBox.emplace_back(minX, maxY, minZ);
result._hitBox.emplace_back(maxX, minY, minZ);
result._hitBox.emplace_back(maxX, maxY, minZ);
_hitBox.emplace_back(minX, minY, minZ);
_hitBox.emplace_back(minX, maxY, minZ);
_hitBox.emplace_back(maxX, minY, minZ);
_hitBox.emplace_back(maxX, maxY, minZ);
result._hitBox.emplace_back(minX, minY, maxZ);
result._hitBox.emplace_back(minX, maxY, maxZ);
result._hitBox.emplace_back(maxX, minY, maxZ);
result._hitBox.emplace_back(maxX, maxY, maxZ);
return result;
_hitBox.emplace_back(minX, minY, maxZ);
_hitBox.emplace_back(minX, maxY, maxZ);
_hitBox.emplace_back(maxX, minY, maxZ);
_hitBox.emplace_back(maxX, maxY, maxZ);
}
void HitBox::generateDetailed(const Mesh &mesh) {
// we dont need to add the same points in hit box
std::set<Vec3D, HitBox::Vec3DLess> points;
for (const auto& t : mesh.triangles())
for (int i = 0; i < 3; i++)
points.insert(Vec3D(t[i]));
_hitBox.reserve(points.size());
for (const auto& it : points)
_hitBox.push_back(it);
_hitBox.shrink_to_fit();
}

View File

@ -15,17 +15,17 @@ private:
std::vector<Vec3D> _hitBox;
void generateSimple(const Mesh &mesh);
void generateDetailed(const Mesh &mesh);
public:
HitBox() = default;
HitBox(const HitBox &hitBox) = default;
explicit HitBox(const Mesh &mesh);
explicit HitBox(const Mesh &mesh, bool useSimpleBox = true);
[[nodiscard]] std::vector<Vec3D>::iterator begin() { return _hitBox.begin(); }
[[nodiscard]] std::vector<Vec3D>::iterator end() { return _hitBox.end(); }
HitBox static Box(const Mesh &mesh);
};

View File

@ -10,15 +10,14 @@
#include "../utils/Time.h"
#include "../Consts.h"
RigidBody::RigidBody(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale) : Mesh(std::move(nameTag),
RigidBody::RigidBody(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale, bool useSimpleBox) : Mesh(std::move(nameTag),
filename, scale),
_hitBox(*this) {
_hitBox(*this, useSimpleBox) {
}
RigidBody::RigidBody(const Mesh &mesh) : Mesh(mesh), _hitBox(mesh) {
RigidBody::RigidBody(const Mesh &mesh, bool useSimpleBox) : Mesh(mesh), _hitBox(mesh, useSimpleBox) {
}
Vec3D RigidBody::_findFurthestPoint(const Vec3D &direction) {
Vec3D maxPoint{0, 0, 0};
@ -41,7 +40,6 @@ Vec3D RigidBody::_findFurthestPoint(const Vec3D &direction) {
Vec3D RigidBody::_support(std::shared_ptr<RigidBody> obj, const Vec3D &direction) {
Vec3D p1 = _findFurthestPoint(direction);
Vec3D p2 = obj->_findFurthestPoint(-direction);
Vec3D res = p1 - p2;
return p1 - p2;
}
@ -349,12 +347,3 @@ void RigidBody::addVelocity(const Vec3D &velocity) {
void RigidBody::setAcceleration(const Vec3D &acceleration) {
_acceleration = acceleration;
}
void RigidBody::setSimpleHitBox(bool b) {
_simpleHitBox = b;
if (_simpleHitBox) {
_hitBox = HitBox::Box(*this);
} else {
_hitBox = HitBox(*this);
}
}

View File

@ -41,23 +41,17 @@ private:
bool _isTrigger = false;
HitBox _hitBox{};
bool _simpleHitBox = false;
bool _inCollision = false;
Vec3D _collisionNormal{0, 0, 0};
Vec3D _findFurthestPoint(const Vec3D &direction);
Vec3D _support(std::shared_ptr<RigidBody> obj, const Vec3D &direction);
std::function<void(const ObjectNameTag &, std::shared_ptr<RigidBody>)> _collisionCallBack;
static NextSimplex _nextSimplex(const Simplex &points);
static NextSimplex _lineCase(const Simplex &points);
static NextSimplex _triangleCase(const Simplex &points);
static NextSimplex _tetrahedronCase(const Simplex &points);
static std::pair<std::vector<FaceNormal>, size_t>
@ -68,49 +62,32 @@ private:
size_t b);
public:
explicit RigidBody(ObjectNameTag nameTag) : Mesh(std::move(nameTag)) {};
RigidBody(const RigidBody &rigidBody) = default;
explicit RigidBody(const Mesh &mesh);
RigidBody(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1});
explicit RigidBody(const Mesh &mesh, bool useSimpleBox = true);
RigidBody(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1}, bool useSimpleBox = true);
[[nodiscard]] std::pair<bool, Simplex> checkGJKCollision(std::shared_ptr<RigidBody> obj);
[[nodiscard]] CollisionPoint EPA(const Simplex &simplex, std::shared_ptr<RigidBody> obj);
void solveCollision(const CollisionPoint &collision);
[[nodiscard]] Vec3D collisionNormal() const { return _collisionNormal; }
[[nodiscard]] bool hasCollision() const { return _hasCollision; }
[[nodiscard]] bool inCollision() const { return _inCollision; }
[[nodiscard]] bool isCollider() const { return _isCollider; }
[[nodiscard]] bool isTrigger() const { return _isTrigger; }
void setInCollision(bool c) { _inCollision = c; }
void setCollision(bool c) { _hasCollision = c; }
void setCollider(bool c) { _isCollider = c; }
void setSimpleHitBox(bool b);
void setTrigger(bool t) { _isTrigger = t; }
void updatePhysicsState();
void setVelocity(const Vec3D &velocity);
void addVelocity(const Vec3D &velocity);
void setAcceleration(const Vec3D &acceleration);
[[nodiscard]] Vec3D velocity() const { return _velocity; }
[[nodiscard]] Vec3D acceleration() const { return _acceleration; }
[[nodiscard]] const std::function<void(const ObjectNameTag &, std::shared_ptr<RigidBody>)> &

View File

@ -9,17 +9,16 @@
using namespace std::chrono;
Time *Time::_instance = nullptr;
bool Time::_validInstance = false;
void Time::init() {
delete _instance;
_instance = new Time();
_validInstance = true;
Log::log("Time::init(): time was initialized");
}
double Time::time() {
if (!_validInstance) {
if (_instance == nullptr) {
return 0;
}
@ -27,7 +26,7 @@ double Time::time() {
}
double Time::deltaTime() {
if (!_validInstance) {
if (_instance == nullptr) {
return 0;
}
@ -35,7 +34,7 @@ double Time::deltaTime() {
}
void Time::update() {
if (!_validInstance) {
if (_instance == nullptr) {
return;
}
@ -63,7 +62,7 @@ void Time::update() {
}
int Time::fps() {
if (!_validInstance) {
if (_instance == nullptr) {
return 0;
}
// Cast is faster than floor and has the same behavior for positive numbers
@ -71,7 +70,7 @@ int Time::fps() {
}
void Time::startTimer(const std::string &timerName) {
if (!_validInstance) {
if (_instance == nullptr) {
return;
}
_instance->_timers.insert({timerName, Timer()});
@ -79,7 +78,7 @@ void Time::startTimer(const std::string &timerName) {
}
void Time::stopTimer(const std::string &timerName) {
if (!_validInstance) {
if (_instance == nullptr) {
return;
}
if(_instance->_timers.count(timerName) > 0) {
@ -88,7 +87,7 @@ void Time::stopTimer(const std::string &timerName) {
}
double Time::elapsedTimerMilliseconds(const std::string &timerName) {
if (!_validInstance) {
if (_instance == nullptr) {
return 0;
}
if(_instance->_timers.count(timerName) > 0) {
@ -98,7 +97,7 @@ double Time::elapsedTimerMilliseconds(const std::string &timerName) {
}
double Time::elapsedTimerSeconds(const std::string &timerName) {
if (!_validInstance) {
if (_instance == nullptr) {
return 0;
}
if(_instance->_timers.count(timerName) > 0) {
@ -109,8 +108,8 @@ double Time::elapsedTimerSeconds(const std::string &timerName) {
void Time::free() {
_validInstance = false;
delete _instance;
_instance = nullptr;
Log::log("Time::free(): pointer to 'Time' was freed");
}

View File

@ -29,7 +29,6 @@ private:
double _deltaTime = 0;
static Time *_instance;
static bool _validInstance;
Time() = default;

View File

@ -161,6 +161,7 @@
<ItemGroup>
<ClCompile Include="engine\animation\Animation.cpp" />
<ClCompile Include="engine\animation\Timeline.cpp" />
<ClInclude Include="engine\animation\Interpolation.cpp" />
<ClCompile Include="engine\Camera.cpp" />
<ClCompile Include="engine\Engine.cpp" />
<ClCompile Include="engine\gui\Button.cpp" />
@ -213,6 +214,7 @@
<ClInclude Include="engine\animation\ARotateLeft.h" />
<ClInclude Include="engine\animation\Interpolation.h" />
<ClInclude Include="engine\animation\Timeline.h" />
<ClInclude Include="engine\animation\Animations.h" />
<ClInclude Include="engine\Camera.h" />
<ClInclude Include="engine\Consts.h" />
<ClInclude Include="engine\Engine.h" />

View File

@ -87,6 +87,9 @@
<ClCompile Include="engine\animation\Timeline.cpp">
<Filter>Исходные файлы\engine\animation</Filter>
</ClCompile>
<ClInclude Include="engine\animation\Interpolation.cpp">
<Filter>Файлы заголовков\engine\animation</Filter>
</ClInclude>
<ClCompile Include="engine\gui\Button.cpp">
<Filter>Исходные файлы\engine\gui</Filter>
</ClCompile>
@ -254,6 +257,9 @@
<ClInclude Include="engine\animation\Interpolation.h">
<Filter>Файлы заголовков\engine\animation</Filter>
</ClInclude>
<ClInclude Include="engine\animation\Animations.h">
<Filter>Файлы заголовков\engine\animation</Filter>
</ClInclude>
<ClInclude Include="engine\network\ClientUDP.h">
<Filter>Файлы заголовков\engine\network</Filter>
</ClInclude>

View File

@ -6,7 +6,6 @@
#define SHOOTER_AK47_H
#include "Weapon.h"
#include "../engine/ResourceManager.h"
#include "../ShooterConsts.h"
class Ak47 final : public Weapon {
@ -17,5 +16,4 @@ public:
Vec3D{3, 3, 3}, Vec3D{-2.3, 0.8, 1.8},Vec3D{0, 0, 0}) {}
};
#endif //SHOOTER_3DZAVR_AK47_H

View File

@ -18,14 +18,14 @@ public:
std::map<ObjectNameTag, double>
processFire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction) override {
const Vec3D &position, const Vec3D &direction) const override {
std::map<ObjectNameTag, double> damagedPlayers;
for (int i = 0; i < 15; i++) {
std::map<ObjectNameTag, double> damaged = addTrace(rayCastFunction, position, direction);
for (auto &player : damaged) {
damagedPlayers[player.first] += player.second;
std::map<ObjectNameTag, double> damaged = fireABullet(rayCastFunction, position, direction);
for (auto &[playerName, damage] : damaged) {
damagedPlayers[playerName] += damage;
}
}

View File

@ -2,12 +2,9 @@
// Created by Иван Ильин on 01.06.2021.
//
#include <utility>
#include "Weapon.h"
#include "../engine/ResourceManager.h"
#include "../engine/utils/Log.h"
#include "../engine/animation/AColor.h"
#include "../ShooterConsts.h"
using namespace std;
@ -79,33 +76,37 @@ void Weapon::reload() {
std::map<ObjectNameTag, double>
Weapon::processFire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction) {
return addTrace(std::move(rayCastFunction), position, direction);
const Vec3D &position, const Vec3D &direction) const {
// Standard weapon usually fire one bullet at a time
// But some types of weapon can fire several bullet at the same time (for ex. shotgun)
// That's why processFire() is s virtual function
return fireABullet(std::move(rayCastFunction), position, direction);
}
std::map<ObjectNameTag, double>
Weapon::addTrace(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &from, const Vec3D &directionTo) {
Weapon::fireABullet(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &cameraPosition, const Vec3D &direction) const {
std::map<ObjectNameTag, double> damagedPlayers;
double spreading = _spreading * ShooterConsts::FIRE_DISTANCE / 100;
double spreading = _spreading * ShooterConsts::FIRE_DISTANCE / 100.0;
//generate random vector
Vec3D randV(spreading * (1.0 - 2.0 * (double) rand() / RAND_MAX),
spreading * (1.0 - 2.0 * (double) rand() / RAND_MAX),
spreading * (1.0 - 2.0 * (double) rand() / RAND_MAX));
Vec3D randV(spreading * (1.0 - 2.0 * static_cast<double>(rand()) / RAND_MAX),
spreading * (1.0 - 2.0 * static_cast<double>(rand()) / RAND_MAX),
spreading * (1.0 - 2.0 * static_cast<double>(rand()) / RAND_MAX));
// damage player
auto rayCast = rayCastFunction(from, from + directionTo * ShooterConsts::FIRE_DISTANCE + randV);
if (rayCast.objectName.str().find("Enemy") != std::string::npos) {
auto rayCast = rayCastFunction(cameraPosition, cameraPosition + direction * ShooterConsts::FIRE_DISTANCE + randV);
if (rayCast.objectName.contains(ObjectNameTag("Enemy"))) {
damagedPlayers[rayCast.objectName] += _damage / (1.0 + rayCast.distanceToObject);
// If you hit the head the damage will be doubled
if (rayCast.objectName.str().find("_head") != std::string::npos) {
if (rayCast.objectName.contains(ObjectNameTag("_head"))) {
damagedPlayers[rayCast.objectName] += _damage / (1.0 + rayCast.distanceToObject);
}
// If you hit the foot the damage will be divided by 2
if (rayCast.objectName.str().find("_foot_") != std::string::npos) {
if (rayCast.objectName.contains(ObjectNameTag("_foot_"))) {
damagedPlayers[rayCast.objectName] -= 0.5 * _damage / (1.0 + rayCast.distanceToObject);
}
}
@ -113,7 +114,7 @@ Weapon::addTrace(std::function<IntersectionInformation(const Vec3D &, const Vec3
// add trace line
Vec3D lineFrom = position() + model() * Vec3D(triangles().back()[0]);
Vec3D lineTo = rayCast.intersected ? rayCast.pointOfIntersection : position() +
directionTo * ShooterConsts::FIRE_DISTANCE +
direction * ShooterConsts::FIRE_DISTANCE +
randV;
_addTraceCallBack(lineFrom, lineTo);

View File

@ -42,12 +42,12 @@ private:
protected:
std::map<ObjectNameTag, double>
addTrace(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction);
fireABullet(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction) const;
virtual std::map<ObjectNameTag, double>
processFire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction);
const Vec3D &position, const Vec3D &direction) const;
public:
Weapon(int initialPack, int clipCapacity, double reloadTime, double fireDelay, double damage, double spreading,
@ -55,7 +55,7 @@ public:
const Vec3D &s, const Vec3D &t, const Vec3D &r);
FireInformation
fire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction, const Vec3D &position,
fire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction, const Vec3D &cameraPosition,
const Vec3D &direction);
void reload();
@ -67,7 +67,7 @@ public:
void setReloadCallBack(std::function<void()> reload) { _reloadCallBack = std::move(reload); }
void addAmmo(int ammoAdd) { _stockAmmo += ammoAdd; }
void addAPack() { _stockAmmo += initialPack(); }
[[nodiscard]] int initialPack() const { return _initialPack; }
};