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/AAttractToPoint.h
engine/animation/ARotateRelativePoint.h engine/animation/ARotateRelativePoint.h
engine/animation/ARotateLeft.h engine/animation/ARotateLeft.h
) engine/animation/Interpolation.cpp engine/animation/Animations.h)
if(APPLE OR UNIX) if(APPLE OR UNIX)
include_directories(/usr/local/include) include_directories(/usr/local/include)

View File

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

View File

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

View File

@ -5,17 +5,9 @@
#include "Shooter.h" #include "Shooter.h"
#include <fstream> #include <fstream>
#include <utility> #include <utility>
#include "engine/animation/AColor.h" #include "engine/animation/Animations.h"
#include "engine/animation/AFunction.h"
#include "engine/animation/ARotate.h"
#include "engine/animation/Timeline.h"
#include "ShooterConsts.h" #include "ShooterConsts.h"
#include "engine/SoundController.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; using namespace std;
@ -199,7 +191,8 @@ void Shooter::drawStatsTable() {
screen->drawText(client->lastEvent(), Vec2D{10, 10}, 25, sf::Color(0, 0, 0, 100)); 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); allPlayers.push_back(player);
for (auto&[playerId, player] : client->players()) for (auto&[playerId, player] : client->players())
allPlayers.push_back(player); allPlayers.push_back(player);
@ -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->addBody(std::make_shared<RigidBody>(Mesh::LineTo(ObjectNameTag(traceName), from, to, 0.05)));
world->body(ObjectNameTag(traceName))->setCollider(false); world->body(ObjectNameTag(traceName))->setCollider(false);
Timeline::animate(AnimationListTag(traceName + "_fadeOut"), Timeline::addAnimation<AColor>(AnimationListTag(traceName + "_fadeOut"), world->body(ObjectNameTag(traceName)),
std::make_shared<AColor>(world->body(ObjectNameTag(traceName)), sf::Color{150, 150, 150, 0})); sf::Color{150, 150, 150, 0});
Timeline::animate(AnimationListTag(traceName + "_delete"), Timeline::addAnimation<AFunction>(AnimationListTag(traceName + "_delete"),
std::make_shared<AFunction>([this, traceName]() { removeFireTrace(ObjectNameTag(traceName)); }, 1, [this, traceName]() { removeFireTrace(ObjectNameTag(traceName)); }, 1,
1)); 1);
} }
void Shooter::removeFireTrace(const ObjectNameTag &traceName) { 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->addBody(std::make_shared<RigidBody>(ObjectNameTag(bonusName), "obj/" + name + ".obj", Vec3D{3, 3, 3}));
world->body(ObjectNameTag(bonusName))->translateToPoint(position); world->body(ObjectNameTag(bonusName))->translateToPoint(position);
world->body(ObjectNameTag(bonusName))->setCollider(false); world->body(ObjectNameTag(bonusName))->setCollider(false);
world->body(ObjectNameTag(bonusName))->setSimpleHitBox(true);
world->body(ObjectNameTag(bonusName))->setTrigger(true); world->body(ObjectNameTag(bonusName))->setTrigger(true);
Timeline::animate(AnimationListTag(bonusName + "_rotation"), Timeline::addAnimation<ARotate>(AnimationListTag(bonusName + "_rotation"),
std::make_shared<ARotate>(world->body(ObjectNameTag(bonusName)), Vec3D{0, 2 * Consts::PI, 0}, 4, world->body(ObjectNameTag(bonusName)),
Animation::LoopOut::Continue, Animation::InterpolationType::Linear)); Vec3D{0, 2 * Consts::PI, 0}, 4,
Animation::LoopOut::Continue,
Animation::InterpolationType::Linear);
} }
void Shooter::removeBonus(const ObjectNameTag &bonusName) { void Shooter::removeBonus(const ObjectNameTag &bonusName) {

View File

@ -8,13 +8,7 @@
#include "engine/utils/Log.h" #include "engine/utils/Log.h"
#include "engine/animation/Timeline.h" #include "engine/animation/Timeline.h"
#include "ShooterMsgType.h" #include "ShooterMsgType.h"
#include "engine/animation/Animations.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"
void ShooterClient::updatePacket() { void ShooterClient::updatePacket() {
sf::Packet packet; sf::Packet packet;
@ -75,18 +69,31 @@ void ShooterClient::processUpdate(sf::Packet &packet) {
} }
if (isAnimate) { if (isAnimate) {
if(foot1 != nullptr && foot2 != nullptr && !Timeline::isInAnimList(AnimationListTag(name + "_foot1_rotation"))) { if (foot1 != nullptr && foot2 != nullptr &&
Timeline::animate(AnimationListTag(name + "_foot1_rotation"), std::make_shared<ARotateLeft>(foot1, 0.6, 0.2, Animation::LoopOut::None, Animation::InterpolationType::Linear)); !Timeline::isInAnimList(AnimationListTag(name + "_foot1_rotation"))) {
Timeline::animate(AnimationListTag(name + "_foot1_rotation"), std::make_shared<AWait>(0)); Timeline::addAnimation<ARotateLeft>(AnimationListTag(name + "_foot1_rotation"),
Timeline::animate(AnimationListTag(name + "_foot1_rotation"), std::make_shared<ARotateLeft>(foot1, -1.2, 0.2, Animation::LoopOut::None, Animation::InterpolationType::Linear)); foot1, 0.6, 0.2, Animation::LoopOut::None,
Timeline::animate(AnimationListTag(name + "_foot1_rotation"), std::make_shared<AWait>(0)); Animation::InterpolationType::Linear);
Timeline::animate(AnimationListTag(name + "_foot1_rotation"), std::make_shared<ARotateLeft>(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::addAnimation<ARotateLeft>(AnimationListTag(name + "_foot2_rotation"),
Timeline::animate(AnimationListTag(name + "_foot2_rotation"), std::make_shared<AWait>(0)); foot2, -0.6, 0.2, Animation::LoopOut::None,
Timeline::animate(AnimationListTag(name + "_foot2_rotation"), std::make_shared<ARotateLeft>(foot2, 1.2, 0.2, Animation::LoopOut::None, Animation::InterpolationType::Linear)); Animation::InterpolationType::Linear);
Timeline::animate(AnimationListTag(name + "_foot2_rotation"), std::make_shared<AWait>(0)); Timeline::addAnimation<AWait>(AnimationListTag(name + "_foot2_rotation"), 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, 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);
} }
} }
@ -150,13 +157,18 @@ void ShooterClient::processCustomPacket(sf::Packet &packet) {
camera->rotateLeft(-camera->angleLeftUpLookAt().x()); camera->rotateLeft(-camera->angleLeftUpLookAt().x());
camera->transform(Matrix4x4::Rotation(-_player->angle())); camera->transform(Matrix4x4::Rotation(-_player->angle()));
Timeline::animate(AnimationListTag("camera_anim"), std::make_shared<ATranslateToPoint>(camera, Vec3D(0, 30, -100))); Timeline::addAnimation<ATranslateToPoint>(AnimationListTag("camera_anim"),
Timeline::animate(AnimationListTag("camera_anim"), std::make_shared<AWait>(0)); camera, Vec3D(0, 30, -100));
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::addAnimation<AWait>(AnimationListTag("camera_anim"), 0);
Timeline::animate(AnimationListTag("camera_anim"), std::make_shared<AWait>(0)); Timeline::addAnimation<ARotateRelativePoint>(AnimationListTag("camera_anim"),
Timeline::animate(AnimationListTag("camera_anim"), std::make_shared<AFunction>([this, camera](){ 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 // 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)}); 50.0 * (-1 + 2.0 * (double) rand() / RAND_MAX)});
_player->reInitWeapons(); _player->reInitWeapons();
_player->setFullAbility(); _player->setFullAbility();
@ -167,7 +179,7 @@ void ShooterClient::processCustomPacket(sf::Packet &packet) {
camera->translateToPoint(_player->position() + Vec3D{0, 1.8, 0}); camera->translateToPoint(_player->position() + Vec3D{0, 1.8, 0});
_player->attach(camera); _player->attach(camera);
}, 1, 0.1)); }, 1, 0.1);
SoundController::playSound(SoundTag("death"), ShooterConsts::DEATH_SOUND); SoundController::playSound(SoundTag("death"), ShooterConsts::DEATH_SOUND);

View File

@ -11,7 +11,7 @@
namespace Consts { namespace Consts {
const int STANDARD_SCREEN_WIDTH = 1920; 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 sf::Color BACKGROUND_COLOR = sf::Color(255, 255, 255);
const std::string PROJECT_NAME = "engine"; const std::string PROJECT_NAME = "engine";
const bool USE_LOG_FILE = true; 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(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) { void Mesh::setColor(const sf::Color &c) {
_color = c; _color = c;
@ -107,7 +103,6 @@ void Mesh::setTriangles(vector<Triangle>&& t) {
} }
Mesh::~Mesh() { Mesh::~Mesh() {
_tris.clear();
delete[] _geometry; delete[] _geometry;
} }

View File

@ -54,8 +54,6 @@ public:
~Mesh() override; ~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, Mesh static LineTo(ObjectNameTag nameTag, const Vec3D &from, const Vec3D &to, double line_width = 0.1,
const sf::Color &color = {150, 150, 150, 100}); const sf::Color &color = {150, 150, 150, 100});

View File

@ -7,6 +7,13 @@
#include "Object.h" #include "Object.h"
#include "Matrix4x4.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) { void Object::transform(const Matrix4x4 &t) {
_transformMatrix = t * _transformMatrix; _transformMatrix = t * _transformMatrix;

View File

@ -23,10 +23,10 @@ public:
[[nodiscard]] std::string str() const { return _name; } [[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; } 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 { class Object {
@ -52,7 +52,7 @@ private:
public: public:
explicit Object(ObjectNameTag nameTag) : _nameTag(std::move(nameTag)) {}; 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 (?) // TODO: implement rotations using quaternions (?)
void transform(const Matrix4x4 &t); void transform(const Matrix4x4 &t);

View File

@ -11,78 +11,16 @@
#include "utils/Log.h" #include "utils/Log.h"
ResourceManager *ResourceManager::_instance = nullptr; ResourceManager *ResourceManager::_instance = nullptr;
bool ResourceManager::_validInstance = false;
void ResourceManager::init() { void ResourceManager::init() {
delete _instance;
_instance = new ResourceManager(); _instance = new ResourceManager();
_validInstance = true;
Log::log("ResourceManager::init(): resource manager was initialized"); 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) { std::shared_ptr<sf::Texture> ResourceManager::loadTexture(const std::string &filename) {
if (!_validInstance) { if (_instance == nullptr) {
return 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) { std::shared_ptr<sf::SoundBuffer> ResourceManager::loadSoundBuffer(const std::string &filename) {
if (!_validInstance) { if (_instance == nullptr) {
return 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) { std::shared_ptr<sf::Font> ResourceManager::loadFont(const std::string &filename) {
if (!_validInstance) { if (_instance == nullptr) {
return 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::vector<std::shared_ptr<Mesh>> objects{};
std::map<std::string, sf::Color> maters{}; std::map<std::string, sf::Color> maters{};
if (!_validInstance) { if (_instance == nullptr) {
return objects; return objects;
} }
@ -241,3 +179,75 @@ std::vector<std::shared_ptr<Mesh>> ResourceManager::loadObjects(const std::strin
return objects; 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; std::map<std::string, std::vector<std::shared_ptr<Mesh>>> _objects;
static ResourceManager *_instance; static ResourceManager *_instance;
static bool _validInstance;
ResourceManager() = default; ResourceManager() = default;

View File

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

View File

@ -30,7 +30,6 @@ private:
std::map<SoundTag, sf::Sound> _sounds; std::map<SoundTag, sf::Sound> _sounds;
static SoundController *_instance; static SoundController *_instance;
static bool _validInstance;
SoundController() = default; 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) { 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 " + Log::log("World::loadBody(): inserted body from " + filename + " with title '" + tag.str() + "' with " +
std::to_string(_objects[tag]->triangles().size()) + " tris."); 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; bool escapeThisBody = false;
for (auto &escapeTag : tagsToSkip) { for (auto &escapeTag : tagsToSkip) {
if (name.str().find(escapeTag) != std::string::npos) { if (name.contains(ObjectNameTag(escapeTag))) {
escapeThisBody = true; escapeThisBody = true;
break; 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) { void World::loadMap(const std::string &filename, const Vec3D &scale) {
auto objs = ResourceManager::loadObjects(filename); auto objs = ResourceManager::loadObjects(filename);
for (auto &i : objs) { 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); addBody(obj);
obj->scale(scale); obj->scale(scale);
} }
@ -122,9 +122,9 @@ void World::checkCollision(const ObjectNameTag &tag) {
} }
void World::update() { void World::update() {
for (auto &m : _objects) { for (auto &[nameTag, obj] : _objects) {
m.second->updatePhysicsState(); obj->updatePhysicsState();
checkCollision(m.first); checkCollision(nameTag);
} }
} }

View File

@ -23,28 +23,23 @@ struct IntersectionInformation final {
class World final { class World final {
private: private:
std::map<ObjectNameTag, std::shared_ptr<RigidBody>> _objects; std::map<ObjectNameTag, std::shared_ptr<RigidBody>> _objects;
public:
World() = default;
void checkCollision(const ObjectNameTag &tag); void checkCollision(const ObjectNameTag &tag);
public:
World() = default;
void update(); void update();
void addBody(std::shared_ptr<RigidBody> mesh); void addBody(std::shared_ptr<RigidBody> mesh);
std::shared_ptr<RigidBody> body(const ObjectNameTag &tag); std::shared_ptr<RigidBody> body(const ObjectNameTag &tag);
void removeBody(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 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 // 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 = ""); 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 begin() { return _objects.begin(); }
std::map<ObjectNameTag, std::shared_ptr<RigidBody>>::iterator end() { return _objects.end(); } std::map<ObjectNameTag, std::shared_ptr<RigidBody>>::iterator end() { return _objects.end(); }
}; };

View File

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

View File

@ -5,8 +5,6 @@
#ifndef ENGINE_ACOLOR_H #ifndef ENGINE_ACOLOR_H
#define ENGINE_ACOLOR_H #define ENGINE_ACOLOR_H
#include <utility>
#include "Animation.h" #include "Animation.h"
#include "../Mesh.h" #include "../Mesh.h"
@ -19,21 +17,23 @@ private:
bool _started = false; bool _started = false;
void update() override { void update() override {
if (_mesh.expired()) { auto mesh = _mesh.lock();
if (mesh == nullptr) {
stop(); stop();
return; return;
} }
if (!_started) { if (!_started) {
_started = true; _started = true;
_startColor = _mesh.lock()->color(); _startColor = mesh->color();
} }
Vec4D start(_startColor.r, _startColor.g, _startColor.b, _startColor.a); Vec4D start(_startColor.r, _startColor.g, _startColor.b, _startColor.a);
Vec4D end(_newColor.r, _newColor.g, _newColor.b, _newColor.a); Vec4D end(_newColor.r, _newColor.g, _newColor.b, _newColor.a);
Vec4D mid = start + (end - start) * progress(); 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()))); 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, 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 interpolationType = InterpolationType::Linear) : Animation(duration, looped,
interpolationType), interpolationType),
_mesh(std::move(mesh)), _newColor(color) { _mesh(mesh), _newColor(color) {
} }
}; };

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,10 +5,7 @@
#ifndef ENGINE_ANIMATION_H #ifndef ENGINE_ANIMATION_H
#define ENGINE_ANIMATION_H #define ENGINE_ANIMATION_H
#include "../utils/Time.h"
#include "../Triangle.h"
#include "Interpolation.h" #include "Interpolation.h"
#include "../Vec2D.h"
class Animation { class Animation {
public: public:
@ -32,8 +29,9 @@ private:
double _progress = 0; double _progress = 0;
double _dprogress = 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()) // If '_waitForFinish' == true then we need to finish all animation before starting this one. (for example AWait)
const bool _waitFor = false; // 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 double _duration = 0;
const LoopOut _looped = LoopOut::None; const LoopOut _looped = LoopOut::None;
const InterpolationType _intType = InterpolationType::Bezier; const InterpolationType _intType = InterpolationType::Bezier;
@ -41,22 +39,20 @@ private:
// You should override this method for your particular animation // You should override this method for your particular animation
virtual void update() = 0; virtual void update() = 0;
protected:
[[nodiscard]] double progress() const { return _progress; }
[[nodiscard]] double dprogress() const { return _dprogress; }
void stop() { _finished = true; }
public: public:
Animation(double duration, LoopOut looped, InterpolationType intType, bool _waitFor = false); Animation(double duration, LoopOut looped, InterpolationType intType, bool _waitFor = false);
virtual ~Animation() = default; virtual ~Animation() = default;
[[nodiscard]] bool waitFor() const { return _waitFor; }
bool updateState(); bool updateState();
[[nodiscard]] double progress() const { return _progress; } [[nodiscard]] bool isWaitingForFinish() const { return _waitForFinish; }
[[nodiscard]] double dprogress() const { return _dprogress; }
void stop() { _finished = true; }
[[nodiscard]] bool isFinished() const { return _finished; }
}; };
#endif //INC_3DZAVR_ANIMATION_H #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 #ifndef ENGINE_INTERPOLATION_H
#define ENGINE_INTERPOLATION_H #define ENGINE_INTERPOLATION_H
#include <cmath>
#include "../Vec2D.h" #include "../Vec2D.h"
#include "../Consts.h"
namespace Interpolation { 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); double dBouncing(double t, double dt);
static 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 #endif //INC_3DZAVR_INTERPOLATION_H

View File

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

View File

@ -4,7 +4,10 @@
#ifndef SHOOTER_TIMELINE_H #ifndef SHOOTER_TIMELINE_H
#define SHOOTER_TIMELINE_H #define SHOOTER_TIMELINE_H
#include <memory> #include <memory>
#include <string>
#include <map>
#include "Animation.h" #include "Animation.h"
@ -28,7 +31,6 @@ private:
std::map<AnimationListTag, std::list<std::shared_ptr<Animation>>> _animations; std::map<AnimationListTag, std::list<std::shared_ptr<Animation>>> _animations;
static Timeline *_instance; static Timeline *_instance;
static bool _validInstance;
Timeline() = default; Timeline() = default;
@ -39,8 +41,6 @@ public:
static void update(); static void update();
static void animate(const AnimationListTag &listName, std::shared_ptr<Animation> anim);
static void deleteAllAnimations(); static void deleteAllAnimations();
static void deleteAnimationList(const AnimationListTag &listName); static void deleteAnimationList(const AnimationListTag &listName);
@ -50,6 +50,15 @@ public:
static void init(); static void init();
static void free(); 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 #endif //SHOOTER_TIMELINE_H

View File

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

View File

@ -19,23 +19,15 @@ bool HitBox::Vec3DLess::operator()(const Vec3D& lhs, const Vec3D& rhs) const noe
return false; return false;
} }
HitBox::HitBox(const Mesh& mesh) { HitBox::HitBox(const Mesh& mesh, bool useSimpleBox) {
// we dont need to add the same points in hit box if (useSimpleBox) {
std::set<Vec3D, HitBox::Vec3DLess> points; generateSimple(mesh);
} else {
for (const auto& t : mesh.triangles()) generateDetailed(mesh);
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::Box(const Mesh &mesh) { void HitBox::generateSimple(const Mesh &mesh) {
HitBox result;
double maxX = -std::numeric_limits<double>::max(); double maxX = -std::numeric_limits<double>::max();
double maxY = -std::numeric_limits<double>::max(); double maxY = -std::numeric_limits<double>::max();
double maxZ = -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); _hitBox.emplace_back(minX, minY, minZ);
result._hitBox.emplace_back(minX, maxY, minZ); _hitBox.emplace_back(minX, maxY, minZ);
result._hitBox.emplace_back(maxX, minY, minZ); _hitBox.emplace_back(maxX, minY, minZ);
result._hitBox.emplace_back(maxX, maxY, minZ); _hitBox.emplace_back(maxX, maxY, minZ);
result._hitBox.emplace_back(minX, minY, maxZ); _hitBox.emplace_back(minX, minY, maxZ);
result._hitBox.emplace_back(minX, maxY, maxZ); _hitBox.emplace_back(minX, maxY, maxZ);
result._hitBox.emplace_back(maxX, minY, maxZ); _hitBox.emplace_back(maxX, minY, maxZ);
result._hitBox.emplace_back(maxX, maxY, maxZ); _hitBox.emplace_back(maxX, maxY, maxZ);
}
return result;
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; std::vector<Vec3D> _hitBox;
void generateSimple(const Mesh &mesh);
void generateDetailed(const Mesh &mesh);
public: public:
HitBox() = default; HitBox() = default;
HitBox(const HitBox &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 begin() { return _hitBox.begin(); }
[[nodiscard]] std::vector<Vec3D>::iterator end() { return _hitBox.end(); } [[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 "../utils/Time.h"
#include "../Consts.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), 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 RigidBody::_findFurthestPoint(const Vec3D &direction) {
Vec3D maxPoint{0, 0, 0}; 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 RigidBody::_support(std::shared_ptr<RigidBody> obj, const Vec3D &direction) {
Vec3D p1 = _findFurthestPoint(direction); Vec3D p1 = _findFurthestPoint(direction);
Vec3D p2 = obj->_findFurthestPoint(-direction); Vec3D p2 = obj->_findFurthestPoint(-direction);
Vec3D res = p1 - p2;
return p1 - p2; return p1 - p2;
} }
@ -349,12 +347,3 @@ void RigidBody::addVelocity(const Vec3D &velocity) {
void RigidBody::setAcceleration(const Vec3D &acceleration) { void RigidBody::setAcceleration(const Vec3D &acceleration) {
_acceleration = 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; bool _isTrigger = false;
HitBox _hitBox{}; HitBox _hitBox{};
bool _simpleHitBox = false;
bool _inCollision = false; bool _inCollision = false;
Vec3D _collisionNormal{0, 0, 0}; Vec3D _collisionNormal{0, 0, 0};
Vec3D _findFurthestPoint(const Vec3D &direction); Vec3D _findFurthestPoint(const Vec3D &direction);
Vec3D _support(std::shared_ptr<RigidBody> obj, const Vec3D &direction); Vec3D _support(std::shared_ptr<RigidBody> obj, const Vec3D &direction);
std::function<void(const ObjectNameTag &, std::shared_ptr<RigidBody>)> _collisionCallBack; std::function<void(const ObjectNameTag &, std::shared_ptr<RigidBody>)> _collisionCallBack;
static NextSimplex _nextSimplex(const Simplex &points); static NextSimplex _nextSimplex(const Simplex &points);
static NextSimplex _lineCase(const Simplex &points); static NextSimplex _lineCase(const Simplex &points);
static NextSimplex _triangleCase(const Simplex &points); static NextSimplex _triangleCase(const Simplex &points);
static NextSimplex _tetrahedronCase(const Simplex &points); static NextSimplex _tetrahedronCase(const Simplex &points);
static std::pair<std::vector<FaceNormal>, size_t> static std::pair<std::vector<FaceNormal>, size_t>
@ -68,49 +62,32 @@ private:
size_t b); size_t b);
public: public:
explicit RigidBody(ObjectNameTag nameTag) : Mesh(std::move(nameTag)) {}; explicit RigidBody(ObjectNameTag nameTag) : Mesh(std::move(nameTag)) {};
RigidBody(const RigidBody &rigidBody) = default; RigidBody(const RigidBody &rigidBody) = default;
explicit RigidBody(const Mesh &mesh, bool useSimpleBox = true);
explicit RigidBody(const Mesh &mesh); RigidBody(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1}, bool useSimpleBox = true);
RigidBody(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1});
[[nodiscard]] std::pair<bool, Simplex> checkGJKCollision(std::shared_ptr<RigidBody> obj); [[nodiscard]] std::pair<bool, Simplex> checkGJKCollision(std::shared_ptr<RigidBody> obj);
[[nodiscard]] CollisionPoint EPA(const Simplex &simplex, std::shared_ptr<RigidBody> obj); [[nodiscard]] CollisionPoint EPA(const Simplex &simplex, std::shared_ptr<RigidBody> obj);
void solveCollision(const CollisionPoint &collision); void solveCollision(const CollisionPoint &collision);
[[nodiscard]] Vec3D collisionNormal() const { return _collisionNormal; } [[nodiscard]] Vec3D collisionNormal() const { return _collisionNormal; }
[[nodiscard]] bool hasCollision() const { return _hasCollision; } [[nodiscard]] bool hasCollision() const { return _hasCollision; }
[[nodiscard]] bool inCollision() const { return _inCollision; } [[nodiscard]] bool inCollision() const { return _inCollision; }
[[nodiscard]] bool isCollider() const { return _isCollider; } [[nodiscard]] bool isCollider() const { return _isCollider; }
[[nodiscard]] bool isTrigger() const { return _isTrigger; } [[nodiscard]] bool isTrigger() const { return _isTrigger; }
void setInCollision(bool c) { _inCollision = c; } void setInCollision(bool c) { _inCollision = c; }
void setCollision(bool c) { _hasCollision = c; } void setCollision(bool c) { _hasCollision = c; }
void setCollider(bool c) { _isCollider = c; } void setCollider(bool c) { _isCollider = c; }
void setSimpleHitBox(bool b);
void setTrigger(bool t) { _isTrigger = t; } void setTrigger(bool t) { _isTrigger = t; }
void updatePhysicsState(); void updatePhysicsState();
void setVelocity(const Vec3D &velocity); void setVelocity(const Vec3D &velocity);
void addVelocity(const Vec3D &velocity); void addVelocity(const Vec3D &velocity);
void setAcceleration(const Vec3D &acceleration); void setAcceleration(const Vec3D &acceleration);
[[nodiscard]] Vec3D velocity() const { return _velocity; } [[nodiscard]] Vec3D velocity() const { return _velocity; }
[[nodiscard]] Vec3D acceleration() const { return _acceleration; } [[nodiscard]] Vec3D acceleration() const { return _acceleration; }
[[nodiscard]] const std::function<void(const ObjectNameTag &, std::shared_ptr<RigidBody>)> & [[nodiscard]] const std::function<void(const ObjectNameTag &, std::shared_ptr<RigidBody>)> &

View File

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

View File

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

View File

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

View File

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

View File

@ -6,7 +6,6 @@
#define SHOOTER_AK47_H #define SHOOTER_AK47_H
#include "Weapon.h" #include "Weapon.h"
#include "../engine/ResourceManager.h"
#include "../ShooterConsts.h" #include "../ShooterConsts.h"
class Ak47 final : public Weapon { 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}) {} Vec3D{3, 3, 3}, Vec3D{-2.3, 0.8, 1.8},Vec3D{0, 0, 0}) {}
}; };
#endif //SHOOTER_3DZAVR_AK47_H #endif //SHOOTER_3DZAVR_AK47_H

View File

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

View File

@ -2,12 +2,9 @@
// Created by Иван Ильин on 01.06.2021. // Created by Иван Ильин on 01.06.2021.
// //
#include <utility>
#include "Weapon.h" #include "Weapon.h"
#include "../engine/ResourceManager.h" #include "../engine/ResourceManager.h"
#include "../engine/utils/Log.h" #include "../engine/utils/Log.h"
#include "../engine/animation/AColor.h"
#include "../ShooterConsts.h" #include "../ShooterConsts.h"
using namespace std; using namespace std;
@ -79,33 +76,37 @@ void Weapon::reload() {
std::map<ObjectNameTag, double> std::map<ObjectNameTag, double>
Weapon::processFire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction, Weapon::processFire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction) { const Vec3D &position, const Vec3D &direction) const {
return addTrace(std::move(rayCastFunction), position, direction); // 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> std::map<ObjectNameTag, double>
Weapon::addTrace(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction, Weapon::fireABullet(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &from, const Vec3D &directionTo) { const Vec3D &cameraPosition, const Vec3D &direction) const {
std::map<ObjectNameTag, double> damagedPlayers; std::map<ObjectNameTag, double> damagedPlayers;
double spreading = _spreading * ShooterConsts::FIRE_DISTANCE / 100; double spreading = _spreading * ShooterConsts::FIRE_DISTANCE / 100.0;
//generate random vector //generate random vector
Vec3D randV(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 * (double) rand() / RAND_MAX), spreading * (1.0 - 2.0 * static_cast<double>(rand()) / RAND_MAX),
spreading * (1.0 - 2.0 * (double) rand() / RAND_MAX)); spreading * (1.0 - 2.0 * static_cast<double>(rand()) / RAND_MAX));
// damage player // damage player
auto rayCast = rayCastFunction(from, from + directionTo * ShooterConsts::FIRE_DISTANCE + randV); auto rayCast = rayCastFunction(cameraPosition, cameraPosition + direction * ShooterConsts::FIRE_DISTANCE + randV);
if (rayCast.objectName.str().find("Enemy") != std::string::npos) { if (rayCast.objectName.contains(ObjectNameTag("Enemy"))) {
damagedPlayers[rayCast.objectName] += _damage / (1.0 + rayCast.distanceToObject); damagedPlayers[rayCast.objectName] += _damage / (1.0 + rayCast.distanceToObject);
// If you hit the head the damage will be doubled // 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); damagedPlayers[rayCast.objectName] += _damage / (1.0 + rayCast.distanceToObject);
} }
// If you hit the foot the damage will be divided by 2 // 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); 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 // add trace line
Vec3D lineFrom = position() + model() * Vec3D(triangles().back()[0]); Vec3D lineFrom = position() + model() * Vec3D(triangles().back()[0]);
Vec3D lineTo = rayCast.intersected ? rayCast.pointOfIntersection : position() + Vec3D lineTo = rayCast.intersected ? rayCast.pointOfIntersection : position() +
directionTo * ShooterConsts::FIRE_DISTANCE + direction * ShooterConsts::FIRE_DISTANCE +
randV; randV;
_addTraceCallBack(lineFrom, lineTo); _addTraceCallBack(lineFrom, lineTo);

View File

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