Compare commits
	
		
			16 Commits
		
	
	
		
			5fdae769e2
			...
			master
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 3729ece918 | |||
| 0536f9fb11 | |||
| 3a526edcf4 | |||
| 66dc91dab3 | |||
| 3e3769f912 | |||
| dc2c106bad | |||
| fc8217a608 | |||
| 1b79d946c3 | |||
| 54fab0ad23 | |||
| 9949ec80fb | |||
| 711fc4c93d | |||
| 06a1e41dc8 | |||
| 93fda88d75 | |||
| 13ea246990 | |||
| 50c9bd68fc | |||
| 5ba62b5312 | 
| @@ -3,7 +3,6 @@ set(PROJECT_NAME "Client") | ||||
| project(${PROJECT_NAME}) | ||||
|  | ||||
| find_package(Vulkan REQUIRED) | ||||
| find_package(OpenSSL REQUIRED) | ||||
|  | ||||
| include(Shaders.cmake) | ||||
| include(FetchContent) | ||||
| @@ -48,6 +47,14 @@ FetchContent_Declare( | ||||
| ) | ||||
| FetchContent_MakeAvailable(ASSIMP) | ||||
|  | ||||
| FetchContent_Declare( | ||||
|     JSONCPP | ||||
|     GIT_REPOSITORY "https://github.com/open-source-parsers/jsoncpp.git" | ||||
|     GIT_TAG "1.9.6" | ||||
|     GIT_SHALLOW ON | ||||
| ) | ||||
| FetchContent_MakeAvailable(JSONCPP) | ||||
|  | ||||
| file(GLOB_RECURSE Sources CONFIGURE_DEPENDS | ||||
|     "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp" | ||||
| ) | ||||
| @@ -59,8 +66,7 @@ target_link_libraries(${PROJECT_NAME} PRIVATE glfw) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE Microsoft.GSL::GSL) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE spdlog) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE assimp::assimp) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE OpenSSL::Crypto) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE OpenSSL::SSL) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE jsoncpp_static) | ||||
|  | ||||
| if(WIN32) | ||||
|     target_link_libraries(${PROJECT_NAME} PRIVATE ws2_32) | ||||
| @@ -107,3 +113,17 @@ add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD | ||||
|     "$<TARGET_FILE_DIR:${PROJECT_NAME}>" | ||||
|     COMMENT "Copying spdlog library files and symlinks to output directory" | ||||
| ) | ||||
|  | ||||
| add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD | ||||
|     COMMAND ${CMAKE_COMMAND} -E copy_if_different | ||||
|     "$<TARGET_FILE:jsoncpp_static>" | ||||
|     "$<TARGET_FILE_DIR:${PROJECT_NAME}>" | ||||
|     COMMENT "Copying jsoncpp DLL/so to output directory" | ||||
| ) | ||||
|  | ||||
| add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD | ||||
|     COMMAND ${CMAKE_COMMAND} -E copy_directory | ||||
|     "$<TARGET_FILE_DIR:jsoncpp_static>" | ||||
|     "$<TARGET_FILE_DIR:${PROJECT_NAME}>" | ||||
|     COMMENT "Copying jsoncpp library files and symlinks to output directory" | ||||
| ) | ||||
| @@ -1,8 +1,11 @@ | ||||
| #pragma once | ||||
| #include "utils/snowflake.h" | ||||
|  | ||||
| extern std::uint8_t CLIENTID; | ||||
|  | ||||
| namespace veng { | ||||
| class Engine; | ||||
| } | ||||
|  | ||||
| void BeginPlay(veng::Engine& engine); | ||||
| void BeginPlay(veng::Engine& engine, utils::Snowflake playerID); | ||||
| void Tick(veng::Engine& engine, std::float_t delta_time); | ||||
|   | ||||
| @@ -1,64 +1,129 @@ | ||||
| #include "asteroid/game.h" | ||||
|  | ||||
| #include "vulkan_engine/vulkan/engine.h" | ||||
| #include "utils/ConfigManager.h" | ||||
|  | ||||
| void BeginPlay(veng::Engine& engine) { | ||||
|   veng::Model* const player = engine.SpawnModel("player", "player"); | ||||
| void BeginPlay(veng::Engine& engine, utils::Snowflake playerID) { | ||||
|   std::random_device rd; | ||||
|   std::mt19937 gen = std::mt19937(rd()); | ||||
|   std::uniform_real_distribution<float> jitterDist = | ||||
|       std::uniform_real_distribution<float>(-2, 2); | ||||
|  | ||||
|   std::shared_ptr<veng::Model> const player = | ||||
|       engine.SpawnLifedModel("player", "player", -1); | ||||
|   { | ||||
|     std::lock_guard lock(player->modding); | ||||
|     if (playerID.snowflake != 0) | ||||
|       player->ID = playerID; | ||||
|     player->position = glm::vec3(jitterDist(gen), jitterDist(gen), 0.f); | ||||
|     player->scale = glm::vec3(.02f); | ||||
|     player->colision = true; | ||||
|   player->OnColision = [](veng::Model* self, veng::Model* other) { | ||||
|     if (other->owner == self) return; | ||||
|     spdlog::info("{} and {} is nearby.", (void*)self, (void*)other); | ||||
|     player->OnColision = [](utils::ThreadPool* thread_pool, | ||||
|                             std::shared_ptr<veng::Model> self, | ||||
|                             std::shared_ptr<veng::Model> other) { | ||||
|       auto self_owner = self->owner.lock(); | ||||
|       auto other_owner = other->owner.lock(); | ||||
|       if (other_owner == nullptr || self_owner == nullptr) return; | ||||
|       if (other_owner->ID == self->ID) return; | ||||
|       spdlog::info("[{}:{}] and [{}:{}] is nearby.", self->name, | ||||
|                    self->ID.snowflake, other->name, other->ID.snowflake); | ||||
|  | ||||
|     spdlog::info("{} 's owner: {}", (void*)self, (void*)self->owner); | ||||
|     spdlog::info("{} 's owner: {}", (void*)other, (void*)other->owner); | ||||
|       spdlog::info("[{}:{}] 's owner: [{}:{}]", self->name, self->ID.snowflake, | ||||
|                    self_owner->name, self_owner->ID.snowflake); | ||||
|       spdlog::info("[{}:{}] 's owner: [{}:{}]", other->name, | ||||
|                    other->ID.snowflake, other_owner->name, | ||||
|                    other_owner->ID.snowflake); | ||||
|  | ||||
|       other->colision = false; | ||||
|       other->visible = false; | ||||
|       other->shouldBeDestroyed = true; | ||||
|     }; | ||||
|   veng::Model* const player_flame = | ||||
|       engine.SpawnModel("player_flame", "player_flame"); | ||||
|   } | ||||
|  | ||||
|   std::shared_ptr<veng::Model> const player_flame = | ||||
|       engine.SpawnLifedModel("player_flame", "player_flame", -1); | ||||
|   { | ||||
|     std::lock_guard lock(player_flame->modding); | ||||
|     player_flame->scale = player->scale; | ||||
|     player_flame->colision = false; | ||||
|     player_flame->networkReplicated = true; | ||||
|     player_flame->needsUpdate = true; | ||||
|   } | ||||
|  | ||||
|   spdlog::info("player addr: {}", (void*)player); | ||||
|  | ||||
|   veng::Model* const other_player = engine.SpawnModel("player", "other_player"); | ||||
|   /*std::shared_ptr<veng::Model> const other_player = | ||||
|       engine.SpawnLifedModel("player", "other_player", -1); | ||||
|   { | ||||
|     std::lock_guard lock(other_player->modding); | ||||
|     other_player->position = glm::vec3(1.f, 0.f, 0.f); | ||||
|     other_player->scale = glm::vec3(.02f); | ||||
|   other_player->colision = true; | ||||
|   other_player->OnColision = [](veng::Model* self, veng::Model* other) { | ||||
|     if (other->owner == self) return; | ||||
|     spdlog::info("{} and {} is nearby.", (void*)self, (void*)other); | ||||
|     player->colision = true; | ||||
|     player->OnColision = [](utils::ThreadPool* thread_pool, | ||||
|                             std::shared_ptr<veng::Model> self, | ||||
|                             std::shared_ptr<veng::Model> other) { | ||||
|       auto self_owner = self->owner.lock(); | ||||
|       auto other_owner = other->owner.lock(); | ||||
|       if (other_owner == nullptr || self_owner == nullptr) return; | ||||
|       if (other_owner->ID == self->ID) return; | ||||
|       spdlog::info("[{}:{}] and [{}:{}] is nearby.", self->name, | ||||
|                    self->ID.snowflake, other->name, other->ID.snowflake); | ||||
|  | ||||
|     spdlog::info("{} 's owner: {}", (void*)self, (void*)self->owner); | ||||
|     spdlog::info("{} 's owner: {}", (void*)other, (void*)other->owner); | ||||
|       spdlog::info("[{}:{}] 's owner: [{}:{}]", self->name, self->ID.snowflake, | ||||
|                    self_owner->name, self_owner->ID.snowflake); | ||||
|       spdlog::info("[{}:{}] 's owner: [{}:{}]", other->name, | ||||
|                    other->ID.snowflake, other_owner->name, | ||||
|                    other_owner->ID.snowflake); | ||||
|  | ||||
|       other->colision = false; | ||||
|       other->visible = false; | ||||
|       other->shouldBeDestroyed = true; | ||||
|     }; | ||||
|     other_player->colision = true; | ||||
|   }*/ | ||||
|  | ||||
|   spdlog::info("other player addr: {}", (void*)other_player); | ||||
|  | ||||
|   veng::Model* const camera_lag = engine.SpawnModel("", "camera_lag"); | ||||
|   std::shared_ptr<veng::Model> const camera_lag = | ||||
|       engine.SpawnLifedModel("", "camera_lag", -1); | ||||
|   { | ||||
|     std::lock_guard lock(camera_lag->modding); | ||||
|     camera_lag->colision = false; | ||||
|     camera_lag->position = player->position; | ||||
|  | ||||
|   veng::Model* const background = engine.SpawnModel("", "background"); | ||||
|   background->colision = false; | ||||
|   background->position = {background->position.x, background->position.y, 30.f}; | ||||
|   background->scale *= 100; | ||||
|  | ||||
|   veng::Model* const background0 = | ||||
|       engine.SpawnModel("background", "background0"); | ||||
|   background0->scale = background->scale; | ||||
|   veng::Model* const background1 = | ||||
|       engine.SpawnModel("background", "background1"); | ||||
|   background1->scale = background->scale; | ||||
|   veng::Model* const background2 = | ||||
|       engine.SpawnModel("background", "background2"); | ||||
|   background2->scale = background->scale; | ||||
|   veng::Model* const background3 = | ||||
|       engine.SpawnModel("background", "background3"); | ||||
|   background3->scale = background->scale; | ||||
|   } | ||||
|  | ||||
|   std::shared_ptr<veng::Model> const background = | ||||
|       engine.SpawnLifedModel("", "background", -1); | ||||
|   { | ||||
|     std::lock_guard lock(background->modding); | ||||
|     background->colision = false; | ||||
|     background->position = {background->position.x, background->position.y, | ||||
|                             30.f}; | ||||
|     background->scale *= 100; | ||||
|     background->networkReplicated = false; | ||||
|   } | ||||
|  | ||||
|   std::shared_ptr<veng::Model> const background0 = | ||||
|       engine.SpawnLifedModel("background", "background0", -1); | ||||
|   { | ||||
|     std::lock_guard lock(background0->modding); | ||||
|     background0->scale = background->scale; | ||||
|     background0->networkReplicated = false; | ||||
|   } | ||||
|   std::shared_ptr<veng::Model> const background1 = | ||||
|       engine.SpawnLifedModel("background", "background1", -1); | ||||
|   { | ||||
|     std::lock_guard lock(background1->modding); | ||||
|     background1->scale = background->scale; | ||||
|     background1->networkReplicated = false; | ||||
|   } | ||||
|   std::shared_ptr<veng::Model> const background2 = | ||||
|       engine.SpawnLifedModel("background", "background2", -1); | ||||
|   { | ||||
|     std::lock_guard lock(background2->modding); | ||||
|     background2->scale = background->scale; | ||||
|     background2->networkReplicated = false; | ||||
|   } | ||||
|   std::shared_ptr<veng::Model> const background3 = | ||||
|       engine.SpawnLifedModel("background", "background3", -1); | ||||
|   { | ||||
|     std::lock_guard lock(background3->modding); | ||||
|     background3->scale = background->scale; | ||||
|     background3->networkReplicated = false; | ||||
|   } | ||||
| } | ||||
|   | ||||
| @@ -3,107 +3,89 @@ | ||||
| #include "glfw/glfw_monitor.h" | ||||
| #include "glfw/glfw_window.h" | ||||
| #include "socket/iocp.h" | ||||
| #include "socket/packet.h" | ||||
| #include "socket/tcp_socket.h" | ||||
| #include "socket/udp_socket.h" | ||||
| #include "socket/wsa_manager.h" | ||||
| #include "utils/ConfigManager.h" | ||||
| #include "utils/log.h" | ||||
| #include "utils/snowflake.h" | ||||
| #include "utils/utils.h" | ||||
| #include "vulkan_engine/vulkan/engine.h" | ||||
| #include "vulkan_engine/vulkan/graphics.h" | ||||
|  | ||||
| std::uint8_t CLIENTID = 0; | ||||
|  | ||||
| std::int32_t main(std::int32_t argc, gsl::zstring* argv) { | ||||
|   Network::WSAManager wsamanager; | ||||
|  #if !defined(NDEBUG) | ||||
|    utils::setDefaultLogger(spdlog::level::level_enum::debug, "log.log", 1024, | ||||
|    2); | ||||
|  #endif | ||||
|  | ||||
|   auto config = utils::ConfigManager::load(); | ||||
|   utils::setDefaultLogger(config.logLevel, config.logFileName, | ||||
|                           config.logfileSize, config.logfileCount); | ||||
|  | ||||
|   utils::ThreadPool tp(0); | ||||
|   Network::IOCP iocp; | ||||
|   iocp.init(&tp, SessionProtocol::TCP); | ||||
|  | ||||
|   Network::Address addr; | ||||
|    in6_addr in6addr; | ||||
|  | ||||
|    addr.set(AF_INET6, "::1", 9010); | ||||
|   addr.set(config.ipVersion, config.IP, config.Port); | ||||
|  | ||||
|    Network::TCPSocket sock; | ||||
|    sock.init(AF_INET6); | ||||
|    if (sock.connect(addr) == INVALID_SOCKET) { | ||||
|   std::shared_ptr<Network::TCPSocket> TCPSock = | ||||
|       std::make_shared<Network::TCPSocket>(config.ipVersion); | ||||
|   if (TCPSock->connect(addr) == INVALID_SOCKET) { | ||||
|     spdlog::error("connect()"); | ||||
|     std::exit(EXIT_FAILURE); | ||||
|   } | ||||
|   iocp.registerSocket(TCPSock); | ||||
|  | ||||
|    Network::IOCPPASSINDATA* data = new Network::IOCPPASSINDATA(16 * 1024); | ||||
|    data->socket = std::make_shared<Network::TCPSocket>(sock); | ||||
|    data->IOCPInstance = &iocp; | ||||
|    iocp.registerSocket(data); | ||||
|   auto result = iocp.recv(TCPSock, 14); | ||||
|   auto header_serialized = utils::CvtListToVector(result.get()); | ||||
|  | ||||
|    std::vector<Network::IOCPPASSINDATA*> send_data; | ||||
|    data->event = Network::IOCPEVENT::WRITE; | ||||
|    data->wsabuf.buf[0] = 'a'; | ||||
|    data->wsabuf.buf[1] = 'b'; | ||||
|    data->wsabuf.buf[2] = ' '; | ||||
|    data->wsabuf.len = 3; | ||||
|    send_data.push_back(data); | ||||
|    Network::IOCPPASSINDATA* data2 = new Network::IOCPPASSINDATA(16 * 1024); | ||||
|    data2->wsabuf.buf[0] = 'b'; | ||||
|    data2->wsabuf.buf[1] = 'a'; | ||||
|    data2->wsabuf.buf[2] = '\0'; | ||||
|    data2->wsabuf.len = 3; | ||||
|    send_data.push_back(data2); | ||||
|    iocp.send(sock.sock, &send_data); | ||||
|   Packet::Header header; | ||||
|   header.Deserialize(header_serialized); | ||||
|  | ||||
|    Network::IOCPPASSINDATA* recv_data = new Network::IOCPPASSINDATA(16 * 1024); | ||||
|    recv_data->socket = std::make_shared<Network::TCPSocket>(sock); | ||||
|    recv_data->IOCPInstance = &iocp; | ||||
|    while (!iocp.recv(recv_data)); // 어떤 데이터를 읽는걸 보장받고 싶다면 그냥 스린락 걸어버리기. | ||||
|  | ||||
|    spdlog::info("recv_data: {}", recv_data->wsabuf.buf); | ||||
|  | ||||
|    std::vector<Network::IOCPPASSINDATA*> send_data2; | ||||
|    data->event = Network::IOCPEVENT::WRITE; | ||||
|    data->wsabuf.buf[0] = 'c'; | ||||
|    data->wsabuf.buf[1] = 'd'; | ||||
|    data->wsabuf.buf[2] = ' '; | ||||
|    data->wsabuf.len = 3; | ||||
|    send_data2.push_back(data); | ||||
|    data2 = new Network::IOCPPASSINDATA(16 * 1024); | ||||
|    data2->wsabuf.buf[0] = 'd'; | ||||
|    data2->wsabuf.buf[1] = 'c'; | ||||
|    data2->wsabuf.buf[2] = '\0'; | ||||
|    data2->wsabuf.len = 3; | ||||
|    send_data2.push_back(data2); | ||||
|    iocp.send(sock.sock, &send_data2); | ||||
|  | ||||
|    recv_data = new Network::IOCPPASSINDATA(16 * 1024); | ||||
|    recv_data->socket = std::make_shared<Network::TCPSocket>(sock); | ||||
|    recv_data->IOCPInstance = &iocp; | ||||
|    while (!iocp.recv(recv_data));  // 어떤 데이터를 읽는걸 보장받고 싶다면 그냥 | ||||
|                                    // 스린락 걸어버리기. | ||||
|  | ||||
|    spdlog::info("recv_data: {}", recv_data->wsabuf.buf); | ||||
|   result = iocp.recv(TCPSock, header.body_length); | ||||
|   std::vector<char> data = utils::CvtListToVector(result.get()); | ||||
|   ::memcpy(&CLIENTID, data.data(), 1);  // id 받기 | ||||
|  | ||||
|   const veng::GlfwInitialization _glfw; | ||||
|  | ||||
|    veng::Window window("Vulkan Engine", {800, 600}); | ||||
|   veng::Window window("Asteroid", {800, 600}); | ||||
|   window.TryMoveToMonitor(0); | ||||
|  | ||||
|   veng::Graphics graphics(&window); | ||||
|    veng::Engine engine(&graphics, &tp); | ||||
|   veng::Engine engine(&graphics, &tp, &iocp); | ||||
|  | ||||
|   engine.LoadModelAsset("assets/player.fbx", "player"); | ||||
|   engine.LoadModelAsset("assets/player_flame.fbx", "player_flame"); | ||||
|   engine.LoadModelAsset("assets/bullet.fbx", "bullet"); | ||||
|   engine.LoadModelAsset("assets/background.fbx", "background"); | ||||
|  | ||||
|    engine.BeginPlay = BeginPlay; | ||||
|   engine.BeginPlay = [ID64 = config.playerid](veng::Engine& engine) { | ||||
|     utils::Snowflake ID; | ||||
|     ID.snowflake = ID64; | ||||
|     BeginPlay(engine, ID); | ||||
|   }; | ||||
|   engine.Tick = Tick; | ||||
|  | ||||
|   engine.init(); | ||||
|  | ||||
|   std::shared_ptr<veng::Model> const player = engine.GetSpawnedObject("player"); | ||||
|   config.playerid = player->ID.snowflake; | ||||
|   utils::ConfigManager::save(config); | ||||
|  | ||||
|   tp.enqueueJob( | ||||
|       [engine = &engine, TCPSock](utils::ThreadPool* tp, std::uint32_t __) { | ||||
|         engine->ResponseToServerAndRefresh(TCPSock); | ||||
|       }, | ||||
|       0); | ||||
|  | ||||
|   while (!window.ShouldClose()) { | ||||
|     glfwPollEvents(); | ||||
|  | ||||
|     engine.Update(); | ||||
|     engine.NetUpdate(TCPSock); | ||||
|   } | ||||
|  | ||||
|   return EXIT_SUCCESS; | ||||
|   | ||||
| @@ -5,15 +5,26 @@ | ||||
| void Tick(veng::Engine& engine, std::float_t delta_time) { | ||||
|   static std::float_t bullet_cooldown = 0.f; | ||||
|  | ||||
|   veng::Model* const player = engine.GetSpawnedObject("player"); | ||||
|   veng::Model* const player_flame = engine.GetSpawnedObject("player_flame"); | ||||
|   veng::Model* const camera_lag = engine.GetSpawnedObject("camera_lag"); | ||||
|   std::shared_ptr<veng::Model> const player = engine.GetSpawnedObject("player"); | ||||
|   std::shared_ptr<veng::Model> const player_flame = engine.GetSpawnedObject("player_flame"); | ||||
|   std::shared_ptr<veng::Model> const camera_lag = engine.GetSpawnedObject("camera_lag"); | ||||
|  | ||||
|   veng::Model* const background = engine.GetSpawnedObject("background"); | ||||
|   veng::Model* const background0 = engine.GetSpawnedObject("background0"); | ||||
|   veng::Model* const background1 = engine.GetSpawnedObject("background1"); | ||||
|   veng::Model* const background2 = engine.GetSpawnedObject("background2"); | ||||
|   veng::Model* const background3 = engine.GetSpawnedObject("background3"); | ||||
|   std::shared_ptr<veng::Model> const background = engine.GetSpawnedObject("background"); | ||||
|   std::shared_ptr<veng::Model> const background0 = engine.GetSpawnedObject("background0"); | ||||
|   std::shared_ptr<veng::Model> const background1 = engine.GetSpawnedObject("background1"); | ||||
|   std::shared_ptr<veng::Model> const background2 = engine.GetSpawnedObject("background2"); | ||||
|   std::shared_ptr<veng::Model> const background3 = engine.GetSpawnedObject("background3"); | ||||
|  | ||||
|   std::lock_guard<std::mutex> lock[] = { | ||||
|       std::lock_guard<std::mutex>(player->modding), | ||||
|       std::lock_guard<std::mutex>(player_flame->modding), | ||||
|       std::lock_guard<std::mutex>(camera_lag->modding), | ||||
|       std::lock_guard<std::mutex>(background->modding), | ||||
|       std::lock_guard<std::mutex>(background0->modding), | ||||
|       std::lock_guard<std::mutex>(background1->modding), | ||||
|       std::lock_guard<std::mutex>(background2->modding), | ||||
|       std::lock_guard<std::mutex>(background3->modding) | ||||
|   }; | ||||
|  | ||||
|   glm::vec3 forward = player->rotation * glm::vec3(0, 1, 0); | ||||
|   glm::vec3 right = player->rotation * glm::vec3(1, 0, 0); | ||||
| @@ -31,17 +42,38 @@ void Tick(veng::Engine& engine, std::float_t delta_time) { | ||||
|       (-stiffness * displacement - damping * camera_lag->linear_velocity) * | ||||
|       delta_time; | ||||
|  | ||||
|   /*camera_lag->linear_velocity = glm::vec3(0); | ||||
|   camera_lag->position = player->position;*/ | ||||
|  | ||||
|   engine.view = glm::lookAt( | ||||
|       glm::vec3(camera_lag->position.x, camera_lag->position.y, -5.f), | ||||
|       camera_lag->position, glm::vec3(0.f, -1.f, 0.f)); | ||||
|  | ||||
|   static bool w_laststate = false; | ||||
|   if (glfwGetKey(engine.vulkan_graphics->window->GetHandle(), GLFW_KEY_W) == | ||||
|       GLFW_PRESS) { | ||||
|     player->linear_acceleration = glm::normalize(forward) * 10.f; | ||||
|     player_flame->linear_velocity = player->linear_velocity; | ||||
|     player_flame->position = player->position; | ||||
|     player_flame->angular_velocity = player->angular_velocity; | ||||
|     player_flame->rotation = player->rotation; | ||||
|     player_flame->visible = true; | ||||
|  | ||||
|     if (!w_laststate) { | ||||
|       player->needsUpdate = true; | ||||
|       player_flame->needsUpdate = true; | ||||
|       player->updateRedundantCount = 0; | ||||
|       w_laststate = true; | ||||
|     } | ||||
|   } else { | ||||
|     player->linear_acceleration = forward * .0f; | ||||
|     player_flame->visible = false; | ||||
|     if (w_laststate) { | ||||
|       player->needsUpdate = true; | ||||
|       player_flame->needsUpdate = true; | ||||
|       player->updateRedundantCount = 0; | ||||
|       w_laststate = false; | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   if (bullet_cooldown > std::numeric_limits<std::float_t>::epsilon()) { | ||||
| @@ -53,28 +85,72 @@ void Tick(veng::Engine& engine, std::float_t delta_time) { | ||||
|       bullet_cooldown -= delta_time; | ||||
|     } else { | ||||
|       bullet_cooldown = .2f; | ||||
|       veng::Model* const bullet = | ||||
|       std::shared_ptr<veng::Model> const bullet = | ||||
|           engine.SpawnLifedModel("bullet", "bullet", 10.f); | ||||
|       bullet->linear_velocity = player->linear_velocity + forward * 10.f; | ||||
|       bullet->position = player->position + forward * player->scale.x * 10.f; | ||||
|       bullet->owner = player; | ||||
|       bullet->OwnerID = player->ID; | ||||
|       bullet->scale = player->scale; | ||||
|       bullet->colision = true; | ||||
|       bullet->OnColision = [](utils::ThreadPool* thread_pool, | ||||
|                               std::shared_ptr<veng::Model> self, | ||||
|                               std::shared_ptr<veng::Model> other) { | ||||
|         auto self_owner = self->owner.lock(); | ||||
|         auto other_owner = other->owner.lock(); | ||||
|         if (other_owner == nullptr || self_owner == nullptr) return; | ||||
|         if (other_owner->ID == self->ID) return; | ||||
|         spdlog::info("[{}:{}] and [{}:{}] is nearby.", self->name, | ||||
|                      self->ID.snowflake, other->name, other->ID.snowflake); | ||||
|  | ||||
|       spdlog::info("bullet address: {}", (void*)bullet); | ||||
|         spdlog::info("[{}:{}] 's owner: [{}:{}]", self->name, | ||||
|                      self->ID.snowflake, self_owner->name, | ||||
|                      self_owner->ID.snowflake); | ||||
|         spdlog::info("[{}:{}] 's owner: [{}:{}]", other->name, | ||||
|                      other->ID.snowflake, other_owner->name, | ||||
|                      other_owner->ID.snowflake); | ||||
|  | ||||
|         other->colision = false; | ||||
|         other->visible = false; | ||||
|         other->shouldBeDestroyed = true; | ||||
|       }; | ||||
|       bullet->networkReplicated = true; | ||||
|       bullet->needsUpdate = true; | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   static bool ad_laststate = false; | ||||
|   right = player->rotation * glm::vec3(0, 0, 1); | ||||
|   if (glfwGetKey(engine.vulkan_graphics->window->GetHandle(), GLFW_KEY_A) == | ||||
|       GLFW_PRESS) { | ||||
|     right = player->rotation * glm::vec3(0, 0, 1); | ||||
|     player->angular_velocity = right * 6.f; | ||||
|   } else if (glfwGetKey(engine.vulkan_graphics->window->GetHandle(), | ||||
|     if (!ad_laststate) { | ||||
|       player->needsUpdate = true; | ||||
|       player->updateRedundantCount = 1; | ||||
|       ad_laststate = true; | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   if (glfwGetKey(engine.vulkan_graphics->window->GetHandle(), | ||||
|                         GLFW_KEY_D) == GLFW_PRESS) { | ||||
|     right = player->rotation * glm::vec3(0, 0, 1); | ||||
|     player->angular_velocity = right * -6.f; | ||||
|   } else { | ||||
|     right = player->rotation * glm::vec3(0, 0, 1); | ||||
|     if (!ad_laststate) { | ||||
|       player->needsUpdate = true; | ||||
|       player->updateRedundantCount = 1; | ||||
|       ad_laststate = true; | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   if (glfwGetKey(engine.vulkan_graphics->window->GetHandle(), GLFW_KEY_A) == | ||||
|           GLFW_RELEASE && | ||||
|       glfwGetKey(engine.vulkan_graphics->window->GetHandle(), GLFW_KEY_D) == | ||||
|           GLFW_RELEASE) { | ||||
|     player->angular_velocity = right * 0.f; | ||||
|     if (ad_laststate) { | ||||
|       player->needsUpdate = true; | ||||
|       player->updateRedundantCount = 2; | ||||
|       ad_laststate = false; | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   player_flame->rotation = player->rotation; | ||||
|   | ||||
							
								
								
									
										60
									
								
								Client/src/utils/ConfigManager.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										60
									
								
								Client/src/utils/ConfigManager.cpp
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,60 @@ | ||||
| #include "Utils/ConfigManager.h" | ||||
|  | ||||
| #include <json/json.h> | ||||
|  | ||||
| #include <fstream> | ||||
| #include <iostream> | ||||
| #include <string> | ||||
|  | ||||
| namespace utils { | ||||
| Config ConfigManager::load() { | ||||
|   Config config; | ||||
|  | ||||
|   std::ifstream configfile("config.json", std::ifstream::binary); | ||||
|   if (!configfile.is_open()) { | ||||
|     std::ofstream defaultConfig("config.json", std::ios::out); | ||||
|     config.configJsonRoot["IP Version"] = AF_INET6; | ||||
|     config.configJsonRoot["IP"] = "::1"; | ||||
|     config.configJsonRoot["Port"] = 9010; | ||||
|     config.configJsonRoot["LogLevel"] = 1; | ||||
|     config.configJsonRoot["LogfileName"] = "log.log"; | ||||
|     config.configJsonRoot["LogfileSize"] = UINT32_MAX; | ||||
|     config.configJsonRoot["LogfileCount"] = 5; | ||||
|     config.configJsonRoot["PlayerID"] = 0; | ||||
|     defaultConfig << config.configJsonRoot; | ||||
|     defaultConfig.close(); | ||||
|     spdlog::critical( | ||||
|         "\"config.json\" is missing. Default configuration has been written."); | ||||
|   } | ||||
|   try { | ||||
|     if (configfile.is_open()) configfile >> config.configJsonRoot; | ||||
|  | ||||
|     config.ipVersion = config.configJsonRoot["IP Version"].asInt(); | ||||
|     if (config.ipVersion != AF_INET && config.ipVersion != AF_INET6) | ||||
|       throw std::runtime_error("Invalid IP Version."); | ||||
|  | ||||
|     config.IP = config.configJsonRoot["IP"].asCString(); | ||||
|  | ||||
|     config.Port = config.configJsonRoot["Port"].asInt(); | ||||
|     if (config.Port < 0 || config.Port > 65535) | ||||
|       throw std::runtime_error("Invalid listen port."); | ||||
|  | ||||
|     int ll_ = config.configJsonRoot["LogLevel"].asInt(); | ||||
|     if (ll_ >= 0 && ll_ < spdlog::level::n_levels) | ||||
|       config.logLevel = (spdlog::level::level_enum)ll_; | ||||
|     else | ||||
|       throw std::runtime_error("Invalid log level."); | ||||
|  | ||||
|     config.logFileName = config.configJsonRoot["LogfileName"].asCString(); | ||||
|     config.logfileSize = config.configJsonRoot["LogfileSize"].asUInt(); | ||||
|     config.logfileCount = config.configJsonRoot["LogfileCount"].asUInt(); | ||||
|  | ||||
|     config.playerid = config.configJsonRoot["PlayerID"].asUInt64(); | ||||
|   } catch (Json::RuntimeError e) { | ||||
|     spdlog::critical( | ||||
|         std::string(std::string("[Json Error: ]") + e.what()).c_str()); | ||||
|     std::exit(EXIT_FAILURE); | ||||
|   } | ||||
|   return config; | ||||
| } | ||||
| }  // namespace Chattr | ||||
| @@ -1,30 +0,0 @@ | ||||
| #include "vulkan_engine/asset/object/model.h" | ||||
|  | ||||
| #include "vulkan_engine/vulkan/graphics.h" | ||||
|  | ||||
| namespace veng { | ||||
|  | ||||
| Model::~Model() { | ||||
|   if (graphics_ == nullptr) return; | ||||
|  | ||||
|   graphics_->DestroyTexture(material.texture_handle); | ||||
|   graphics_->DestroyBuffer(vertex_buffer); | ||||
|   graphics_->DestroyBuffer(index_buffer); | ||||
| } | ||||
|  | ||||
| void veng::Model::Update(float dt) { | ||||
|   linear_velocity += linear_acceleration * dt; | ||||
|   position += linear_velocity * dt; | ||||
|  | ||||
|   angular_velocity += angular_acceleration * dt; | ||||
|   if (glm::length(angular_velocity) > 1e-6f) { | ||||
|     rotation = | ||||
|         glm::normalize(glm::rotate(rotation, glm::length(angular_velocity * dt), | ||||
|                                    glm::normalize(angular_velocity))); | ||||
|   } | ||||
|  | ||||
|   transform = glm::translate(glm::mat4(1.0f), position) * | ||||
|                glm::mat4_cast(rotation) * glm::scale(glm::mat4(1.0f), scale); | ||||
| } | ||||
|  | ||||
| }  // namespace veng | ||||
| @@ -1,177 +0,0 @@ | ||||
| #include "vulkan_engine/vulkan/engine.h" | ||||
|  | ||||
| #include "precomp.h" | ||||
|  | ||||
| namespace veng { | ||||
|  | ||||
| void Engine::init() { | ||||
|   glm::ivec2 window_size_ = vulkan_graphics->window->GetFramebufferSize(); | ||||
|   view = glm::lookAt(glm::vec3(0.f, 0.f, -5.f), glm::vec3(0.f, 0.f, 0.f), | ||||
|                      glm::vec3(0.f, -1.f, 0.f)); | ||||
|   projection = glm::perspective( | ||||
|       glm::radians(103.f), | ||||
|       (std::float_t)window_size_.x / (std::float_t)window_size_.y, 0.1f, | ||||
|       1000.f); | ||||
|   vulkan_graphics->SetViewProjection(view, projection); | ||||
|  | ||||
|   if (BeginPlay != nullptr) BeginPlay(*this); | ||||
| } | ||||
|  | ||||
| void Engine::LoadModelAsset(std::string path, std::string name) { | ||||
|   veng::Model model(vulkan_graphics); | ||||
|   asset_loader_.setPath(path); | ||||
|   asset_loader_.loadModel(model); | ||||
|  | ||||
|   model.vertex_buffer = vulkan_graphics->CreateVertexBuffer(model.vertices); | ||||
|   model.index_buffer = vulkan_graphics->CreateIndexBuffer(model.indices); | ||||
|   model.material.texture_handle = | ||||
|       vulkan_graphics->CreateTexture(asset_loader_.readTexture()); | ||||
|   model_assets_[name] = std::move(model); | ||||
| } | ||||
|  | ||||
| const Model* Engine::GetStaticModel(std::string name) { | ||||
|   if (model_assets_.find(name) != model_assets_.end()) | ||||
|     return &model_assets_[name]; | ||||
|   return nullptr; | ||||
| } | ||||
|  | ||||
| Model* Engine::SpawnModel(std::string asset_name, std::string name) { | ||||
|   if (asset_name == "") { | ||||
|     Model model_to_spawn(nullptr); | ||||
|     model_to_spawn.visible = false; | ||||
|     dynamic_immortal_models_[name] = std::move(model_to_spawn); | ||||
|     return &dynamic_immortal_models_[name]; | ||||
|   } | ||||
|  | ||||
|   if (dynamic_immortal_models_.find(name) == dynamic_immortal_models_.end()) { | ||||
|     Model model_to_spawn(*GetStaticModel(asset_name)); | ||||
|     dynamic_immortal_models_[name] = std::move(model_to_spawn); | ||||
|     return &dynamic_immortal_models_[name]; | ||||
|   } | ||||
|  | ||||
|   std::uint32_t i = 0; | ||||
|   for (i = 0; i < std::numeric_limits<std::uint32_t>::max();) { | ||||
|     if (dynamic_immortal_models_.find(name + std::to_string(i)) == | ||||
|         dynamic_immortal_models_.end()) { | ||||
|       Model model_to_spawn(*GetStaticModel(asset_name)); | ||||
|       dynamic_immortal_models_[name + std::to_string(i)] = | ||||
|           std::move(model_to_spawn); | ||||
|       break; | ||||
|     } | ||||
|     i++; | ||||
|   } | ||||
|  | ||||
|   if (i == std::numeric_limits<std::uint32_t>::max() - 1) | ||||
|     return nullptr; | ||||
|   else | ||||
|     return &dynamic_immortal_models_[name + std::to_string(i)]; | ||||
| } | ||||
|  | ||||
| Model* Engine::SpawnLifedModel(std::string asset_name, std::string name, | ||||
|                                std::float_t lifespan) { | ||||
|   if (asset_name == "") { | ||||
|     Model model_to_spawn(nullptr); | ||||
|     model_to_spawn.visible = false; | ||||
|     dynamic_models_[name] = std::make_pair(std::move(model_to_spawn), lifespan); | ||||
|     return &dynamic_models_[name].first; | ||||
|   } | ||||
|   if (dynamic_models_.find(name) == dynamic_models_.end()) { | ||||
|     Model model_to_spawn(*GetStaticModel(asset_name)); | ||||
|     dynamic_models_[name] = std::make_pair(std::move(model_to_spawn), lifespan); | ||||
|     return &dynamic_models_[name].first; | ||||
|   } | ||||
|  | ||||
|   std::uint32_t i = 0; | ||||
|   for (i = 0; i < std::numeric_limits<std::uint32_t>::max();) { | ||||
|     if (dynamic_models_.find(name + std::to_string(i)) == | ||||
|         dynamic_models_.end()) { | ||||
|       Model model_to_spawn(*GetStaticModel(asset_name)); | ||||
|       dynamic_models_[name + std::to_string(i)] = | ||||
|           std::make_pair(std::move(model_to_spawn), lifespan); | ||||
|       break; | ||||
|     } | ||||
|     i++; | ||||
|   } | ||||
|  | ||||
|   if (i == std::numeric_limits<std::uint32_t>::max() - 1) | ||||
|     return nullptr; | ||||
|   else | ||||
|     return &dynamic_models_[name + std::to_string(i)].first; | ||||
| } | ||||
|  | ||||
| Model* Engine::GetSpawnedObject(std::string name) { | ||||
|   for (auto it = dynamic_immortal_models_.begin(); | ||||
|        it != dynamic_immortal_models_.end();) { | ||||
|     if (it->first == name) return &it->second; | ||||
|     ++it; | ||||
|   } | ||||
|  | ||||
|   for (auto it = dynamic_models_.begin(); it != dynamic_models_.end();) { | ||||
|     if (it->first == name) return &it->second.first; | ||||
|     ++it; | ||||
|   } | ||||
|  | ||||
|   return nullptr; | ||||
| } | ||||
|  | ||||
| void Engine::Update() { | ||||
|   glm::ivec2 framebuffer_size = vulkan_graphics->window->GetFramebufferSize(); | ||||
|   if (framebuffer_size != window_size_ && framebuffer_size.x != 0 && | ||||
|       framebuffer_size.y != 0) { | ||||
|     window_size_ = framebuffer_size; | ||||
|     auto grater = (framebuffer_size.x > framebuffer_size.y) | ||||
|                       ? framebuffer_size.x | ||||
|                       : framebuffer_size.y; | ||||
|     view = glm::lookAt(glm::vec3(0.f, 0.f, -5.f), glm::vec3(0.f, 0.f, 0.f), | ||||
|                        glm::vec3(0.f, -1.f, 0.f)); | ||||
|     projection = glm::perspective( | ||||
|         glm::radians(103.f), | ||||
|         (std::float_t)framebuffer_size.x / (std::float_t)framebuffer_size.y, | ||||
|         0.1f, 1000.f); | ||||
|   } | ||||
|   vulkan_graphics->SetViewProjection(view, projection); | ||||
|  | ||||
|   if (vulkan_graphics->BeginFrame()) { | ||||
|     std::double_t current_time = glfwGetTime(); | ||||
|     std::float_t delta_time = | ||||
|         static_cast<std::float_t>(current_time - last_frame_time_); | ||||
|     last_frame_time_ = current_time; | ||||
|  | ||||
|     if (Tick != nullptr) Tick(*this, delta_time); | ||||
|  | ||||
|     std::vector<Model*> models; | ||||
|     models.reserve(dynamic_immortal_models_.size() + | ||||
|                                dynamic_models_.size()); | ||||
|  | ||||
|     for (auto it = dynamic_immortal_models_.begin(); | ||||
|          it != dynamic_immortal_models_.end();) { | ||||
|       models.push_back(&it->second); | ||||
|  | ||||
|       ++it; | ||||
|     } | ||||
|  | ||||
|     for (auto it = dynamic_models_.begin(); it != dynamic_models_.end();) { | ||||
|       if (it->second.second < 0.f) { | ||||
|         it = dynamic_models_.erase(it); | ||||
|         continue; | ||||
|       } | ||||
|       else { | ||||
|         it->second.second -= delta_time; | ||||
|       } | ||||
|       models.push_back(&it->second.first); | ||||
|  | ||||
|       ++it; | ||||
|     } | ||||
|  | ||||
|     for (auto it : models) { | ||||
|       it->Update(delta_time); | ||||
|       vulkan_graphics->RenderModel(it); | ||||
|     } | ||||
|  | ||||
|     physics_controller_.invokeOnColisionEvent(thread_pool_, {models.data(), models.size()}); | ||||
|  | ||||
|     vulkan_graphics->EndFrame(); | ||||
|   } | ||||
| } | ||||
|  | ||||
| }  // namespace veng | ||||
| @@ -4,10 +4,112 @@ set(PROJECT_NAME "Server") | ||||
|  | ||||
| project(${PROJECT_NAME}) | ||||
|  | ||||
| add_executable(${PROJECT_NAME} | ||||
|     "${CMAKE_CURRENT_SOURCE_DIR}/src/echoserver.cpp" | ||||
| find_package(Vulkan REQUIRED) | ||||
|  | ||||
| include(FetchContent) | ||||
|  | ||||
| FetchContent_Declare( | ||||
|     glm | ||||
|     GIT_REPOSITORY "https://github.com/g-truc/glm.git" | ||||
|     GIT_TAG "1.0.1" | ||||
|     GIT_SHALLOW ON | ||||
| ) | ||||
| FetchContent_MakeAvailable(glm) | ||||
|  | ||||
| FetchContent_Declare( | ||||
|     spdlog | ||||
|     GIT_REPOSITORY "https://github.com/gabime/spdlog.git" | ||||
|     GIT_TAG "v1.15.2" | ||||
|     GIT_SHALLOW ON | ||||
| ) | ||||
| FetchContent_MakeAvailable(spdlog) | ||||
|  | ||||
| FetchContent_Declare( | ||||
|     glfw | ||||
|     GIT_REPOSITORY "https://github.com/glfw/glfw.git" | ||||
|     GIT_TAG "3.4" | ||||
|     GIT_SHALLOW ON | ||||
| ) | ||||
| FetchContent_MakeAvailable(glfw) | ||||
|  | ||||
| FetchContent_Declare( | ||||
|     GSL | ||||
|     GIT_REPOSITORY "https://github.com/microsoft/GSL.git" | ||||
|     GIT_TAG "v4.2.0" | ||||
|     GIT_SHALLOW ON | ||||
| ) | ||||
| FetchContent_MakeAvailable(GSL) | ||||
|  | ||||
| FetchContent_Declare( | ||||
|     ASSIMP | ||||
|     GIT_REPOSITORY "https://github.com/assimp/assimp.git" | ||||
|     GIT_TAG "v5.4.3" | ||||
|     GIT_SHALLOW ON | ||||
| ) | ||||
| FetchContent_MakeAvailable(ASSIMP) | ||||
|  | ||||
| FetchContent_Declare( | ||||
|     JSONCPP | ||||
|     GIT_REPOSITORY "https://github.com/open-source-parsers/jsoncpp.git" | ||||
|     GIT_TAG "1.9.6" | ||||
|     GIT_SHALLOW ON | ||||
| ) | ||||
| FetchContent_MakeAvailable(JSONCPP) | ||||
|  | ||||
| file(GLOB_RECURSE Sources CONFIGURE_DEPENDS | ||||
|     "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp" | ||||
| ) | ||||
|  | ||||
| add_executable(${PROJECT_NAME} ${RootProjectSources} ${Sources}) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE Vulkan::Vulkan) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE glm) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE glfw) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE Microsoft.GSL::GSL) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE spdlog) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE assimp::assimp) | ||||
| target_link_libraries(${PROJECT_NAME} PRIVATE jsoncpp_static) | ||||
|  | ||||
| if(WIN32) | ||||
|     target_link_libraries(${PROJECT_NAME} PRIVATE ws2_32) | ||||
| endif() | ||||
| if(UNIX AND NOT APPLE AND CMAKE_BUILD_TYPE STREQUAL "Release") | ||||
|     set_target_properties(${PROJECT_NAME} PROPERTIES | ||||
|         BUILD_WITH_INSTALL_RPATH TRUE | ||||
|         INSTALL_RPATH "$ORIGIN" | ||||
|         SKIP_BUILD_RPATH FALSE | ||||
|         BUILD_RPATH "$ORIGIN" | ||||
|     ) | ||||
| endif() | ||||
|  | ||||
| target_include_directories(${PROJECT_NAME} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../include" "${CMAKE_CURRENT_SOURCE_DIR}/include") | ||||
| target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_20) | ||||
|  | ||||
| target_precompile_headers(${PROJECT_NAME} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../include/precomp.h") | ||||
|  | ||||
| add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD | ||||
|     COMMAND ${CMAKE_COMMAND} -E copy_if_different | ||||
|     "$<TARGET_FILE:spdlog>" | ||||
|     "$<TARGET_FILE_DIR:${PROJECT_NAME}>" | ||||
|     COMMENT "Copying spdlog DLL/so to output directory" | ||||
| ) | ||||
|  | ||||
| add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD | ||||
|     COMMAND ${CMAKE_COMMAND} -E copy_directory | ||||
|     "$<TARGET_FILE_DIR:spdlog>" | ||||
|     "$<TARGET_FILE_DIR:${PROJECT_NAME}>" | ||||
|     COMMENT "Copying spdlog library files and symlinks to output directory" | ||||
| ) | ||||
|  | ||||
| add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD | ||||
|     COMMAND ${CMAKE_COMMAND} -E copy_if_different | ||||
|     "$<TARGET_FILE:jsoncpp_static>" | ||||
|     "$<TARGET_FILE_DIR:${PROJECT_NAME}>" | ||||
|     COMMENT "Copying jsoncpp DLL/so to output directory" | ||||
| ) | ||||
|  | ||||
| add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD | ||||
|     COMMAND ${CMAKE_COMMAND} -E copy_directory | ||||
|     "$<TARGET_FILE_DIR:jsoncpp_static>" | ||||
|     "$<TARGET_FILE_DIR:${PROJECT_NAME}>" | ||||
|     COMMENT "Copying jsoncpp library files and symlinks to output directory" | ||||
| ) | ||||
| @@ -1,93 +0,0 @@ | ||||
| #pragma once | ||||
|  | ||||
| #ifdef _WIN32 | ||||
| #include <winsock2.h> | ||||
| #include <ws2tcpip.h> | ||||
| #include <ws2bth.h> | ||||
| #include <ws2def.h> | ||||
| #include <windows.h> | ||||
| #define in_addr_t ULONG | ||||
| #elif __linux__ | ||||
| #include <sys/types.h> | ||||
| #include <sys/socket.h> | ||||
| #include <sys/epoll.h> | ||||
| #include <arpa/inet.h> | ||||
| #include <fcntl.h> | ||||
| #include <errno.h> | ||||
| #include <netinet/in.h> | ||||
| #include <sys/eventfd.h> | ||||
| #define SOCKET int | ||||
| #define INVALID_SOCKET -1 | ||||
| #define SOCKET_ERROR -1 | ||||
| #else | ||||
| #error "이 플랫폼은 지원되지 않습니다." | ||||
| #endif | ||||
|  | ||||
| #include <chrono> | ||||
|  | ||||
| void err_quit(const char *msg) { | ||||
|   char *msgbuf = strerror(errno); | ||||
|   fprintf(stderr, "[%s] %s\n", msg, msgbuf); | ||||
|   exit(1); | ||||
| } | ||||
|  | ||||
| void err_display(const char *msg) { | ||||
|   char *msgbuf = strerror(errno); | ||||
|   fprintf(stderr, "[%s] %s\n", msg, msgbuf); | ||||
| } | ||||
|  | ||||
| #define LISTENIP "::" | ||||
| #define LISTENPORT 9010 | ||||
| #define BUFSIZE 100 | ||||
|  | ||||
| int main(int argc, char *argv[]) { | ||||
|   WSADATA wsa; | ||||
|   if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { | ||||
|     err_quit("WSAStartup()"); | ||||
|     return EXIT_FAILURE; | ||||
|   } | ||||
|   SOCKET listenSocket = socket(AF_INET6, SOCK_STREAM, 0); | ||||
|   if (listenSocket == INVALID_SOCKET) err_quit("socket()"); | ||||
|  | ||||
|   struct sockaddr_in6 serverAddr; | ||||
|   memset(&serverAddr, 0, sizeof(serverAddr)); | ||||
|   serverAddr.sin6_family = AF_INET6; | ||||
|   inet_pton(AF_INET6, LISTENIP, &serverAddr.sin6_addr); | ||||
|   serverAddr.sin6_port = htons(LISTENPORT); | ||||
|  | ||||
|   if (SOCKET_ERROR == | ||||
|       bind(listenSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr))) | ||||
|     err_quit("bind()"); | ||||
|   if (SOCKET_ERROR == listen(listenSocket, SOMAXCONN)) err_quit("listen()"); | ||||
|  | ||||
|   SOCKET client_sock; | ||||
|   struct sockaddr_in6 client_addr; | ||||
|   socklen_t addr_len; | ||||
|  | ||||
|   addr_len = sizeof(client_addr); | ||||
|   printf("Waiting for connection...\n"); | ||||
|   client_sock = | ||||
|       accept(listenSocket, (struct sockaddr *)&client_addr, &addr_len); | ||||
|   if (client_sock == INVALID_SOCKET) err_quit("accept()"); | ||||
|   printf("Connection established!\n"); | ||||
|  | ||||
|   char buf[BUFSIZE + 1]; | ||||
|  | ||||
|   while (2) { | ||||
|     int retVal = recv(client_sock, buf, BUFSIZE, 0); | ||||
|     if (retVal == SOCKET_ERROR) | ||||
|       err_display("recv()"); | ||||
|     else if (retVal == 0) | ||||
|       break; | ||||
|  | ||||
|     char ipv6str[INET6_ADDRSTRLEN]; | ||||
|     inet_ntop(AF_INET6, &client_addr, ipv6str, sizeof(ipv6str)); | ||||
|     buf[retVal] = '\0'; | ||||
|     printf("[TCP/%s:%d] %s\n", ipv6str, ntohs(client_addr.sin6_port), buf); | ||||
|  | ||||
|     if (SOCKET_ERROR == send(client_sock, buf, BUFSIZE, 0)) | ||||
|       err_display("send()"); | ||||
|   } | ||||
|  | ||||
|   WSACleanup(); | ||||
| } | ||||
							
								
								
									
										227
									
								
								Server/src/server.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										227
									
								
								Server/src/server.cpp
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,227 @@ | ||||
| #include "glfw/glfw_initialization.h" | ||||
| #include "glfw/glfw_monitor.h" | ||||
| #include "glfw/glfw_window.h" | ||||
| #include "socket/iocp.h" | ||||
| #include "socket/packet.h" | ||||
| #include "socket/tcp_socket.h" | ||||
| #include "socket/udp_socket.h" | ||||
| #include "socket/wsa_manager.h" | ||||
| #include "utils/ConfigManager.h" | ||||
| #include "utils/log.h" | ||||
| #include "utils/snowflake.h" | ||||
| #include "utils/utils.h" | ||||
| #include "vulkan_engine/asset/object/model.h" | ||||
| #include "vulkan_engine/vulkan/physics.h" | ||||
|  | ||||
| #define TICKRATE 30 | ||||
| constexpr double TICKDELAY = (1 / TICKRATE); | ||||
|  | ||||
| std::uint8_t CLIENTID = 0; | ||||
|  | ||||
| std::unordered_map<utils::Snowflake, std::shared_ptr<veng::Model>> MODELS; | ||||
| std::mutex MODELS_MUTEX; | ||||
| std::list<std::shared_ptr<Network::Socket>> CLIENTS; | ||||
| std::mutex CLIENTS_MUTEX; | ||||
|  | ||||
| void EchoClient(utils::ThreadPool* tp, Network::IOCP* iocp, | ||||
|                 std::shared_ptr<Network::Socket> NewSock, | ||||
|                 Network::Address NewAddr) { | ||||
|   if (NewSock->sock == 0) return; | ||||
|   std::future<std::list<char>> result; | ||||
|   Packet::Header header; | ||||
|   std::vector<char> recv_data; | ||||
|  | ||||
|   result = iocp->recv(NewSock, 14); | ||||
|   recv_data = utils::CvtListToVector(result.get()); | ||||
|  | ||||
|   header.Deserialize(recv_data); | ||||
|  | ||||
|   result = iocp->recv(NewSock, header.body_length); | ||||
|   recv_data = utils::CvtListToVector(result.get()); | ||||
|  | ||||
|   switch (header.opcode) { | ||||
|     case Packet::Opcode::UPDATEMODEL: { | ||||
|       veng::Model model; | ||||
|       model.Deserialize(recv_data); | ||||
|  | ||||
|       std::lock_guard lock(MODELS_MUTEX); | ||||
|       auto ID = model.ID; | ||||
|       if (MODELS.find(ID) == MODELS.end()) { | ||||
|         spdlog::info("model received: {}:{}", model.name, ID.snowflake); | ||||
|         MODELS[ID] = std::make_shared<veng::Model>(); | ||||
|         MODELS[ID]->Deserialize(recv_data); | ||||
|         MODELS[ID]->OnColision = [](utils::ThreadPool* thread_pool, | ||||
|                                    std::shared_ptr<veng::Model> self, | ||||
|                                    std::shared_ptr<veng::Model> other) { | ||||
|           if (self->shouldBeDestroyed || other->shouldBeDestroyed) return; | ||||
|           spdlog::info("[{}:{}] and [{}:{}] is nearby.", self->name, | ||||
|                        self->ID.snowflake, other->name, other->ID.snowflake); | ||||
|  | ||||
|           other->colision = false; | ||||
|           other->visible = false; | ||||
|           other->shouldBeDestroyed = true; | ||||
|           self->colision = false; | ||||
|           self->visible = false; | ||||
|           self->shouldBeDestroyed = true; | ||||
|         }; | ||||
|       } else { | ||||
|         MODELS[ID]->Deserialize(recv_data); | ||||
|       } | ||||
|       MODELS[ID]->needsUpdate = true; | ||||
|     } break; | ||||
|     default: | ||||
|       spdlog::error("unknown data type"); | ||||
|   } | ||||
|  | ||||
|   tp->enqueueJob(EchoClient, iocp, NewSock, NewAddr); | ||||
| } | ||||
|  | ||||
| void ClientRefresher(utils::ThreadPool* tp, Network::IOCP* iocp) { | ||||
|   static double last_all_updated; | ||||
|   static double last_frame_time_; | ||||
|   auto current_time = glfwGetTime(); | ||||
|   bool needs_all_update = false; | ||||
|   if (current_time - last_all_updated >= TICKDELAY) { | ||||
|     needs_all_update = true; | ||||
|     last_all_updated = glfwGetTime(); | ||||
|   } | ||||
|   auto delta_time = current_time - last_frame_time_; | ||||
|   last_frame_time_ = current_time; | ||||
|  | ||||
|   std::lock_guard client_lock(CLIENTS_MUTEX); | ||||
|   for (auto it = CLIENTS.begin(); it != CLIENTS.end();) { | ||||
|     if (*it == nullptr || it->get()->sock == 0) | ||||
|       it = CLIENTS.erase(it); | ||||
|     else | ||||
|       ++it; | ||||
|   } | ||||
|  | ||||
|   std::lock_guard model_lock(MODELS_MUTEX); | ||||
|   for (auto it = MODELS.begin(); it != MODELS.end();) { | ||||
|     auto& model = it->second; | ||||
|  | ||||
|     if (model->shouldBeDestroyed) { | ||||
|       it = MODELS.erase(it); | ||||
|       continue; | ||||
|     } | ||||
|     ++it; | ||||
|   } | ||||
|  | ||||
|   for (auto it = MODELS.begin(); it != MODELS.end();) { | ||||
|     auto& model = it->second; | ||||
|  | ||||
|     if (std::abs(model->lifespan + 1.f) < | ||||
|         std::numeric_limits<float>::epsilon()) { | ||||
|       ++it; | ||||
|       continue; | ||||
|     } | ||||
|  | ||||
|     if (model->lifespan <= 0.f) { | ||||
|       it->second->shouldBeDestroyed = true; | ||||
|       ++it; | ||||
|       continue; | ||||
|     } | ||||
|  | ||||
|     model->lifespan -= delta_time; | ||||
|     ++it; | ||||
|   } | ||||
|  | ||||
|   for (auto& model : MODELS) { | ||||
|     if (model.second->name == "camera_lag") continue; | ||||
|     model.second->Update(delta_time); | ||||
|     veng::Physics::invokeOnColisionEvent(tp, MODELS); | ||||
|     for (auto& client : CLIENTS) { | ||||
|       if (client->sock == 0) continue; | ||||
|       std::vector<char> send_data; | ||||
|       auto model_serialized = model.second->Serialize(); | ||||
|       Packet::Header header; | ||||
|  | ||||
|       if (model.second->shouldBeDestroyed) { | ||||
|         header.opcode = Packet::Opcode::DESPAWNMODEL; | ||||
|       } else { | ||||
|         header.opcode = Packet::Opcode::UPDATEMODEL; | ||||
|       } | ||||
|  | ||||
|       header.timestamp = glfwGetTime(); | ||||
|       header.body_length = model_serialized.size(); | ||||
|       auto header_serialized = header.Serialize(); | ||||
|       send_data.insert(send_data.end(), header_serialized.begin(), | ||||
|                        header_serialized.end()); | ||||
|       send_data.insert(send_data.end(), model_serialized.begin(), | ||||
|                        model_serialized.end()); | ||||
|       /*if (!model.second->needsUpdate && !needs_all_update && | ||||
|           !model.second->shouldBeDestroyed) { | ||||
|         continue; | ||||
|       }*/ | ||||
|       if (!needs_all_update) { | ||||
|         continue; | ||||
|       } | ||||
|       model.second->needsUpdate = false; | ||||
|       if (iocp->send(client, send_data) == -1) { | ||||
|         client->sock = 0; | ||||
|       } | ||||
|       // spdlog::debug("server-side updated : [{}:{}]", model.second.name, | ||||
|       // model.second.ID.snowflake); | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   tp->enqueueJob(ClientRefresher, iocp); | ||||
| } | ||||
|  | ||||
| int main(int argc, char* argv[]) { | ||||
|   Network::WSAManager wsamanager; | ||||
|   const veng::GlfwInitialization _glfw; | ||||
|   utils::Config config = utils::ConfigManager::load(); | ||||
|   utils::setDefaultLogger(config.logLevel, config.logFileName, | ||||
|                           config.logfileSize, config.logfileCount); | ||||
|  | ||||
|   utils::ThreadPool tp(0); | ||||
|   Network::IOCP iocp; | ||||
|   iocp.init(&tp, SessionProtocol::TCP); | ||||
|  | ||||
|   Network::Address addr; | ||||
|  | ||||
|   addr.set(config.ipVersion, config.IP, config.Port); | ||||
|  | ||||
|   std::shared_ptr<Network::TCPSocket> TCPSock = | ||||
|       std::make_shared<Network::TCPSocket>(config.ipVersion); | ||||
|   if (TCPSock->bind(addr) == INVALID_SOCKET) { | ||||
|     spdlog::error("bind()"); | ||||
|     std::exit(EXIT_FAILURE); | ||||
|   } | ||||
|   if (TCPSock->listen(SOMAXCONN) == INVALID_SOCKET) { | ||||
|     spdlog::error("listen()"); | ||||
|     std::exit(EXIT_FAILURE); | ||||
|   } | ||||
|  | ||||
|   tp.enqueueJob(ClientRefresher, &iocp); | ||||
|  | ||||
|   while (true) { | ||||
|     std::shared_ptr<Network::TCPSocket> NewSock; | ||||
|     Network::Address NewAddr = addr; | ||||
|     spdlog::info("Waiting for connection"); | ||||
|     TCPSock->accept(NewSock, NewAddr); | ||||
|  | ||||
|     iocp.registerSocket(NewSock); | ||||
|  | ||||
|     Packet::Header header; | ||||
|     std::vector<char> packet; | ||||
|  | ||||
|     header.opcode = Packet::Opcode::CLIENTID; | ||||
|     header.timestamp = glfwGetTime(); | ||||
|     header.body_length = 1; | ||||
|     packet = header.Serialize(); | ||||
|     packet.resize(packet.size() + 1); | ||||
|  | ||||
|     std::lock_guard lock(CLIENTS_MUTEX); | ||||
|     std::uint8_t client_id = (std::uint8_t)(CLIENTS.size() - 1); | ||||
|     ::memcpy(packet.data() + 14, &client_id, 1); | ||||
|  | ||||
|     iocp.send(NewSock, packet); | ||||
|  | ||||
|     auto ping = glfwGetTime() - header.timestamp; | ||||
|     CLIENTS.push_back(NewSock); | ||||
|  | ||||
|     tp.enqueueJob(EchoClient, &iocp, NewSock, NewAddr); | ||||
|   } | ||||
| } | ||||
							
								
								
									
										57
									
								
								Server/src/utils/ConfigManager.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										57
									
								
								Server/src/utils/ConfigManager.cpp
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,57 @@ | ||||
| #include "utils/ConfigManager.h" | ||||
|  | ||||
| #include <json/json.h> | ||||
|  | ||||
| #include <fstream> | ||||
| #include <iostream> | ||||
| #include <string> | ||||
|  | ||||
| namespace utils { | ||||
| Config ConfigManager::load() { | ||||
|   Config config; | ||||
|  | ||||
|   std::ifstream configfile("config.json", std::ifstream::binary); | ||||
|   if (!configfile.is_open()) { | ||||
|     std::ofstream defaultConfig("config.json", std::ios::out); | ||||
|     config.configJsonRoot["IP Version"] = AF_INET6; | ||||
|     config.configJsonRoot["IP"] = "::1"; | ||||
|     config.configJsonRoot["Port"] = 9010; | ||||
|     config.configJsonRoot["LogLevel"] = 1; | ||||
|     config.configJsonRoot["LogfileName"] = "log.log"; | ||||
|     config.configJsonRoot["LogfileSize"] = UINT32_MAX; | ||||
|     config.configJsonRoot["LogfileCount"] = 5; | ||||
|     defaultConfig << config.configJsonRoot; | ||||
|     defaultConfig.close(); | ||||
|     spdlog::critical( | ||||
|         "\"config.json\" is missing. Default configuration has been written."); | ||||
|   } | ||||
|   try { | ||||
|     if (configfile.is_open()) configfile >> config.configJsonRoot; | ||||
|  | ||||
|     config.ipVersion = config.configJsonRoot["IP Version"].asInt(); | ||||
|     if (config.ipVersion != AF_INET && config.ipVersion != AF_INET6) | ||||
|       throw std::runtime_error("Invalid IP Version."); | ||||
|  | ||||
|     config.IP = config.configJsonRoot["IP"].asCString(); | ||||
|  | ||||
|     config.Port = config.configJsonRoot["Port"].asInt(); | ||||
|     if (config.Port < 0 || config.Port > 65535) | ||||
|       throw std::runtime_error("Invalid listen port."); | ||||
|  | ||||
|     int ll_ = config.configJsonRoot["LogLevel"].asInt(); | ||||
|     if (ll_ >= 0 && ll_ < spdlog::level::n_levels) | ||||
|       config.logLevel = (spdlog::level::level_enum)ll_; | ||||
|     else | ||||
|       throw std::runtime_error("Invalid log level."); | ||||
|  | ||||
|     config.logFileName = config.configJsonRoot["LogfileName"].asCString(); | ||||
|     config.logfileSize = config.configJsonRoot["LogfileSize"].asUInt(); | ||||
|     config.logfileCount = config.configJsonRoot["LogfileCount"].asUInt(); | ||||
|   } catch (Json::RuntimeError e) { | ||||
|     spdlog::critical( | ||||
|         std::string(std::string("[Json Error: ]") + e.what()).c_str()); | ||||
|     std::exit(EXIT_FAILURE); | ||||
|   } | ||||
|   return config; | ||||
| } | ||||
| }  // namespace Chattr | ||||
| @@ -11,36 +11,11 @@ Session::Session(gsl::not_null<Network::IOCP*> iocp, utils::ThreadPool* tp, | ||||
|     : iocp_(iocp), tp_(tp), proto_(proto) { | ||||
|   switch (proto) { | ||||
|     case SessionProtocol::UDP: | ||||
|     case SessionProtocol::QUIC: { | ||||
|       Network::UDPSocket* sock = new Network::UDPSocket(); | ||||
|       sock_ = sock; | ||||
|       sock->init(addr.family); | ||||
|       switch (type) { | ||||
|         case SessionType::CONNECT: | ||||
|           ssl_ctx_ = ::SSL_CTX_new(::OSSL_QUIC_client_method()); | ||||
|           if (ssl_ctx_ == nullptr) { | ||||
|             spdlog::critical("SSL_CTX_new()"); | ||||
|             std::exit(EXIT_FAILURE); | ||||
|           } | ||||
|           ::SSL_CTX_set_verify(ssl_ctx_, SSL_VERIFY_PEER, NULL); | ||||
|  | ||||
|           if (!::SSL_CTX_set_default_verify_paths(ssl_ctx_)) { | ||||
|             spdlog::critical("SSL_CTX_set_default_verify_paths()"); | ||||
|             std::exit(EXIT_FAILURE); | ||||
|           } | ||||
|           break; | ||||
|         case SessionType::LISTEN: | ||||
|           sock->bind(addr); | ||||
|           break; | ||||
|         default: | ||||
|           std::exit(EXIT_FAILURE); | ||||
|       } | ||||
|     } break; | ||||
|     case SessionProtocol::QUIC:  | ||||
|     case SessionProtocol::TCP: | ||||
|     case SessionProtocol::TLS: { | ||||
|       Network::TCPSocket* sock = new Network::TCPSocket(); | ||||
|       Network::TCPSocket* sock = new Network::TCPSocket(addr.family); | ||||
|       sock_ = sock; | ||||
|       sock->init(addr.family); | ||||
|       switch (type) { | ||||
|         case SessionType::CONNECT: | ||||
|           sock->connect(addr); | ||||
| @@ -56,12 +31,6 @@ Session::Session(gsl::not_null<Network::IOCP*> iocp, utils::ThreadPool* tp, | ||||
|     default: | ||||
|       std::exit(EXIT_FAILURE); | ||||
|   } | ||||
|  | ||||
|   ssl_ = ::SSL_new(ssl_ctx_); | ||||
|   if (ssl_ == nullptr) { | ||||
|     spdlog::critical("SSL_new()"); | ||||
|     std::exit(EXIT_FAILURE); | ||||
|   } | ||||
| } | ||||
|  | ||||
| Session::~Session() { | ||||
|   | ||||
| @@ -4,50 +4,6 @@ | ||||
|  | ||||
| namespace Network { | ||||
|  | ||||
| //void Address::set(int type, gsl::czstring presentationAddr, | ||||
| //                  std::uint16_t port) { | ||||
| //  zeroFill(); | ||||
| //  setType(type); | ||||
| // | ||||
| //  if (type == AF_INET) { | ||||
| //    ::inet_pton(AF_INET, presentationAddr, &addr_in.sin_addr); | ||||
| //    addr_in.sin_port = htons(port); | ||||
| //  } else if (type == AF_INET6) { | ||||
| //    ::inet_pton(AF_INET6, presentationAddr, &addr_in6.sin6_addr); | ||||
| //    addr_in6.sin6_port = htons(port); | ||||
| //  } | ||||
| // | ||||
| //  BIO_ADDRINFO* res; | ||||
| //  if (!BIO_lookup_ex(presentationAddr, std::to_string(port).c_str(), | ||||
| //                     BIO_LOOKUP_CLIENT, type, SOCK_DGRAM, 0, &res)) { | ||||
| //    ::BIO_ADDRINFO_free(res); | ||||
| //    throw std::runtime_error("can't resolve address"); | ||||
| //  } | ||||
| // | ||||
| //  int sock = -1; | ||||
| //  for (const BIO_ADDRINFO* ai = res; ai != nullptr; | ||||
| //       ai = ::BIO_ADDRINFO_next(ai)) { | ||||
| //    sock = ::BIO_socket(BIO_ADDRINFO_family(ai), type, 0, 0); | ||||
| //    if (sock == -1) | ||||
| //      continue; | ||||
| //    else { | ||||
| //      auto bio_addr = ::BIO_ADDRINFO_address(ai); | ||||
| //      BIO_ADDR_rawaddress(bio_addr, &addr, (unsigned long long*)&length); | ||||
| //      bio_addr_info = ::BIO_ADDR_dup(bio_addr); | ||||
| // | ||||
| //      break; | ||||
| //    } | ||||
| //  } | ||||
| // | ||||
| //  if (sock != -1) | ||||
| //    ::close(sock); | ||||
| // | ||||
| //  ::BIO_ADDRINFO_free(res); | ||||
| // | ||||
| //  addr_in.sin_family = type; | ||||
| //  addr_in.sin_port = htons(port); | ||||
| //} | ||||
|  | ||||
| Address::Address() { zeroFill(); } | ||||
|  | ||||
| Address::Address(int type, gsl::czstring presentationAddr, std::uint16_t port) { | ||||
| @@ -58,19 +14,18 @@ void Address::zeroFill() { memset(&addr_in6, 0, sizeof(addr_in6)); } | ||||
|  | ||||
| void Address::set(int type, gsl::czstring presentationAddr, | ||||
|                   std::uint16_t port) { | ||||
|   zeroFill(); | ||||
|   setType(type); | ||||
|  | ||||
|   if (type == AF_INET) { | ||||
|     addr_in.sin_family = AF_INET; | ||||
|     ::inet_pton(AF_INET, presentationAddr, &addr_in.sin_addr); | ||||
|     addr_in.sin_port = htons(port); | ||||
|     length = sizeof(sockaddr_in); | ||||
|   } else if (type == AF_INET6) { | ||||
|     addr_in6.sin6_family = AF_INET6; | ||||
|     ::inet_pton(AF_INET6, presentationAddr, &addr_in6.sin6_addr); | ||||
|     addr_in6.sin6_port = htons(port); | ||||
|     length = sizeof(sockaddr_in6); | ||||
|   } | ||||
|   family = type; | ||||
| } | ||||
|  | ||||
| void Address::setType(int type) { | ||||
| @@ -87,12 +42,12 @@ Address::operator std::string() { | ||||
|  | ||||
|   if (!port) return std::string(); | ||||
|  | ||||
|   if (length == sizeof(addr_in)) { | ||||
|   if (family == AF_INET) { | ||||
|     char addrStr[INET_ADDRSTRLEN]; | ||||
|     ::inet_ntop(AF_INET, &addr_in.sin_addr, addrStr, sizeof(addrStr)); | ||||
|  | ||||
|     return std::format("{}:{}", addrStr, port.value()); | ||||
|   } else if (length == sizeof(addr_in6)) { | ||||
|   } else if (family == AF_INET6) { | ||||
|     char addrStr[INET6_ADDRSTRLEN]; | ||||
|     ::inet_ntop(AF_INET6, &addr_in6.sin6_addr, addrStr, sizeof(addrStr)); | ||||
|  | ||||
|   | ||||
| @@ -4,7 +4,7 @@ | ||||
|  | ||||
| namespace Network { | ||||
|  | ||||
| IOCP::IOCP() { | ||||
| IOCP::IOCP() : IOCPThread_(nullptr), proto_(SessionProtocol::TCP) { | ||||
|   gen_ = std::mt19937(rd_()); | ||||
|   jitterDist_ = std::uniform_int_distribution<int>(-10, 10); | ||||
| } | ||||
| @@ -40,81 +40,126 @@ void IOCP::destruct() { | ||||
| #endif | ||||
| } | ||||
|  | ||||
| void IOCP::registerSocket(IOCPPASSINDATA* data) { | ||||
| void IOCP::registerSocket(std::shared_ptr<Socket> sock) { | ||||
| #ifdef _WIN32 | ||||
|   HANDLE returnData = ::CreateIoCompletionPort( | ||||
|       (HANDLE)data->socket->sock, completionPort_, data->socket->sock, 0); | ||||
|   HANDLE returnData = ::CreateIoCompletionPort((HANDLE)sock->sock, | ||||
|                                                completionPort_, sock->sock, 0); | ||||
|   if (returnData == 0) completionPort_ = returnData; | ||||
|  | ||||
|   IOCPPASSINDATA* recv_data = new IOCPPASSINDATA(data->bufsize); | ||||
|   recv_data->event = IOCPEVENT::READ; | ||||
|   recv_data->socket = data->socket; | ||||
|   DWORD recvbytes = 0, flags = 0; | ||||
|   int result = ::WSARecv(recv_data->socket->sock, &recv_data->wsabuf, 1, | ||||
|                          &recvbytes, &flags, &recv_data->overlapped, NULL); | ||||
|   if (result == SOCKET_ERROR) { | ||||
|     int err = ::WSAGetLastError(); | ||||
|     if (err != WSA_IO_PENDING) { | ||||
|       spdlog::error("WSARecv failed: {}", err); | ||||
|       // 반드시 여기서 리턴하거나 처리해야 합니다. | ||||
|     } | ||||
|   } | ||||
|  | ||||
| #endif | ||||
| } | ||||
|  | ||||
| int IOCP::recv(IOCPPASSINDATA* data) { //읽은 바이트수가 무조건 100임? 왜..? | ||||
|   SOCKET sock = data->socket->sock; | ||||
|   std::lock_guard lock(*GetRecvQueueMutex_(sock)); | ||||
|   auto queue = GetRecvQueue_(sock); | ||||
| std::future<std::vector<char>> IOCP::recvFull(std::shared_ptr<Socket> sock, | ||||
|                                               std::uint32_t bufsize) { | ||||
|   auto promise = std::make_shared<std::promise<std::vector<char>>>(); | ||||
|   auto future = promise->get_future(); | ||||
|  | ||||
|   std::uint32_t left_data = data->wsabuf.len; | ||||
|   std::uint32_t copied = 0; | ||||
|   auto buffer = std::make_shared<std::vector<char>>(); | ||||
|   buffer->reserve(bufsize); | ||||
|  | ||||
|   while (!queue->empty() && left_data != 0) { | ||||
|     auto front = queue->front(); | ||||
|     queue->pop_front(); | ||||
|   std::function<void(std::uint32_t)> recvChunk; | ||||
|   recvChunk = [=](std::uint32_t remaining) mutable { | ||||
|     this->recv(sock, remaining, | ||||
|                [=](utils::ThreadPool* th, IOCPPASSINDATA* data) { | ||||
|                  buffer->insert(buffer->end(), data->wsabuf.buf, | ||||
|                                 data->wsabuf.buf + data->transferredbytes); | ||||
|  | ||||
|     std::uint32_t offset = front.second; | ||||
|     std::uint32_t available = front.first.size() - offset; | ||||
|     std::uint32_t to_copy = (left_data < available) ? left_data : available; | ||||
|                  std::uint32_t still_left = | ||||
|                      bufsize - static_cast<std::uint32_t>(buffer->size()); | ||||
|                  if (still_left > 0) { | ||||
|                    recvChunk(still_left); | ||||
|                  } else { | ||||
|                    promise->set_value(std::move(*buffer)); | ||||
|                  } | ||||
|  | ||||
|     ::memcpy(data->wsabuf.buf + copied, front.first.data() + offset, to_copy); | ||||
|     copied += to_copy; | ||||
|     left_data -= to_copy; | ||||
|     offset += to_copy; | ||||
|                  return std::list<char>(); | ||||
|                }); | ||||
|   }; | ||||
|  | ||||
|     if (offset < front.first.size()) { | ||||
|       front.second = offset; | ||||
|       queue->push_front(front); | ||||
|       break; | ||||
|   recvChunk(bufsize); | ||||
|  | ||||
|   return future; | ||||
| } | ||||
|  | ||||
| std::list<char> DEFAULT_RECVALL_CALLBACK(utils::ThreadPool* th, | ||||
|                                          IOCPPASSINDATA* data) { | ||||
|   std::list<char> return_value; | ||||
|   return_value.insert(return_value.end(), data->wsabuf.buf, | ||||
|                       data->wsabuf.buf + data->transferredbytes); | ||||
|  | ||||
|   if (data->transferredbytes < data->wsabuf.len) { | ||||
|     auto future = data->IOCPInstance->recv( | ||||
|         data->socket, data->wsabuf.len - data->transferredbytes, | ||||
|         DEFAULT_RECVALL_CALLBACK); | ||||
|     auto result = future.get(); | ||||
|     return_value.insert(return_value.end(), result.begin(), result.end()); | ||||
|   } | ||||
|  | ||||
|   return return_value; | ||||
| } | ||||
|  | ||||
| std::future<std::list<char>> IOCP::recv( | ||||
|     std::shared_ptr<Socket> sock, std::uint32_t bufsize, | ||||
|     std::function<std::list<char>(utils::ThreadPool*, IOCPPASSINDATA*)> | ||||
|         callback) { | ||||
|   std::lock_guard lock(*GetRecvQueueMutex(sock->sock)); | ||||
|   auto queue = GetRecvQueue(sock->sock); | ||||
|  | ||||
|   Network::IOCPPASSINDATA* data; | ||||
|   std::packaged_task<std::list<char>(utils::ThreadPool*, IOCPPASSINDATA*)> task; | ||||
|   std::future<std::list<char>> future; | ||||
|   if (callback != nullptr) { | ||||
|     task = std::packaged_task<std::list<char>(utils::ThreadPool*, | ||||
|                                               IOCPPASSINDATA*)>(callback); | ||||
|     future = task.get_future(); | ||||
|     data = new Network::IOCPPASSINDATA(sock, bufsize, this, std::move(task)); | ||||
|   } else { | ||||
|     data = new Network::IOCPPASSINDATA(sock, bufsize, this); | ||||
|   } | ||||
|  | ||||
|   int result = SOCKET_ERROR; | ||||
|   DWORD recvbytes = 0, flags = 0; | ||||
|   result = ::WSARecv(sock->sock, &data->wsabuf, 1, &recvbytes, &flags, | ||||
|                      &data->overlapped, NULL); | ||||
|   if (result == SOCKET_ERROR) { | ||||
|     int err = ::WSAGetLastError(); | ||||
|     if (err != WSA_IO_PENDING) { | ||||
|       auto err_msg = std::format("WSARecv failed: {}", err); | ||||
|       throw std::runtime_error(err_msg); | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   return copied; | ||||
|   return future; | ||||
| } | ||||
|  | ||||
| int IOCP::send(SOCKET sock, std::vector<IOCPPASSINDATA*>* data) { | ||||
|   auto lk = GetSendQueueMutex_(sock); | ||||
|   auto queue = GetSendQueue_(sock); | ||||
| int IOCP::send(std::shared_ptr<Socket> sock, std::vector<char>& data) { | ||||
|   auto lk = GetSendQueueMutex(sock->sock); | ||||
|   auto queue = GetSendQueue(sock->sock); | ||||
|   std::lock_guard lock(*lk); | ||||
|   for (auto& it : *data) { | ||||
|     it->event = IOCPEVENT::WRITE; | ||||
|     queue->push_back(it); | ||||
|   } | ||||
|  | ||||
|   Network::IOCPPASSINDATA* packet = new Network::IOCPPASSINDATA(sock, data.size(), this); | ||||
|   packet->event = IOCPEVENT::WRITE; | ||||
|   ::memcpy(packet->wsabuf.buf, data.data(), data.size()); | ||||
|   packet->wsabuf.len = data.size(); | ||||
|   queue->push_back(packet); | ||||
|  | ||||
|   IOCPThread_->enqueueJob( | ||||
|       [this, sock](utils::ThreadPool* th, std::uint8_t __) { | ||||
|       [this, sock = sock->sock](utils::ThreadPool* th, std::uint8_t __) { | ||||
|         packet_sender_(sock); | ||||
|       }, | ||||
|       0); | ||||
|   return 0; | ||||
| } | ||||
|  | ||||
| int IOCP::GetRecvedPacketCount(SOCKET sock) { | ||||
| int IOCP::GetRecvedBytes(SOCKET sock) { | ||||
|   auto queue = GetRecvQueue(sock); | ||||
|   std::lock_guard lock(socket_mod_mutex_); | ||||
|   auto queue = GetRecvQueue_(sock); | ||||
|   return queue->size(); | ||||
|  | ||||
|   int bytes = 0; | ||||
|   for (auto it : *queue) { | ||||
|     bytes += it.first.size() - it.second; | ||||
|   } | ||||
|  | ||||
|   return bytes; | ||||
| } | ||||
|  | ||||
| void IOCP::iocpWatcher_(utils::ThreadPool* IOCPThread) { | ||||
| @@ -137,48 +182,34 @@ void IOCP::iocpWatcher_(utils::ThreadPool* IOCPThread) { | ||||
|     data->event = IOCPEVENT::QUIT; | ||||
|     spdlog::debug("Disconnected. [{}]", | ||||
|                   (std::string)(data->socket->remoteAddr)); | ||||
|     auto task = [this, IOCPThread, data = std::move(data)]( | ||||
|                     utils::ThreadPool* th, std::uint8_t __) { | ||||
|       if (data->callback.valid()) { | ||||
|         data->callback(th, data); | ||||
|       } | ||||
|       data->socket->destruct(); | ||||
|       delete data; | ||||
|     }; | ||||
|     IOCPThread->enqueueJob(task, 0); | ||||
|     IOCPThread->enqueueJob( | ||||
|         [this](utils::ThreadPool* th, std::uint8_t __) { iocpWatcher_(th); }, | ||||
|         0); | ||||
|     return; | ||||
|   } else { | ||||
|     data->transferredbytes = cbTransfrred; | ||||
|   } | ||||
|  | ||||
|   std::vector<char> buf(16384);  // SSL_read최대 반환 크기 | ||||
|   int red_data = 0; | ||||
|   std::lock_guard lock(*GetRecvQueueMutex_(sock)); | ||||
|   auto queue_list = GetRecvQueue_(data->socket->sock); | ||||
|   if (data->event == IOCPEVENT::READ) { | ||||
|     if (proto_ == SessionProtocol::TLS || proto_ == SessionProtocol::QUIC) { | ||||
|       ::BIO_write(::SSL_get_rbio(data->ssl.get()), data->wsabuf.buf, | ||||
|                   cbTransfrred); | ||||
|  | ||||
|       while ((red_data = ::SSL_read(data->ssl.get(), buf.data(), buf.size())) > | ||||
|              0) { | ||||
|         queue_list->emplace_back(std::make_pair( | ||||
|             std::vector<char>(buf.begin(), buf.begin() + red_data), 0)); | ||||
|       } | ||||
|     } else { | ||||
|       ::memcpy(buf.data(), data->wsabuf.buf, data->transferredbytes); | ||||
|       queue_list->emplace_back(std::make_pair( | ||||
|           std::vector<char>(buf.begin(), buf.begin() + data->transferredbytes), | ||||
|           0)); | ||||
|     } | ||||
|     DWORD recvbytes = 0, flags = 0; | ||||
|  | ||||
|     IOCPPASSINDATA* recv_data = new IOCPPASSINDATA(data->bufsize); | ||||
|     recv_data->event = IOCPEVENT::READ; | ||||
|     recv_data->socket = data->socket; | ||||
|  | ||||
|   auto task = [this, IOCPThread, data = std::move(data)](utils::ThreadPool* th, | ||||
|                                                          std::uint8_t __) { | ||||
|     if (data->callback.valid()) data->callback(th, data); | ||||
|     delete data; | ||||
|     ::WSARecv(recv_data->socket->sock, &recv_data->wsabuf, 1, &recvbytes, | ||||
|               &flags, &recv_data->overlapped, NULL); | ||||
|   } else {  // WRITE 시, 무시한다. | ||||
|     delete data; | ||||
|   } | ||||
|   }; | ||||
|   IOCPThread->enqueueJob(task, 0); | ||||
|   IOCPThread->enqueueJob( | ||||
|       [this](utils::ThreadPool* th, std::uint8_t __) { iocpWatcher_(th); }, 0); | ||||
| } | ||||
|  | ||||
| std::shared_ptr<std::list<IOCPPASSINDATA*>> IOCP::GetSendQueue_(SOCKET sock) { | ||||
| std::shared_ptr<std::list<IOCPPASSINDATA*>> IOCP::GetSendQueue(SOCKET sock) { | ||||
|   std::lock_guard lock(socket_mod_mutex_); | ||||
|   if (send_queue_.find(sock) == send_queue_.end()) { | ||||
|     send_queue_[sock] = std::make_shared<std::list<IOCPPASSINDATA*>>( | ||||
| @@ -188,7 +219,7 @@ std::shared_ptr<std::list<IOCPPASSINDATA*>> IOCP::GetSendQueue_(SOCKET sock) { | ||||
| } | ||||
|  | ||||
| std::shared_ptr<std::list<std::pair<std::vector<char>, std::uint32_t>>> | ||||
| IOCP::GetRecvQueue_(SOCKET sock) { | ||||
| IOCP::GetRecvQueue(SOCKET sock) { | ||||
|   std::lock_guard lock(socket_mod_mutex_); | ||||
|   if (recv_queue_.find(sock) == recv_queue_.end()) { | ||||
|     recv_queue_[sock] = std::make_shared< | ||||
| @@ -198,7 +229,7 @@ IOCP::GetRecvQueue_(SOCKET sock) { | ||||
|   return recv_queue_[sock]; | ||||
| } | ||||
|  | ||||
| std::shared_ptr<std::mutex> IOCP::GetSendQueueMutex_(SOCKET sock) { | ||||
| std::shared_ptr<std::mutex> IOCP::GetSendQueueMutex(SOCKET sock) { | ||||
|   std::lock_guard lock(socket_mod_mutex_); | ||||
|   if (send_queue_mutex_.find(sock) == send_queue_mutex_.end()) { | ||||
|     send_queue_mutex_[sock] = std::make_shared<std::mutex>(); | ||||
| @@ -206,7 +237,7 @@ std::shared_ptr<std::mutex> IOCP::GetSendQueueMutex_(SOCKET sock) { | ||||
|   return send_queue_mutex_[sock]; | ||||
| } | ||||
|  | ||||
| std::shared_ptr<std::mutex> IOCP::GetRecvQueueMutex_(SOCKET sock) { | ||||
| std::shared_ptr<std::mutex> IOCP::GetRecvQueueMutex(SOCKET sock) { | ||||
|   std::lock_guard lock(socket_mod_mutex_); | ||||
|   if (recv_queue_mutex_.find(sock) == recv_queue_mutex_.end()) { | ||||
|     recv_queue_mutex_[sock] = std::make_shared<std::mutex>(); | ||||
| @@ -215,8 +246,8 @@ std::shared_ptr<std::mutex> IOCP::GetRecvQueueMutex_(SOCKET sock) { | ||||
| } | ||||
|  | ||||
| void IOCP::packet_sender_(SOCKET sock) { | ||||
|   auto queue = GetSendQueue_(sock); | ||||
|   std::unique_lock lock(*GetSendQueueMutex_(sock)); | ||||
|   auto queue = GetSendQueue(sock); | ||||
|   std::unique_lock lock(*GetSendQueueMutex(sock)); | ||||
|  | ||||
|   std::vector<char> buf(16384); | ||||
|   WSABUF wsabuf; | ||||
| @@ -229,33 +260,11 @@ void IOCP::packet_sender_(SOCKET sock) { | ||||
|  | ||||
|     int data_len = 0; | ||||
|  | ||||
|     if (proto_ == SessionProtocol::TLS || proto_ == SessionProtocol::QUIC) { | ||||
|       int ret = ::SSL_write(front->ssl.get(), front->wsabuf.buf, front->wsabuf.len); | ||||
|       if (ret <= 0) { | ||||
|         int err = ::SSL_get_error(front->ssl.get(), ret); | ||||
|         if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { | ||||
|           queue->push_front(front); | ||||
|           break; | ||||
|         } | ||||
|         std::unique_lock lk(socket_mod_mutex_); | ||||
|         send_queue_.erase(sock); | ||||
|         break; | ||||
|       } | ||||
|  | ||||
|       while ((data_len = ::BIO_read(::SSL_get_wbio(front->ssl.get()), buf.data(), buf.size())) > 0) { | ||||
|         wsabuf.buf = buf.data(); | ||||
|         wsabuf.len = data_len; | ||||
|  | ||||
|         ::WSASend(sock, &wsabuf, 1, &sendbytes, 0, nullptr, nullptr); | ||||
|       } | ||||
|  | ||||
|     } else { | ||||
|     data_len = front->wsabuf.len; | ||||
|     wsabuf.buf = front->wsabuf.buf; | ||||
|     wsabuf.len = data_len; | ||||
|     ::WSASend(sock, &wsabuf, 1, &sendbytes, 0, nullptr, nullptr); | ||||
|   } | ||||
| } | ||||
| } | ||||
|  | ||||
| }  // namespace Network | ||||
|   | ||||
| @@ -2,6 +2,10 @@ | ||||
|  | ||||
| namespace Network { | ||||
|  | ||||
| Socket::Socket() { | ||||
|   init(AF_INET, SOCK_STREAM, 0); | ||||
| } | ||||
|  | ||||
| Socket::Socket(int domain, int type, int protocol) { | ||||
|   init(domain, type, protocol); | ||||
| } | ||||
| @@ -12,6 +16,7 @@ int Socket::init(int domain, int type, int protocol) { | ||||
|   this->domain = domain; | ||||
|  | ||||
|   sock = ::socket(domain, type, protocol); | ||||
|   // sock = ::WSASocket(domain, type, protocol, NULL, 0, WSA_FLAG_OVERLAPPED); | ||||
|   if (sock == INVALID_SOCKET) spdlog::critical("socket()"); | ||||
|  | ||||
|   valid_ = true; | ||||
| @@ -27,6 +32,7 @@ void Socket::destruct() { | ||||
|   ::close(sock); | ||||
| #endif | ||||
|   valid_ = false; | ||||
|   sock = 0; | ||||
| } | ||||
|  | ||||
| Socket::operator SOCKET() { | ||||
| @@ -40,7 +46,7 @@ Socket::operator SOCKET() { | ||||
|  | ||||
| void Socket::set(const SOCKET __sock, int __domain) { | ||||
|   if (__sock == INVALID_SOCKET) { | ||||
|     spdlog::critical("socket()"); | ||||
|     spdlog::error("set failed errno:{} {}", errno, strerror(errno)); | ||||
|     std::exit(EXIT_FAILURE); | ||||
|   } | ||||
|  | ||||
| @@ -59,12 +65,35 @@ int Socket::bind(Address __addr) { | ||||
|   bindAddr = __addr; | ||||
|   int retVal = ::bind(sock, &__addr.addr, __addr.length); | ||||
|   if (retVal == INVALID_SOCKET) { | ||||
|     int err = WSAGetLastError(); | ||||
|     spdlog::error("bind() failed: WSA error {} (0x{:X})", err, err); | ||||
|     spdlog::critical("bind()"); | ||||
|     std::exit(EXIT_FAILURE); | ||||
|   } | ||||
|   return retVal; | ||||
| } | ||||
|  | ||||
| int Socket::connect(Address& serveraddr) { | ||||
|   std::string addr_string = serveraddr; | ||||
|   int retVal = -1; | ||||
|   if (serveraddr.family == AF_INET) { | ||||
|     retVal = ::connect(sock, (const sockaddr*)&serveraddr.addr_in, | ||||
|                        serveraddr.length); | ||||
|   } else if (serveraddr.family == AF_INET6) { | ||||
|     retVal = ::connect(sock, (const sockaddr*)&serveraddr.addr_in6, | ||||
|                        serveraddr.length); | ||||
|   } | ||||
|   memcpy(&remoteAddr, &serveraddr, sizeof(Address)); | ||||
|   if (retVal == INVALID_SOCKET) { | ||||
| #ifdef _WIN32 | ||||
|     int err = WSAGetLastError(); | ||||
|     spdlog::error("connect() failed: WSA error {} (0x{:X})", err, err); | ||||
| #endif | ||||
|     spdlog::error("connect()"); | ||||
|   } | ||||
|   return retVal; | ||||
| } | ||||
|  | ||||
| int Socket::recvfrom(void* __restrict __buf, size_t __n, int __flags, | ||||
|                         struct Address& __addr) { | ||||
|   std::lock_guard<std::mutex> lock(readMutex); | ||||
| @@ -88,12 +117,6 @@ Socket::Socket(const Socket& other_) { | ||||
|   valid_ = false; | ||||
| } | ||||
|  | ||||
| Socket::Socket(Socket&& other_) noexcept { | ||||
|   other_.valid_ = false; | ||||
|   memcpy(this, &other_, sizeof(Socket)); | ||||
|   valid_ = true; | ||||
| } | ||||
|  | ||||
| Socket& Socket::operator=(const Socket& other_) { | ||||
|   memcpy(this, &other_, sizeof(Socket)); | ||||
|   valid_ = false; | ||||
| @@ -101,6 +124,12 @@ Socket& Socket::operator=(const Socket& other_) { | ||||
|   return *this; | ||||
| } | ||||
|  | ||||
| Socket::Socket(Socket&& other_) noexcept { | ||||
|   other_.valid_ = false; | ||||
|   memcpy(this, &other_, sizeof(Socket)); | ||||
|   valid_ = true; | ||||
| } | ||||
|  | ||||
| Socket& Socket::operator=(Socket&& other_) noexcept { | ||||
|   other_.valid_ = false; | ||||
|   memcpy(this, &other_, sizeof(Socket)); | ||||
|   | ||||
| @@ -2,6 +2,8 @@ | ||||
|  | ||||
| namespace Network { | ||||
|  | ||||
| TCPSocket::TCPSocket(int domain) { init(domain); } | ||||
|  | ||||
| int TCPSocket::init(int domain) { return init(domain, SOCK_STREAM, 0); } | ||||
|  | ||||
| int TCPSocket::listen(int __n) { | ||||
| @@ -10,30 +12,17 @@ int TCPSocket::listen(int __n) { | ||||
|   return retVal; | ||||
| } | ||||
|  | ||||
| void TCPSocket::accept(TCPSocket &newSock, Address &__addr) { | ||||
|   newSock.set(::accept(sock, &__addr.addr, &__addr.length), domain); | ||||
|   memcpy(&newSock.remoteAddr, &__addr, sizeof(Address)); | ||||
|   if (newSock.sock == INVALID_SOCKET) spdlog::error("accept()"); | ||||
| void TCPSocket::accept(std::shared_ptr<TCPSocket> &newSock, | ||||
|                                 Address &__addr) { | ||||
|   SOCKET newsock = INVALID_SOCKET; | ||||
|   newsock = ::accept(sock, &__addr.addr, &__addr.length); | ||||
|   if (newsock == INVALID_SOCKET) { | ||||
|     spdlog::error("accept() errno:{} {}", errno, strerror(errno)); | ||||
|     std::exit(EXIT_FAILURE); | ||||
|   } | ||||
|  | ||||
| int TCPSocket::connect(Address &serveraddr) { | ||||
|   std::string addr_string = serveraddr; | ||||
|   int retVal = -1; | ||||
|   if (serveraddr.family == AF_INET) | ||||
|     retVal = ::connect(sock, (const sockaddr *)&serveraddr.addr_in, | ||||
|                        serveraddr.length); | ||||
|   else | ||||
|     retVal = ::connect(sock, (const sockaddr *)&serveraddr.addr_in6, | ||||
|                        serveraddr.length); | ||||
|   memcpy(&remoteAddr, &serveraddr, sizeof(Address)); | ||||
|   if (retVal == INVALID_SOCKET) { | ||||
| #ifdef _WIN32 | ||||
|     int err = WSAGetLastError(); | ||||
|     spdlog::error("connect() failed: WSA error {} (0x{:X})", err, err); | ||||
| #endif | ||||
|     spdlog::error("connect()"); | ||||
|   } | ||||
|   return retVal; | ||||
|   newSock = std::make_shared<TCPSocket>(); | ||||
|   newSock->set(newsock, domain); | ||||
|   newSock->remoteAddr = __addr; | ||||
| } | ||||
|  | ||||
| int TCPSocket::recv(void *__restrict __buf, size_t __n, int __flags) { | ||||
|   | ||||
| @@ -4,4 +4,24 @@ namespace Network { | ||||
|  | ||||
| int UDPSocket::init(int domain) { return init(domain, SOCK_DGRAM, 0); } | ||||
|  | ||||
| int UDPSocket::connect(Address &serveraddr) { | ||||
|   std::string addr_string = serveraddr; | ||||
|   int retVal = -1; | ||||
|   if (serveraddr.family == AF_INET) | ||||
|     retVal = ::connect(sock, (const sockaddr *)&serveraddr.addr_in, | ||||
|                        serveraddr.length); | ||||
|   else | ||||
|     retVal = ::connect(sock, (const sockaddr *)&serveraddr.addr_in6, | ||||
|                        serveraddr.length); | ||||
|   memcpy(&remoteAddr, &serveraddr, sizeof(Address)); | ||||
|   if (retVal == INVALID_SOCKET) { | ||||
| #ifdef _WIN32 | ||||
|     int err = WSAGetLastError(); | ||||
|     spdlog::error("connect() failed: WSA error {} (0x{:X})", err, err); | ||||
| #endif | ||||
|     spdlog::error("connect()"); | ||||
|   } | ||||
|   return retVal; | ||||
| } | ||||
|  | ||||
| }  // namespace Network | ||||
|   | ||||
							
								
								
									
										16
									
								
								impl/utils/ConfigManager.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								impl/utils/ConfigManager.cpp
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,16 @@ | ||||
| #include "Utils/ConfigManager.h" | ||||
|  | ||||
| #include <json/json.h> | ||||
|  | ||||
| #include <fstream> | ||||
|  | ||||
| namespace utils { | ||||
| void ConfigManager::save(Config& config) { | ||||
|  | ||||
|   std::ofstream configfile("config.json", std::ios::out); | ||||
|  | ||||
|   configfile << config.configJsonRoot; | ||||
|  | ||||
|   configfile.close(); | ||||
| } | ||||
| }  // namespace utils | ||||
| @@ -9,13 +9,15 @@ static struct EpochInitializer { | ||||
|   std::chrono::system_clock::time_point EPOCH; | ||||
| } epochInitializer; | ||||
|  | ||||
| Snowflake GenerateID() { | ||||
| Snowflake GenerateID(std::uint8_t instance) { | ||||
|   static std::mutex snowflakeGenerateMutex_; | ||||
|  | ||||
|   std::lock_guard<std::mutex> lock(snowflakeGenerateMutex_); | ||||
|  | ||||
|   std::size_t tid = | ||||
|       std::hash<std::thread::id>{}(std::this_thread::get_id()); | ||||
|   instance = instance << 3; | ||||
|   tid += instance; | ||||
|  | ||||
|   thread_local static int sequence = 0; | ||||
|   Snowflake id = {}; | ||||
|   | ||||
							
								
								
									
										11
									
								
								impl/utils/utils.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										11
									
								
								impl/utils/utils.cpp
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,11 @@ | ||||
| #include "utils/utils.h" | ||||
|  | ||||
| namespace utils { | ||||
|  | ||||
| std::vector<char> CvtListToVector(std::list<char> data) { | ||||
|   std::vector<char> returnValue; | ||||
|   returnValue.insert(returnValue.end(), data.begin(), data.end()); | ||||
|   return returnValue; | ||||
| } | ||||
|  | ||||
| } | ||||
							
								
								
									
										117
									
								
								impl/vulkan_engine/asset/object/model.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										117
									
								
								impl/vulkan_engine/asset/object/model.cpp
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,117 @@ | ||||
| #include "vulkan_engine/asset/object/model.h" | ||||
|  | ||||
| #include "vulkan_engine/vulkan/graphics.h" | ||||
|  | ||||
| namespace veng { | ||||
|  | ||||
| Model::~Model() { | ||||
|   if (graphics_ == nullptr) return; | ||||
|  | ||||
|   graphics_->DestroyTexture(material.texture_handle); | ||||
|   graphics_->DestroyBuffer(vertex_buffer); | ||||
|   graphics_->DestroyBuffer(index_buffer); | ||||
| } | ||||
|  | ||||
| template <typename T> | ||||
| void Append(std::vector<char>& buffer, const T& value) { | ||||
|   const char* data = reinterpret_cast<const char*>(&value); | ||||
|   buffer.insert(buffer.end(), data, data + sizeof(T)); | ||||
| } | ||||
|  | ||||
| void Append(std::vector<char>& buffer, const std::string& value) { | ||||
|   size_t length = value.size(); | ||||
|   Append(buffer, length); | ||||
|   buffer.insert(buffer.end(), value.begin(), value.end()); | ||||
| } | ||||
|  | ||||
| template <typename T> | ||||
| void Read(const std::vector<char>& buffer, size_t& offset, T& out) { | ||||
|   std::memcpy(&out, buffer.data() + offset, sizeof(T)); | ||||
|   offset += sizeof(T); | ||||
| } | ||||
|  | ||||
| void Read(const std::vector<char>& buffer, size_t& offset, std::string& out) { | ||||
|   size_t length = 0; | ||||
|   Read(buffer, offset, length); | ||||
|   out.assign(buffer.data() + offset, length); | ||||
|   offset += length; | ||||
| } | ||||
|  | ||||
| std::vector<char> Model::Serialize() { | ||||
|   std::vector<char> buffer; | ||||
|  | ||||
|   Append(buffer, ID); | ||||
|   Append(buffer, name); | ||||
|   Append(buffer, asset_name); | ||||
|  | ||||
|   Append(buffer, position); | ||||
|   Append(buffer, linear_velocity); | ||||
|   Append(buffer, linear_acceleration); | ||||
|  | ||||
|   Append(buffer, rotation); | ||||
|   Append(buffer, angular_velocity); | ||||
|   Append(buffer, angular_acceleration); | ||||
|  | ||||
|   Append(buffer, scale); | ||||
|  | ||||
|   Append(buffer, original_offset); | ||||
|  | ||||
|   Append(buffer, OwnerID); | ||||
|  | ||||
|   Append(buffer, radius); | ||||
|   Append(buffer, lifespan); | ||||
|  | ||||
|   Append(buffer, visible); | ||||
|   Append(buffer, colision); | ||||
|  | ||||
|   Append(buffer, lastUpdatedTime); | ||||
|  | ||||
|   return buffer; | ||||
| } | ||||
|  | ||||
| void Model::Deserialize(std::vector<char> data) { | ||||
|   size_t offset = 0; | ||||
|  | ||||
|   Read(data, offset, ID); | ||||
|   Read(data, offset, name); | ||||
|   Read(data, offset, asset_name); | ||||
|  | ||||
|   Read(data, offset, position); | ||||
|   Read(data, offset, linear_velocity); | ||||
|   Read(data, offset, linear_acceleration); | ||||
|  | ||||
|   Read(data, offset, rotation); | ||||
|   Read(data, offset, angular_velocity); | ||||
|   Read(data, offset, angular_acceleration); | ||||
|  | ||||
|   Read(data, offset, scale); | ||||
|  | ||||
|   Read(data, offset, original_offset); | ||||
|  | ||||
|   Read(data, offset, OwnerID); | ||||
|  | ||||
|   Read(data, offset, radius); | ||||
|   Read(data, offset, lifespan); | ||||
|  | ||||
|   Read(data, offset, visible); | ||||
|   Read(data, offset, colision); | ||||
|  | ||||
|   Read(data, offset, lastUpdatedTime); | ||||
| } | ||||
|  | ||||
| void veng::Model::Update(float dt) { | ||||
|   linear_velocity += linear_acceleration * dt; | ||||
|   position += linear_velocity * dt; | ||||
|  | ||||
|   angular_velocity += angular_acceleration * dt; | ||||
|   if (glm::length(angular_velocity) > 1e-6f) { | ||||
|     rotation = | ||||
|         glm::normalize(glm::rotate(rotation, glm::length(angular_velocity * dt), | ||||
|                                    glm::normalize(angular_velocity))); | ||||
|   } | ||||
|  | ||||
|   transform = glm::translate(glm::mat4(1.0f), position) * | ||||
|               glm::mat4_cast(rotation) * glm::scale(glm::mat4(1.0f), scale); | ||||
| } | ||||
|  | ||||
| }  // namespace veng | ||||
| @@ -170,7 +170,7 @@ void Graphics::RenderIndexedBuffer(BufferHandle vertex_buffer, | ||||
|   vkCmdDrawIndexed(frames_[current_frame_].command_buffer, count, 1, 0, 0, 0); | ||||
|   SetModelMatrix(glm::mat4(1.f)); | ||||
| } | ||||
| void Graphics::RenderModel(Model* model) { | ||||
| void Graphics::RenderModel(std::shared_ptr<Model> model) { | ||||
|   if (!model->visible) return; | ||||
|   SetTexture(model->material.texture_handle); | ||||
|   SetModelMatrix(model->transform); | ||||
							
								
								
									
										360
									
								
								impl/vulkan_engine/vulkan/engine.cpp
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										360
									
								
								impl/vulkan_engine/vulkan/engine.cpp
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,360 @@ | ||||
| #include "vulkan_engine/vulkan/engine.h" | ||||
|  | ||||
| #include "precomp.h" | ||||
| #include "socket/packet.h" | ||||
| #include "utils/utils.h" | ||||
|  | ||||
| #define TICKRATE 10 | ||||
| constexpr double TICKDELAY = (1 / TICKRATE); | ||||
|  | ||||
| namespace veng { | ||||
|  | ||||
| void Engine::init() { | ||||
|   glm::ivec2 window_size_ = vulkan_graphics->window->GetFramebufferSize(); | ||||
|   view = glm::lookAt(glm::vec3(0.f, 0.f, -5.f), glm::vec3(0.f, 0.f, 0.f), | ||||
|                      glm::vec3(0.f, -1.f, 0.f)); | ||||
|   projection = glm::perspective( | ||||
|       glm::radians(103.f), | ||||
|       (std::float_t)window_size_.x / (std::float_t)window_size_.y, 0.1f, | ||||
|       1000.f); | ||||
|   vulkan_graphics->SetViewProjection(view, projection); | ||||
|  | ||||
|   if (BeginPlay != nullptr) BeginPlay(*this); | ||||
| } | ||||
|  | ||||
| void Engine::LoadModelAsset(std::string path, std::string name) { | ||||
|   model_assets_[name] = veng::Model(vulkan_graphics); | ||||
|   asset_loader_.setPath(path); | ||||
|   asset_loader_.loadModel(model_assets_[name]); | ||||
|  | ||||
|   model_assets_[name].vertex_buffer = | ||||
|       vulkan_graphics->CreateVertexBuffer(model_assets_[name].vertices); | ||||
|   model_assets_[name].index_buffer = | ||||
|       vulkan_graphics->CreateIndexBuffer(model_assets_[name].indices); | ||||
|   model_assets_[name].material.texture_handle = | ||||
|       vulkan_graphics->CreateTexture(asset_loader_.readTexture()); | ||||
| } | ||||
|  | ||||
| const Model* Engine::GetStaticModel(std::string name) { | ||||
|   if (model_assets_.find(name) != model_assets_.end()) | ||||
|     return &model_assets_[name]; | ||||
|   return nullptr; | ||||
| } | ||||
|  | ||||
| std::shared_ptr<Model> Engine::SpawnLifedModel(std::string asset_name, | ||||
|                                                std::string name, | ||||
|                                                std::float_t lifespan) { | ||||
|   if (asset_name == "") { | ||||
|     Model model_to_spawn(nullptr); | ||||
|     model_to_spawn.asset_name = ""; | ||||
|     model_to_spawn.name = name; | ||||
|     model_to_spawn.visible = false; | ||||
|     model_to_spawn.lifespan = lifespan; | ||||
|     models_[name] = std::make_shared<Model>(model_to_spawn); | ||||
|     model_to_spawn.owner = models_[name]; | ||||
|     return models_[name]; | ||||
|   } | ||||
|  | ||||
|   if (models_.find(name) == models_.end()) { | ||||
|     Model model_to_spawn(*GetStaticModel(asset_name)); | ||||
|     model_to_spawn.asset_name = asset_name; | ||||
|     model_to_spawn.name = name; | ||||
|     model_to_spawn.lifespan = lifespan; | ||||
|     models_[name] = std::make_shared<Model>(model_to_spawn); | ||||
|     model_to_spawn.owner = models_[name]; | ||||
|     return models_[name]; | ||||
|   } | ||||
|  | ||||
|   std::uint32_t i = 0; | ||||
|   for (i = 0; i < std::numeric_limits<std::uint32_t>::max();) { | ||||
|     if (models_.find(name + std::to_string(i)) == models_.end()) { | ||||
|       Model model_to_spawn(*GetStaticModel(asset_name)); | ||||
|       model_to_spawn.asset_name = asset_name; | ||||
|       model_to_spawn.name = name + std::to_string(i); | ||||
|       model_to_spawn.lifespan = lifespan; | ||||
|  | ||||
|       models_[name + std::to_string(i)] = | ||||
|           std::make_shared<Model>(model_to_spawn); | ||||
|       model_to_spawn.owner = models_[name + std::to_string(i)]; | ||||
|       break; | ||||
|     } | ||||
|     i++; | ||||
|   } | ||||
|  | ||||
|   if (i == std::numeric_limits<std::uint32_t>::max() - 1) | ||||
|     return nullptr; | ||||
|   else | ||||
|     return models_[name + std::to_string(i)]; | ||||
| } | ||||
|  | ||||
| std::shared_ptr<Model> Engine::GetSpawnedObject(std::string name) { | ||||
|   for (auto it = models_.begin(); it != models_.end();) { | ||||
|     if (it->first == name) return it->second; | ||||
|     ++it; | ||||
|   } | ||||
|  | ||||
|   return nullptr; | ||||
| } | ||||
|  | ||||
| void Engine::Update() { | ||||
|   glm::ivec2 framebuffer_size = vulkan_graphics->window->GetFramebufferSize(); | ||||
|   if (framebuffer_size != window_size_ && framebuffer_size.x != 0 && | ||||
|       framebuffer_size.y != 0) { | ||||
|     window_size_ = framebuffer_size; | ||||
|     auto grater = (framebuffer_size.x > framebuffer_size.y) | ||||
|                       ? framebuffer_size.x | ||||
|                       : framebuffer_size.y; | ||||
|     view = glm::lookAt(glm::vec3(0.f, 0.f, -5.f), glm::vec3(0.f, 0.f, 0.f), | ||||
|                        glm::vec3(0.f, -1.f, 0.f)); | ||||
|     projection = glm::perspective( | ||||
|         glm::radians(103.f), | ||||
|         (std::float_t)framebuffer_size.x / (std::float_t)framebuffer_size.y, | ||||
|         0.1f, 1000.f); | ||||
|   } | ||||
|   vulkan_graphics->SetViewProjection(view, projection); | ||||
|  | ||||
|   if (vulkan_graphics->BeginFrame()) { | ||||
|     std::double_t current_time = glfwGetTime(); | ||||
|     std::float_t delta_time = | ||||
|         static_cast<std::float_t>(current_time - last_frame_time_); | ||||
|     last_frame_time_ = current_time; | ||||
|  | ||||
|     if (Tick != nullptr) Tick(*this, delta_time); | ||||
|  | ||||
|     for (auto it = models_.begin(); it != models_.end();) { | ||||
|       auto& model = it->second; | ||||
|  | ||||
|       if (std::abs(model->lifespan + 1.f) < | ||||
|           std::numeric_limits<float>::epsilon()) { | ||||
|         ++it; | ||||
|         continue; | ||||
|       } | ||||
|  | ||||
|       if (model->lifespan <= 0.f) { | ||||
|         it = models_.erase(it); | ||||
|         continue; | ||||
|       } | ||||
|  | ||||
|       if (model->shouldBeDestroyed) { | ||||
|         it = models_.erase(it); | ||||
|         continue; | ||||
|       } | ||||
|  | ||||
|       model->lifespan -= delta_time; | ||||
|       ++it; | ||||
|     } | ||||
|  | ||||
|     for (auto& it : models_) { | ||||
|       it.second->Update(it.second->lastUpdatedTime + delta_time); | ||||
|       vulkan_graphics->RenderModel(it.second); | ||||
|     } | ||||
|  | ||||
|     // Physics::invokeOnColisionEvent(thread_pool_, models_); | ||||
|  | ||||
|     vulkan_graphics->EndFrame(); | ||||
|   } | ||||
| } | ||||
| void Engine::NetUpdate(std::shared_ptr<Network::Socket> sock) { | ||||
|   NetworkUpload(sock); | ||||
| } | ||||
|  | ||||
| void Engine::NetworkUpload(std::shared_ptr<Network::Socket> sock) { | ||||
|   static double last_all_updated; | ||||
|   auto current_time = glfwGetTime(); | ||||
|   bool needs_all_update = false; | ||||
|   if (current_time - last_all_updated >= TICKDELAY) { | ||||
|     needs_all_update = true; | ||||
|     last_all_updated = glfwGetTime(); | ||||
|   } | ||||
|  | ||||
|   std::vector<char> data; | ||||
|   for (auto& it : models_) { | ||||
|     std::lock_guard lock(it.second->modding); | ||||
|     if (!it.second->networkReplicated && !needs_all_update) continue; | ||||
|     if (!it.second->needsUpdate && !needs_all_update) continue; | ||||
|  | ||||
|     Packet::Header header; | ||||
|     header.opcode = Packet::Opcode::UPDATEMODEL; | ||||
|     header.timestamp = glfwGetTime(); | ||||
|     std::vector<char> model = it.second->Serialize(); | ||||
|     header.body_length = model.size(); | ||||
|     std::vector<char> header_serialized = header.Serialize(); | ||||
|  | ||||
|     data.insert(data.end(), header_serialized.begin(), header_serialized.end()); | ||||
|     data.insert(data.end(), model.begin(), model.end()); | ||||
|     if (it.second->updateRedundantCount <= 1) { | ||||
|       it.second->needsUpdate = false; | ||||
|     } else { | ||||
|       it.second->updateRedundantCount--; | ||||
|     } | ||||
|     spdlog::debug("{} uploaded", it.second->name); | ||||
|   } | ||||
|   iocp_->send(sock, data); | ||||
| } | ||||
|  | ||||
| float GetAlpha(double old_time, double new_time) { | ||||
|   return (glfwGetTime() - old_time) / (new_time - old_time) * 0.5; | ||||
| } | ||||
|  | ||||
| void Interpolation(Packet::Header header, std::shared_ptr<veng::Model> local, | ||||
|                    std::shared_ptr<veng::Model> remote) { | ||||
|   constexpr float position_threshold = 5.0f;  // 위치 차이 임계값 | ||||
|   constexpr float rotation_threshold = 0.5f;  // 회전 차이 임계값 (라디안 기준) | ||||
|  | ||||
|   std::lock_guard lock(local->modding); | ||||
|   float alpha = GetAlpha(local->lastUpdatedTime, header.timestamp); | ||||
|  | ||||
|   // 위치 보간 또는 강제 이동 | ||||
|   if (glm::distance(local->position, remote->position) > position_threshold) { | ||||
|     local->position = remote->position; | ||||
|   } else { | ||||
|     local->position = glm::mix(local->position, remote->position, alpha); | ||||
|   } | ||||
|  | ||||
|   // 선속도 | ||||
|   if (glm::length(remote->linear_velocity - local->linear_velocity) > | ||||
|       position_threshold) { | ||||
|     local->linear_velocity = remote->linear_velocity; | ||||
|   } else { | ||||
|     local->linear_velocity = | ||||
|         glm::mix(local->linear_velocity, remote->linear_velocity, alpha); | ||||
|   } | ||||
|  | ||||
|   local->linear_acceleration = | ||||
|       glm::mix(local->linear_acceleration, remote->linear_acceleration, alpha); | ||||
|  | ||||
|   // 회전 보간 또는 강제 이동 | ||||
|   if (glm::length(remote->rotation - local->rotation) > rotation_threshold) { | ||||
|     local->rotation = remote->rotation; | ||||
|   } else { | ||||
|     local->rotation = glm::mix(local->rotation, remote->rotation, alpha); | ||||
|   } | ||||
|  | ||||
|   local->angular_velocity = | ||||
|       glm::mix(local->angular_velocity, remote->angular_velocity, alpha); | ||||
|  | ||||
|   local->angular_acceleration = glm::mix(local->angular_acceleration, | ||||
|                                          remote->angular_acceleration, alpha); | ||||
|  | ||||
|   // 스케일은 보간만 적용 | ||||
|   local->scale = glm::mix(local->scale, remote->scale, alpha); | ||||
|  | ||||
|   // 동기화 항목은 그대로 적용 | ||||
|   local->original_offset = remote->original_offset; | ||||
|   local->radius = remote->radius; | ||||
|   local->lifespan = remote->lifespan; | ||||
|   local->visible = remote->visible; | ||||
|   local->colision = remote->colision; | ||||
| } | ||||
|  | ||||
|  | ||||
| //void Interpolation(Packet::Header header, std::shared_ptr<veng::Model> local, | ||||
| //                   std::shared_ptr<veng::Model> remote) { | ||||
| //  std::lock_guard lock(local->modding); | ||||
| //  local->position = | ||||
| //      glm::mix(local->position, remote->position, | ||||
| //               GetAlpha(local->lastUpdatedTime, header.timestamp)); | ||||
| //  local->linear_velocity = | ||||
| //      glm::mix(local->linear_velocity, remote->linear_velocity, | ||||
| //               GetAlpha(local->lastUpdatedTime, header.timestamp)); | ||||
| //  local->linear_acceleration = | ||||
| //      glm::mix(local->linear_acceleration, remote->linear_acceleration, | ||||
| //               GetAlpha(local->lastUpdatedTime, header.timestamp)); | ||||
| // | ||||
| //  local->rotation = | ||||
| //      glm::mix(local->rotation, remote->rotation, | ||||
| //               GetAlpha(local->lastUpdatedTime, header.timestamp)); | ||||
| //  local->angular_velocity = | ||||
| //      glm::mix(local->angular_velocity, remote->angular_velocity, | ||||
| //               GetAlpha(local->lastUpdatedTime, header.timestamp)); | ||||
| //  local->angular_acceleration = | ||||
| //      glm::mix(local->angular_acceleration, remote->angular_acceleration, | ||||
| //               GetAlpha(local->lastUpdatedTime, header.timestamp)); | ||||
| // | ||||
| //  local->scale = glm::mix(local->scale, remote->scale, | ||||
| //                          GetAlpha(local->lastUpdatedTime, header.timestamp)); | ||||
| // | ||||
| //  local->original_offset = remote->original_offset; | ||||
| //  local->radius = remote->radius; | ||||
| //  local->lifespan = remote->lifespan; | ||||
| // | ||||
| //  local->visible = remote->visible; | ||||
| //  local->colision = remote->colision; | ||||
| //} | ||||
|  | ||||
| void Engine::ResponseToServerAndRefresh(std::shared_ptr<Network::Socket> sock) { | ||||
|   if (sock->sock == 0) return; | ||||
|  | ||||
|   auto result = iocp_->recv(sock, 14); | ||||
|   auto recv_data = utils::CvtListToVector(result.get()); // 여기서 막혀서 프로그램이 리턴을 못하는 문제가 있음.. | ||||
|  | ||||
|   Packet::Header header; | ||||
|   header.Deserialize(recv_data); | ||||
|  | ||||
|   result = iocp_->recv(sock, header.body_length); | ||||
|   recv_data = utils::CvtListToVector(result.get()); | ||||
|  | ||||
|   switch (header.opcode) { | ||||
|     case Packet::Opcode::UPDATEMODEL: { | ||||
|       std::shared_ptr<veng::Model> model = std::make_shared<veng::Model>(); | ||||
|       model->Deserialize(recv_data); | ||||
|  | ||||
|       bool found = false; | ||||
|       for (auto& it : models_) { | ||||
|         if (it.second->ID == model->ID) { | ||||
|           Interpolation(header, it.second, model); | ||||
|           // spdlog::debug("model updated: [{}:{}]", model->name, model->ID.snowflake); | ||||
|           found = true; | ||||
|           break; | ||||
|         } | ||||
|       } | ||||
|  | ||||
|       if (!found) { | ||||
|         auto spawnedModel = | ||||
|             SpawnLifedModel(model->asset_name, model->name, model->lifespan); | ||||
|         std::lock_guard lock(spawnedModel->modding); | ||||
|         spawnedModel->ID = model->ID; | ||||
|         spawnedModel->position = model->position; | ||||
|         spawnedModel->linear_velocity = model->linear_velocity; | ||||
|         spawnedModel->linear_acceleration = model->linear_acceleration; | ||||
|  | ||||
|         spawnedModel->rotation = model->rotation; | ||||
|         spawnedModel->angular_velocity = model->angular_velocity; | ||||
|         spawnedModel->angular_acceleration = model->angular_acceleration; | ||||
|  | ||||
|         spawnedModel->scale = model->scale; | ||||
|         spawnedModel->transform = model->transform; | ||||
|  | ||||
|         spawnedModel->original_offset = model->original_offset; | ||||
|         spawnedModel->radius = model->radius; | ||||
|         spawnedModel->lifespan = model->lifespan; | ||||
|  | ||||
|         spawnedModel->visible = model->visible; | ||||
|         spawnedModel->colision = model->colision; | ||||
|         spawnedModel->networkReplicated = false; | ||||
|         spdlog::info("model spawned: {}", model->ID.snowflake); | ||||
|       } | ||||
|     } break; | ||||
|     case Packet::Opcode::DESPAWNMODEL: { | ||||
|       std::shared_ptr<veng::Model> model = std::make_shared<veng::Model>(); | ||||
|       model->Deserialize(recv_data); | ||||
|  | ||||
|       for (auto it = models_.begin(); it != models_.end();) { | ||||
|         if (it->second->ID == model->ID) { | ||||
|           models_.erase(it); | ||||
|           break; | ||||
|         } | ||||
|         ++it; | ||||
|       } | ||||
|     } break; | ||||
|     default: | ||||
|       spdlog::error("unknown data type"); | ||||
|   } | ||||
|   thread_pool_->enqueueJob( | ||||
|       [this, sock](utils::ThreadPool* tp, std::uint32_t __) { | ||||
|         ResponseToServerAndRefresh(sock); | ||||
|       }, | ||||
|       0); | ||||
| } | ||||
|  | ||||
| }  // namespace veng | ||||
| @@ -5,35 +5,64 @@ | ||||
| 
 | ||||
| namespace veng { | ||||
| void Physics::invokeOnColisionEvent( | ||||
|     gsl::not_null<utils::ThreadPool*> thread_pool, gsl::span<Model*> models) { | ||||
|     gsl::not_null<utils::ThreadPool*> thread_pool, | ||||
|     std::unordered_map<std::string, std::shared_ptr<Model>>& models) { | ||||
|   constexpr std::float_t EPSILON = std::numeric_limits<std::float_t>::epsilon(); | ||||
| 
 | ||||
|   for (int first = 0; first < models.size(); first++) { | ||||
|     if (!models[first]->colision) continue; | ||||
|     for (int second = first + 1; second < models.size(); second++) { | ||||
|       if (!models[second]->colision) continue; | ||||
|   for (std::unordered_map<std::string, std::shared_ptr<Model>>::iterator | ||||
|            iter_A = models.begin(); | ||||
|        iter_A != models.end(); iter_A++) { | ||||
|     for (auto iter_B = std::next(iter_A); iter_B != models.end(); iter_B++) { | ||||
|       auto model_A = iter_A->second; | ||||
|       std::lock_guard<std::mutex> Alock(model_A->modding); | ||||
|       auto model_B = iter_B->second; | ||||
|       std::lock_guard<std::mutex> Block(model_B->modding); | ||||
|       if (!model_A->colision || !model_B->colision) continue; | ||||
|       std::float_t distance = | ||||
|           glm::distance(models[first]->position, models[second]->position); | ||||
|       std::float_t model1_radius = | ||||
|           models[first]->radius * models[first]->scale.x; | ||||
|       std::float_t model2_radius = | ||||
|           models[second]->radius * models[second]->scale.x; | ||||
|       if (distance <= model1_radius + model2_radius) { | ||||
|         if (models[first]->OnColision != nullptr) | ||||
|           thread_pool->enqueueJob( | ||||
|               [OnColision = models[first]->OnColision]( | ||||
|                   utils::ThreadPool* thread_pool, Model* self, Model* other) { | ||||
|                 OnColision(self, other); | ||||
|               }, | ||||
|               models[first], models[second]); | ||||
|         if (models[second]->OnColision != nullptr) | ||||
|           thread_pool->enqueueJob( | ||||
|               [OnColision = models[second]->OnColision]( | ||||
|                   utils::ThreadPool* thread_pool, Model* self, Model* other) { | ||||
|                 OnColision(self, other); | ||||
|               }, | ||||
|               models[second], models[first]); | ||||
|         break; | ||||
|           glm::distance(model_A->position, model_B->position); | ||||
|       std::float_t modelA_radius = model_A->radius * model_A->scale.x; | ||||
|       std::float_t modelB_radius = model_B->radius * model_B->scale.x; | ||||
|       if (distance <= modelA_radius + modelB_radius) { | ||||
|         model_A = iter_A->second; | ||||
|         model_B = iter_B->second; | ||||
|         if (model_A->OnColision) | ||||
|           thread_pool->enqueueJob(model_A->OnColision, model_A, model_B); | ||||
|         model_A = iter_A->second; | ||||
|         model_B = iter_B->second; | ||||
|         if (model_B->OnColision) | ||||
|           thread_pool->enqueueJob(model_B->OnColision, model_A, model_B); | ||||
|       } | ||||
|     } | ||||
|   } | ||||
| } | ||||
| 
 | ||||
| void Physics::invokeOnColisionEvent( | ||||
|     gsl::not_null<utils::ThreadPool*> thread_pool, | ||||
|     std::unordered_map<utils::Snowflake, std::shared_ptr<Model>>& models) { | ||||
|   constexpr std::float_t EPSILON = std::numeric_limits<std::float_t>::epsilon(); | ||||
| 
 | ||||
|   for (std::unordered_map<utils::Snowflake, std::shared_ptr<Model>>::iterator | ||||
|            iter_A = models.begin(); | ||||
|        iter_A != models.end(); iter_A++) { | ||||
|     for (auto iter_B = std::next(iter_A); iter_B != models.end(); iter_B++) { | ||||
|       auto model_A = iter_A->second; | ||||
|       std::lock_guard<std::mutex> Alock(model_A->modding); | ||||
|       auto model_B = iter_B->second; | ||||
|       std::lock_guard<std::mutex> Block(model_B->modding); | ||||
|       if (!model_A->colision || !model_B->colision) continue; | ||||
|       std::float_t distance = | ||||
|           glm::distance(model_A->position, model_B->position); | ||||
|       std::float_t modelA_radius = model_A->radius * model_A->scale.x; | ||||
|       std::float_t modelB_radius = model_B->radius * model_B->scale.x; | ||||
|       if (distance <= modelA_radius + modelB_radius) { | ||||
|         model_A = iter_A->second; | ||||
|         model_B = iter_B->second; | ||||
|         if (model_A->OnColision) | ||||
|           thread_pool->enqueueJob(model_A->OnColision, model_A, model_B); | ||||
|         model_A = iter_A->second; | ||||
|         model_B = iter_B->second; | ||||
|         if (model_B->OnColision) | ||||
|           thread_pool->enqueueJob(model_B->OnColision, model_A, model_B); | ||||
|       } | ||||
|     } | ||||
|   } | ||||
| @@ -42,7 +71,7 @@ void Physics::invokeOnColisionEvent( | ||||
| bool Physics::RayTrace(const glm::vec3& rayOrigin, const glm::vec3& rayDir, | ||||
|                        const glm::vec3& v0, const glm::vec3& v1, | ||||
|                        const glm::vec3& v2, std::float_t& outDistance) { | ||||
|   const std::float_t EPSILON = std::numeric_limits<std::float_t>::epsilon(); | ||||
|   constexpr std::float_t EPSILON = std::numeric_limits<std::float_t>::epsilon(); | ||||
| 
 | ||||
|   // 삼각형 엣지와 노멀 계산
 | ||||
|   glm::vec3 edge1 = v1 - v0; | ||||
| @@ -1,9 +1,5 @@ | ||||
| #pragma once | ||||
|  | ||||
| #include <openssl/bio.h> | ||||
| #include <openssl/err.h> | ||||
| #include <openssl/ssl.h> | ||||
|  | ||||
| #include "socket/iocp.h" | ||||
| #include "utils/thread_pool.h" | ||||
|  | ||||
| @@ -23,8 +19,5 @@ class Session { | ||||
|  | ||||
|   SessionProtocol proto_; | ||||
|   Network::Socket* sock_ = nullptr; | ||||
|  | ||||
|   SSL_CTX* ssl_ctx_ = nullptr; | ||||
|   SSL* ssl_ = nullptr; | ||||
| }; | ||||
| }  // namespace Network | ||||
|   | ||||
| @@ -1,9 +1,5 @@ | ||||
| #pragma once | ||||
|  | ||||
| #include <openssl/bio.h> | ||||
| #include <openssl/err.h> | ||||
| #include <openssl/ssl.h> | ||||
|  | ||||
| namespace Network { | ||||
|  | ||||
| struct Address { | ||||
| @@ -14,6 +10,9 @@ struct Address { | ||||
|   void set(int type, gsl::czstring presentationAddr, std::uint16_t port); | ||||
|   void setType(int type); | ||||
|  | ||||
|   Address(const Address&) = default; | ||||
|   Address& operator=(const Address&) = default; | ||||
|  | ||||
|   operator std::string(); | ||||
|   std::uint16_t getPort() const; | ||||
|  | ||||
| @@ -24,8 +23,6 @@ struct Address { | ||||
|     struct sockaddr_in6 addr_in6; | ||||
|   }; | ||||
|   socklen_t length; | ||||
|  | ||||
|   BIO_ADDR* bio_addr_info; | ||||
| }; | ||||
|  | ||||
| }  // namespace Chattr | ||||
|   | ||||
| @@ -1,7 +1,4 @@ | ||||
| #pragma once | ||||
| #include <openssl/bio.h> | ||||
| #include <openssl/err.h> | ||||
| #include <openssl/ssl.h> | ||||
|  | ||||
| #include <functional> | ||||
| #include <queue> | ||||
| @@ -27,91 +24,10 @@ typedef struct __WSABUF { | ||||
|  | ||||
| namespace Network { | ||||
|  | ||||
| class IOCP; | ||||
| struct IOCPPASSINDATA; | ||||
|  | ||||
| enum class IOCPEVENT { QUIT, READ, WRITE }; | ||||
|  | ||||
| struct IOCPPASSINDATA { | ||||
|   OVERLAPPED overlapped; | ||||
|   IOCPEVENT event; | ||||
|   std::shared_ptr<Socket> socket; | ||||
|   std::shared_ptr<SSL> ssl; | ||||
|   std::uint32_t transferredbytes; | ||||
|   WSABUF wsabuf; | ||||
|   std::uint32_t bufsize; | ||||
|   IOCP* IOCPInstance; | ||||
| #ifdef __linux__ | ||||
|   std::shared_ptr<std::queue<IOCPPASSINDATA*>> sendQueue; | ||||
| #endif | ||||
|  | ||||
|   IOCPPASSINDATA(std::uint32_t bufsize) { | ||||
|     std::memset(&overlapped, 0, sizeof(overlapped)); | ||||
|     event = IOCPEVENT::QUIT; | ||||
|     socket = nullptr; | ||||
|     ssl = nullptr; | ||||
|     transferredbytes = 0; | ||||
|     this->bufsize = bufsize; | ||||
|     IOCPInstance = nullptr; | ||||
|  | ||||
|     wsabuf.buf = new char[bufsize]; | ||||
|     wsabuf.len = bufsize; | ||||
|   } | ||||
|   IOCPPASSINDATA(std::uint32_t bufsize, SSL_CTX* ctx) { | ||||
|     std::memset(&overlapped, 0, sizeof(overlapped)); | ||||
|     event = IOCPEVENT::QUIT; | ||||
|     socket = nullptr; | ||||
|     ssl = std::shared_ptr<SSL>(::SSL_new(ctx), ::SSL_free); | ||||
|     ::SSL_set_bio(ssl.get(), ::BIO_new(::BIO_s_mem()), | ||||
|                   ::BIO_new(::BIO_s_mem())); | ||||
|     transferredbytes = 0; | ||||
|     this->bufsize = bufsize; | ||||
|     IOCPInstance = nullptr; | ||||
|  | ||||
|     wsabuf.buf = new char[bufsize]; | ||||
|     wsabuf.len = bufsize; | ||||
|   } | ||||
|  | ||||
|   IOCPPASSINDATA(const IOCPPASSINDATA& other) { | ||||
|     if (this != &other) { | ||||
|       std::memset(&overlapped, 0, sizeof(overlapped)); | ||||
|       event = other.event; | ||||
|       socket = other.socket; | ||||
|       transferredbytes = other.transferredbytes; | ||||
|       bufsize = other.bufsize; | ||||
|       IOCPInstance = other.IOCPInstance; | ||||
| #ifdef __linux__ | ||||
|       sendQueue = other.sendQueue; | ||||
| #endif | ||||
|       wsabuf.buf = new char[other.bufsize]; | ||||
|       wsabuf.len = other.bufsize; | ||||
|       std::memcpy(wsabuf.buf, other.wsabuf.buf, other.wsabuf.len); | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   ~IOCPPASSINDATA() { | ||||
|     if (wsabuf.buf != nullptr) delete[] wsabuf.buf; | ||||
|     wsabuf.buf = nullptr; | ||||
|   } | ||||
|  | ||||
|   IOCPPASSINDATA& operator=(const IOCPPASSINDATA& other) { | ||||
|     if (this != &other) { | ||||
|       std::memset(&overlapped, 0, sizeof(overlapped)); | ||||
|       event = other.event; | ||||
|       socket = other.socket; | ||||
|       transferredbytes = other.transferredbytes; | ||||
|       bufsize = other.bufsize; | ||||
|       IOCPInstance = other.IOCPInstance; | ||||
| #ifdef __linux__ | ||||
|       sendQueue = other.sendQueue; | ||||
| #endif | ||||
|       if (wsabuf.buf != nullptr) delete[] wsabuf.buf; | ||||
|       wsabuf.buf = new char[other.bufsize]; | ||||
|       wsabuf.len = other.bufsize; | ||||
|       std::memcpy(wsabuf.buf, other.wsabuf.buf, other.wsabuf.len); | ||||
|     } | ||||
|     return *this; | ||||
|   } | ||||
| }; | ||||
| std::list<char> DEFAULT_RECVALL_CALLBACK(utils::ThreadPool* th, | ||||
|                                          IOCPPASSINDATA* data); | ||||
|  | ||||
| class IOCP { | ||||
|  public: | ||||
| @@ -122,13 +38,25 @@ class IOCP { | ||||
|  | ||||
|   void destruct(); | ||||
|  | ||||
|   void registerSocket(IOCPPASSINDATA* data); | ||||
|   void registerSocket(std::shared_ptr<Socket> sock); | ||||
|  | ||||
|   int recv(IOCPPASSINDATA* data); | ||||
|   std::future<std::vector<char>> recvFull( | ||||
|       std::shared_ptr<Socket> sock, std::uint32_t bufsize); | ||||
|  | ||||
|   std::future<std::list<char>> recv( | ||||
|       std::shared_ptr<Socket> sock, std::uint32_t bufsize, | ||||
|       std::function<std::list<char>(utils::ThreadPool*, IOCPPASSINDATA*)> | ||||
|           callback = DEFAULT_RECVALL_CALLBACK); | ||||
|   // data는 한 가지 소켓에 보내는 패킷만 담아야 합니다 | ||||
|   int send(SOCKET sock, std::vector<IOCPPASSINDATA*>* data); | ||||
|   int send(std::shared_ptr<Socket> sock, std::vector<char>& data); | ||||
|  | ||||
|   int GetRecvedPacketCount(SOCKET sock); | ||||
|   int GetRecvedBytes(SOCKET sock); | ||||
|  | ||||
|   std::shared_ptr<std::list<IOCPPASSINDATA*>> GetSendQueue(SOCKET sock); | ||||
|   std::shared_ptr<std::list<std::pair<std::vector<char>, std::uint32_t>>> | ||||
|   GetRecvQueue(SOCKET sock); | ||||
|   std::shared_ptr<std::mutex> GetSendQueueMutex(SOCKET sock); | ||||
|   std::shared_ptr<std::mutex> GetRecvQueueMutex(SOCKET sock); | ||||
|  | ||||
|  private: | ||||
| #ifdef _WIN32 | ||||
| @@ -137,12 +65,6 @@ class IOCP { | ||||
|  | ||||
| #endif | ||||
|  | ||||
|   std::shared_ptr<std::list<IOCPPASSINDATA*>> GetSendQueue_(SOCKET sock); | ||||
|   std::shared_ptr<std::list<std::pair<std::vector<char>, std::uint32_t>>> | ||||
|   GetRecvQueue_(SOCKET sock); | ||||
|   std::shared_ptr<std::mutex> GetSendQueueMutex_(SOCKET sock); | ||||
|   std::shared_ptr<std::mutex> GetRecvQueueMutex_(SOCKET sock); | ||||
|  | ||||
|   void packet_sender_(SOCKET sock); | ||||
|   utils::ThreadPool* IOCPThread_; | ||||
|  | ||||
| @@ -195,4 +117,56 @@ class IOCP { | ||||
| #endif | ||||
| }; | ||||
|  | ||||
| enum class IOCPEVENT { QUIT, READ, WRITE }; | ||||
|  | ||||
| struct IOCPPASSINDATA { | ||||
|   OVERLAPPED overlapped; | ||||
|   IOCPEVENT event; | ||||
|   std::shared_ptr<Socket> socket; | ||||
|   std::uint32_t transferredbytes; | ||||
|   WSABUF wsabuf; | ||||
|   IOCP* IOCPInstance; | ||||
|   std::packaged_task<std::list<char>(utils::ThreadPool*, IOCPPASSINDATA*)> | ||||
|       callback; | ||||
| #ifdef __linux__ | ||||
|   std::shared_ptr<std::queue<IOCPPASSINDATA*>> sendQueue; | ||||
| #endif | ||||
|   IOCPPASSINDATA(std::shared_ptr<Socket> socket, std::uint32_t bufsize, | ||||
|                  IOCP* IOCPInstance) | ||||
|       : event(IOCPEVENT::QUIT), | ||||
|         socket(socket), | ||||
|         transferredbytes(0), | ||||
|         IOCPInstance(IOCPInstance) { | ||||
|     std::memset(&overlapped, 0, sizeof(overlapped)); | ||||
|  | ||||
|     wsabuf.buf = new char[bufsize]; | ||||
|     wsabuf.len = bufsize; | ||||
|   } | ||||
|  | ||||
|   IOCPPASSINDATA( | ||||
|       std::shared_ptr<Socket> socket, std::uint32_t bufsize, IOCP* IOCPInstance, | ||||
|       std::packaged_task<std::list<char>(utils::ThreadPool*, IOCPPASSINDATA*)> | ||||
|           callback_) | ||||
|       : event(IOCPEVENT::QUIT), | ||||
|         socket(socket), | ||||
|         transferredbytes(0), | ||||
|         IOCPInstance(IOCPInstance), | ||||
|         callback(std::move(callback_)) { | ||||
|     std::memset(&overlapped, 0, sizeof(overlapped)); | ||||
|  | ||||
|     wsabuf.buf = new char[bufsize]; | ||||
|     wsabuf.len = bufsize; | ||||
|   } | ||||
|  | ||||
|   ~IOCPPASSINDATA() { | ||||
|     if (wsabuf.buf != nullptr) delete[] wsabuf.buf; | ||||
|     wsabuf.buf = nullptr; | ||||
|   } | ||||
|  | ||||
|   IOCPPASSINDATA(const IOCPPASSINDATA& other) = delete; | ||||
|   IOCPPASSINDATA& operator=(const IOCPPASSINDATA&) = delete; | ||||
|   IOCPPASSINDATA(IOCPPASSINDATA&&) = default; | ||||
|   IOCPPASSINDATA& operator=(IOCPPASSINDATA&&) = default; | ||||
| }; | ||||
|  | ||||
| }  // namespace Network | ||||
|   | ||||
							
								
								
									
										37
									
								
								include/socket/packet.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										37
									
								
								include/socket/packet.h
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,37 @@ | ||||
| #pragma once | ||||
|  | ||||
| #include <cstdint> | ||||
|  | ||||
| namespace Packet { | ||||
|  | ||||
| enum class Opcode : std::uint16_t { | ||||
|   NOP, | ||||
|   SPAWNMODEL, | ||||
|   DESPAWNMODEL, | ||||
|   UPDATEMODEL, | ||||
|   REQUESTMODELIDLIST, | ||||
|   CLIENTID, | ||||
|   COUNT | ||||
| }; | ||||
|  | ||||
| struct Header { | ||||
|   Opcode opcode; | ||||
|   double timestamp; | ||||
|   std::uint32_t body_length; | ||||
|  | ||||
|   std::vector<char> Serialize() { | ||||
|     std::vector<char> serialize(14); | ||||
|     ::memcpy(serialize.data(), &opcode, 2); | ||||
|     ::memcpy(serialize.data() + 2, ×tamp, 8); | ||||
|     ::memcpy(serialize.data() + 10, &body_length, 4); | ||||
|     return serialize; | ||||
|   } | ||||
|  | ||||
|   void Deserialize(std::vector<char>& data) { | ||||
|     ::memcpy(&opcode, data.data(), 2); | ||||
|     ::memcpy(×tamp, data.data() + 2, 8); | ||||
|     ::memcpy(&body_length, data.data() + 10, 4); | ||||
|   } | ||||
| }; | ||||
|  | ||||
| }  // namespace Packet | ||||
| @@ -7,7 +7,7 @@ struct Address; | ||||
|  | ||||
| class Socket { | ||||
|  public: | ||||
|   Socket() = default; | ||||
|   Socket(); | ||||
|   Socket(int domain, int type, int protocol); | ||||
|   ~Socket(); | ||||
|  | ||||
| @@ -19,14 +19,16 @@ class Socket { | ||||
|   int setsockopt(int level, int optname, const char* optval, int optlen); | ||||
|  | ||||
|   int bind(Address __addr); | ||||
|   int connect(Network::Address& serveraddr); | ||||
|  | ||||
|   int recvfrom(void* __restrict __buf, size_t __n, int __flags, | ||||
|                struct Address& __addr); | ||||
|   int sendto(const void* __buf, size_t __n, int __flags, struct Address __addr); | ||||
|  | ||||
|   Socket(const Socket&); | ||||
|   Socket(Socket&&) noexcept; | ||||
|   Socket& operator=(const Socket&); | ||||
|  | ||||
|   Socket(Socket&&) noexcept; | ||||
|   Socket& operator=(Socket&&) noexcept; | ||||
|  | ||||
|   struct Address bindAddr = {}; | ||||
| @@ -38,7 +40,7 @@ class Socket { | ||||
|   std::mutex readMutex; | ||||
|   std::mutex writeMutex; | ||||
|  | ||||
|  protected: | ||||
| private: | ||||
|   bool valid_ = false; | ||||
| }; | ||||
|  | ||||
|   | ||||
| @@ -7,10 +7,11 @@ class TCPSocket : public Socket { | ||||
|  public: | ||||
|   using Socket::init; | ||||
|   using Socket::Socket; | ||||
|   TCPSocket(int domain); | ||||
|  | ||||
|   int init(int domain); | ||||
|   int listen(int __n); | ||||
|   void accept(TCPSocket& newSock, Address& addr); | ||||
|   int connect(Network::Address& serveraddr); | ||||
|   void accept(std::shared_ptr<TCPSocket>& newSock, Address& addr); | ||||
|   int recv(void* __restrict __buf, size_t __n, int __flags); | ||||
|   int send(const void* __buf, size_t __n, int __flags); | ||||
| }; | ||||
|   | ||||
| @@ -10,6 +10,7 @@ class UDPSocket : public Socket { | ||||
|   using Socket::init; | ||||
|   using Socket::Socket; | ||||
|   int init(int domain); | ||||
|   int connect(Network::Address& serveraddr); | ||||
| }; | ||||
|  | ||||
| }  // namespace Socket | ||||
|   | ||||
							
								
								
									
										29
									
								
								include/utils/ConfigManager.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										29
									
								
								include/utils/ConfigManager.h
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,29 @@ | ||||
| #pragma once | ||||
| #include <json/json.h> | ||||
|  | ||||
| #include <fstream> | ||||
|  | ||||
| namespace utils { | ||||
|  | ||||
| struct Config; | ||||
|  | ||||
| class ConfigManager { | ||||
|  public: | ||||
|   static Config load(); | ||||
|   static void save(Config&); | ||||
| }; | ||||
|  | ||||
| struct Config { | ||||
|   ~Config() { ConfigManager::save(*this); } | ||||
|   Json::Value configJsonRoot; | ||||
|   std::uint32_t ipVersion = 0; | ||||
|   gsl::czstring IP = ""; | ||||
|   std::uint32_t Port = 0; | ||||
|   spdlog::level::level_enum logLevel = spdlog::level::off; | ||||
|   gsl::czstring logFileName = ""; | ||||
|   std::uint32_t logfileSize = 0; | ||||
|   std::uint32_t logfileCount = 0; | ||||
|   std::uint64_t playerid = 0; | ||||
| }; | ||||
|  | ||||
| }  // namespace utils | ||||
| @@ -16,9 +16,15 @@ struct Snowflake { | ||||
|   bool operator==(const Snowflake& other) const { | ||||
|     return snowflake == other.snowflake; | ||||
|   } | ||||
|  | ||||
|   std::vector<char> Serialize() { | ||||
|     std::vector<char> serialized(8); | ||||
|     ::memcpy(serialized.data(), &snowflake, 8); | ||||
|     return serialized; | ||||
|   } | ||||
| }; | ||||
|  | ||||
| Snowflake GenerateID(); | ||||
| Snowflake GenerateID(std::uint8_t instance); | ||||
|  | ||||
| }  // namespace Chattr | ||||
|  | ||||
|   | ||||
							
								
								
									
										9
									
								
								include/utils/utils.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								include/utils/utils.h
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,9 @@ | ||||
| #pragma once | ||||
| #include <list> | ||||
| #include <vector> | ||||
|  | ||||
| namespace utils { | ||||
|  | ||||
| std::vector<char> CvtListToVector(std::list<char> data); | ||||
|  | ||||
| }  // namespace std | ||||
| @@ -5,17 +5,27 @@ | ||||
| #include <vector> | ||||
| 
 | ||||
| #include "material.h" | ||||
| #include "utils/snowflake.h" | ||||
| #include "vulkan_engine/vulkan/buffer_handle.h" | ||||
| #include "vulkan_engine/vulkan/vertex.h" | ||||
| #include "utils/thread_pool.h" | ||||
| 
 | ||||
| extern std::uint8_t CLIENTID; | ||||
| 
 | ||||
| namespace veng { | ||||
| struct Model { | ||||
|   Model() : graphics_(nullptr) {} | ||||
|   Model(class Graphics* graphics) : graphics_(graphics) {} | ||||
|   Model() : ID(utils::GenerateID(CLIENTID)), graphics_(nullptr) { | ||||
|   } | ||||
|   Model(class Graphics* graphics) | ||||
|       : ID(utils::GenerateID(CLIENTID)), graphics_(graphics) { | ||||
|   } | ||||
|   ~Model(); | ||||
| 
 | ||||
|   Model(const Model& other) | ||||
|       : vertices(other.vertices), | ||||
|       : ID(utils::GenerateID(CLIENTID)), | ||||
|         name(/*"_" + */other.name), | ||||
|         asset_name(other.asset_name), | ||||
|         vertices(other.vertices), | ||||
|         vertex_buffer(other.vertex_buffer), | ||||
|         indices(other.indices), | ||||
|         index_buffer(other.index_buffer), | ||||
| @@ -31,17 +41,23 @@ struct Model { | ||||
|         original_offset(other.original_offset), | ||||
|         owner(other.owner), | ||||
|         radius(other.radius), | ||||
|         lifespan(other.lifespan), | ||||
|         OnColision(other.OnColision), | ||||
|         visible(other.visible), | ||||
|         colision(other.colision) { | ||||
|         colision(other.colision), | ||||
|         networkReplicated(other.networkReplicated), | ||||
|         lastUpdatedTime(other.lastUpdatedTime) { | ||||
|     graphics_ = nullptr; | ||||
|   } | ||||
| 
 | ||||
|   Model(Model&& other) | ||||
|       : vertices(other.vertices), | ||||
|         vertex_buffer(other.vertex_buffer), | ||||
|         indices(other.indices), | ||||
|         index_buffer(other.index_buffer), | ||||
|       : ID(other.ID), | ||||
|         name(other.name), | ||||
|         asset_name(other.asset_name), | ||||
|         vertices(std::move(other.vertices)), | ||||
|         vertex_buffer(std::move(other.vertex_buffer)), | ||||
|         indices(std::move(other.indices)), | ||||
|         index_buffer(std::move(other.index_buffer)), | ||||
|         transform(other.transform), | ||||
|         position(other.position), | ||||
|         linear_velocity(other.linear_velocity), | ||||
| @@ -54,46 +70,28 @@ struct Model { | ||||
|         original_offset(other.original_offset), | ||||
|         owner(other.owner), | ||||
|         radius(other.radius), | ||||
|         lifespan(other.lifespan), | ||||
|         OnColision(other.OnColision), | ||||
|         visible(other.visible), | ||||
|         colision(other.colision) { | ||||
|         colision(other.colision), | ||||
|         networkReplicated(other.networkReplicated), | ||||
|         lastUpdatedTime(other.lastUpdatedTime) { | ||||
|     ::memset(&other.ID, 0, 8); | ||||
| 
 | ||||
|     graphics_ = other.graphics_; | ||||
|     other.graphics_ = nullptr; | ||||
|   } | ||||
| 
 | ||||
|   Model& operator=(const Model& other) { | ||||
|     if (this != &other) { | ||||
|       vertices = other.vertices; | ||||
|       vertex_buffer = other.vertex_buffer; | ||||
|       indices = other.indices; | ||||
|       index_buffer = other.index_buffer; | ||||
|       transform = other.transform; | ||||
|       position = other.position; | ||||
|       linear_velocity = other.linear_velocity; | ||||
|       linear_acceleration = other.linear_acceleration; | ||||
|       rotation = other.rotation; | ||||
|       angular_velocity = other.angular_velocity; | ||||
|       angular_acceleration = other.angular_acceleration; | ||||
|       scale = other.scale; | ||||
|       material = other.material; | ||||
|       original_offset = other.original_offset; | ||||
|       owner = other.owner; | ||||
|       radius = other.radius; | ||||
|       OnColision = other.OnColision; | ||||
|       visible = other.visible; | ||||
|       colision = other.colision; | ||||
| 
 | ||||
|       graphics_ = nullptr; | ||||
|     } | ||||
|     return *this; | ||||
|   } | ||||
| 
 | ||||
|   Model& operator=(Model&& other) noexcept { | ||||
|     if (this != &other) { | ||||
|       ID = other.ID; | ||||
|       ::memset(&other.ID, 0, 8); | ||||
|       name = other.name; | ||||
|       asset_name = other.asset_name; | ||||
|       vertices = std::move(other.vertices); | ||||
|       vertex_buffer = other.vertex_buffer; | ||||
|       vertex_buffer = std::move(other.vertex_buffer); | ||||
|       indices = std::move(other.indices); | ||||
|       index_buffer = other.index_buffer; | ||||
|       index_buffer = std::move(other.index_buffer); | ||||
|       transform = other.transform; | ||||
|       position = other.position; | ||||
|       linear_velocity = other.linear_velocity; | ||||
| @@ -105,17 +103,26 @@ struct Model { | ||||
|       material = std::move(other.material); | ||||
|       original_offset = other.original_offset; | ||||
|       owner = other.owner; | ||||
|       OwnerID = ID; | ||||
|       radius = other.radius; | ||||
|       lifespan = other.lifespan; | ||||
|       OnColision = other.OnColision; | ||||
|       visible = other.visible; | ||||
|       colision = other.colision; | ||||
|       networkReplicated = other.networkReplicated; | ||||
|       lastUpdatedTime = other.lastUpdatedTime; | ||||
| 
 | ||||
|       // graphics_만 옮기고, 원본은 nullptr
 | ||||
|       graphics_ = other.graphics_; | ||||
|       other.graphics_ = nullptr; | ||||
|     } | ||||
|     return *this; | ||||
|   } | ||||
|   utils::Snowflake ID; | ||||
|   std::string name; | ||||
|   std::string asset_name; | ||||
| 
 | ||||
|   std::vector<char> Serialize(); | ||||
|   void Deserialize(std::vector<char> data); | ||||
| 
 | ||||
|   std::vector<veng::Vertex> vertices; | ||||
|   veng::BufferHandle vertex_buffer; | ||||
| @@ -141,14 +148,29 @@ struct Model { | ||||
| 
 | ||||
|   glm::vec3 original_offset = glm::vec3(0.f); | ||||
| 
 | ||||
|   Model* owner = this; | ||||
|   std::weak_ptr<Model> owner; | ||||
|   utils::Snowflake OwnerID; | ||||
| 
 | ||||
|   std::float_t radius = 0.f; | ||||
| 
 | ||||
|   std::function<void(Model* self, Model* other)> OnColision = nullptr; | ||||
|   std::float_t lifespan = -1.f; | ||||
| 
 | ||||
|   std::function<void(utils::ThreadPool* thread_pool, std::shared_ptr<Model> self, | ||||
|                      std::shared_ptr<Model> other)> | ||||
|       OnColision = nullptr; | ||||
| 
 | ||||
|   bool visible = true; | ||||
|   bool colision = false; | ||||
|   bool networkReplicated = true; | ||||
|   bool shouldBeDestroyed = false; | ||||
| 
 | ||||
|   bool needsUpdate = true; | ||||
| 
 | ||||
|   double lastUpdatedTime = 0.f;  // 서버 기준 업데이트된 시간임
 | ||||
| 
 | ||||
|   std::uint8_t updateRedundantCount = 0; | ||||
| 
 | ||||
|   std::mutex modding; | ||||
| 
 | ||||
|  private: | ||||
|   class Graphics* graphics_; | ||||
| @@ -4,26 +4,31 @@ | ||||
| #include "graphics.h" | ||||
| #include "physics.h" | ||||
| #include "utils/thread_pool.h" | ||||
| #include "socket/iocp.h" | ||||
| 
 | ||||
| namespace veng { | ||||
| 
 | ||||
| class Engine { | ||||
|  public: | ||||
|   Engine(gsl::not_null<Graphics*> vulkan_graphics, | ||||
|          utils::ThreadPool* thread_pool) | ||||
|       : vulkan_graphics(vulkan_graphics), thread_pool_(thread_pool) {} | ||||
|          utils::ThreadPool* thread_pool, Network::IOCP* iocp) | ||||
|       : vulkan_graphics(vulkan_graphics), thread_pool_(thread_pool), iocp_(iocp) {} | ||||
| 
 | ||||
|   void init(); | ||||
| 
 | ||||
|   void LoadModelAsset(std::string path, std::string name); | ||||
|   const Model* GetStaticModel(std::string name); | ||||
| 
 | ||||
|   Model* SpawnModel(std::string asset_name, std::string name); | ||||
|   Model* SpawnLifedModel(std::string asset_name, std::string name, | ||||
|   // 수명을 무제한으로 놓고 싶으면 lifespan을 -1으로 설정하면 됨
 | ||||
|   std::shared_ptr<Model> SpawnLifedModel(std::string asset_name, std::string name, | ||||
|                          std::float_t lifespan); | ||||
|   Model* GetSpawnedObject(std::string name); | ||||
|   std::shared_ptr<Model> GetSpawnedObject(std::string name); | ||||
| 
 | ||||
|   void Update(); | ||||
|   void NetUpdate(std::shared_ptr<Network::Socket> sock); | ||||
| 
 | ||||
|   void NetworkUpload(std::shared_ptr<Network::Socket> sock); | ||||
|   void ResponseToServerAndRefresh(std::shared_ptr<Network::Socket> sock); | ||||
| 
 | ||||
|   std::function<void(Engine&)> BeginPlay = [](Engine& engine) {}; | ||||
|   std::function<void(Engine&, std::float_t delta_time)> Tick = | ||||
| @@ -39,17 +44,15 @@ class Engine { | ||||
| 
 | ||||
|  private: | ||||
|   Loader asset_loader_; | ||||
|   Physics physics_controller_; | ||||
|   utils::ThreadPool* thread_pool_; | ||||
|   Network::IOCP* iocp_; | ||||
| 
 | ||||
|   glm::ivec2 window_size_ = {0, 0}; | ||||
|   std::double_t last_frame_time_ = 0.0; | ||||
| 
 | ||||
|   std::unordered_map<std::string, veng::Model> model_assets_; | ||||
| 
 | ||||
|   std::unordered_map<std::string, veng::Model> dynamic_immortal_models_; | ||||
|   std::unordered_map<std::string, std::pair<veng::Model, std::float_t>> | ||||
|       dynamic_models_; | ||||
|   std::unordered_map<std::string, std::shared_ptr<Model>> models_; | ||||
| }; | ||||
| 
 | ||||
| }  // namespace veng
 | ||||
| @@ -33,7 +33,7 @@ class Graphics final { | ||||
|   void RenderBuffer(BufferHandle handle, std::uint32_t vertex_count); | ||||
|   void RenderIndexedBuffer(BufferHandle vertex_buffer, | ||||
|                            BufferHandle index_buffer, std::uint32_t count); | ||||
|   void RenderModel(struct Model* model); | ||||
|   void RenderModel(std::shared_ptr<struct Model> model); | ||||
|   void EndFrame(); | ||||
| 
 | ||||
|   BufferHandle CreateVertexBuffer(gsl::span<Vertex> vertices); | ||||
| @@ -1,13 +1,18 @@ | ||||
| #pragma once | ||||
| 
 | ||||
| #include "utils/thread_pool.h" | ||||
| #include "vulkan_engine/asset/object/model.h" | ||||
| #include "vulkan_engine/vulkan/vertex.h" | ||||
| #include "utils/thread_pool.h" | ||||
| 
 | ||||
| namespace veng { | ||||
| class Physics { | ||||
|  public: | ||||
|   void invokeOnColisionEvent(gsl::not_null<utils::ThreadPool *> thread_pool, gsl::span<Model*> models); | ||||
|   static void invokeOnColisionEvent( | ||||
|       gsl::not_null<utils::ThreadPool*> thread_pool, | ||||
|       std::unordered_map<std::string, std::shared_ptr<Model>>& models); | ||||
|   static void invokeOnColisionEvent( | ||||
|       gsl::not_null<utils::ThreadPool*> thread_pool, | ||||
|       std::unordered_map<utils::Snowflake, std::shared_ptr<Model>>& models); | ||||
| 
 | ||||
|   bool RayTrace(const glm::vec3& rayOrigin, const glm::vec3& rayDir, | ||||
|                 const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2, | ||||
		Reference in New Issue
	
	Block a user