code refactoring

master
Vectozavr 2021-10-31 15:39:08 +07:00
parent c2620aa8a5
commit 785850ec43
88 changed files with 1432 additions and 958 deletions

View File

@ -13,9 +13,11 @@ Player::Player(ObjectNameTag name) : RigidBody(name) {
setVisible(false); setVisible(false);
Vec3D randColor = Vec3D::Random(); Vec3D randColor = Vec3D::Random();
setColor({static_cast<sf::Uint8>(randColor.x()*255), static_cast<sf::Uint8>(randColor.y()*255), static_cast<sf::Uint8>(randColor.z()*255)}); setColor({static_cast<sf::Uint8>(randColor.x() * 255), static_cast<sf::Uint8>(randColor.y() * 255),
static_cast<sf::Uint8>(randColor.z() * 255)});
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) { void Player::rotateWeaponsRelativePoint(const Vec3D &point4D, const Vec3D &v, double val) {

View File

@ -44,63 +44,83 @@ public:
explicit Player(ObjectNameTag name); explicit Player(ObjectNameTag name);
void setHealth(double h) { _health = h; } void setHealth(double h) { _health = h; }
void setAbility(double a) { _ability = a; } void setAbility(double a) { _ability = a; }
[[nodiscard]] double health() const { return _health; } [[nodiscard]] double health() const { return _health; }
[[nodiscard]] double ability() const { return _ability; } [[nodiscard]] double ability() const { return _ability; }
void setFullHealth(); void setFullHealth();
void setFullAbility(); void setFullAbility();
void initWeapons(); void initWeapons();
void addWeapon(std::shared_ptr<Weapon> weapon); void addWeapon(std::shared_ptr<Weapon> weapon);
[[nodiscard]] std::pair<double, double> balance() const { return _weapons[_selectedWeapon]->balance(); } [[nodiscard]] std::pair<double, double> balance() const { return _weapons[_selectedWeapon]->balance(); }
void nextWeapon(); void nextWeapon();
void previousWeapon(); void previousWeapon();
bool fire(); bool fire();
void reload(); void reload();
[[nodiscard]] ObjectNameTag weaponName() const { return _weapons[_selectedWeapon]->name(); } [[nodiscard]] ObjectNameTag weaponName() const { return _weapons[_selectedWeapon]->name(); }
std::shared_ptr<Weapon> weapon() { return _weapons[_selectedWeapon]; } std::shared_ptr<Weapon> weapon() { return _weapons[_selectedWeapon]; }
void rotateWeaponsRelativePoint(const Vec3D &point, const Vec3D &v, double val); void rotateWeaponsRelativePoint(const Vec3D &point, const Vec3D &v, double val);
[[nodiscard]] int kills() const { return _kills; } [[nodiscard]] int kills() const { return _kills; }
[[nodiscard]] int deaths() const { return _deaths; } [[nodiscard]] int deaths() const { return _deaths; }
void addKill() { _kills++; } void addKill() { _kills++; }
void addDeath() { _deaths++; } void addDeath() { _deaths++; }
void setKills(int kills) { _kills = kills; } void setKills(int kills) { _kills = kills; }
void setDeaths(int deaths) { _deaths = deaths; } void setDeaths(int deaths) { _deaths = deaths; }
void setDamagePlayerCallBack(std::function<void(sf::Uint16 targetId, double)> hit) { void setDamagePlayerCallBack(std::function<void(sf::Uint16 targetId, double)> hit) {
_damagePlayerCallBack = std::move(hit); _damagePlayerCallBack = std::move(hit);
} }
void setAddTraceCallBack(std::function<void(const Vec3D &, const Vec3D &)> add) { void setAddTraceCallBack(std::function<void(const Vec3D &, const Vec3D &)> add) {
_addTraceCallBack = std::move(add); _addTraceCallBack = std::move(add);
} }
void setTakeBonusCallBack(std::function<void(const std::string &)> take) { void setTakeBonusCallBack(std::function<void(const std::string &)> take) {
_takeBonusCallBack = std::move(take); _takeBonusCallBack = std::move(take);
} }
void setAddWeaponCallBack(std::function<void(std::shared_ptr<Weapon>)> addWeapon) { void setAddWeaponCallBack(std::function<void(std::shared_ptr<Weapon>)> addWeapon) {
_addWeaponCallBack = std::move(addWeapon); _addWeaponCallBack = std::move(addWeapon);
} }
void setRemoveWeaponCallBack(std::function<void(std::shared_ptr<Weapon>)> removeWeapon) { void setRemoveWeaponCallBack(std::function<void(std::shared_ptr<Weapon>)> removeWeapon) {
_removeWeaponCallBack = std::move(removeWeapon); _removeWeaponCallBack = std::move(removeWeapon);
} }
void setRayCastFunction(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction) { void setRayCastFunction(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction) {
_rayCastFunction = std::move(rayCastFunction); _rayCastFunction = std::move(rayCastFunction);
} }
// This is for situation when you want to store the position of the head but you dont have attached camera // This is for situation when you want to store the position of the head but you dont have attached camera
void setHeadAngle(double a) { _headAngle = a; } void setHeadAngle(double a) { _headAngle = a; }
[[nodiscard]] double headAngle() const { return _headAngle; }; [[nodiscard]] double headAngle() const { return _headAngle; };
void collisionWithObject(const ObjectNameTag &tag, std::shared_ptr<RigidBody> obj); void collisionWithObject(const ObjectNameTag &tag, std::shared_ptr<RigidBody> obj);
[[nodiscard]] std::string playerNickName() const { return _nickName; } [[nodiscard]] std::string playerNickName() const { return _nickName; }
void setPlayerNickName(const std::string &name) { _nickName = name; } void setPlayerNickName(const std::string &name) { _nickName = name; }
}; };

View File

@ -12,7 +12,8 @@
PlayerController::PlayerController(std::shared_ptr<Player> player, PlayerController::PlayerController(std::shared_ptr<Player> player,
std::shared_ptr<Keyboard> keyboard, std::shared_ptr<Keyboard> keyboard,
std::shared_ptr<Mouse> mouse) : _player(player), _keyboard(keyboard), _mouse(mouse) {} std::shared_ptr<Mouse> mouse) : _player(player), _keyboard(keyboard),
_mouse(mouse) {}
void PlayerController::update() { void PlayerController::update() {
// friction // friction
@ -27,7 +28,8 @@ void PlayerController::update() {
_player->setAbility(0); _player->setAbility(0);
_isInSlowMo = false; _isInSlowMo = false;
_player->setVelocity(_player->velocity() * ShooterConsts::SLOW_MO_COEFFICIENT); _player->setVelocity(_player->velocity() * ShooterConsts::SLOW_MO_COEFFICIENT);
_player->setAcceleration(_player->acceleration() * ShooterConsts::SLOW_MO_COEFFICIENT * ShooterConsts::SLOW_MO_COEFFICIENT); _player->setAcceleration(
_player->acceleration() * ShooterConsts::SLOW_MO_COEFFICIENT * ShooterConsts::SLOW_MO_COEFFICIENT);
SoundController::stopSound(SoundTag("slowMo")); SoundController::stopSound(SoundTag("slowMo"));
SoundController::playSound(SoundTag("unSlowMo"), ShooterConsts::UN_SLOW_MO_SOUND); SoundController::playSound(SoundTag("unSlowMo"), ShooterConsts::UN_SLOW_MO_SOUND);
} }
@ -44,25 +46,43 @@ 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"), 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<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<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_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<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<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<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<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<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<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<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::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::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"), std::make_shared<ATranslateToPoint>( camera, _player->position() + Vec3D{0, 1.8, 0}, 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.15,
Animation::LoopOut::None,
Animation::InterpolationType::Cos));
} }
// Left and right // Left and right
@ -100,7 +120,9 @@ void PlayerController::update() {
// slow mo // slow mo
_isInSlowMo = true; _isInSlowMo = true;
_player->setVelocity(_player->velocity() / ShooterConsts::SLOW_MO_COEFFICIENT); _player->setVelocity(_player->velocity() / ShooterConsts::SLOW_MO_COEFFICIENT);
_player->setAcceleration(Vec3D(0, -ShooterConsts::GRAVITY / (ShooterConsts::SLOW_MO_COEFFICIENT * ShooterConsts::SLOW_MO_COEFFICIENT), 0)); _player->setAcceleration(Vec3D(0, -ShooterConsts::GRAVITY /
(ShooterConsts::SLOW_MO_COEFFICIENT * ShooterConsts::SLOW_MO_COEFFICIENT),
0));
SoundController::stopSound(SoundTag("unSlowMo")); SoundController::stopSound(SoundTag("unSlowMo"));
SoundController::playSound(SoundTag("slowMo"), ShooterConsts::SLOW_MO_SOUND); SoundController::playSound(SoundTag("slowMo"), ShooterConsts::SLOW_MO_SOUND);
} else if (_isInSlowMo && !Keyboard::isKeyPressed(sf::Keyboard::LShift)) { } else if (_isInSlowMo && !Keyboard::isKeyPressed(sf::Keyboard::LShift)) {
@ -143,7 +165,8 @@ void PlayerController::update() {
Vec2D displacement = _mouse->getMouseDisplacement(); Vec2D displacement = _mouse->getMouseDisplacement();
_player->rotate(Vec3D{0, -displacement.x() * ShooterConsts::MOUSE_SENSITIVITY, 0}); _player->rotate(Vec3D{0, -displacement.x() * ShooterConsts::MOUSE_SENSITIVITY, 0});
_player->setVelocity(Matrix4x4::RotationY(-displacement.x() * ShooterConsts::MOUSE_SENSITIVITY) * _player->velocity()); _player->setVelocity(
Matrix4x4::RotationY(-displacement.x() * ShooterConsts::MOUSE_SENSITIVITY) * _player->velocity());
double rotationLeft = displacement.y() * ShooterConsts::MOUSE_SENSITIVITY; double rotationLeft = displacement.y() * ShooterConsts::MOUSE_SENSITIVITY;
@ -182,6 +205,7 @@ void PlayerController::update() {
} }
if ((_inRunning || _player->velocity().sqrAbs() > 3) && _player->inCollision() && !walkSoundPlayed) { if ((_inRunning || _player->velocity().sqrAbs() > 3) && _player->inCollision() && !walkSoundPlayed) {
int soundNum = (int) ((double) rand() / RAND_MAX * 6) + 1; int soundNum = (int) ((double) rand() / RAND_MAX * 6) + 1;
SoundController::playSound(SoundTag("walkSound_" + std::to_string(soundNum)), "sound/stonestep" + std::to_string(soundNum) + ".ogg"); SoundController::playSound(SoundTag("walkSound_" + std::to_string(soundNum)),
"sound/stonestep" + std::to_string(soundNum) + ".ogg");
} }
} }

View File

@ -21,6 +21,7 @@ private:
public: public:
PlayerController(std::shared_ptr<Player> player, std::shared_ptr<Keyboard> keyboard, std::shared_ptr<Mouse> mouse); PlayerController(std::shared_ptr<Player> player, std::shared_ptr<Keyboard> keyboard, std::shared_ptr<Mouse> mouse);
void update(); void update();
}; };

View File

@ -24,8 +24,8 @@ void Shooter::InitNetwork() {
std::ifstream connectFile("connect.txt", std::ifstream::in); std::ifstream connectFile("connect.txt", std::ifstream::in);
// If failed to read client settings // If failed to read client settings
if (!connectFile.is_open() || !(connectFile >> clientIp >> clientPort >> playerName) || sf::IpAddress(clientIp) == sf::IpAddress::None) if (!connectFile.is_open() || !(connectFile >> clientIp >> clientPort >> playerName) ||
{ sf::IpAddress(clientIp) == sf::IpAddress::None) {
connectFile.close(); connectFile.close();
// Create file and write default settings // Create file and write default settings
clientIp = "127.0.0.1"; clientIp = "127.0.0.1";
@ -39,8 +39,7 @@ void Shooter::InitNetwork() {
// If failed to read server settings // If failed to read server settings
connectFile.open("server.txt", std::ifstream::in); connectFile.open("server.txt", std::ifstream::in);
if (!connectFile.is_open() || !(connectFile >> serverPort)) if (!connectFile.is_open() || !(connectFile >> serverPort)) {
{
connectFile.close(); connectFile.close();
// Create file and write default settings // Create file and write default settings
serverPort = 54000; serverPort = 54000;
@ -63,9 +62,11 @@ void Shooter::InitNetwork() {
client->setSpawnPlayerCallBack([this](sf::Uint16 id) { spawnPlayer(id); }); client->setSpawnPlayerCallBack([this](sf::Uint16 id) { spawnPlayer(id); });
client->setRemovePlayerCallBack([this](sf::Uint16 id) { removePlayer(id); }); client->setRemovePlayerCallBack([this](sf::Uint16 id) { removePlayer(id); });
client->setAddFireTraceCallBack([this](const Vec3D &from, const Vec3D &to) { addFireTrace(from, to); }); client->setAddFireTraceCallBack([this](const Vec3D &from, const Vec3D &to) { addFireTrace(from, to); });
client->setAddBonusCallBack([this](const std::string& bonusName, const Vec3D& position){ addBonus(bonusName, position); }); client->setAddBonusCallBack(
[this](const std::string &bonusName, const Vec3D &position) { addBonus(bonusName, position); });
client->setRemoveBonusCallBack([this](const ObjectNameTag &bonusName) { removeBonus(bonusName); }); client->setRemoveBonusCallBack([this](const ObjectNameTag &bonusName) { removeBonus(bonusName); });
client->setChangeEnemyWeaponCallBack([this](const std::string& weaponName, sf::Uint16 id){ changeEnemyWeapon(weaponName, id); }); client->setChangeEnemyWeaponCallBack(
[this](const std::string &weaponName, sf::Uint16 id) { changeEnemyWeapon(weaponName, id); });
} }
void Shooter::start() { void Shooter::start() {
@ -79,9 +80,14 @@ void Shooter::start() {
player->scale(Vec3D(3, 1, 3)); player->scale(Vec3D(3, 1, 3));
// TODO: encapsulate call backs inside Player // TODO: encapsulate call backs inside Player
player->setAddTraceCallBack([this](const Vec3D& from, const Vec3D& to){ client->addTrace(from, to); addFireTrace(from, to); }); player->setAddTraceCallBack([this](const Vec3D &from, const Vec3D &to) {
player->setDamagePlayerCallBack([this] (sf::Uint16 targetId, double damage) { client->damagePlayer(targetId, damage); }); client->addTrace(from, to);
player->setRayCastFunction([this](const Vec3D& from, const Vec3D& to) { return world->rayCast(from, to, "Player Weapon"); }); addFireTrace(from, to);
});
player->setDamagePlayerCallBack(
[this](sf::Uint16 targetId, double damage) { client->damagePlayer(targetId, damage); });
player->setRayCastFunction(
[this](const Vec3D &from, const Vec3D &to) { return world->rayCast(from, to, "Player Weapon"); });
player->setTakeBonusCallBack([this](const string &bonusName) { client->takeBonus(bonusName); }); player->setTakeBonusCallBack([this](const string &bonusName) { client->takeBonus(bonusName); });
player->setAddWeaponCallBack([this](std::shared_ptr<Weapon> weapon) { addWeapon(std::move(weapon)); }); player->setAddWeaponCallBack([this](std::shared_ptr<Weapon> weapon) { addWeapon(std::move(weapon)); });
player->setRemoveWeaponCallBack([this](std::shared_ptr<Weapon> weapon) { removeWeapon(std::move(weapon)); }); player->setRemoveWeaponCallBack([this](std::shared_ptr<Weapon> weapon) { removeWeapon(std::move(weapon)); });
@ -112,10 +118,23 @@ void Shooter::start() {
mainMenu.setTitle("Main menu"); mainMenu.setTitle("Main menu");
mainMenu.setBackgroundTexture(ShooterConsts::MAIN_MENU_BACK, 1.1, 1.1, screen->width(), screen->height()); mainMenu.setBackgroundTexture(ShooterConsts::MAIN_MENU_BACK, 1.1, 1.1, screen->width(), screen->height());
mainMenu.addButton(screen->width()/2, 200, 200, 20, [this] () { this->play(); SoundController::playSound(SoundTag("click"), ShooterConsts::CLICK_SOUND);}, "Server: " + client->serverIp().toString(), 5, 5, ShooterConsts::MAIN_MENU_GUI, {0, 66}, {0, 86}, {0, 46}, Consts::MEDIUM_FONT, {255, 255, 255}); mainMenu.addButton(screen->width() / 2, 200, 200, 20, [this]() {
mainMenu.addButton(screen->width()/2, 350, 200, 20, [this] () { this->player->translateToPoint(Vec3D{0, 0, 0}); this->player->setVelocity({}); this->play(); SoundController::playSound(SoundTag("click"), ShooterConsts::CLICK_SOUND);}, "Respawn", 5, 5, ShooterConsts::MAIN_MENU_GUI, {0, 66}, {0, 86}, {0, 46}, Consts::MEDIUM_FONT, {255, 255, 255}); this->play();
SoundController::playSound(SoundTag("click"), ShooterConsts::CLICK_SOUND);
}, "Server: " + client->serverIp().toString(), 5, 5, ShooterConsts::MAIN_MENU_GUI, {0, 66}, {0, 86}, {0, 46},
Consts::MEDIUM_FONT, {255, 255, 255});
mainMenu.addButton(screen->width() / 2, 350, 200, 20, [this]() {
this->player->translateToPoint(Vec3D{0, 0, 0});
this->player->setVelocity({});
this->play();
SoundController::playSound(SoundTag("click"), ShooterConsts::CLICK_SOUND);
}, "Respawn", 5, 5, ShooterConsts::MAIN_MENU_GUI, {0, 66}, {0, 86}, {0, 46}, Consts::MEDIUM_FONT, {255, 255, 255});
mainMenu.addButton(screen->width()/2, 500, 200, 20, [this] () { client->disconnect(); server->stop(); this->exit();}, "Exit", 5, 5, ShooterConsts::MAIN_MENU_GUI, {0, 66}, {0, 86}, {0, 46}, Consts::MEDIUM_FONT, {255, 255, 255}); mainMenu.addButton(screen->width() / 2, 500, 200, 20, [this]() {
client->disconnect();
server->stop();
this->exit();
}, "Exit", 5, 5, ShooterConsts::MAIN_MENU_GUI, {0, 66}, {0, 86}, {0, 46}, Consts::MEDIUM_FONT, {255, 255, 255});
} }
void Shooter::update() { void Shooter::update() {
@ -156,7 +175,8 @@ void Shooter::gui() {
sprite.setTexture(*ResourceManager::loadTexture(ShooterConsts::MAIN_MENU_GUI)); sprite.setTexture(*ResourceManager::loadTexture(ShooterConsts::MAIN_MENU_GUI));
sprite.setTextureRect(sf::IntRect(243, 3, 9, 9)); sprite.setTextureRect(sf::IntRect(243, 3, 9, 9));
sprite.scale(3, 3); sprite.scale(3, 3);
sprite.setPosition(static_cast<float>(screen->width()) / 2.0f - 27.0f/2.0f, static_cast<float>(screen->height()) / 2.0f - 27.0f/2.0f); sprite.setPosition(static_cast<float>(screen->width()) / 2.0f - 27.0f / 2.0f,
static_cast<float>(screen->height()) / 2.0f - 27.0f / 2.0f);
sprite.setColor(sf::Color(0, 0, 0, 250)); sprite.setColor(sf::Color(0, 0, 0, 250));
screen->drawSprite(sprite); screen->drawSprite(sprite);
@ -180,7 +200,8 @@ void Shooter::drawStatsTable() {
}); });
for (auto &p : allPlayers) { for (auto &p : allPlayers) {
screen->drawText(std::to_string(i) + "\t" + p->playerNickName() + "\t" + std::to_string(p->kills()) + " / " + std::to_string(p->deaths()), screen->drawText(std::to_string(i) + "\t" + p->playerNickName() + "\t" + std::to_string(p->kills()) + " / " +
std::to_string(p->deaths()),
Vec2D{10, 15 + 35.0 * i}, 25, sf::Color(0, 0, 0, 150)); Vec2D{10, 15 + 35.0 * i}, 25, sf::Color(0, 0, 0, 150));
i++; i++;
} }
@ -198,7 +219,9 @@ void Shooter::drawPlayerStats() {
Vec2D{xPos + width * player->health() / ShooterConsts::HEALTH_MAX, yPos}, Vec2D{xPos + width * player->health() / ShooterConsts::HEALTH_MAX, yPos},
Vec2D{xPos + width * player->health() / ShooterConsts::HEALTH_MAX, yPos + height}, Vec2D{xPos + width * player->health() / ShooterConsts::HEALTH_MAX, yPos + height},
Vec2D{xPos, yPos + height}, Vec2D{xPos, yPos + height},
{ static_cast<sf::Uint8>((ShooterConsts::HEALTH_MAX - player->health())/ShooterConsts::HEALTH_MAX * 255), static_cast<sf::Uint8>(player->health() * 255 / ShooterConsts::HEALTH_MAX), 0, 100 }); {static_cast<sf::Uint8>((ShooterConsts::HEALTH_MAX - player->health()) /
ShooterConsts::HEALTH_MAX * 255),
static_cast<sf::Uint8>(player->health() * 255 / ShooterConsts::HEALTH_MAX), 0, 100});
screen->drawTetragon(Vec2D{xPos, yPos - 15}, screen->drawTetragon(Vec2D{xPos, yPos - 15},
Vec2D{xPos + width * player->ability() / ShooterConsts::ABILITY_MAX, yPos - 15}, Vec2D{xPos + width * player->ability() / ShooterConsts::ABILITY_MAX, yPos - 15},
@ -208,8 +231,10 @@ void Shooter::drawPlayerStats() {
auto balance = player->balance(); auto balance = player->balance();
screen->drawText(std::to_string((int)balance.first), Vec2D{150, static_cast<double>(screen->height() - 150)}, 100, sf::Color(0, 0, 0, 100)); screen->drawText(std::to_string((int) balance.first), Vec2D{150, static_cast<double>(screen->height() - 150)}, 100,
screen->drawText(std::to_string((int)balance.second), Vec2D{50, static_cast<double>(screen->height() - 100)}, 50, sf::Color(0, 0, 0, 70)); sf::Color(0, 0, 0, 100));
screen->drawText(std::to_string((int) balance.second), Vec2D{50, static_cast<double>(screen->height() - 100)}, 50,
sf::Color(0, 0, 0, 70));
} }
void Shooter::play() { void Shooter::play() {
@ -263,8 +288,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"), std::make_shared<AColor>(world->body(ObjectNameTag(traceName)), sf::Color{150, 150, 150, 0})); Timeline::animate(AnimationListTag(traceName + "_fadeOut"),
Timeline::animate(AnimationListTag(traceName + "_delete"), std::make_shared<AFunction>([this, traceName](){ removeFireTrace(ObjectNameTag(traceName)); }, 1, 2)); 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,
2));
} }
void Shooter::removeFireTrace(const ObjectNameTag &traceName) { void Shooter::removeFireTrace(const ObjectNameTag &traceName) {
@ -279,7 +307,9 @@ 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);
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::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));
} }
void Shooter::removeBonus(const ObjectNameTag &bonusName) { void Shooter::removeBonus(const ObjectNameTag &bonusName) {
@ -308,9 +338,9 @@ void Shooter::changeEnemyWeapon(const std::string& weaponName, sf::Uint16 enemyI
world->body(weaponTag)->setCollider(false); world->body(weaponTag)->setCollider(false);
world->body(weaponTag)->scale(Vec3D(3, 3, 3)); world->body(weaponTag)->scale(Vec3D(3, 3, 3));
world->body(weaponTag)->translateToPoint(head->position() - enemy->left() - enemy->up()); world->body(weaponTag)->translateToPoint(head->position() - enemy->left()*2 - enemy->up()*0.5);
world->body(weaponTag)->rotate(Vec3D(0, Consts::PI + head->angle().y(), 0)); world->body(weaponTag)->rotate(Vec3D(0, Consts::PI + enemy->angle().y(), 0));
world->body(weaponTag)->rotateLeft(-head->angleLeftUpLookAt().x()); world->body(weaponTag)->rotateLeft(-head->angleLeftUpLookAt().x());
enemy->attach(world->body(weaponTag)); enemy->attach(world->body(weaponTag));
} }

View File

@ -30,6 +30,7 @@ private:
int fireTraces = 0; int fireTraces = 0;
void start() override; void start() override;
void update() override; void update() override;
void gui() override; void gui() override;
@ -37,18 +38,29 @@ private:
void play(); void play();
void drawPlayerStats(); void drawPlayerStats();
void drawStatsTable(); void drawStatsTable();
void InitNetwork(); void InitNetwork();
void spawnPlayer(sf::Uint16 id); void spawnPlayer(sf::Uint16 id);
void removePlayer(sf::Uint16 id); void removePlayer(sf::Uint16 id);
void addFireTrace(const Vec3D &from, const Vec3D &to); void addFireTrace(const Vec3D &from, const Vec3D &to);
void removeFireTrace(const ObjectNameTag &traceName); void removeFireTrace(const ObjectNameTag &traceName);
void addBonus(const std::string &bonusName, const Vec3D &position); void addBonus(const std::string &bonusName, const Vec3D &position);
void removeBonus(const ObjectNameTag &bonusName); void removeBonus(const ObjectNameTag &bonusName);
void addWeapon(std::shared_ptr<Weapon> weapon); void addWeapon(std::shared_ptr<Weapon> weapon);
void removeWeapon(std::shared_ptr<Weapon> weapon); void removeWeapon(std::shared_ptr<Weapon> weapon);
void changeEnemyWeapon(const std::string &weaponName, sf::Uint16 enemyId); void changeEnemyWeapon(const std::string &weaponName, sf::Uint16 enemyId);
public: public:
Shooter() : mainMenu(screen, mouse) {}; Shooter() : mainMenu(screen, mouse) {};
}; };

View File

@ -7,12 +7,12 @@
#include <utility> #include <utility>
#include "engine/utils/Log.h" #include "engine/utils/Log.h"
#include "engine/animation/Timeline.h" #include "engine/animation/Timeline.h"
#include "engine/animation/ATranslateToPoint.h"
#include "ShooterMsgType.h" #include "ShooterMsgType.h"
void ShooterClient::updatePacket() { void ShooterClient::updatePacket() {
sf::Packet packet; sf::Packet packet;
packet << MsgType::ClientUpdate << _player->position().x() << _player->position().y() << _player->position().z() << _player->angle().y() << _player->headAngle() << _player->playerNickName(); packet << MsgType::ClientUpdate << _player->position().x() << _player->position().y() << _player->position().z()
<< _player->angle().y() << _player->headAngle() << _player->playerNickName();
_socket.send(packet, _socket.serverId()); _socket.send(packet, _socket.serverId());
} }
@ -21,8 +21,7 @@ void ShooterClient::processInit(sf::Packet& packet) {
double buf[4]; double buf[4];
int kills, deaths; int kills, deaths;
while (packet >> targetId >> buf[0] >> buf[1] >> buf[2] >> buf[3] >> kills >> deaths) while (packet >> targetId >> buf[0] >> buf[1] >> buf[2] >> buf[3] >> kills >> deaths) {
{
if (targetId != _socket.ownId()) { if (targetId != _socket.ownId()) {
if (_spawnPlayerCallBack != nullptr) { if (_spawnPlayerCallBack != nullptr) {
_spawnPlayerCallBack(targetId); _spawnPlayerCallBack(targetId);
@ -102,8 +101,7 @@ void ShooterClient::processCustomPacket(sf::Packet& packet) {
_player->addKill(); _player->addKill();
SoundController::playSound(SoundTag("kill"), ShooterConsts::KILL_SOUND); SoundController::playSound(SoundTag("kill"), ShooterConsts::KILL_SOUND);
_lastEvent += _player->playerNickName(); _lastEvent += _player->playerNickName();
} } else {
else {
_players[buffId[1]]->addKill(); _players[buffId[1]]->addKill();
_lastEvent += _players[buffId[1]]->playerNickName(); _lastEvent += _players[buffId[1]]->playerNickName();
} }
@ -112,13 +110,14 @@ void ShooterClient::processCustomPacket(sf::Packet& packet) {
if (buffId[0] == _socket.ownId()) { if (buffId[0] == _socket.ownId()) {
_player->addDeath(); _player->addDeath();
// respawn // respawn
_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->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->initWeapons(); _player->initWeapons();
_player->setFullAbility(); _player->setFullAbility();
SoundController::playSound(SoundTag("death"), ShooterConsts::DEATH_SOUND); SoundController::playSound(SoundTag("death"), ShooterConsts::DEATH_SOUND);
_lastEvent += _player->playerNickName(); _lastEvent += _player->playerNickName();
} } else {
else {
_players[buffId[0]]->addDeath(); _players[buffId[0]]->addDeath();
_lastEvent += _players[buffId[0]]->playerNickName(); _lastEvent += _players[buffId[0]]->playerNickName();
} }
@ -160,7 +159,8 @@ void ShooterClient::processCustomPacket(sf::Packet& packet) {
} }
break; break;
default: default:
Log::log("ShooterClient::processCustomPacket: unknown message type " + std::to_string(static_cast<int>(type))); Log::log("ShooterClient::processCustomPacket: unknown message type " +
std::to_string(static_cast<int>(type)));
return; return;
} }
} }
@ -183,7 +183,8 @@ void ShooterClient::damagePlayer(sf::Uint16 targetId, double damage) {
void ShooterClient::addTrace(const Vec3D &from, const Vec3D &to) { void ShooterClient::addTrace(const Vec3D &from, const Vec3D &to) {
sf::Packet packet; sf::Packet packet;
packet << MsgType::Custom << ShooterMsgType::FireTrace << from.x() << from.y() << from.z() << to.x() << to.y() << to.z(); packet << MsgType::Custom << ShooterMsgType::FireTrace << from.x() << from.y() << from.z() << to.x() << to.y()
<< to.z();
_socket.send(packet, _socket.serverId()); _socket.send(packet, _socket.serverId());
} }
@ -229,6 +230,7 @@ void ShooterClient::setRemoveBonusCallBack(std::function<void(const ObjectNameTa
_removeBonusCallBack = std::move(removeBonus); _removeBonusCallBack = std::move(removeBonus);
} }
void ShooterClient::setChangeEnemyWeaponCallBack(std::function<void(const std::string&, sf::Uint16)> changeEnemyWeapon) { void
ShooterClient::setChangeEnemyWeaponCallBack(std::function<void(const std::string &, sf::Uint16)> changeEnemyWeapon) {
_changeEnemyWeaponCallBack = std::move(changeEnemyWeapon); _changeEnemyWeaponCallBack = std::move(changeEnemyWeapon);
} }

View File

@ -27,16 +27,23 @@ public:
void updatePacket() override; void updatePacket() override;
void setSpawnPlayerCallBack(std::function<void(sf::Uint16)> spawn); void setSpawnPlayerCallBack(std::function<void(sf::Uint16)> spawn);
void setRemovePlayerCallBack(std::function<void(sf::Uint16)> remove); void setRemovePlayerCallBack(std::function<void(sf::Uint16)> remove);
void setAddFireTraceCallBack(std::function<void(const Vec3D &, const Vec3D &)> addTrace); void setAddFireTraceCallBack(std::function<void(const Vec3D &, const Vec3D &)> addTrace);
void setAddBonusCallBack(std::function<void(const std::string &, const Vec3D &)> addBonus); void setAddBonusCallBack(std::function<void(const std::string &, const Vec3D &)> addBonus);
void setRemoveBonusCallBack(std::function<void(const ObjectNameTag &)> removeBonus); void setRemoveBonusCallBack(std::function<void(const ObjectNameTag &)> removeBonus);
void setChangeEnemyWeaponCallBack(std::function<void(const std::string &, sf::Uint16)> changeEnemyWeapon); void setChangeEnemyWeaponCallBack(std::function<void(const std::string &, sf::Uint16)> changeEnemyWeapon);
void processInit(sf::Packet &packet) override; void processInit(sf::Packet &packet) override;
void processUpdate(sf::Packet &packet) override; void processUpdate(sf::Packet &packet) override;
void processNewClient(sf::Packet &packet) override; void processNewClient(sf::Packet &packet) override;
void processDisconnect(sf::Uint16 targetId) override; void processDisconnect(sf::Uint16 targetId) override;
void processCustomPacket(sf::Packet &packet) override; void processCustomPacket(sf::Packet &packet) override;
@ -52,6 +59,7 @@ public:
void changeWeapon(const std::string &weaponName); void changeWeapon(const std::string &weaponName);
void addPlayer(sf::Uint16 id, std::shared_ptr<Player> player); void addPlayer(sf::Uint16 id, std::shared_ptr<Player> player);
[[nodiscard]] std::map<sf::Uint16, std::shared_ptr<Player>> const &players() const { return _players; } [[nodiscard]] std::map<sf::Uint16, std::shared_ptr<Player>> const &players() const { return _players; }
[[nodiscard]] std::string lastEvent() const { return _lastEvent; } [[nodiscard]] std::string lastEvent() const { return _lastEvent; }

View File

@ -4,13 +4,11 @@
#include "ShooterMsgType.h" #include "ShooterMsgType.h"
sf::Packet& operator<<(sf::Packet& packet, ShooterMsgType type) sf::Packet &operator<<(sf::Packet &packet, ShooterMsgType type) {
{
return packet << (sf::Uint16) type; return packet << (sf::Uint16) type;
} }
sf::Packet& operator>>(sf::Packet& packet, ShooterMsgType& type) sf::Packet &operator>>(sf::Packet &packet, ShooterMsgType &type) {
{
sf::Uint16 temp; sf::Uint16 temp;
packet >> temp; packet >> temp;
type = (ShooterMsgType) temp; type = (ShooterMsgType) temp;

View File

@ -7,8 +7,7 @@
#include <SFML/Network.hpp> #include <SFML/Network.hpp>
enum class ShooterMsgType enum class ShooterMsgType {
{
Damage, Damage,
Kill, Kill,
FireTrace, FireTrace,
@ -19,6 +18,7 @@ enum class ShooterMsgType
}; };
sf::Packet &operator<<(sf::Packet &packet, ShooterMsgType type); sf::Packet &operator<<(sf::Packet &packet, ShooterMsgType type);
sf::Packet &operator>>(sf::Packet &packet, ShooterMsgType &type); sf::Packet &operator>>(sf::Packet &packet, ShooterMsgType &type);
#endif //SHOOTER_SHOOTERMSGTYPE_H #endif //SHOOTER_SHOOTERMSGTYPE_H

View File

@ -11,7 +11,8 @@ void ShooterServer::broadcast() {
updatePacket << MsgType::ServerUpdate; updatePacket << MsgType::ServerUpdate;
for (auto&[playerId, player] : _players) { for (auto&[playerId, player] : _players) {
updatePacket << playerId << player->position().x() << player->position().y() << player->position().z() << player->health() << player->angle().y() << player->headAngle() << player->playerNickName(); updatePacket << playerId << player->position().x() << player->position().y() << player->position().z()
<< player->health() << player->angle().y() << player->headAngle() << player->playerNickName();
} }
for (auto &player : _players) { for (auto &player : _players) {
@ -29,7 +30,8 @@ void ShooterServer::processConnect(sf::Uint16 targetId) {
sendPacket1 << MsgType::Init << targetId; sendPacket1 << MsgType::Init << targetId;
_players.insert({targetId, std::make_shared<Player>(ObjectNameTag("Player_" + std::to_string(targetId)))}); _players.insert({targetId, std::make_shared<Player>(ObjectNameTag("Player_" + std::to_string(targetId)))});
for (const auto&[playerId, player] : _players) { for (const auto&[playerId, player] : _players) {
sendPacket1 << playerId << player->position().x() << player->position().y() << player->position().z() << player->health() << player->kills() << player->deaths(); sendPacket1 << playerId << player->position().x() << player->position().y() << player->position().z()
<< player->health() << player->kills() << player->deaths();
if (playerId != targetId) if (playerId != targetId)
_socket.sendRely(extraPacket, playerId); _socket.sendRely(extraPacket, playerId);
} }
@ -98,7 +100,8 @@ void ShooterServer::processCustomPacket(sf::Packet& packet, sf::Uint16 senderId)
break; break;
case ShooterMsgType::FireTrace: case ShooterMsgType::FireTrace:
packet >> dbuff[0] >> dbuff[1] >> dbuff[2] >> dbuff[3] >> dbuff[4] >> dbuff[5]; packet >> dbuff[0] >> dbuff[1] >> dbuff[2] >> dbuff[3] >> dbuff[4] >> dbuff[5];
sendPacket << MsgType::Custom << ShooterMsgType::FireTrace << dbuff[0] << dbuff[1] << dbuff[2] << dbuff[3] << dbuff[4] << dbuff[5]; sendPacket << MsgType::Custom << ShooterMsgType::FireTrace << dbuff[0] << dbuff[1] << dbuff[2] << dbuff[3]
<< dbuff[4] << dbuff[5];
for (auto &player : _players) { for (auto &player : _players) {
if (player.first != senderId) { if (player.first != senderId) {
_socket.send(sendPacket, player.first); _socket.send(sendPacket, player.first);
@ -137,7 +140,8 @@ void ShooterServer::processCustomPacket(sf::Packet& packet, sf::Uint16 senderId)
break; break;
default: default:
Log::log("ShooterServer::processCustomPacket: unknown message type " + std::to_string(static_cast<int>(type))); Log::log("ShooterServer::processCustomPacket: unknown message type " +
std::to_string(static_cast<int>(type)));
return; return;
} }
} }
@ -148,33 +152,48 @@ void ShooterServer::processStop() {
} }
void ShooterServer::generateBonuses() { void ShooterServer::generateBonuses() {
_bonuses.insert({"Bonus_gun_1", std::make_shared<BonusInfo>(BonusInfo{Vec3D(-10, -2, -15), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); _bonuses.insert({"Bonus_gun_1", std::make_shared<BonusInfo>(
_bonuses.insert({"Bonus_gun_2", std::make_shared<BonusInfo>(BonusInfo{Vec3D(10, -2, 15), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); BonusInfo{Vec3D(-10, -2, -15), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_gun_2", std::make_shared<BonusInfo>(
BonusInfo{Vec3D(10, -2, 15), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_shotgun_1", std::make_shared<BonusInfo>(BonusInfo{Vec3D(-10, 13, -24), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); _bonuses.insert({"Bonus_shotgun_1", std::make_shared<BonusInfo>(
_bonuses.insert({"Bonus_shotgun_2", std::make_shared<BonusInfo>(BonusInfo{Vec3D(10, 13, 24), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); BonusInfo{Vec3D(-10, 13, -24), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_shotgun_2", std::make_shared<BonusInfo>(
BonusInfo{Vec3D(10, 13, 24), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_ak47_1", std::make_shared<BonusInfo>(BonusInfo{Vec3D(-25, 30, 50), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); _bonuses.insert({"Bonus_ak47_1", std::make_shared<BonusInfo>(
_bonuses.insert({"Bonus_ak47_2", std::make_shared<BonusInfo>(BonusInfo{Vec3D(25, 30, -50), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); BonusInfo{Vec3D(-25, 30, 50), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_ak47_2", std::make_shared<BonusInfo>(
BonusInfo{Vec3D(25, 30, -50), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_gold_ak47_1", std::make_shared<BonusInfo>(BonusInfo{Vec3D(-35, 80, 25), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); _bonuses.insert({"Bonus_gold_ak47_1", std::make_shared<BonusInfo>(
_bonuses.insert({"Bonus_gold_ak47_2", std::make_shared<BonusInfo>(BonusInfo{Vec3D(35, 80, -25), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); BonusInfo{Vec3D(-35, 80, 25), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_gold_ak47_2", std::make_shared<BonusInfo>(
BonusInfo{Vec3D(35, 80, -25), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_rifle_1", std::make_shared<BonusInfo>(BonusInfo{Vec3D(40, -2, 45), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); _bonuses.insert({"Bonus_rifle_1", std::make_shared<BonusInfo>(
_bonuses.insert({"Bonus_rifle_2", std::make_shared<BonusInfo>(BonusInfo{Vec3D(-40, -2, -45), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); BonusInfo{Vec3D(40, -2, 45), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_rifle_2", std::make_shared<BonusInfo>(
BonusInfo{Vec3D(-40, -2, -45), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_hill_1", std::make_shared<BonusInfo>(BonusInfo{Vec3D(-40, -2, 45), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); _bonuses.insert({"Bonus_hill_1", std::make_shared<BonusInfo>(
_bonuses.insert({"Bonus_hill_2", std::make_shared<BonusInfo>(BonusInfo{Vec3D(40, -2, -45), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); BonusInfo{Vec3D(-40, -2, 45), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_hill_2", std::make_shared<BonusInfo>(
BonusInfo{Vec3D(40, -2, -45), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_ability_1", std::make_shared<BonusInfo>(BonusInfo{Vec3D(25, 18, -33), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); _bonuses.insert({"Bonus_ability_1", std::make_shared<BonusInfo>(
_bonuses.insert({"Bonus_ability_2", std::make_shared<BonusInfo>(BonusInfo{Vec3D(-25, 18, 33), -2*ShooterConsts::BONUS_RECHARGE_TIME, true})}); BonusInfo{Vec3D(25, 18, -33), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
_bonuses.insert({"Bonus_ability_2", std::make_shared<BonusInfo>(
BonusInfo{Vec3D(-25, 18, 33), -2 * ShooterConsts::BONUS_RECHARGE_TIME, true})});
} }
void ShooterServer::updateInfo() { void ShooterServer::updateInfo() {
for (auto&[bonusName, bonusInfo] : _bonuses) { for (auto&[bonusName, bonusInfo] : _bonuses) {
if (!bonusInfo->onTheMap && std::abs(Time::time() - bonusInfo->lastTake) > ShooterConsts::BONUS_RECHARGE_TIME) { if (!bonusInfo->onTheMap && std::abs(Time::time() - bonusInfo->lastTake) > ShooterConsts::BONUS_RECHARGE_TIME) {
sf::Packet sendPacket; sf::Packet sendPacket;
sendPacket << MsgType::Custom << ShooterMsgType::AddBonus << bonusName << bonusInfo->position.x() << bonusInfo->position.y() << bonusInfo->position.z(); sendPacket << MsgType::Custom << ShooterMsgType::AddBonus << bonusName << bonusInfo->position.x()
<< bonusInfo->position.y() << bonusInfo->position.z();
for (const auto &player : _players) { for (const auto &player : _players) {
_socket.sendRely(sendPacket, player.first); _socket.sendRely(sendPacket, player.first);
} }

View File

@ -24,7 +24,9 @@ public:
void broadcast() override; void broadcast() override;
void processConnect(sf::Uint16 senderId) override; void processConnect(sf::Uint16 senderId) override;
void processClientUpdate(sf::Uint16 senderId, sf::Packet &packet) override; void processClientUpdate(sf::Uint16 senderId, sf::Packet &packet) override;
void processDisconnect(sf::Uint16 senderId) override; void processDisconnect(sf::Uint16 senderId) override;
void processCustomPacket(sf::Packet &packet, sf::Uint16 senderId) override; void processCustomPacket(sf::Packet &packet, sf::Uint16 senderId) override;

View File

@ -2,10 +2,11 @@
// Created by Иван Ильин on 14.01.2021. // Created by Иван Ильин on 14.01.2021.
// //
#include <cmath>
#include "Camera.h" #include "Camera.h"
#include "utils/Log.h" #include "utils/Log.h"
#include "Consts.h" #include "Consts.h"
#include <cmath>
std::vector<std::shared_ptr<Triangle>> Camera::project(std::shared_ptr<Mesh> mesh) { std::vector<std::shared_ptr<Triangle>> Camera::project(std::shared_ptr<Mesh> mesh) {

View File

@ -6,9 +6,11 @@
#define ENGINE_CAMERA_H #define ENGINE_CAMERA_H
#include <vector> #include <vector>
#include <SFML/OpenGL.hpp>
#include "Plane.h" #include "Plane.h"
#include "Mesh.h" #include "Mesh.h"
#include <SFML/OpenGL.hpp>
class Camera final : public Object { class Camera final : public Object {
private: private:
@ -18,9 +20,9 @@ private:
double _aspect = 0; double _aspect = 0;
Matrix4x4 _SP; Matrix4x4 _SP;
public: public:
Camera() : Object(ObjectNameTag("Camera")) {}; Camera() : Object(ObjectNameTag("Camera")) {};
Camera(const Camera &camera) = delete; Camera(const Camera &camera) = delete;
void init(int width, int height, double fov = 110.0, double ZNear = 0.1, double ZFar = 5000.0); void init(int width, int height, double fov = 110.0, double ZNear = 0.1, double ZFar = 5000.0);
@ -30,6 +32,7 @@ public:
void clear(); void clear();
[[nodiscard]] int buffSize() const { return _triangles.size(); } [[nodiscard]] int buffSize() const { return _triangles.size(); }
std::vector<std::shared_ptr<Triangle>> sorted(); std::vector<std::shared_ptr<Triangle>> sorted();
}; };

View File

@ -4,7 +4,9 @@
#ifndef SHOOTER_CONSTS_H #ifndef SHOOTER_CONSTS_H
#define SHOOTER_CONSTS_H #define SHOOTER_CONSTS_H
#include <SFML/Graphics.hpp> #include <SFML/Graphics.hpp>
#include "Vec2D.h" #include "Vec2D.h"
namespace Consts { namespace Consts {
@ -37,8 +39,6 @@ namespace Consts {
const int NETWORK_WORLD_UPDATE_RATE = 30; const int NETWORK_WORLD_UPDATE_RATE = 30;
const double NETWORK_RELIABLE_RETRY_TIME = 1.0 / 20; const double NETWORK_RELIABLE_RETRY_TIME = 1.0 / 20;
const uint16_t NETWORK_MAX_CLIENTS = 64; const uint16_t NETWORK_MAX_CLIENTS = 64;
} }
#endif //SHOOTER_CONSTS_H #endif //SHOOTER_CONSTS_H

View File

@ -2,9 +2,10 @@
// Created by Иван Ильин on 14.01.2021. // Created by Иван Ильин on 14.01.2021.
// //
#include <iostream>
#include "Engine.h" #include "Engine.h"
#include "utils/Time.h" #include "utils/Time.h"
#include <iostream>
#include "ResourceManager.h" #include "ResourceManager.h"
#include "animation/Timeline.h" #include "animation/Timeline.h"
#include "SoundController.h" #include "SoundController.h"
@ -16,11 +17,13 @@ Engine::Engine() {
SoundController::init(); SoundController::init();
} }
void Engine::create(int screenWidth, int screenHeight, const std::string &name, bool verticalSync, sf::Color background, sf::Uint32 style) { void Engine::create(int screenWidth, int screenHeight, const std::string &name, bool verticalSync, sf::Color background,
sf::Uint32 style) {
_name = name; _name = name;
screen->open(screenWidth, screenHeight, name, verticalSync, background, style); screen->open(screenWidth, screenHeight, name, verticalSync, background, style);
Log::log("Engine::create(): started engine (" + std::to_string(screenWidth) + "x" + std::to_string(screenHeight) + ") with title '" + name + "'."); Log::log("Engine::create(): started engine (" + std::to_string(screenWidth) + "x" + std::to_string(screenHeight) +
") with title '" + name + "'.");
Time::update(); Time::update();
start(); start();
@ -70,7 +73,8 @@ void Engine::create(int screenWidth, int screenHeight, const std::string &name,
} }
if (Consts::SHOW_FPS_COUNTER) { if (Consts::SHOW_FPS_COUNTER) {
screen->drawText(std::to_string(Time::fps()) + " fps", Vec2D(screen->width() - 100, 10), 25, sf::Color(100,100,100)); screen->drawText(std::to_string(Time::fps()) + " fps", Vec2D(screen->width() - 100, 10), 25,
sf::Color(100, 100, 100));
} }
printDebugText(); printDebugText();
@ -90,8 +94,8 @@ void Engine::exit() {
Timeline::free(); Timeline::free();
Time::free(); Time::free();
Log::log("Engine::exit(): exit engine (" + std::to_string(screen->width()) + "x" + std::to_string(screen->height()) + ") with title '" + Log::log("Engine::exit(): exit engine (" + std::to_string(screen->width()) + "x" +
screen->title() + "'."); std::to_string(screen->height()) + ") with title '" + screen->title() + "'.");
} }
void Engine::printDebugText() const { void Engine::printDebugText() const {

View File

@ -8,7 +8,6 @@
#include "Screen.h" #include "Screen.h"
#include "Keyboard.h" #include "Keyboard.h"
#include "Mouse.h" #include "Mouse.h"
#include "World.h" #include "World.h"
#include "Camera.h" #include "Camera.h"
#include "utils/Log.h" #include "utils/Log.h"
@ -23,6 +22,7 @@ private:
bool _useOpenGL = Consts::USE_OPEN_GL; bool _useOpenGL = Consts::USE_OPEN_GL;
void printDebugText() const; void printDebugText() const;
protected: protected:
const std::shared_ptr<Screen> screen = std::make_shared<Screen>(); const std::shared_ptr<Screen> screen = std::make_shared<Screen>();
const std::shared_ptr<Keyboard> keyboard = std::make_shared<Keyboard>(); const std::shared_ptr<Keyboard> keyboard = std::make_shared<Keyboard>();
@ -32,19 +32,26 @@ protected:
const std::shared_ptr<Camera> camera = std::make_shared<Camera>(); const std::shared_ptr<Camera> camera = std::make_shared<Camera>();
virtual void start() {}; virtual void start() {};
virtual void update() {}; virtual void update() {};
void setDebugText(bool value) { _debugText = value; } void setDebugText(bool value) { _debugText = value; }
void setUpdateWorld(bool value) { _updateWorld = value; } void setUpdateWorld(bool value) { _updateWorld = value; }
void setGlEnable(bool value) { _useOpenGL = value; } void setGlEnable(bool value) { _useOpenGL = value; }
virtual void gui() {} virtual void gui() {}
public: public:
Engine(); Engine();
virtual ~Engine() = default; virtual ~Engine() = default;
void create(int screenWidth = Consts::STANDARD_SCREEN_WIDTH, int screenHeight = Consts::STANDARD_SCREEN_HEIGHT, const std::string& name = Consts::PROJECT_NAME, bool verticalSync = true, sf::Color background = Consts::BACKGROUND_COLOR, sf::Uint32 style = sf::Style::Default); void create(int screenWidth = Consts::STANDARD_SCREEN_WIDTH, int screenHeight = Consts::STANDARD_SCREEN_HEIGHT,
const std::string &name = Consts::PROJECT_NAME, bool verticalSync = true,
sf::Color background = Consts::BACKGROUND_COLOR, sf::Uint32 style = sf::Style::Default);
void exit(); void exit();
}; };

View File

@ -13,8 +13,11 @@ private:
public: public:
Keyboard() = default; Keyboard() = default;
static bool isKeyPressed(sf::Keyboard::Key key); // returns true if this key is _pressed // returns true if this key is _pressed
bool isKeyTapped(sf::Keyboard::Key key); // returns true if this key is tapped and 1/5 sec passed (_button bouncing problem solved) static bool isKeyPressed(sf::Keyboard::Key key);
// returns true if this key is tapped and 1/5 sec passed (_button bouncing problem solved)
bool isKeyTapped(sf::Keyboard::Key key);
}; };

View File

@ -2,10 +2,9 @@
// Created by Иван Ильин on 12.01.2021. // Created by Иван Ильин on 12.01.2021.
// //
#include "Matrix4x4.h"
#include <cassert>
#include <cmath> #include <cmath>
#include "Matrix4x4.h"
#include "Consts.h" #include "Consts.h"
Matrix4x4 Matrix4x4::operator*(const Matrix4x4 &matrix4X4) const { Matrix4x4 Matrix4x4::operator*(const Matrix4x4 &matrix4X4) const {

View File

@ -6,6 +6,7 @@
#define ENGINE_MATRIX4X4_H #define ENGINE_MATRIX4X4_H
#include <array> #include <array>
#include "Vec4D.h" #include "Vec4D.h"
#include "Vec3D.h" #include "Vec3D.h"
@ -15,33 +16,49 @@ private:
public: public:
Matrix4x4() = default; Matrix4x4() = default;
Matrix4x4 &operator=(const Matrix4x4 &matrix4X4) = default; Matrix4x4 &operator=(const Matrix4x4 &matrix4X4) = default;
[[nodiscard]] Matrix4x4 operator*(const Matrix4x4 &matrix4X4) const; [[nodiscard]] Matrix4x4 operator*(const Matrix4x4 &matrix4X4) const;
[[nodiscard]] Vec4D operator*(const Vec4D &point4D) const; [[nodiscard]] Vec4D operator*(const Vec4D &point4D) const;
[[nodiscard]] Vec3D operator*(const Vec3D &vec) const; [[nodiscard]] Vec3D operator*(const Vec3D &vec) const;
[[nodiscard]] Vec3D x() const; [[nodiscard]] Vec3D x() const;
[[nodiscard]] Vec3D y() const; [[nodiscard]] Vec3D y() const;
[[nodiscard]] Vec3D z() const; [[nodiscard]] Vec3D z() const;
[[nodiscard]] Vec3D w() const; [[nodiscard]] Vec3D w() const;
// Any useful matrix (static methods) // Any useful matrix (static methods)
Matrix4x4 static Identity(); Matrix4x4 static Identity();
Matrix4x4 static Zero(); Matrix4x4 static Zero();
Matrix4x4 static Constant(double value); Matrix4x4 static Constant(double value);
Matrix4x4 static Scale(const Vec3D &factor); Matrix4x4 static Scale(const Vec3D &factor);
Matrix4x4 static Translation(const Vec3D &v); Matrix4x4 static Translation(const Vec3D &v);
Matrix4x4 static Rotation(const Vec3D &r); Matrix4x4 static Rotation(const Vec3D &r);
Matrix4x4 static RotationX(double rx); Matrix4x4 static RotationX(double rx);
Matrix4x4 static RotationY(double ry); Matrix4x4 static RotationY(double ry);
Matrix4x4 static RotationZ(double rz); Matrix4x4 static RotationZ(double rz);
Matrix4x4 static Rotation(const Vec3D &v, double rv); Matrix4x4 static Rotation(const Vec3D &v, double rv);
Matrix4x4 static View(const Vec3D &left, const Vec3D &up, const Vec3D &lookAt, const Vec3D &eye); Matrix4x4 static View(const Vec3D &left, const Vec3D &up, const Vec3D &lookAt, const Vec3D &eye);
Matrix4x4 static Projection(double fov = 90.0, double aspect = 1.0, double ZNear = 1.0, double ZFar = 10.0); Matrix4x4 static Projection(double fov = 90.0, double aspect = 1.0, double ZNear = 1.0, double ZFar = 10.0);
Matrix4x4 static ScreenSpace(int width, int height); Matrix4x4 static ScreenSpace(int width, int height);
}; };

View File

@ -3,6 +3,7 @@
// //
#include <utility> #include <utility>
#include "Mesh.h" #include "Mesh.h"
#include "ResourceManager.h" #include "ResourceManager.h"
@ -51,7 +52,8 @@ void Mesh::setColor(const sf::Color& c) {
setTriangles(newTriangles); setTriangles(newTriangles);
} }
Mesh Mesh::LineTo(ObjectNameTag nameTag, const Vec3D& from, const Vec3D& to, double line_width, const sf::Color& color) { Mesh
Mesh::LineTo(ObjectNameTag nameTag, const Vec3D &from, const Vec3D &to, double line_width, const sf::Color &color) {
Mesh line(std::move(nameTag)); Mesh line(std::move(nameTag));

View File

@ -7,8 +7,10 @@
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "Triangle.h"
#include <SFML/Graphics.hpp> #include <SFML/Graphics.hpp>
#include "Triangle.h"
#include "Object.h" #include "Object.h"
class Mesh : public Object { class Mesh : public Object {
@ -18,32 +20,42 @@ private:
bool _visible = true; bool _visible = true;
Mesh &operator*=(const Matrix4x4 &matrix4X4); Mesh &operator*=(const Matrix4x4 &matrix4X4);
public: public:
explicit Mesh(ObjectNameTag nameTag) : Object(std::move(nameTag)) {}; explicit Mesh(ObjectNameTag nameTag) : Object(std::move(nameTag)) {};
Mesh &operator=(const Mesh &mesh) = delete; Mesh &operator=(const Mesh &mesh) = delete;
Mesh(const Mesh &mesh) = default; Mesh(const Mesh &mesh) = default;
explicit Mesh(ObjectNameTag nameTag, const std::vector<Triangle> &tries); explicit Mesh(ObjectNameTag nameTag, const std::vector<Triangle> &tries);
explicit Mesh(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1}); explicit Mesh(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1});
void loadObj(const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1}); void loadObj(const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1});
[[nodiscard]] std::vector<Triangle> const &triangles() const { return _tris; } [[nodiscard]] std::vector<Triangle> const &triangles() const { return _tris; }
[[nodiscard]] std::vector<Triangle> &triangles() { return _tris; } [[nodiscard]] std::vector<Triangle> &triangles() { return _tris; }
void setTriangles(const std::vector<Triangle> &t); void setTriangles(const std::vector<Triangle> &t);
[[nodiscard]] int size() const { return _tris.size()*3; } [[nodiscard]] size_t size() const { return _tris.size() * 3; }
[[nodiscard]] sf::Color color() const { return _color; } [[nodiscard]] sf::Color color() const { return _color; }
void setColor(const sf::Color &c); void setColor(const sf::Color &c);
void setVisible(bool visibility) { _visible = visibility; } void setVisible(bool visibility) { _visible = visibility; }
[[nodiscard]] bool isVisible() const { return _visible; } [[nodiscard]] bool isVisible() const { return _visible; }
~Mesh() override; ~Mesh() override;
Mesh static Obj(ObjectNameTag nameTag, const std::string &filename); 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});
Mesh static LineTo(ObjectNameTag nameTag, const Vec3D &from, const Vec3D &to, double line_width = 0.1,
const sf::Color &color = {150, 150, 150, 100});
}; };
#endif //INC_3DZAVR_MESH_H #endif //INC_3DZAVR_MESH_H

View File

@ -12,16 +12,17 @@ Vec2D Mouse::getMousePosition() const {
} }
Vec2D Mouse::getMouseDisplacement() const { Vec2D Mouse::getMouseDisplacement() const {
// TODO: getMouseDisplacement() should return displacement from the previous position but not from the center
sf::Vector2<int> mousePos = sf::Mouse::getPosition(*_screen->renderWindow()); sf::Vector2<int> mousePos = sf::Mouse::getPosition(*_screen->renderWindow());
sf::Vector2<int> center = sf::Vector2<int>(_screen->width() / 2, _screen->height() / 2); sf::Vector2<int> center = sf::Vector2<int>(_screen->width() / 2, _screen->height() / 2);
sf::Vector2<int> displacement = mousePos - center; sf::Vector2<int> displacement = mousePos - center;
//setMouseInCenter();
return Vec2D(displacement.x, displacement.y); return Vec2D(displacement.x, displacement.y);
} }
void Mouse::setMouseInCenter() const { void Mouse::setMouseInCenter() const {
sf::Mouse::setPosition({ static_cast<int>(_screen->width() / 2), static_cast<int>(_screen->height() / 2) }, *_screen->renderWindow()); sf::Mouse::setPosition({static_cast<int>(_screen->width() / 2), static_cast<int>(_screen->height() / 2)},
*_screen->renderWindow());
} }
bool Mouse::isButtonPressed(sf::Mouse::Button button) { bool Mouse::isButtonPressed(sf::Mouse::Button button) {

View File

@ -7,6 +7,7 @@
#include <memory> #include <memory>
#include <utility> #include <utility>
#include "Screen.h" #include "Screen.h"
#include "Vec2D.h" #include "Vec2D.h"
@ -18,11 +19,16 @@ private:
public: public:
explicit Mouse(std::shared_ptr<Screen> screen) : _screen(std::move(screen)) {}; explicit Mouse(std::shared_ptr<Screen> screen) : _screen(std::move(screen)) {};
static bool isButtonPressed(sf::Mouse::Button button); // returns true if this _button is _pressed // returns true if this _button is _pressed
bool isButtonTapped(sf::Mouse::Button button); // returns true if this _button is tapped and 1/5 sec passed (_button bouncing problem solved) static bool isButtonPressed(sf::Mouse::Button button);
// returns true if this _button is tapped and 1/5 sec passed (_button bouncing problem solved)
bool isButtonTapped(sf::Mouse::Button button);
[[nodiscard]] Vec2D getMousePosition() const; [[nodiscard]] Vec2D getMousePosition() const;
[[nodiscard]] Vec2D getMouseDisplacement() const; [[nodiscard]] Vec2D getMouseDisplacement() const;
void setMouseInCenter() const; void setMouseInCenter() const;
}; };

View File

@ -14,6 +14,7 @@ void Object::transform(const Matrix4x4& t) {
} }
} }
} }
void Object::transformRelativePoint(const Vec3D &point, const Matrix4x4 &transform) { void Object::transformRelativePoint(const Vec3D &point, const Matrix4x4 &transform) {
// translate object in new coordinate system (connected with point) // translate object in new coordinate system (connected with point)
@ -49,6 +50,7 @@ void Object::scale(const Vec3D &s) {
void Object::rotate(const Vec3D &r) { void Object::rotate(const Vec3D &r) {
_angle = _angle + r; _angle = _angle + r;
// TODO: when you rotate body _angle is changed only for this body but all attached objects have incorrect _angle
Matrix4x4 rotationMatrix = Matrix4x4::RotationZ(r.z()) * Matrix4x4::RotationY(r.y()) * Matrix4x4::RotationX(r.z()); Matrix4x4 rotationMatrix = Matrix4x4::RotationZ(r.z()) * Matrix4x4::RotationY(r.y()) * Matrix4x4::RotationX(r.z());
transform(rotationMatrix); transform(rotationMatrix);
} }

View File

@ -6,10 +6,11 @@
#define ENGINE_OBJECT_H #define ENGINE_OBJECT_H
#include <map> #include <map>
#include "Vec3D.h"
#include <string> #include <string>
#include <utility> #include <utility>
#include <memory> #include <memory>
#include "Vec3D.h"
#include "Matrix4x4.h" #include "Matrix4x4.h"
#include <SFML/OpenGL.hpp> #include <SFML/OpenGL.hpp>
@ -18,16 +19,20 @@ private:
const std::string _name; const std::string _name;
public: public:
explicit ObjectNameTag(std::string name = "") : _name(std::move(name)) {} explicit ObjectNameTag(std::string name = "") : _name(std::move(name)) {}
[[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; }
}; };
class Object { class Object {
private: private:
bool checkIfAttached(Object *obj); bool checkIfAttached(Object *obj);
const ObjectNameTag _nameTag; const ObjectNameTag _nameTag;
Matrix4x4 _transformMatrix = Matrix4x4::Identity(); Matrix4x4 _transformMatrix = Matrix4x4::Identity();
@ -39,33 +44,52 @@ private:
Vec3D _angleLeftUpLookAt{0, 0, 0}; Vec3D _angleLeftUpLookAt{0, 0, 0};
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) : _nameTag(object.name()), _transformMatrix(object.model()) {};
// TODO: implement rotations using quaternions (?) // TODO: implement rotations using quaternions (?)
void transform(const Matrix4x4 &t); void transform(const Matrix4x4 &t);
void transformRelativePoint(const Vec3D &point, const Matrix4x4 &transform); void transformRelativePoint(const Vec3D &point, const Matrix4x4 &transform);
void translate(const Vec3D &dv); void translate(const Vec3D &dv);
void translateToPoint(const Vec3D &point); void translateToPoint(const Vec3D &point);
void scale(const Vec3D &s); void scale(const Vec3D &s);
void rotate(const Vec3D &r); void rotate(const Vec3D &r);
void rotate(const Vec3D &v, double rv); void rotate(const Vec3D &v, double rv);
void rotateToAngle(const Vec3D &v); void rotateToAngle(const Vec3D &v);
void rotateRelativePoint(const Vec3D &s, const Vec3D &r); void rotateRelativePoint(const Vec3D &s, const Vec3D &r);
void rotateRelativePoint(const Vec3D &s, const Vec3D &v, double r); void rotateRelativePoint(const Vec3D &s, const Vec3D &v, double r);
void rotateLeft(double rl); void rotateLeft(double rl);
void rotateUp(double ru); void rotateUp(double ru);
void rotateLookAt(double rlAt); void rotateLookAt(double rlAt);
[[nodiscard]] Vec3D left() const { return _transformMatrix.x(); } [[nodiscard]] Vec3D left() const { return _transformMatrix.x(); }
[[nodiscard]] Vec3D up() const { return _transformMatrix.y(); } [[nodiscard]] Vec3D up() const { return _transformMatrix.y(); }
[[nodiscard]] Vec3D lookAt() const { return _transformMatrix.z(); } [[nodiscard]] Vec3D lookAt() const { return _transformMatrix.z(); }
[[nodiscard]] Vec3D position() const { return _position; } [[nodiscard]] Vec3D position() const { return _position; }
[[nodiscard]] Vec3D angle() const { return _angle; } [[nodiscard]] Vec3D angle() const { return _angle; }
[[nodiscard]] Vec3D angleLeftUpLookAt() const { return _angleLeftUpLookAt; } [[nodiscard]] Vec3D angleLeftUpLookAt() const { return _angleLeftUpLookAt; }
void attach(std::shared_ptr<Object> object); void attach(std::shared_ptr<Object> object);
void unattach(const ObjectNameTag &tag); void unattach(const ObjectNameTag &tag);
std::shared_ptr<Object> attached(const ObjectNameTag &tag); std::shared_ptr<Object> attached(const ObjectNameTag &tag);
[[nodiscard]] ObjectNameTag name() const { return _nameTag; } [[nodiscard]] ObjectNameTag name() const { return _nameTag; }
@ -74,6 +98,7 @@ public:
// OpenGL function // OpenGL function
[[nodiscard]] GLfloat *glModel() const; [[nodiscard]] GLfloat *glModel() const;
[[nodiscard]] GLfloat *glView() const; [[nodiscard]] GLfloat *glView() const;
virtual ~Object(); virtual ~Object();

View File

@ -14,18 +14,24 @@ private:
const Vec3D _point; const Vec3D _point;
public: public:
Plane() = delete; Plane() = delete;
Plane(const Plane &plane) = default; Plane(const Plane &plane) = default;
// You can define plane by defining the points in 3D space // You can define plane by defining the points in 3D space
explicit Plane(const Triangle &tri); explicit Plane(const Triangle &tri);
// Or by defining normal vector and one val laying on the plane // Or by defining normal vector and one val laying on the plane
Plane(const Vec3D &N, const Vec3D &P); Plane(const Vec3D &N, const Vec3D &P);
[[nodiscard]] double distance(const Vec3D &point4D) const; [[nodiscard]] double distance(const Vec3D &point4D) const;
// Vec4D in space where line ('start' to 'end') intersects plain with normal vector '_n' and val '_p' lays on the plane // Vec4D in space where line ('start' to 'end') intersects plain with normal vector '_n' and val '_p' lays on the plane
[[nodiscard]] std::pair<Vec3D, double> intersection(const Vec3D &start, const Vec3D &end) const; [[nodiscard]] std::pair<Vec3D, double> intersection(const Vec3D &start, const Vec3D &end) const;
[[nodiscard]] std::vector<Triangle> clip(const Triangle &tri) const; [[nodiscard]] std::vector<Triangle> clip(const Triangle &tri) const;
[[nodiscard]] Vec3D N() const { return _normal; } [[nodiscard]] Vec3D N() const { return _normal; }
[[nodiscard]] Vec3D P() const { return _point; } [[nodiscard]] Vec3D P() const { return _point; }
}; };

View File

@ -2,13 +2,14 @@
// Created by Neirokan on 09.05.2020 // Created by Neirokan on 09.05.2020
// //
#include "ResourceManager.h"
#include "utils/Log.h"
#include <map> #include <map>
#include <memory> #include <memory>
#include <sstream> #include <sstream>
#include <fstream> #include <fstream>
#include "ResourceManager.h"
#include "utils/Log.h"
ResourceManager *ResourceManager::_instance = nullptr; ResourceManager *ResourceManager::_instance = nullptr;
bool ResourceManager::_validInstance = false; bool ResourceManager::_validInstance = false;
@ -38,7 +39,8 @@ void ResourceManager::unloadSoundBuffers() {
} }
_instance->_soundBuffers.clear(); _instance->_soundBuffers.clear();
Log::log("ResourceManager::unloadSoundBuffers(): all " + std::to_string(soundBuffersCounter) + " soundBuffers was unloaded"); Log::log("ResourceManager::unloadSoundBuffers(): all " + std::to_string(soundBuffersCounter) +
" soundBuffers was unloaded");
} }
void ResourceManager::unloadFonts() { void ResourceManager::unloadFonts() {
@ -193,11 +195,12 @@ std::vector<std::shared_ptr<Mesh>> ResourceManager::loadObjects(const std::strin
char junk; char junk;
if (line[0] == 'o') { if (line[0] == 'o') {
if (!tris.empty()) if (!tris.empty())
objects.push_back(std::make_shared<Mesh>(ObjectNameTag(filename + "_temp_obj_" + std::to_string(objects.size())), tris)); objects.push_back(
std::make_shared<Mesh>(ObjectNameTag(filename + "_temp_obj_" + std::to_string(objects.size())),
tris));
tris.clear(); tris.clear();
} }
if (line[0] == 'v') if (line[0] == 'v') {
{
double x, y, z; double x, y, z;
s >> junk >> x >> y >> z; s >> junk >> x >> y >> z;
verts.emplace_back(x, y, z, 1.0); verts.emplace_back(x, y, z, 1.0);
@ -208,14 +211,12 @@ std::vector<std::shared_ptr<Mesh>> ResourceManager::loadObjects(const std::strin
std::string colorName = matInfo.substr(matInfo.size() - 3, 3); std::string colorName = matInfo.substr(matInfo.size() - 3, 3);
currentColor = maters[matInfo.substr(matInfo.size() - 3, 3)]; currentColor = maters[matInfo.substr(matInfo.size() - 3, 3)];
} }
if (line[0] == 'f') if (line[0] == 'f') {
{
int f[3]; int f[3];
s >> junk >> f[0] >> f[1] >> f[2]; s >> junk >> f[0] >> f[1] >> f[2];
tris.emplace_back(verts[f[0] - 1], verts[f[1] - 1], verts[f[2] - 1], currentColor); tris.emplace_back(verts[f[0] - 1], verts[f[1] - 1], verts[f[2] - 1], currentColor);
} }
if(line[0] == 'm') if (line[0] == 'm') {
{
int color[4]; int color[4];
std::string matName; std::string matName;

View File

@ -5,9 +5,11 @@
#ifndef ENGINE_RESOURCEMANAGER_H #ifndef ENGINE_RESOURCEMANAGER_H
#define ENGINE_RESOURCEMANAGER_H #define ENGINE_RESOURCEMANAGER_H
#include <memory>
#include <SFML/Graphics.hpp> #include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp> #include <SFML/Audio.hpp>
#include <memory>
#include "Mesh.h" #include "Mesh.h"
class ResourceManager final { class ResourceManager final {
@ -21,27 +23,36 @@ private:
static bool _validInstance; static bool _validInstance;
ResourceManager() = default; ResourceManager() = default;
// Unloads all currently loaded textures. // Unloads all currently loaded textures.
static void unloadObjects(); static void unloadObjects();
static void unloadTextures(); static void unloadTextures();
static void unloadSoundBuffers(); static void unloadSoundBuffers();
static void unloadFonts(); static void unloadFonts();
public: public:
ResourceManager(const ResourceManager &) = delete; ResourceManager(const ResourceManager &) = delete;
ResourceManager &operator=(ResourceManager &) = delete; ResourceManager &operator=(ResourceManager &) = delete;
static void unloadAllResources(); static void unloadAllResources();
static void init(); static void init();
static void free(); static void free();
// Try to load texture from file. // Try to load texture from file.
// If success returns pointer to texture. // If success returns pointer to texture.
// Otherwise returns nullptr. // Otherwise returns nullptr.
static std::vector<std::shared_ptr<Mesh>> loadObjects(const std::string &filename); static std::vector<std::shared_ptr<Mesh>> loadObjects(const std::string &filename);
static std::shared_ptr<sf::Texture> loadTexture(const std::string &filename); static std::shared_ptr<sf::Texture> loadTexture(const std::string &filename);
static std::shared_ptr<sf::Font> loadFont(const std::string &filename); static std::shared_ptr<sf::Font> loadFont(const std::string &filename);
static std::shared_ptr<sf::SoundBuffer> loadSoundBuffer(const std::string &filename); static std::shared_ptr<sf::SoundBuffer> loadSoundBuffer(const std::string &filename);
}; };

View File

@ -2,16 +2,18 @@
// Created by Иван Ильин on 14.01.2021. // Created by Иван Ильин on 14.01.2021.
// //
#include "Screen.h"
#include "utils/Time.h"
#include <utility> #include <utility>
#include "utils/Log.h"
#include "ResourceManager.h"
#include <SFML/OpenGL.hpp>
#include <cmath> #include <cmath>
#include <SFML/OpenGL.hpp>
void Screen::open(int screenWidth, int screenHeight, const std::string &name, bool verticalSync, sf::Color background, sf::Uint32 style) { #include "Screen.h"
#include "utils/Time.h"
#include "utils/Log.h"
#include "ResourceManager.h"
void Screen::open(int screenWidth, int screenHeight, const std::string &name, bool verticalSync, sf::Color background,
sf::Uint32 style) {
_title = name; _title = name;
_w = screenWidth; _w = screenWidth;
_h = screenHeight; _h = screenHeight;
@ -46,8 +48,7 @@ void Screen::clear() {
_window->clear(_background); _window->clear(_background);
} }
void Screen::drawTriangle(const Triangle& triangle) void Screen::drawTriangle(const Triangle &triangle) {
{
sf::Vertex tris[3] = sf::Vertex tris[3] =
{ {
sf::Vertex(sf::Vector2f((float) triangle[0].x(), (float) triangle[0].y()), triangle.color()), sf::Vertex(sf::Vector2f((float) triangle[0].x(), (float) triangle[0].y()), triangle.color()),

View File

@ -7,9 +7,11 @@
#include <string> #include <string>
#include "Triangle.h"
#include <SFML/Graphics.hpp>
#include <map> #include <map>
#include <SFML/Graphics.hpp>
#include "Triangle.h"
#include "utils/Time.h" #include "utils/Time.h"
#include "Consts.h" #include "Consts.h"
#include "Mesh.h" #include "Mesh.h"
@ -26,24 +28,34 @@ private:
const std::shared_ptr<sf::RenderWindow> _window = std::make_shared<sf::RenderWindow>(); const std::shared_ptr<sf::RenderWindow> _window = std::make_shared<sf::RenderWindow>();
public: public:
void open(int screenWidth = Consts::STANDARD_SCREEN_WIDTH, int screenHeight = Consts::STANDARD_SCREEN_HEIGHT, const std::string& name = Consts::PROJECT_NAME, bool verticalSync = true, sf::Color background = Consts::BACKGROUND_COLOR, sf::Uint32 style = sf::Style::Default); void open(int screenWidth = Consts::STANDARD_SCREEN_WIDTH, int screenHeight = Consts::STANDARD_SCREEN_HEIGHT,
const std::string &name = Consts::PROJECT_NAME, bool verticalSync = true,
sf::Color background = Consts::BACKGROUND_COLOR, sf::Uint32 style = sf::Style::Default);
void display(); void display();
void clear(); void clear();
[[nodiscard]] bool hasFocus() const { return _window->hasFocus(); } [[nodiscard]] bool hasFocus() const { return _window->hasFocus(); }
void drawTriangle(const Triangle &triangle); void drawTriangle(const Triangle &triangle);
void drawTetragon(const Vec2D &p1, const Vec2D &p2, const Vec2D &p3, const Vec2D &p4, sf::Color color); void drawTetragon(const Vec2D &p1, const Vec2D &p2, const Vec2D &p3, const Vec2D &p4, sf::Color color);
void drawText(const std::string &string, const Vec2D &position, int size, sf::Color color); void drawText(const std::string &string, const Vec2D &position, int size, sf::Color color);
void drawText(const sf::Text &text); void drawText(const sf::Text &text);
void drawSprite(const sf::Sprite &sprite); void drawSprite(const sf::Sprite &sprite);
void setTitle(const std::string &title); void setTitle(const std::string &title);
[[nodiscard]] std::string title() const { return _title; }; [[nodiscard]] std::string title() const { return _title; };
bool isOpen(); bool isOpen();
[[nodiscard]] int width() const { return _window->getSize().x; } [[nodiscard]] int width() const { return _window->getSize().x; }
[[nodiscard]] int height() const { return _window->getSize().y; } [[nodiscard]] int height() const { return _window->getSize().y; }
void close(); void close();
@ -52,6 +64,7 @@ public:
// OpenGL functions // OpenGL functions
void glDrawMesh(GLfloat *geometry, GLfloat *view, GLfloat *model, size_t count); void glDrawMesh(GLfloat *geometry, GLfloat *view, GLfloat *model, size_t count);
static GLfloat *glMeshToGLfloatArray(std::shared_ptr<Mesh> mesh, const Vec3D &cameraPosition); static GLfloat *glMeshToGLfloatArray(std::shared_ptr<Mesh> mesh, const Vec3D &cameraPosition);
[[nodiscard]] std::shared_ptr<sf::RenderWindow> renderWindow() { return _window; } [[nodiscard]] std::shared_ptr<sf::RenderWindow> renderWindow() { return _window; }

View File

@ -7,6 +7,7 @@
#include <string> #include <string>
#include <map> #include <map>
#include <SFML/Audio.hpp> #include <SFML/Audio.hpp>
class SoundTag final { class SoundTag final {
@ -14,10 +15,13 @@ private:
const std::string _name; const std::string _name;
public: public:
explicit SoundTag(std::string name = "") : _name(std::move(name)) {} explicit SoundTag(std::string name = "") : _name(std::move(name)) {}
[[nodiscard]] std::string str() const { return _name; } [[nodiscard]] std::string str() const { return _name; }
bool operator==(const SoundTag &tag) const { return _name == tag._name; } bool operator==(const SoundTag &tag) const { return _name == tag._name; }
bool operator!=(const SoundTag &tag) const { return _name != tag._name; } bool operator!=(const SoundTag &tag) const { return _name != tag._name; }
bool operator<(const SoundTag &tag) const { return _name < tag._name; } bool operator<(const SoundTag &tag) const { return _name < tag._name; }
}; };
@ -29,16 +33,22 @@ private:
static bool _validInstance; static bool _validInstance;
SoundController() = default; SoundController() = default;
public: public:
SoundController(const SoundController &) = delete; SoundController(const SoundController &) = delete;
SoundController &operator=(SoundController &) = delete; SoundController &operator=(SoundController &) = delete;
static void playSound(const SoundTag &soundTag, const std::string &filename); static void playSound(const SoundTag &soundTag, const std::string &filename);
static void pauseSound(const SoundTag &soundTag); static void pauseSound(const SoundTag &soundTag);
static void stopSound(const SoundTag &soundTag); static void stopSound(const SoundTag &soundTag);
static sf::Sound::Status getStatus(const SoundTag &soundTag); static sf::Sound::Status getStatus(const SoundTag &soundTag);
static void init(); static void init();
static void free(); static void free();
}; };

View File

@ -5,10 +5,12 @@
#include "Triangle.h" #include "Triangle.h"
#include "Consts.h" #include "Consts.h"
Triangle::Triangle(const Vec4D& p1, const Vec4D& p2, const Vec4D& p3, sf::Color color) : _color(color), _points{p1, p2, p3} { Triangle::Triangle(const Vec4D &p1, const Vec4D &p2, const Vec4D &p3, sf::Color color) : _color(color),
_points{p1, p2, p3} {
} }
Triangle::Triangle(const Triangle &triangle) : _points{triangle._points[0], triangle._points[1], triangle._points[2]}, _color(triangle._color) { Triangle::Triangle(const Triangle &triangle) : _points{triangle._points[0], triangle._points[1], triangle._points[2]},
_color(triangle._color) {
} }
Triangle Triangle::operator*(const Matrix4x4 &matrix4X4) const { Triangle Triangle::operator*(const Matrix4x4 &matrix4X4) const {

View File

@ -5,10 +5,11 @@
#ifndef ENGINE_TRIANGLE_H #ifndef ENGINE_TRIANGLE_H
#define ENGINE_TRIANGLE_H #define ENGINE_TRIANGLE_H
#include <SFML/Graphics.hpp>
#include "Vec4D.h" #include "Vec4D.h"
#include "Vec3D.h" #include "Vec3D.h"
#include "Matrix4x4.h" #include "Matrix4x4.h"
#include <SFML/Graphics.hpp>
class Triangle final { class Triangle final {
private: private:
@ -16,11 +17,15 @@ private:
Vec4D _points[3]; Vec4D _points[3];
public: public:
Triangle() : _points{Vec4D{}, Vec4D{}, Vec4D{}} {}; Triangle() : _points{Vec4D{}, Vec4D{}, Vec4D{}} {};
Triangle(const Triangle &triangle); Triangle(const Triangle &triangle);
Triangle(const Vec4D &p1, const Vec4D &p2, const Vec4D &p3, sf::Color color = {0, 0, 0}); Triangle(const Vec4D &p1, const Vec4D &p2, const Vec4D &p3, sf::Color color = {0, 0, 0});
Triangle &operator=(const Triangle &) = default; Triangle &operator=(const Triangle &) = default;
[[nodiscard]] Vec4D operator[](int i) const; [[nodiscard]] Vec4D operator[](int i) const;
[[nodiscard]] Vec3D norm() const; [[nodiscard]] Vec3D norm() const;
// Operations with Matrix4x4 // Operations with Matrix4x4

View File

@ -3,6 +3,7 @@
// //
#include <cmath> #include <cmath>
#include "Vec2D.h" #include "Vec2D.h"
#include "Consts.h" #include "Consts.h"
@ -28,6 +29,7 @@ Vec2D Vec2D::operator-() const {
bool Vec2D::operator==(const Vec2D &vec) const { bool Vec2D::operator==(const Vec2D &vec) const {
return (*this - vec).sqrAbs() < Consts::EPS; return (*this - vec).sqrAbs() < Consts::EPS;
} }
bool Vec2D::operator!=(const Vec2D &vec) const { bool Vec2D::operator!=(const Vec2D &vec) const {
return !(*this == vec); return !(*this == vec);
} }
@ -35,6 +37,7 @@ bool Vec2D::operator!=(const Vec2D& vec) const {
Vec2D Vec2D::operator+(const Vec2D &vec) const { Vec2D Vec2D::operator+(const Vec2D &vec) const {
return Vec2D(x() + vec.x(), y() + vec.y()); return Vec2D(x() + vec.x(), y() + vec.y());
} }
Vec2D Vec2D::operator-(const Vec2D &vec) const { Vec2D Vec2D::operator-(const Vec2D &vec) const {
return Vec2D(*this) + -vec; return Vec2D(*this) + -vec;
} }

View File

@ -6,6 +6,7 @@
#define SHOOTER_VEC2D_H #define SHOOTER_VEC2D_H
#include <array> #include <array>
#include "Vec4D.h" #include "Vec4D.h"
class Vec2D final { class Vec2D final {
@ -14,9 +15,13 @@ private:
public: public:
Vec2D() = default; Vec2D() = default;
Vec2D(const Vec2D &vec); Vec2D(const Vec2D &vec);
explicit Vec2D(const Vec4D &point4D); explicit Vec2D(const Vec4D &point4D);
explicit Vec2D(double x, double y = 0.0); explicit Vec2D(double x, double y = 0.0);
Vec2D &operator=(const Vec2D &) = default; Vec2D &operator=(const Vec2D &) = default;
[[nodiscard]] double x() const { return _arr_point[0]; } [[nodiscard]] double x() const { return _arr_point[0]; }

View File

@ -2,11 +2,12 @@
// Created by Иван Ильин on 09.10.2021. // Created by Иван Ильин on 09.10.2021.
// //
#include "Vec3D.h"
#include "Consts.h"
#include <cmath> #include <cmath>
#include <stdexcept> #include <stdexcept>
#include "Vec3D.h"
#include "Consts.h"
Vec3D::Vec3D(const Vec3D &vec) { Vec3D::Vec3D(const Vec3D &vec) {
_arr_point[0] = vec.x(); _arr_point[0] = vec.x();
_arr_point[1] = vec.y(); _arr_point[1] = vec.y();
@ -32,6 +33,7 @@ Vec3D Vec3D::operator-() const {
bool Vec3D::operator==(const Vec3D &vec) const { bool Vec3D::operator==(const Vec3D &vec) const {
return (*this - vec).sqrAbs() < Consts::EPS; return (*this - vec).sqrAbs() < Consts::EPS;
} }
bool Vec3D::operator!=(const Vec3D &vec) const { bool Vec3D::operator!=(const Vec3D &vec) const {
return !(*this == vec); return !(*this == vec);
} }
@ -40,6 +42,7 @@ bool Vec3D::operator!=(const Vec3D& vec) const {
Vec3D Vec3D::operator+(const Vec3D &vec) const { Vec3D Vec3D::operator+(const Vec3D &vec) const {
return Vec3D(x() + vec.x(), y() + vec.y(), z() + vec.z()); return Vec3D(x() + vec.x(), y() + vec.y(), z() + vec.z());
} }
Vec3D Vec3D::operator-(const Vec3D &vec) const { Vec3D Vec3D::operator-(const Vec3D &vec) const {
return Vec3D(*this) + -vec; return Vec3D(*this) + -vec;
} }

View File

@ -6,6 +6,7 @@
#define SHOOTER_VEC3D_H #define SHOOTER_VEC3D_H
#include <array> #include <array>
#include "Vec4D.h" #include "Vec4D.h"
class Vec3D final { class Vec3D final {
@ -14,9 +15,13 @@ private:
public: public:
Vec3D() = default; Vec3D() = default;
Vec3D(const Vec3D &vec); Vec3D(const Vec3D &vec);
explicit Vec3D(const Vec4D &vec); explicit Vec3D(const Vec4D &vec);
explicit Vec3D(double x, double y = 0.0, double z = 0.0); explicit Vec3D(double x, double y = 0.0, double z = 0.0);
Vec3D &operator=(const Vec3D &) = default; Vec3D &operator=(const Vec3D &) = default;
[[nodiscard]] double x() const { return _arr_point[0]; } [[nodiscard]] double x() const { return _arr_point[0]; }

View File

@ -2,11 +2,12 @@
// Created by Иван Ильин on 12.01.2021. // Created by Иван Ильин on 12.01.2021.
// //
#include "Vec4D.h"
#include "Consts.h"
#include <cmath> #include <cmath>
#include <stdexcept> #include <stdexcept>
#include "Vec4D.h"
#include "Consts.h"
Vec4D::Vec4D(double x, double y, double z, double w) { Vec4D::Vec4D(double x, double y, double z, double w) {
_arr_point[0] = x; _arr_point[0] = x;
_arr_point[1] = y; _arr_point[1] = y;

View File

@ -13,10 +13,12 @@ private:
public: public:
Vec4D() = default; Vec4D() = default;
Vec4D (const Vec4D& point4D);
explicit Vec4D (double x, double y = 0.0, double z = 0.0, double w = 0.0);
Vec4D& operator=(const Vec4D& point4D) = default;
Vec4D(const Vec4D &point4D);
explicit Vec4D(double x, double y = 0.0, double z = 0.0, double w = 0.0);
Vec4D &operator=(const Vec4D &point4D) = default;
[[nodiscard]] double x() const { return _arr_point[0]; } [[nodiscard]] double x() const { return _arr_point[0]; }
[[nodiscard]] double y() const { return _arr_point[1]; } [[nodiscard]] double y() const { return _arr_point[1]; }
@ -27,6 +29,7 @@ public:
// Boolean operations // Boolean operations
bool operator==(const Vec4D &point4D) const; bool operator==(const Vec4D &point4D) const;
bool operator!=(const Vec4D &point4D) const; bool operator!=(const Vec4D &point4D) const;
// Operations with Vec4D // Operations with Vec4D

View File

@ -2,23 +2,26 @@
// Created by Иван Ильин on 13.01.2021. // Created by Иван Ильин on 13.01.2021.
// //
#include <sstream>
#include <cmath>
#include "World.h" #include "World.h"
#include "utils/Log.h" #include "utils/Log.h"
#include "Plane.h" #include "Plane.h"
#include "ResourceManager.h" #include "ResourceManager.h"
#include <sstream>
#include <cmath>
using namespace std; using namespace std;
void World::addBody(std::shared_ptr<RigidBody> body) { void World::addBody(std::shared_ptr<RigidBody> body) {
_objects.emplace(body->name(), body); _objects.emplace(body->name(), body);
Log::log("World::addBody(): inserted body '" + body->name().str() + "' with " + std::to_string(_objects[body->name()]->triangles().size()) + " tris."); Log::log("World::addBody(): inserted body '" + body->name().str() + "' with " +
std::to_string(_objects[body->name()]->triangles().size()) + " tris.");
} }
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>(Mesh(tag, filename, scale)));
Log::log("World::loadBody(): inserted body from " + filename + " with title '" + tag.str() + "' with " + std::to_string(_objects[tag]->triangles().size()) + " tris."); Log::log("World::loadBody(): inserted body from " + filename + " with title '" + tag.str() + "' with " +
std::to_string(_objects[tag]->triangles().size()) + " tris.");
} }
IntersectionInformation World::rayCast(const Vec3D &from, const Vec3D &to, const std::string &skipTags) { IntersectionInformation World::rayCast(const Vec3D &from, const Vec3D &to, const std::string &skipTags) {
@ -68,7 +71,8 @@ IntersectionInformation World::rayCast(const Vec3D& from, const Vec3D& to, const
} }
} }
} }
return IntersectionInformation{point, sqrt(minDistance), triangle, ObjectNameTag(bodyName), intersectedBody, intersected}; return IntersectionInformation{point, sqrt(minDistance), triangle, ObjectNameTag(bodyName), intersectedBody,
intersected};
} }
void World::loadMap(const std::string &filename, const Vec3D &scale) { void World::loadMap(const std::string &filename, const Vec3D &scale) {

View File

@ -6,6 +6,7 @@
#define ENGINE_WORLD_H #define ENGINE_WORLD_H
#include <map> #include <map>
#include "Camera.h" #include "Camera.h"
#include "Screen.h" #include "Screen.h"
#include "physics/RigidBody.h" #include "physics/RigidBody.h"
@ -26,11 +27,15 @@ public:
World() = default; World() = default;
void checkCollision(const ObjectNameTag &tag); void checkCollision(const ObjectNameTag &tag);
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});
// 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
@ -39,6 +44,7 @@ public:
void loadMap(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::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

@ -33,10 +33,15 @@ private:
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()), static_cast<sf::Uint8>(mid.z()), static_cast<sf::Uint8>(mid.w()))); _mesh.lock()->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())));
} }
public: 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) { 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) {
} }
}; };

View File

@ -6,6 +6,7 @@
#define ENGINE_AFUNCTION_H #define ENGINE_AFUNCTION_H
#include <utility> #include <utility>
#include "Animation.h" #include "Animation.h"
class AFunction final : public Animation { class AFunction final : public Animation {
@ -22,7 +23,9 @@ private:
} }
public: public:
explicit AFunction(std::function<void()> function, int calls = 1, double duration = 1, LoopOut looped = LoopOut::None, InterpolationType interpolationType = InterpolationType::Linear) : Animation(duration, looped, interpolationType), _callBack(std::move(function)), _allCalls(calls) { explicit AFunction(std::function<void()> function, int calls = 1, double duration = 1,
LoopOut looped = LoopOut::None, InterpolationType interpolationType = InterpolationType::Linear)
: Animation(duration, looped, interpolationType), _callBack(std::move(function)), _allCalls(calls) {
} }
}; };

View File

@ -23,8 +23,11 @@ private:
_object.lock()->rotate(_rotationValue * dprogress()); _object.lock()->rotate(_rotationValue * dprogress());
} }
public: public:
ARotate(std::weak_ptr<Object> object, const Vec3D& r, double duration = 1, LoopOut looped = LoopOut::None, InterpolationType interpolationType = InterpolationType::Bezier) : Animation(duration, looped, interpolationType), _object(std::move(object)), _rotationValue(r) { ARotate(std::weak_ptr<Object> object, const Vec3D &r, double duration = 1, LoopOut looped = LoopOut::None,
InterpolationType interpolationType = InterpolationType::Bezier)
: Animation(duration, looped, interpolationType), _object(std::move(object)), _rotationValue(r) {
} }
}; };

View File

@ -23,13 +23,18 @@ private:
std::vector<Triangle> newTriangles; std::vector<Triangle> newTriangles;
for (auto &t : _object->triangles()) { for (auto &t : _object->triangles()) {
newTriangles.emplace_back(t * Matrix4x4::Scale(Vec3D{1, 1, 1} + (_scalingValue - Vec3D{1, 1, 1}) * progress())); newTriangles.emplace_back(
t * Matrix4x4::Scale(Vec3D{1, 1, 1} + (_scalingValue - Vec3D{1, 1, 1}) * progress()));
} }
_object.lock()->setTriangles(newTriangles); _object.lock()->setTriangles(newTriangles);
return updateState(); return updateState();
} }
public: public:
AScale(std::weak_ptr<RigidBody> object, const Vec3D &s, double duration = 1, LoopOut looped = LoopOut::None, InterpolationType interpolationType = InterpolationType::Bezier) : Animation(duration, looped, interpolationType), _object(object), _scalingValue(s) { AScale(std::weak_ptr<RigidBody> object, const Vec3D &s, double duration = 1, LoopOut looped = LoopOut::None,
InterpolationType interpolationType = InterpolationType::Bezier) : Animation(duration, looped,
interpolationType),
_object(object), _scalingValue(s) {
} }
}; };

View File

@ -23,8 +23,13 @@ private:
_object.lock()->translate(_translationValue * dprogress()); _object.lock()->translate(_translationValue * dprogress());
} }
public: 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)), _translationValue(t){ 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)),
_translationValue(t) {
} }
}; };

View File

@ -30,8 +30,11 @@ private:
} }
_object.lock()->translate(_translationValue * dprogress()); _object.lock()->translate(_translationValue * dprogress());
} }
public: public:
ATranslateToPoint(std::weak_ptr<Object> object, const Vec3D& p, double duration = 1, LoopOut looped = LoopOut::None, InterpolationType interpolationType = InterpolationType::Bezier) : Animation(duration, looped, interpolationType), _targetPoint(p), _object(object) { ATranslateToPoint(std::weak_ptr<Object> object, const Vec3D &p, double duration = 1, LoopOut looped = LoopOut::None,
InterpolationType interpolationType = InterpolationType::Bezier)
: Animation(duration, looped, interpolationType), _targetPoint(p), _object(object) {
} }
}; };

View File

@ -10,6 +10,7 @@
class AWait final : public Animation { class AWait final : public Animation {
private: private:
void update() override {} void update() override {}
public: public:
explicit AWait(double duration = 1) : Animation(duration, LoopOut::None, InterpolationType::Linear, true) { explicit AWait(double duration = 1) : Animation(duration, LoopOut::None, InterpolationType::Linear, true) {
} }

View File

@ -4,11 +4,13 @@
#include "Animation.h" #include "Animation.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 waitFor)
: _duration(duration), _looped(looped), _intType(intType), _waitFor(waitFor) {
} }
bool Animation::updateState() { bool Animation::updateState() {
if (_finished || std::abs(_duration) < Consts::EPS) { if (_finished || std::abs(_duration) < Consts::EPS) {
_finished = true;
return false; return false;
} }
@ -38,7 +40,8 @@ bool Animation::updateState() {
_dprogress = Interpolation::dCos(_time, _dtime); _dprogress = Interpolation::dCos(_time, _dtime);
break; break;
default: default:
throw std::logic_error{"Animation::updateState: unknown interpolation type " + std::to_string(static_cast<int>(_intType))}; throw std::logic_error{
"Animation::updateState: unknown interpolation type " + std::to_string(static_cast<int>(_intType))};
} }
update(); update();

View File

@ -41,8 +41,10 @@ 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;
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; } [[nodiscard]] bool waitFor() const { return _waitFor; }
@ -50,7 +52,9 @@ public:
bool updateState(); bool updateState();
[[nodiscard]] double progress() const { return _progress; } [[nodiscard]] double progress() const { return _progress; }
[[nodiscard]] double dprogress() const { return _dprogress; } [[nodiscard]] double dprogress() const { return _dprogress; }
void stop() { _finished = true; } void stop() { _finished = true; }
}; };

View File

@ -5,20 +5,26 @@
#ifndef ENGINE_INTERPOLATION_H #ifndef ENGINE_INTERPOLATION_H
#define ENGINE_INTERPOLATION_H #define ENGINE_INTERPOLATION_H
#include "../Vec2D.h"
#include <cmath> #include <cmath>
#include "../Vec2D.h"
#include "../Consts.h" #include "../Consts.h"
namespace Interpolation { namespace Interpolation {
static double Linear(double t); static double Linear(double t);
static double Cos(double t); static double Cos(double t);
static double Bezier(const Vec2D &p1, const Vec2D &p2, double t); static double Bezier(const Vec2D &p1, const Vec2D &p2, double t);
static double Bouncing(double t); static double Bouncing(double t);
static double dLinear(double t, double dt); static double dLinear(double t, double dt);
static double dCos(double t, double dt); static double dCos(double t, double dt);
static 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); static double dBouncing(double t, double dt);
}; };
@ -67,7 +73,8 @@ double Interpolation::Bezier(const Vec2D &p1, const Vec2D &p2, double t) {
double Interpolation::Bouncing(double t) { double Interpolation::Bouncing(double t) {
t = Interpolation::Linear(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)))); 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) { double Interpolation::dLinear(double t, double dt) {

View File

@ -3,9 +3,9 @@
// //
#include <list> #include <list>
#include "Animation.h" #include "Animation.h"
#include "Timeline.h" #include "Timeline.h"
#include <iostream>
#include "../utils/Log.h" #include "../utils/Log.h"
Timeline *Timeline::_instance = nullptr; Timeline *Timeline::_instance = nullptr;
@ -53,7 +53,8 @@ void Timeline::deleteAnimationList(const AnimationListTag& listName) {
_instance->_animations[listName].clear(); _instance->_animations[listName].clear();
_instance->_animations.erase(listName); _instance->_animations.erase(listName);
Log::log("Timeline::deleteAnimationList(): list '" + listName.str() +"' with " + std::to_string(animCounter) + " animations was deleted" ); Log::log("Timeline::deleteAnimationList(): list '" + listName.str() + "' with " + std::to_string(animCounter) +
" animations was deleted");
} }
[[nodiscard]] bool Timeline::isInAnimList(const AnimationListTag &listName) { [[nodiscard]] bool Timeline::isInAnimList(const AnimationListTag &listName) {

View File

@ -12,10 +12,13 @@ private:
const std::string _name; const std::string _name;
public: public:
explicit AnimationListTag(std::string name = "") : _name(std::move(name)) {} explicit AnimationListTag(std::string name = "") : _name(std::move(name)) {}
[[nodiscard]] std::string str() const { return _name; } [[nodiscard]] std::string str() const { return _name; }
bool operator==(const AnimationListTag &tag) const { return _name == tag._name; } bool operator==(const AnimationListTag &tag) const { return _name == tag._name; }
bool operator!=(const AnimationListTag &tag) const { return _name != tag._name; } bool operator!=(const AnimationListTag &tag) const { return _name != tag._name; }
bool operator<(const AnimationListTag &tag) const { return _name < tag._name; } bool operator<(const AnimationListTag &tag) const { return _name < tag._name; }
}; };
@ -27,19 +30,24 @@ private:
static bool _validInstance; static bool _validInstance;
Timeline() = default; Timeline() = default;
public: public:
Timeline(const Timeline &) = delete; Timeline(const Timeline &) = delete;
Timeline &operator=(Timeline &) = delete; Timeline &operator=(Timeline &) = delete;
static void update(); static void update();
static void animate(const AnimationListTag &listName, std::shared_ptr<Animation> anim); 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);
[[nodiscard]] static bool isInAnimList(const AnimationListTag &listName); [[nodiscard]] static bool isInAnimList(const AnimationListTag &listName);
static void init(); static void init();
static void free(); static void free();
}; };

View File

@ -2,29 +2,26 @@
// Created by Иван Ильин on 26.03.2021. // Created by Иван Ильин on 26.03.2021.
// //
#include "Button.h"
#include <utility> #include <utility>
#include "Button.h"
#include "../ResourceManager.h" #include "../ResourceManager.h"
void Button::select() void Button::select() {
{
if (!_selected && !_pressed) { if (!_selected && !_pressed) {
_button.setTextureRect(sf::IntRect(_selectedState.tx, _selectedState.ty, _w, _h)); _button.setTextureRect(sf::IntRect(_selectedState.tx, _selectedState.ty, _w, _h));
_selected = true; _selected = true;
} }
} }
void Button::unSelect() void Button::unSelect() {
{
if (_selected && !_pressed) { if (_selected && !_pressed) {
_button.setTextureRect(sf::IntRect(_usualState.tx, _usualState.ty, _w, _h)); _button.setTextureRect(sf::IntRect(_usualState.tx, _usualState.ty, _w, _h));
_selected = false; _selected = false;
} }
} }
void Button::press() void Button::press() {
{
if (!_pressed) { if (!_pressed) {
_button.setTextureRect(sf::IntRect(_pressedState.tx, _pressedState.ty, _w, _h)); _button.setTextureRect(sf::IntRect(_pressedState.tx, _pressedState.ty, _w, _h));
if (_checkBox) { if (_checkBox) {
@ -42,20 +39,24 @@ void Button::press()
void Button::init() { void Button::init() {
_button.setTexture(*ResourceManager::loadTexture(_texture)); _button.setTexture(*ResourceManager::loadTexture(_texture));
_button.setTextureRect(sf::IntRect(_usualState.tx, _usualState.ty, _w, _h)); _button.setTextureRect(sf::IntRect(_usualState.tx, _usualState.ty, _w, _h));
_button.scale((float)_sx, (float)_sy); _button.scale(static_cast<float>(_sx), static_cast<float>(_sy));
_button.setPosition((float)(_x - _w * _sx / 2), (float)(_y - _h * _sy / 2)); _button.setPosition(static_cast<float>(_x) - static_cast<float>(_w * _sx) / 2.0f,
static_cast<float>(_y) - static_cast<float>(_h * _sy) / 2.0f);
_text.setFont(*ResourceManager::loadFont(_font)); _text.setFont(*ResourceManager::loadFont(_font));
_text.setString(_textString); _text.setString(_textString);
_text.setCharacterSize((unsigned int)(_h * _sy / 2)); _text.setCharacterSize(static_cast<unsigned int>((_h * _sy) / 2));
_text.setFillColor(_textColor); _text.setFillColor(_textColor);
_text.setPosition((float)(_x - _text.getLocalBounds().width / 2), (float)(_y - _h * _sy / 2 + _text.getLocalBounds().height / 4)); _text.setPosition(static_cast<float>(_x) - _text.getLocalBounds().width / 2.0f,
static_cast<float>(_y) - static_cast<float>(_h * _sy) / 2.0f + _text.getLocalBounds().height / 4.0f);
} }
Button::Button(int x, int y, int width, int height, std::function<void()> click, std::string text, double sx, Button::Button(int x, int y, int width, int height, std::function<void()> click, std::string text, double sx,
double sy, std::string texture, tPos usualState, tPos selectedState, tPos pressedState, double sy, std::string texture, tPos usualState, tPos selectedState, tPos pressedState,
std::string font, sf::Color textColor) : _x(x), _y(y), _w(width), _h(height), _click(std::move(click)), std::string font, sf::Color textColor) : _x(x), _y(y), _w(width), _h(height), _click(std::move(click)),
_textString(std::move(text)), _sx(sx), _sy(sy), _texture(std::move(texture)), _usualState(usualState), _selectedState(selectedState), _pressedState(pressedState), _textString(std::move(text)), _sx(sx), _sy(sy),
_texture(std::move(texture)), _usualState(usualState),
_selectedState(selectedState), _pressedState(pressedState),
_font(std::move(font)), _textColor(textColor) { _font(std::move(font)), _textColor(textColor) {
} }

View File

@ -5,9 +5,10 @@
#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> #include <SFML/Audio.hpp>
#include <functional>
struct tPos final { struct tPos final {
const int tx; const int tx;
@ -46,21 +47,33 @@ private:
public: public:
Button() = default; Button() = default;
Button(int x, int y, int width, int height, std::function<void()> click, std::string text, double sx, double sy, std::string texture, tPos usualState, tPos selectedState, tPos pressedState, std::string font, sf::Color textColor);
Button(int x, int y, int width, int height, std::function<void()> click, std::string text, double sx, double sy,
std::string texture, tPos usualState, tPos selectedState, tPos pressedState, std::string font,
sf::Color textColor);
void select(); void select();
void unSelect(); void unSelect();
void press(); void press();
void init(); void init();
[[nodiscard]] int x() const { return _x; } [[nodiscard]] int x() const { return _x; }
[[nodiscard]] int y() const { return _y; } [[nodiscard]] int y() const { return _y; }
[[nodiscard]] int w() const { return _w; } [[nodiscard]] int w() const { return _w; }
[[nodiscard]] int h() const { return _h; } [[nodiscard]] int h() const { return _h; }
[[nodiscard]] double sx() const { return _sx; } [[nodiscard]] double sx() const { return _sx; }
[[nodiscard]] double sy() const { return _sy; } [[nodiscard]] double sy() const { return _sy; }
[[nodiscard]] sf::Sprite const &sprite() const { return _button; } [[nodiscard]] sf::Sprite const &sprite() const { return _button; }
[[nodiscard]] sf::Text const &text() const { return _text; } [[nodiscard]] sf::Text const &text() const { return _text; }
}; };

View File

@ -2,15 +2,17 @@
// Created by Иван Ильин on 26.03.2021. // Created by Иван Ильин on 26.03.2021.
// //
#include "Window.h"
#include <utility> #include <utility>
#include "Window.h"
#include "../ResourceManager.h" #include "../ResourceManager.h"
void Window::addButton(int x, int y, int w, int h, std::function<void()> click, const std::string &text, double sx, double sy, void Window::addButton(int x, int y, int w, int h, std::function<void()> click, const std::string &text, double sx,
double sy,
const std::string &texture, tPos usualState, tPos selectedState, tPos pressedState, const std::string &texture, tPos usualState, tPos selectedState, tPos pressedState,
const std::string &font, sf::Color textColor) { const std::string &font, sf::Color textColor) {
_buttons.emplace_back(x, y, w, h, std::move(click), text, sx, sy, texture, usualState, selectedState, pressedState, font, textColor); _buttons.emplace_back(x, y, w, h, std::move(click), text, sx, sy, texture, usualState, selectedState, pressedState,
font, textColor);
_buttons.back().init(); _buttons.back().init();
} }
@ -21,12 +23,15 @@ void Window::update() {
Vec2D mousePos = _mouse->getMousePosition(); Vec2D mousePos = _mouse->getMousePosition();
Vec2D dMousePos = mousePos - _prevMousePosition; Vec2D dMousePos = mousePos - _prevMousePosition;
_back.setPosition(_back.getPosition() - sf::Vector2f((float)(dMousePos.x() / 30), (float)(dMousePos.y() / 30))); _back.setPosition(_back.getPosition() - sf::Vector2f(static_cast<float>(dMousePos.x()) / 30.0f,
static_cast<float>(dMousePos.y()) / 30.0f));
bool isPressed = _mouse->isButtonTapped(sf::Mouse::Left); bool isPressed = _mouse->isButtonTapped(sf::Mouse::Left);
for (auto &button : _buttons) { for (auto &button : _buttons) {
if( mousePos.x() > button.x() - button.w() * button.sx() / 2 && mousePos.y() > button.y() - button.h() * button.sy() / 2 && if (mousePos.x() > button.x() - button.w() * button.sx() / 2.0f &&
mousePos.x() < button.x() + button.w() * button.sx() / 2 && mousePos.y() < button.y() + button.h() * button.sy() / 2) { mousePos.y() > button.y() - button.h() * button.sy() / 2.0f &&
mousePos.x() < button.x() + button.w() * button.sx() / 2.0f &&
mousePos.y() < button.y() + button.h() * button.sy() / 2.0f) {
button.select(); button.select();
if (isPressed) if (isPressed)
button.press(); button.press();
@ -47,7 +52,7 @@ void Window::setBackgroundTexture(const std::string &texture, double sx, double
_backTexture = texture; _backTexture = texture;
std::shared_ptr<sf::Texture> t = ResourceManager::loadTexture(_backTexture); std::shared_ptr<sf::Texture> t = ResourceManager::loadTexture(_backTexture);
t->setRepeated(true); t->setRepeated(true);
_back = sf::Sprite(*t, sf::IntRect(0, 0, (int)(w + w / 30.0), (int)(h + h / 30.0))); _back = sf::Sprite(*t, sf::IntRect(0, 0, static_cast<int>(w + w / 30.0), static_cast<int>(h + h / 30.0)));
_back.scale((float) sx, (float) sy); _back.scale((float) sx, (float) sy);
_back.setPosition(sf::Vector2f(-w / 30.0f, -h / 30.0f)); _back.setPosition(sf::Vector2f(static_cast<float>(-w) / 30.0f, static_cast<float>(-h) / 30.0f));
} }

View File

@ -25,12 +25,15 @@ private:
std::shared_ptr<Screen> _screen; std::shared_ptr<Screen> _screen;
std::shared_ptr<Mouse> _mouse; std::shared_ptr<Mouse> _mouse;
public: public:
explicit Window(std::shared_ptr<Screen> screen, std::shared_ptr<Mouse> mouse, std::string name = "Menu", std::string backTexture = "") : _screen(std::move(screen)), _mouse(std::move(mouse)), _name(std::move(name)), _backTexture(std::move(backTexture)){} explicit Window(std::shared_ptr<Screen> screen, std::shared_ptr<Mouse> mouse, std::string name = "Menu",
std::string backTexture = "") : _screen(std::move(screen)), _mouse(std::move(mouse)),
_name(std::move(name)), _backTexture(std::move(backTexture)) {}
void addButton(int x, int y, int w, int h, void addButton(int x, int y, int w, int h,
std::function<void()> click, std::function<void()> click,
const std::string &text = "_button", double sx = 1, double sy = 1, const std::string &text = "_button", double sx = 1, double sy = 1,
const std::string& texture = "", tPos usualState = {}, tPos selectedState = {}, tPos pressedState = {}, const std::string &texture = "", tPos usualState = {}, tPos selectedState = {},
tPos pressedState = {},
const std::string &font = Consts::MEDIUM_FONT, sf::Color textColor = {255, 255, 255}); const std::string &font = Consts::MEDIUM_FONT, sf::Color textColor = {255, 255, 255});
void setTitle(const std::string &title) { _name = title; } void setTitle(const std::string &title) { _name = title; }

View File

@ -4,9 +4,7 @@
#include "ClientUDP.h" #include "ClientUDP.h"
#include "MsgType.h" #include "MsgType.h"
#include <thread>
#include "../utils/Time.h" #include "../utils/Time.h"
#include <cmath>
#include "../utils/Log.h" #include "../utils/Log.h"
#include "../Consts.h" #include "../Consts.h"

View File

@ -18,6 +18,7 @@ protected:
sf::IpAddress _ip{}; sf::IpAddress _ip{};
bool process(); bool process();
bool timeout(sf::Uint16 id); bool timeout(sf::Uint16 id);
public: public:
@ -25,20 +26,28 @@ public:
explicit ClientUDP(); explicit ClientUDP();
[[nodiscard]] bool isWorking() const; [[nodiscard]] bool isWorking() const;
[[nodiscard]] bool connected() const; [[nodiscard]] bool connected() const;
void connect(sf::IpAddress ip, sf::Uint16 port); void connect(sf::IpAddress ip, sf::Uint16 port);
void disconnect(); void disconnect();
void update(); void update();
[[nodiscard]] sf::IpAddress serverIp() const { return _ip; } [[nodiscard]] sf::IpAddress serverIp() const { return _ip; }
[[nodiscard]] sf::Uint16 serverPort() const { return _port; } [[nodiscard]] sf::Uint16 serverPort() const { return _port; }
// virtual functions // virtual functions
virtual void updatePacket() {}; virtual void updatePacket() {};
virtual void processInit(sf::Packet &packet) {}; virtual void processInit(sf::Packet &packet) {};
virtual void processUpdate(sf::Packet &packet) {}; virtual void processUpdate(sf::Packet &packet) {};
virtual void processNewClient(sf::Packet &packet) {}; virtual void processNewClient(sf::Packet &packet) {};
virtual void processDisconnect(sf::Uint16 targetId) {}; virtual void processDisconnect(sf::Uint16 targetId) {};
virtual void processCustomPacket(sf::Packet &packet) {}; virtual void processCustomPacket(sf::Packet &packet) {};

View File

@ -4,13 +4,11 @@
#include "MsgType.h" #include "MsgType.h"
sf::Packet& operator<<(sf::Packet& packet, MsgType type) sf::Packet &operator<<(sf::Packet &packet, MsgType type) {
{
return packet << (sf::Uint16) type; return packet << (sf::Uint16) type;
} }
sf::Packet& operator>>(sf::Packet& packet, MsgType& type) sf::Packet &operator>>(sf::Packet &packet, MsgType &type) {
{
sf::Uint16 temp; sf::Uint16 temp;
packet >> temp; packet >> temp;
type = (MsgType) temp; type = (MsgType) temp;

View File

@ -7,8 +7,7 @@
#include <SFML/Network.hpp> #include <SFML/Network.hpp>
enum class MsgType enum class MsgType {
{
// internal messages // internal messages
Empty, // Empty message (there are no message) Empty, // Empty message (there are no message)
Error, // Error message (something went wrong) Error, // Error message (something went wrong)
@ -27,6 +26,7 @@ enum class MsgType
}; };
sf::Packet &operator<<(sf::Packet &packet, MsgType type); sf::Packet &operator<<(sf::Packet &packet, MsgType type);
sf::Packet &operator>>(sf::Packet &packet, MsgType &type); sf::Packet &operator>>(sf::Packet &packet, MsgType &type);

View File

@ -2,16 +2,19 @@
// Created by Neirokan on 30.04.2020 // Created by Neirokan on 30.04.2020
// //
#include <cmath>
#include "ReliableMsg.h" #include "ReliableMsg.h"
#include "../utils/Time.h" #include "../utils/Time.h"
#include "../Consts.h" #include "../Consts.h"
ReliableMsg::ReliableMsg(sf::Packet& packet, sf::IpAddress address, sf::Uint16 port) : packet(packet), address(address), port(port), lastTry(-std::numeric_limits<double>::max()), firstTry(Time::time()) {} ReliableMsg::ReliableMsg(sf::Packet &packet, sf::IpAddress address, sf::Uint16 port) : packet(packet), address(address),
ReliableMsg::ReliableMsg(const ReliableMsg& msg) : packet(msg.packet), address(msg.address), port(msg.port), lastTry(msg.lastTry), firstTry(msg.firstTry) {} port(port),
lastTry(-std::numeric_limits<double>::max()),
firstTry(Time::time()) {}
bool ReliableMsg::trySend(sf::UdpSocket& socket) ReliableMsg::ReliableMsg(const ReliableMsg &msg) : packet(msg.packet), address(msg.address), port(msg.port),
{ lastTry(msg.lastTry), firstTry(msg.firstTry) {}
bool ReliableMsg::trySend(sf::UdpSocket &socket) {
if (Time::time() - firstTry > Consts::NETWORK_TIMEOUT) { if (Time::time() - firstTry > Consts::NETWORK_TIMEOUT) {
return false; return false;
} }

View File

@ -17,6 +17,7 @@ private:
public: public:
ReliableMsg(sf::Packet &packet, sf::IpAddress address, sf::Uint16 port); ReliableMsg(sf::Packet &packet, sf::IpAddress address, sf::Uint16 port);
ReliableMsg(const ReliableMsg &msg); ReliableMsg(const ReliableMsg &msg);
bool trySend(sf::UdpSocket &socket); bool trySend(sf::UdpSocket &socket);

View File

@ -19,14 +19,19 @@ protected:
bool _working = false; bool _working = false;
bool process(); bool process();
bool timeout(sf::Uint16 id); bool timeout(sf::Uint16 id);
std::set<sf::Uint16> _clients{}; std::set<sf::Uint16> _clients{};
public: public:
explicit ServerUDP(); explicit ServerUDP();
[[nodiscard]] bool isWorking() const; [[nodiscard]] bool isWorking() const;
bool start(sf::Uint16 port); bool start(sf::Uint16 port);
void stop(); void stop();
void update(); void update();
virtual void updateInfo() {}; virtual void updateInfo() {};
@ -36,7 +41,9 @@ public:
// here you have to send Init message _back to 'targetId' and send NewClient message to all '_clients' // here you have to send Init message _back to 'targetId' and send NewClient message to all '_clients'
virtual void processConnect(sf::Uint16 senderId) {}; virtual void processConnect(sf::Uint16 senderId) {};
virtual void processClientUpdate(sf::Uint16 senderId, sf::Packet &packet) {}; virtual void processClientUpdate(sf::Uint16 senderId, sf::Packet &packet) {};
virtual void processDisconnect(sf::Uint16 senderId) {}; virtual void processDisconnect(sf::Uint16 senderId) {};
virtual void processCustomPacket(sf::Packet &packet, sf::Uint16 senderId) {}; virtual void processCustomPacket(sf::Packet &packet, sf::Uint16 senderId) {};

View File

@ -6,7 +6,8 @@
#include "../utils/Time.h" #include "../utils/Time.h"
#include "../Consts.h" #include "../Consts.h"
UDPConnection::UDPConnection(sf::Uint16 id, sf::IpAddress ip, sf::Uint16 port) : _id(id), _ip(ip), _port(port), lastMsg(Time::time()) {} UDPConnection::UDPConnection(sf::Uint16 id, sf::IpAddress ip, sf::Uint16 port) : _id(id), _ip(ip), _port(port),
lastMsg(Time::time()) {}
sf::Uint16 UDPConnection::id() const { sf::Uint16 UDPConnection::id() const {
return _id; return _id;

View File

@ -16,12 +16,19 @@ private:
public: public:
explicit UDPConnection(sf::Uint16 id, sf::IpAddress ip, sf::Uint16 port); explicit UDPConnection(sf::Uint16 id, sf::IpAddress ip, sf::Uint16 port);
[[nodiscard]] sf::Uint16 id() const; [[nodiscard]] sf::Uint16 id() const;
[[nodiscard]] const sf::IpAddress &ip() const; [[nodiscard]] const sf::IpAddress &ip() const;
[[nodiscard]] sf::Uint16 port() const; [[nodiscard]] sf::Uint16 port() const;
[[nodiscard]] bool timeout() const; [[nodiscard]] bool timeout() const;
bool same(sf::IpAddress& ip, sf::Uint16 port) const;
[[nodiscard]] bool same(sf::IpAddress &ip, sf::Uint16 port) const;
void update(); void update();
void send(sf::UdpSocket &socket, sf::Packet &packet); void send(sf::UdpSocket &socket, sf::Packet &packet);
}; };

View File

@ -2,9 +2,10 @@
// Created by Neirokan on 30.04.2020 // Created by Neirokan on 30.04.2020
// //
#include <algorithm>
#include "UDPSocket.h" #include "UDPSocket.h"
#include "../utils/Time.h" #include "../utils/Time.h"
#include <algorithm>
#include "../Consts.h" #include "../Consts.h"
UDPSocket::UDPSocket() : _ownId(0), _nextRelyMsgId(0) { UDPSocket::UDPSocket() : _ownId(0), _nextRelyMsgId(0) {
@ -158,7 +159,8 @@ MsgType UDPSocket::receive(sf::Packet& packet, sf::Uint16& senderId) {
_connections.insert({senderId, UDPConnection(senderId, ip, port)}); _connections.insert({senderId, UDPConnection(senderId, ip, port)});
} }
if (!_connections.count(senderId) || !_connections.at(senderId).same(ip, port) || reply && confirmed(msgId, senderId)) { if (!_connections.count(senderId) || !_connections.at(senderId).same(ip, port) ||
reply && confirmed(msgId, senderId)) {
return MsgType::Error; return MsgType::Error;
} }
return type; return type;

View File

@ -8,6 +8,7 @@
#include <memory> #include <memory>
#include <map> #include <map>
#include <functional> #include <functional>
#include "ReliableMsg.h" #include "ReliableMsg.h"
#include "UDPConnection.h" #include "UDPConnection.h"
#include "MsgType.h" #include "MsgType.h"
@ -28,22 +29,33 @@ private:
public: public:
explicit UDPSocket(); explicit UDPSocket();
bool bind(sf::Uint16 port); bool bind(sf::Uint16 port);
void unbind(); void unbind();
void setTimeoutCallback(std::function<bool(sf::Uint16)> callback); void setTimeoutCallback(std::function<bool(sf::Uint16)> callback);
void addConnection(sf::Uint16 id, sf::IpAddress ip, sf::Uint16 port); void addConnection(sf::Uint16 id, sf::IpAddress ip, sf::Uint16 port);
void removeConnection(sf::Uint16 id); void removeConnection(sf::Uint16 id);
void setId(sf::Uint16 id); void setId(sf::Uint16 id);
[[nodiscard]] sf::Uint16 ownId() const; [[nodiscard]] sf::Uint16 ownId() const;
[[nodiscard]] sf::Uint16 serverId() const; [[nodiscard]] sf::Uint16 serverId() const;
void send(const sf::Packet &packet, const sf::IpAddress &ip, sf::Uint16 port); void send(const sf::Packet &packet, const sf::IpAddress &ip, sf::Uint16 port);
void send(const sf::Packet &packet, sf::Uint16 id); void send(const sf::Packet &packet, sf::Uint16 id);
void sendRely(const sf::Packet &packet, const sf::IpAddress &ip, sf::Uint16 port); void sendRely(const sf::Packet &packet, const sf::IpAddress &ip, sf::Uint16 port);
void sendRely(const sf::Packet &packet, sf::Uint16 id); void sendRely(const sf::Packet &packet, sf::Uint16 id);
void update(); void update();
MsgType receive(sf::Packet &packet, sf::Uint16 &senderId); MsgType receive(sf::Packet &packet, sf::Uint16 &senderId);
~UDPSocket(); ~UDPSocket();

View File

@ -2,16 +2,16 @@
// Created by Иван Ильин on 05.02.2021. // Created by Иван Ильин on 05.02.2021.
// //
#include <cmath>
#include <utility>
#include "RigidBody.h" #include "RigidBody.h"
#include "../utils/Log.h" #include "../utils/Log.h"
#include "../utils/Time.h" #include "../utils/Time.h"
#include <iostream>
#include <cmath>
#include <fstream>
#include <utility>
#include "../Consts.h" #include "../Consts.h"
RigidBody::RigidBody(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale) : Mesh(std::move(nameTag), filename, scale) { RigidBody::RigidBody(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale) : Mesh(std::move(nameTag),
filename, scale) {
} }
Vec3D RigidBody::_findFurthestPoint(const Vec3D &direction) { Vec3D RigidBody::_findFurthestPoint(const Vec3D &direction) {
@ -20,6 +20,7 @@ Vec3D RigidBody::_findFurthestPoint(const Vec3D& direction) {
for (auto &tri : triangles()) { for (auto &tri : triangles()) {
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
// TODO: multiplying model() * tri[i] costs too much time to compute
Vec3D point(model() * tri[i]); Vec3D point(model() * tri[i]);
double distance = point.dot(direction.normalized()); double distance = point.dot(direction.normalized());
@ -43,11 +44,15 @@ Vec3D RigidBody::_support(std::shared_ptr<RigidBody> obj, const Vec3D& direction
NextSimplex RigidBody::_nextSimplex(const Simplex &points) { NextSimplex RigidBody::_nextSimplex(const Simplex &points) {
switch (points.type()) { switch (points.type()) {
case SimplexType::Line: return _lineCase(points); case SimplexType::Line:
case SimplexType::Triangle: return _triangleCase(points); return _lineCase(points);
case SimplexType::Tetrahedron: return _tetrahedronCase(points); case SimplexType::Triangle:
return _triangleCase(points);
case SimplexType::Tetrahedron:
return _tetrahedronCase(points);
default: throw std::logic_error{"RigidBody::_nextSimplex: simplex is not Line, Triangle or Tetrahedron"}; default:
throw std::logic_error{"RigidBody::_nextSimplex: simplex is not Line, Triangle or Tetrahedron"};
} }
} }
@ -89,15 +94,13 @@ NextSimplex RigidBody::_triangleCase(const Simplex &points) {
if (ac.dot(ao) > 0) { if (ac.dot(ao) > 0) {
newPoints = Simplex{a, c}; newPoints = Simplex{a, c};
newDirection = ac.cross(ao).cross(ac); newDirection = ac.cross(ao).cross(ac);
} } else {
else {
return _lineCase(Simplex{a, b}); return _lineCase(Simplex{a, b});
} }
} else { } else {
if (ab.cross(abc).dot(ao) > 0) { if (ab.cross(abc).dot(ao) > 0) {
return _lineCase(Simplex{a, b}); return _lineCase(Simplex{a, b});
} } else {
else {
if (abc.dot(ao) > 0) { if (abc.dot(ao) > 0) {
newDirection = abc; newDirection = abc;
} else { } else {
@ -259,7 +262,8 @@ CollisionPoint RigidBody::EPA(const Simplex& simplex, std::shared_ptr<RigidBody>
return CollisionPoint{minNormal, minDistance + Consts::EPA_EPS}; return CollisionPoint{minNormal, minDistance + Consts::EPA_EPS};
} }
std::pair<std::vector<FaceNormal>, size_t> RigidBody::_getFaceNormals(const std::vector<Vec3D>& polytope, const std::vector<size_t>& faces) { std::pair<std::vector<FaceNormal>, size_t>
RigidBody::_getFaceNormals(const std::vector<Vec3D> &polytope, const std::vector<size_t> &faces) {
std::vector<FaceNormal> normals; std::vector<FaceNormal> normals;
size_t nearestFaceIndex = 0; size_t nearestFaceIndex = 0;
double minDistance = std::numeric_limits<double>::max(); double minDistance = std::numeric_limits<double>::max();
@ -289,7 +293,9 @@ std::pair<std::vector<FaceNormal>, size_t> RigidBody::_getFaceNormals(const std:
return {normals, nearestFaceIndex}; return {normals, nearestFaceIndex};
} }
std::vector<std::pair<size_t, size_t>> RigidBody::_addIfUniqueEdge(const std::vector<std::pair<size_t, size_t>>& edges, const std::vector<size_t>& faces, size_t a, size_t b) { std::vector<std::pair<size_t, size_t>>
RigidBody::_addIfUniqueEdge(const std::vector<std::pair<size_t, size_t>> &edges, const std::vector<size_t> &faces,
size_t a, size_t b) {
std::vector<std::pair<size_t, size_t>> newEdges = edges; std::vector<std::pair<size_t, size_t>> newEdges = edges;

View File

@ -9,6 +9,7 @@
#include <vector> #include <vector>
#include <memory> #include <memory>
#include <functional> #include <functional>
#include "../Triangle.h" #include "../Triangle.h"
#include "Simplex.h" #include "Simplex.h"
#include "../Mesh.h" #include "../Mesh.h"
@ -32,17 +33,25 @@ struct NextSimplex final {
class RigidBody : public Mesh { class RigidBody : public Mesh {
private: private:
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> _getFaceNormals(const std::vector<Vec3D>& polytope, const std::vector<size_t>& faces); static std::pair<std::vector<FaceNormal>, size_t>
static std::vector<std::pair<size_t, size_t>> _addIfUniqueEdge(const std::vector<std::pair<size_t, size_t>>& edges, const std::vector<size_t>& faces, size_t a, size_t b); _getFaceNormals(const std::vector<Vec3D> &polytope, const std::vector<size_t> &faces);
static std::vector<std::pair<size_t, size_t>>
_addIfUniqueEdge(const std::vector<std::pair<size_t, size_t>> &edges, const std::vector<size_t> &faces, size_t a,
size_t b);
protected: protected:
Vec3D _velocity{0, 0, 0}; Vec3D _velocity{0, 0, 0};
@ -56,34 +65,50 @@ protected:
public: public:
explicit RigidBody(ObjectNameTag nameTag) : Mesh(std::move(nameTag)) {}; explicit RigidBody(ObjectNameTag nameTag) : Mesh(std::move(nameTag)) {};
explicit RigidBody(const RigidBody& rigidBody) = default;
RigidBody(const RigidBody &rigidBody) = default;
explicit RigidBody(const Mesh &mesh); explicit RigidBody(const Mesh &mesh);
RigidBody(ObjectNameTag nameTag, const std::string &filename, const Vec3D &scale = Vec3D{1, 1, 1}); 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 isCollision() const { return _collision; } [[nodiscard]] bool isCollision() const { return _collision; }
[[nodiscard]] bool inCollision() const { return _inCollision; } [[nodiscard]] bool inCollision() const { return _inCollision; }
[[nodiscard]] bool isCollider() const { return _isCollider; } [[nodiscard]] bool isCollider() const { return _isCollider; }
void setInCollision(bool c) { _inCollision = c; } void setInCollision(bool c) { _inCollision = c; }
void setCollision(bool c) { _collision = c; } void setCollision(bool c) { _collision = c; }
void setCollider(bool c) { _isCollider = c; } void setCollider(bool c) { _isCollider = c; }
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>)>& collisionCallBack() const { return _collisionCallBack; } [[nodiscard]] const std::function<void(const ObjectNameTag &, std::shared_ptr<RigidBody>)> &
void setCollisionCallBack(const std::function<void(const ObjectNameTag& tag, std::shared_ptr<RigidBody>)>& f) { _collisionCallBack = f; } collisionCallBack() const { return _collisionCallBack; }
void setCollisionCallBack(const std::function<void(const ObjectNameTag &tag,
std::shared_ptr<RigidBody>)> &f) { _collisionCallBack = f; }
~RigidBody() override = default; ~RigidBody() override = default;
}; };

View File

@ -5,9 +5,10 @@
#ifndef ENGINE_SIMPLEX_H #ifndef ENGINE_SIMPLEX_H
#define ENGINE_SIMPLEX_H #define ENGINE_SIMPLEX_H
#include "../Vec3D.h"
#include <list> #include <list>
#include "../Vec3D.h"
enum class SimplexType { enum class SimplexType {
Zero, Zero,
Point, Point,
@ -26,27 +27,32 @@ public:
Simplex(std::initializer_list<Vec3D> list) { Simplex(std::initializer_list<Vec3D> list) {
for (const auto &v : list) { for (const auto &v : list) {
_points.push_back(v); _points.push_back(v);
if(_points.size() > 4) if (_points.size() > 4) {
_points.pop_front(); _points.pop_front();
} }
} }
}
void push_front(const Vec3D &point) { void push_front(const Vec3D &point) {
_points.push_front(point); _points.push_front(point);
if(_points.size() > 4) if (_points.size() > 4) {
_points.pop_back(); _points.pop_back();
} }
}
Vec3D operator[](unsigned i) const { Vec3D operator[](unsigned i) const {
auto it = _points.begin(); auto it = _points.begin();
for(unsigned k=0; k<i; k++) for (unsigned k = 0; k < i; k++) {
++it; ++it;
}
return *it; return *it;
} }
[[nodiscard]] unsigned size() const { return _points.size(); } [[nodiscard]] unsigned size() const { return _points.size(); }
[[nodiscard]] auto begin() const { return _points.begin(); } [[nodiscard]] auto begin() const { return _points.begin(); }
[[nodiscard]] auto end() const { return _points.end(); } [[nodiscard]] auto end() const { return _points.end(); }
[[nodiscard]] SimplexType type() const { return static_cast<SimplexType>(_points.size()); } [[nodiscard]] SimplexType type() const { return static_cast<SimplexType>(_points.size()); }

View File

@ -4,16 +4,16 @@
#define _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS
#include "Log.h"
#include "Time.h"
#include <ctime> #include <ctime>
#include <iomanip> #include <iomanip>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include "Log.h"
#include "Time.h"
#include "../Consts.h" #include "../Consts.h"
namespace Log namespace Log {
{
void log(const std::string &message) { void log(const std::string &message) {
if (Consts::USE_LOG_FILE) { if (Consts::USE_LOG_FILE) {
std::time_t const now_c = std::time(nullptr); std::time_t const now_c = std::time(nullptr);

View File

@ -7,8 +7,7 @@
#include <string> #include <string>
namespace Log namespace Log {
{
void log(const std::string &message); void log(const std::string &message);
}; };

View File

@ -3,8 +3,8 @@
// //
#include "Time.h" #include "Time.h"
#include "../Consts.h"
#include "Log.h" #include "Log.h"
#include "../Consts.h"
using namespace std::chrono; using namespace std::chrono;
@ -44,13 +44,15 @@ void Time::update() {
_instance->_deltaTime = duration<double>(t - _instance->_last).count(); _instance->_deltaTime = duration<double>(t - _instance->_last).count();
_instance->_time = duration<double>(t - _instance->_start).count(); _instance->_time = duration<double>(t - _instance->_start).count();
// in case when fps < 10 it is useful to decrease _deltaTime (to avoid collision problems) // in case when fps < 10 it is useful to decrease _deltaTime (to avoid collision problems)
if(_instance->_deltaTime > Consts::LARGEST_TIME_STEP) if (_instance->_deltaTime > Consts::LARGEST_TIME_STEP) {
_instance->_deltaTime = Consts::LARGEST_TIME_STEP; _instance->_deltaTime = Consts::LARGEST_TIME_STEP;
}
_instance->_last = t; _instance->_last = t;
if(_instance->_deltaTime > 10000) if (_instance->_deltaTime > 10000) {
return; return;
}
_instance->_fpsCounter++; _instance->_fpsCounter++;
if (t - _instance->_fpsStart > _instance->_fpsCountTime) { if (t - _instance->_fpsStart > _instance->_fpsCountTime) {

View File

@ -30,14 +30,19 @@ private:
public: public:
Time(const Time &) = delete; Time(const Time &) = delete;
Time &operator=(Time &) = delete; Time &operator=(Time &) = delete;
static int fps(); static int fps();
static double time(); static double time();
static double deltaTime(); static double deltaTime();
static void update(); static void update();
static void init(); static void init();
static void free(); static void free();
}; };

View File

@ -8,5 +8,8 @@
using namespace std; using namespace std;
Ak47::Ak47() : Weapon(100, 30, 3.0, 0.1, 300, 2.0, ShooterConsts::AK47_FIRE_SOUND, ShooterConsts::AK47_RELOAD_SOUND, ObjectNameTag("ak47"), ShooterConsts::AK47_OBJ, Vec3D{3, 3, 3}, Vec3D{-2.2, 1.0, 1.3}, Vec3D{0, Consts::PI, 0}) { Ak47::Ak47() : Weapon(100, 30, 3.0, 0.1, 300, 2.0,
ShooterConsts::AK47_FIRE_SOUND, ShooterConsts::AK47_RELOAD_SOUND,
ObjectNameTag("ak47"), ShooterConsts::AK47_OBJ,
Vec3D{3, 3, 3}, Vec3D{-2.2, 1.0, 1.3},Vec3D{0, Consts::PI, 0}) {
} }

View File

@ -10,7 +10,11 @@
class Gold_Ak47 final : public Weapon { class Gold_Ak47 final : public Weapon {
public: public:
explicit Gold_Ak47() : Weapon(200, 60, 1.5, 0.05, 600, 1.0, ShooterConsts::GOLD_AK47_FIRE_SOUND, ShooterConsts::GOLD_AK47_RELOAD_SOUND, ObjectNameTag("gold_ak47"), ShooterConsts::GOLD_AK47_OBJ, Vec3D{3, 3, 3}, Vec3D{-2.2, 1.0, 1.3}, Vec3D{0, Consts::PI, 0}) { explicit Gold_Ak47() : Weapon(200, 60, 1.5, 0.05, 600, 1.0,
ShooterConsts::GOLD_AK47_FIRE_SOUND,
ShooterConsts::GOLD_AK47_RELOAD_SOUND, ObjectNameTag("gold_ak47"),
ShooterConsts::GOLD_AK47_OBJ, Vec3D{3, 3, 3}, Vec3D{-2.2, 1.0, 1.3},
Vec3D{0, Consts::PI, 0}) {
} }
}; };

View File

@ -8,5 +8,8 @@
using namespace std; using namespace std;
Gun::Gun() : Weapon(30, 6, 2.0, 0.3, 800, 3.0, ShooterConsts::GUN_FIRE_SOUND, ShooterConsts::GUN_RELOAD_SOUND, ObjectNameTag("gun"), ShooterConsts::GUN_OBJ, Vec3D{3, 3, 3}, Vec3D{-1.8, 1.3, 1.8}, Vec3D{0, Consts::PI, 0}) { Gun::Gun() : Weapon(30, 6, 2.0, 0.3, 800, 3.0,
ShooterConsts::GUN_FIRE_SOUND, ShooterConsts::GUN_RELOAD_SOUND, ObjectNameTag("gun"),
ShooterConsts::GUN_OBJ, Vec3D{3, 3, 3},
Vec3D{-1.8, 1.3, 1.8}, Vec3D{0, Consts::PI, 0}) {
} }

View File

@ -6,5 +6,8 @@
#include "Rifle.h" #include "Rifle.h"
#include "../ShooterConsts.h" #include "../ShooterConsts.h"
Rifle::Rifle() : Weapon(5, 1, 1.0, 1.0, 30000, 0.5, ShooterConsts::RIFLE_FIRE_SOUND, ShooterConsts::RIFLE_RELOAD_SOUND, ObjectNameTag("rifle"), ShooterConsts::RIFLE_OBJ, Vec3D{3, 3, 3}, Vec3D{-2.3, 1, 1.3}, Vec3D{0, Consts::PI, 0}) { Rifle::Rifle() : Weapon(5, 1, 1.0, 1.0, 30000, 0.5,
ShooterConsts::RIFLE_FIRE_SOUND, ShooterConsts::RIFLE_RELOAD_SOUND,
ObjectNameTag("rifle"), ShooterConsts::RIFLE_OBJ, Vec3D{3, 3, 3},
Vec3D{-2.3, 1, 1.3},Vec3D{0, Consts::PI, 0}) {
} }

View File

@ -4,16 +4,18 @@
#include "../engine/ResourceManager.h" #include "../engine/ResourceManager.h"
#include "Shotgun.h" #include "Shotgun.h"
#include "../engine/animation/AFunction.h"
#include "../ShooterConsts.h" #include "../ShooterConsts.h"
using namespace std; using namespace std;
Shotgun::Shotgun() : Weapon(15, 1, 1.0, 1.0, 400, 5.0, ShooterConsts::SHOTGUN_FIRE_SOUND, ShooterConsts::SHOTGUN_RELOAD_SOUND, ObjectNameTag("shotgun"), ShooterConsts::SHOTGUN_OBJ, Vec3D{3, 3, 3}, Vec3D{-1.95, 0.8, 1.5}, Vec3D{0, Consts::PI, 0}) { Shotgun::Shotgun() : Weapon(15, 1, 1.0, 1.0, 400, 5.0, ShooterConsts::SHOTGUN_FIRE_SOUND,
ShooterConsts::SHOTGUN_RELOAD_SOUND, ObjectNameTag("shotgun"), ShooterConsts::SHOTGUN_OBJ,
Vec3D{3, 3, 3}, Vec3D{-1.95, 0.8, 1.5}, Vec3D{0, Consts::PI, 0}) {
} }
std::map<ObjectNameTag, double> std::map<ObjectNameTag, double>
Shotgun::processFire(std::function<IntersectionInformation(const Vec3D&, const Vec3D&)> rayCastFunction, const Vec3D& position, const Vec3D& direction) { Shotgun::processFire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction) {
std::map<ObjectNameTag, double> damagedPlayers; std::map<ObjectNameTag, double> damagedPlayers;
for (int i = 0; i < 15; i++) { for (int i = 0; i < 15; i++) {

View File

@ -10,7 +10,10 @@
class Shotgun final : public Weapon { class Shotgun final : public Weapon {
public: public:
explicit Shotgun(); explicit Shotgun();
std::map<ObjectNameTag, double> processFire(std::function<IntersectionInformation(const Vec3D&, const Vec3D&)> rayCastFunction, const Vec3D& position, const Vec3D& direction) override;
std::map<ObjectNameTag, double>
processFire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction) override;
}; };

View File

@ -11,7 +11,14 @@
using namespace std; using namespace std;
Weapon::Weapon(int initialPack, int clipCapacity, double reloadTime, double fireDelay, double damage, double spreading, std::string fireSound, std::string reloadSound, ObjectNameTag weaponName, const std::string& objFileName, const Vec3D& s, const Vec3D& t, const Vec3D& r) : RigidBody(std::move(weaponName), objFileName), _initialPack(initialPack), _clipCapacity(clipCapacity), _reloadTime(reloadTime), _fireDelay(fireDelay), _damage(damage), _spreading(spreading), _fireSound(std::move(fireSound)), _reloadSound(std::move(reloadSound)) { Weapon::Weapon(int initialPack, int clipCapacity, double reloadTime, double fireDelay, double damage, double spreading,
std::string fireSound, std::string reloadSound, ObjectNameTag weaponName, const std::string &objFileName,
const Vec3D &s, const Vec3D &t, const Vec3D &r) : RigidBody(std::move(weaponName), objFileName),
_initialPack(initialPack), _clipCapacity(clipCapacity),
_reloadTime(reloadTime), _fireDelay(fireDelay),
_damage(damage), _spreading(spreading),
_fireSound(std::move(fireSound)),
_reloadSound(std::move(reloadSound)) {
_stockAmmo = _initialPack - _clipCapacity; _stockAmmo = _initialPack - _clipCapacity;
_clipAmmo = _clipCapacity; _clipAmmo = _clipCapacity;
@ -21,7 +28,8 @@ Weapon::Weapon(int initialPack, int clipCapacity, double reloadTime, double fire
translate(t); translate(t);
} }
FireInformation Weapon::fire(std::function<IntersectionInformation(const Vec3D&, const Vec3D&)> rayCastFunction, const Vec3D& position, const Vec3D& direction) { FireInformation Weapon::fire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction) {
if (_clipAmmo == 0) { if (_clipAmmo == 0) {
reload(); reload();
if (_clipAmmo == 0) { if (_clipAmmo == 0) {
@ -29,7 +37,8 @@ FireInformation Weapon::fire(std::function<IntersectionInformation(const Vec3D&,
} }
} }
if(_clipAmmo <= 0 || std::abs(Time::time() - _lastFireTime) < _fireDelay || std::abs(Time::time() - _lastReloadTime) < _reloadTime) { if (_clipAmmo <= 0 || std::abs(Time::time() - _lastFireTime) < _fireDelay ||
std::abs(Time::time() - _lastReloadTime) < _reloadTime) {
return FireInformation{std::map<ObjectNameTag, double>(), false}; return FireInformation{std::map<ObjectNameTag, double>(), false};
} }
@ -63,17 +72,23 @@ void Weapon::reload() {
_lastReloadTime = Time::time(); _lastReloadTime = Time::time();
} }
std::map<ObjectNameTag, double> Weapon::processFire(std::function<IntersectionInformation(const Vec3D&, const Vec3D&)> rayCastFunction, const Vec3D& position, const Vec3D& direction) { 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); return addTrace(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) { std::map<ObjectNameTag, double>
Weapon::addTrace(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &from, const Vec3D &directionTo) {
std::map<ObjectNameTag, double> damagedPlayers; std::map<ObjectNameTag, double> damagedPlayers;
double spreading = _spreading * ShooterConsts::FIRE_DISTANCE / 100; double spreading = _spreading * ShooterConsts::FIRE_DISTANCE / 100;
//generate random vector //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 * (double) rand() / RAND_MAX),
spreading * (1.0 - 2.0 * (double) rand() / RAND_MAX),
spreading * (1.0 - 2.0 * (double) rand() / RAND_MAX));
// damage player // damage player
auto rayCast = rayCastFunction(from, from + directionTo * ShooterConsts::FIRE_DISTANCE + randV); auto rayCast = rayCastFunction(from, from + directionTo * ShooterConsts::FIRE_DISTANCE + randV);
@ -83,7 +98,8 @@ std::map<ObjectNameTag, double> Weapon::addTrace(std::function<IntersectionInfor
// 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() + -lookAt() * ShooterConsts::FIRE_DISTANCE + randV; Vec3D lineTo = rayCast.intersected ? rayCast.pointOfIntersection : position() +
-lookAt() * ShooterConsts::FIRE_DISTANCE + randV;
_addTraceCallBack(lineFrom, lineTo); _addTraceCallBack(lineFrom, lineTo);
return damagedPlayers; return damagedPlayers;

View File

@ -40,13 +40,23 @@ private:
std::function<void(const Vec3D &, const Vec3D &)> _addTraceCallBack; std::function<void(const Vec3D &, const Vec3D &)> _addTraceCallBack;
protected: protected:
std::map<ObjectNameTag, double> addTrace(std::function<IntersectionInformation(const Vec3D&, const Vec3D&)> rayCastFunction, const Vec3D& position, const Vec3D& direction); std::map<ObjectNameTag, double>
virtual std::map<ObjectNameTag, double> processFire(std::function<IntersectionInformation(const Vec3D&, const Vec3D&)> rayCastFunction, const Vec3D& position, const Vec3D& direction); addTrace(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction);
virtual std::map<ObjectNameTag, double>
processFire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction,
const Vec3D &position, const Vec3D &direction);
public: public:
Weapon(int initialPack, int clipCapacity, double reloadTime, double fireDelay, double damage, double spreading, std::string fireSound, std::string reloadSound, ObjectNameTag weaponName, const std::string& objFileName, const Vec3D& s, const Vec3D& t, const Vec3D& r); Weapon(int initialPack, int clipCapacity, double reloadTime, double fireDelay, double damage, double spreading,
std::string fireSound, std::string reloadSound, ObjectNameTag weaponName, const std::string &objFileName,
const Vec3D &s, const Vec3D &t, const Vec3D &r);
FireInformation
fire(std::function<IntersectionInformation(const Vec3D &, const Vec3D &)> rayCastFunction, const Vec3D &position,
const Vec3D &direction);
FireInformation fire(std::function<IntersectionInformation(const Vec3D&, const Vec3D&)> rayCastFunction, const Vec3D& position, const Vec3D& direction);
void reload(); void reload();
[[nodiscard]] std::pair<double, double> balance() const { return std::make_pair(_clipAmmo, _stockAmmo); } [[nodiscard]] std::pair<double, double> balance() const { return std::make_pair(_clipAmmo, _stockAmmo); }