serialization.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. #include "serialization.h"
  2. #include "../map/terrain.h"
  3. #include "../map/terrain_service.h"
  4. #include "../units/spawn_type.h"
  5. #include "../units/troop_type.h"
  6. #include "component.h"
  7. #include "entity.h"
  8. #include "world.h"
  9. #include <QByteArray>
  10. #include <QDebug>
  11. #include <QFile>
  12. #include <QJsonArray>
  13. #include <QJsonObject>
  14. #include <QString>
  15. #include <QVector3D>
  16. #include <algorithm>
  17. #include <array>
  18. #include <cstddef>
  19. #include <cstdint>
  20. #include <memory>
  21. #include <qfiledevice.h>
  22. #include <qglobal.h>
  23. #include <qjsonarray.h>
  24. #include <qjsondocument.h>
  25. #include <qjsonobject.h>
  26. #include <qjsonvalue.h>
  27. #include <qstringliteral.h>
  28. #include <qstringview.h>
  29. #include <vector>
  30. #include "../systems/owner_registry.h"
  31. namespace Engine::Core {
  32. namespace {
  33. auto combatModeToString(AttackComponent::CombatMode mode) -> QString {
  34. switch (mode) {
  35. case AttackComponent::CombatMode::Melee:
  36. return "melee";
  37. case AttackComponent::CombatMode::Ranged:
  38. return "ranged";
  39. case AttackComponent::CombatMode::Auto:
  40. default:
  41. return "auto";
  42. }
  43. }
  44. auto combatModeFromString(const QString &value) -> AttackComponent::CombatMode {
  45. if (value == "melee") {
  46. return AttackComponent::CombatMode::Melee;
  47. }
  48. if (value == "ranged") {
  49. return AttackComponent::CombatMode::Ranged;
  50. }
  51. return AttackComponent::CombatMode::Auto;
  52. }
  53. auto serializeColor(const std::array<float, 3> &color) -> QJsonArray {
  54. QJsonArray array;
  55. array.append(color[0]);
  56. array.append(color[1]);
  57. array.append(color[2]);
  58. return array;
  59. }
  60. void deserializeColor(const QJsonArray &array, std::array<float, 3> &color) {
  61. if (array.size() >= 3) {
  62. color[0] = static_cast<float>(array.at(0).toDouble());
  63. color[1] = static_cast<float>(array.at(1).toDouble());
  64. color[2] = static_cast<float>(array.at(2).toDouble());
  65. }
  66. }
  67. } // namespace
  68. auto Serialization::serializeEntity(const Entity *entity) -> QJsonObject {
  69. QJsonObject entity_obj;
  70. entity_obj["id"] = static_cast<qint64>(entity->getId());
  71. if (const auto *transform = entity->getComponent<TransformComponent>()) {
  72. QJsonObject transform_obj;
  73. transform_obj["posX"] = transform->position.x;
  74. transform_obj["posY"] = transform->position.y;
  75. transform_obj["posZ"] = transform->position.z;
  76. transform_obj["rotX"] = transform->rotation.x;
  77. transform_obj["rotY"] = transform->rotation.y;
  78. transform_obj["rotZ"] = transform->rotation.z;
  79. transform_obj["scale_x"] = transform->scale.x;
  80. transform_obj["scaleY"] = transform->scale.y;
  81. transform_obj["scale_z"] = transform->scale.z;
  82. transform_obj["hasDesiredYaw"] = transform->hasDesiredYaw;
  83. transform_obj["desiredYaw"] = transform->desiredYaw;
  84. entity_obj["transform"] = transform_obj;
  85. }
  86. if (const auto *renderable = entity->getComponent<RenderableComponent>()) {
  87. QJsonObject renderable_obj;
  88. renderable_obj["meshPath"] = QString::fromStdString(renderable->meshPath);
  89. renderable_obj["texturePath"] =
  90. QString::fromStdString(renderable->texturePath);
  91. renderable_obj["visible"] = renderable->visible;
  92. renderable_obj["mesh"] = static_cast<int>(renderable->mesh);
  93. renderable_obj["color"] = serializeColor(renderable->color);
  94. entity_obj["renderable"] = renderable_obj;
  95. }
  96. if (const auto *unit = entity->getComponent<UnitComponent>()) {
  97. QJsonObject unit_obj;
  98. unit_obj["health"] = unit->health;
  99. unit_obj["max_health"] = unit->max_health;
  100. unit_obj["speed"] = unit->speed;
  101. unit_obj["vision_range"] = unit->vision_range;
  102. unit_obj["unit_type"] = QString::fromStdString(
  103. Game::Units::spawn_typeToString(unit->spawn_type));
  104. unit_obj["owner_id"] = unit->owner_id;
  105. entity_obj["unit"] = unit_obj;
  106. }
  107. if (const auto *movement = entity->getComponent<MovementComponent>()) {
  108. QJsonObject movement_obj;
  109. movement_obj["hasTarget"] = movement->hasTarget;
  110. movement_obj["target_x"] = movement->target_x;
  111. movement_obj["target_y"] = movement->target_y;
  112. movement_obj["goalX"] = movement->goalX;
  113. movement_obj["goalY"] = movement->goalY;
  114. movement_obj["vx"] = movement->vx;
  115. movement_obj["vz"] = movement->vz;
  116. movement_obj["pathPending"] = movement->pathPending;
  117. movement_obj["pendingRequestId"] =
  118. static_cast<qint64>(movement->pendingRequestId);
  119. movement_obj["repathCooldown"] = movement->repathCooldown;
  120. movement_obj["lastGoalX"] = movement->lastGoalX;
  121. movement_obj["lastGoalY"] = movement->lastGoalY;
  122. movement_obj["timeSinceLastPathRequest"] =
  123. movement->timeSinceLastPathRequest;
  124. QJsonArray path_array;
  125. for (const auto &waypoint : movement->path) {
  126. QJsonObject waypoint_obj;
  127. waypoint_obj["x"] = waypoint.first;
  128. waypoint_obj["y"] = waypoint.second;
  129. path_array.append(waypoint_obj);
  130. }
  131. movement_obj["path"] = path_array;
  132. entity_obj["movement"] = movement_obj;
  133. }
  134. if (const auto *attack = entity->getComponent<AttackComponent>()) {
  135. QJsonObject attack_obj;
  136. attack_obj["range"] = attack->range;
  137. attack_obj["damage"] = attack->damage;
  138. attack_obj["cooldown"] = attack->cooldown;
  139. attack_obj["timeSinceLast"] = attack->timeSinceLast;
  140. attack_obj["meleeRange"] = attack->meleeRange;
  141. attack_obj["meleeDamage"] = attack->meleeDamage;
  142. attack_obj["meleeCooldown"] = attack->meleeCooldown;
  143. attack_obj["preferredMode"] = combatModeToString(attack->preferredMode);
  144. attack_obj["currentMode"] = combatModeToString(attack->currentMode);
  145. attack_obj["canMelee"] = attack->canMelee;
  146. attack_obj["canRanged"] = attack->canRanged;
  147. attack_obj["max_heightDifference"] = attack->max_heightDifference;
  148. attack_obj["inMeleeLock"] = attack->inMeleeLock;
  149. attack_obj["meleeLockTargetId"] =
  150. static_cast<qint64>(attack->meleeLockTargetId);
  151. entity_obj["attack"] = attack_obj;
  152. }
  153. if (const auto *attack_target =
  154. entity->getComponent<AttackTargetComponent>()) {
  155. QJsonObject attack_target_obj;
  156. attack_target_obj["target_id"] =
  157. static_cast<qint64>(attack_target->target_id);
  158. attack_target_obj["shouldChase"] = attack_target->shouldChase;
  159. entity_obj["attack_target"] = attack_target_obj;
  160. }
  161. if (const auto *patrol = entity->getComponent<PatrolComponent>()) {
  162. QJsonObject patrol_obj;
  163. patrol_obj["currentWaypoint"] = static_cast<int>(patrol->currentWaypoint);
  164. patrol_obj["patrolling"] = patrol->patrolling;
  165. QJsonArray waypoints_array;
  166. for (const auto &waypoint : patrol->waypoints) {
  167. QJsonObject waypoint_obj;
  168. waypoint_obj["x"] = waypoint.first;
  169. waypoint_obj["y"] = waypoint.second;
  170. waypoints_array.append(waypoint_obj);
  171. }
  172. patrol_obj["waypoints"] = waypoints_array;
  173. entity_obj["patrol"] = patrol_obj;
  174. }
  175. if (entity->getComponent<BuildingComponent>() != nullptr) {
  176. entity_obj["building"] = true;
  177. }
  178. if (const auto *production = entity->getComponent<ProductionComponent>()) {
  179. QJsonObject production_obj;
  180. production_obj["inProgress"] = production->inProgress;
  181. production_obj["buildTime"] = production->buildTime;
  182. production_obj["timeRemaining"] = production->timeRemaining;
  183. production_obj["producedCount"] = production->producedCount;
  184. production_obj["maxUnits"] = production->maxUnits;
  185. production_obj["product_type"] = QString::fromStdString(
  186. Game::Units::troop_typeToString(production->product_type));
  187. production_obj["rallyX"] = production->rallyX;
  188. production_obj["rallyZ"] = production->rallyZ;
  189. production_obj["rallySet"] = production->rallySet;
  190. production_obj["villagerCost"] = production->villagerCost;
  191. QJsonArray queue_array;
  192. for (const auto &queued : production->productionQueue) {
  193. queue_array.append(
  194. QString::fromStdString(Game::Units::troop_typeToString(queued)));
  195. }
  196. production_obj["queue"] = queue_array;
  197. entity_obj["production"] = production_obj;
  198. }
  199. if (entity->getComponent<AIControlledComponent>() != nullptr) {
  200. entity_obj["aiControlled"] = true;
  201. }
  202. if (const auto *capture = entity->getComponent<CaptureComponent>()) {
  203. QJsonObject capture_obj;
  204. capture_obj["capturing_player_id"] = capture->capturing_player_id;
  205. capture_obj["captureProgress"] =
  206. static_cast<double>(capture->captureProgress);
  207. capture_obj["requiredTime"] = static_cast<double>(capture->requiredTime);
  208. capture_obj["isBeingCaptured"] = capture->isBeingCaptured;
  209. entity_obj["capture"] = capture_obj;
  210. }
  211. return entity_obj;
  212. }
  213. void Serialization::deserializeEntity(Entity *entity, const QJsonObject &json) {
  214. if (json.contains("transform")) {
  215. const auto transform_obj = json["transform"].toObject();
  216. auto *transform = entity->addComponent<TransformComponent>();
  217. transform->position.x =
  218. static_cast<float>(transform_obj["posX"].toDouble());
  219. transform->position.y =
  220. static_cast<float>(transform_obj["posY"].toDouble());
  221. transform->position.z =
  222. static_cast<float>(transform_obj["posZ"].toDouble());
  223. transform->rotation.x =
  224. static_cast<float>(transform_obj["rotX"].toDouble());
  225. transform->rotation.y =
  226. static_cast<float>(transform_obj["rotY"].toDouble());
  227. transform->rotation.z =
  228. static_cast<float>(transform_obj["rotZ"].toDouble());
  229. transform->scale.x =
  230. static_cast<float>(transform_obj["scale_x"].toDouble());
  231. transform->scale.y = static_cast<float>(transform_obj["scaleY"].toDouble());
  232. transform->scale.z =
  233. static_cast<float>(transform_obj["scale_z"].toDouble());
  234. transform->hasDesiredYaw = transform_obj["hasDesiredYaw"].toBool(false);
  235. transform->desiredYaw =
  236. static_cast<float>(transform_obj["desiredYaw"].toDouble());
  237. }
  238. if (json.contains("renderable")) {
  239. const auto renderable_obj = json["renderable"].toObject();
  240. auto *renderable = entity->addComponent<RenderableComponent>("", "");
  241. renderable->meshPath = renderable_obj["meshPath"].toString().toStdString();
  242. renderable->texturePath =
  243. renderable_obj["texturePath"].toString().toStdString();
  244. renderable->visible = renderable_obj["visible"].toBool(true);
  245. renderable->mesh =
  246. static_cast<RenderableComponent::MeshKind>(renderable_obj["mesh"].toInt(
  247. static_cast<int>(RenderableComponent::MeshKind::Cube)));
  248. if (renderable_obj.contains("color")) {
  249. deserializeColor(renderable_obj["color"].toArray(), renderable->color);
  250. }
  251. }
  252. if (json.contains("unit")) {
  253. const auto unit_obj = json["unit"].toObject();
  254. auto *unit = entity->addComponent<UnitComponent>();
  255. unit->health = unit_obj["health"].toInt(Defaults::kUnitDefaultHealth);
  256. unit->max_health =
  257. unit_obj["max_health"].toInt(Defaults::kUnitDefaultHealth);
  258. unit->speed = static_cast<float>(unit_obj["speed"].toDouble());
  259. unit->vision_range = static_cast<float>(unit_obj["vision_range"].toDouble(
  260. static_cast<double>(Defaults::kUnitDefaultVisionRange)));
  261. QString const unit_type_str = unit_obj["unit_type"].toString();
  262. Game::Units::SpawnType spawn_type;
  263. if (Game::Units::tryParseSpawnType(unit_type_str, spawn_type)) {
  264. unit->spawn_type = spawn_type;
  265. } else {
  266. qWarning() << "Unknown spawn type in save file:" << unit_type_str
  267. << "- defaulting to Archer";
  268. unit->spawn_type = Game::Units::SpawnType::Archer;
  269. }
  270. unit->owner_id = unit_obj["owner_id"].toInt(0);
  271. }
  272. if (json.contains("movement")) {
  273. const auto movement_obj = json["movement"].toObject();
  274. auto *movement = entity->addComponent<MovementComponent>();
  275. movement->hasTarget = movement_obj["hasTarget"].toBool(false);
  276. movement->target_x =
  277. static_cast<float>(movement_obj["target_x"].toDouble());
  278. movement->target_y =
  279. static_cast<float>(movement_obj["target_y"].toDouble());
  280. movement->goalX = static_cast<float>(movement_obj["goalX"].toDouble());
  281. movement->goalY = static_cast<float>(movement_obj["goalY"].toDouble());
  282. movement->vx = static_cast<float>(movement_obj["vx"].toDouble());
  283. movement->vz = static_cast<float>(movement_obj["vz"].toDouble());
  284. movement->pathPending = movement_obj["pathPending"].toBool(false);
  285. movement->pendingRequestId = static_cast<std::uint64_t>(
  286. movement_obj["pendingRequestId"].toVariant().toULongLong());
  287. movement->repathCooldown =
  288. static_cast<float>(movement_obj["repathCooldown"].toDouble());
  289. movement->lastGoalX =
  290. static_cast<float>(movement_obj["lastGoalX"].toDouble());
  291. movement->lastGoalY =
  292. static_cast<float>(movement_obj["lastGoalY"].toDouble());
  293. movement->timeSinceLastPathRequest =
  294. static_cast<float>(movement_obj["timeSinceLastPathRequest"].toDouble());
  295. movement->path.clear();
  296. const auto path_array = movement_obj["path"].toArray();
  297. movement->path.reserve(path_array.size());
  298. for (const auto &value : path_array) {
  299. const auto waypoint_obj = value.toObject();
  300. movement->path.emplace_back(
  301. static_cast<float>(waypoint_obj["x"].toDouble()),
  302. static_cast<float>(waypoint_obj["y"].toDouble()));
  303. }
  304. }
  305. if (json.contains("attack")) {
  306. const auto attack_obj = json["attack"].toObject();
  307. auto *attack = entity->addComponent<AttackComponent>();
  308. attack->range = static_cast<float>(attack_obj["range"].toDouble());
  309. attack->damage = attack_obj["damage"].toInt(0);
  310. attack->cooldown = static_cast<float>(attack_obj["cooldown"].toDouble());
  311. attack->timeSinceLast =
  312. static_cast<float>(attack_obj["timeSinceLast"].toDouble());
  313. attack->meleeRange = static_cast<float>(attack_obj["meleeRange"].toDouble(
  314. static_cast<double>(Defaults::kAttackMeleeRange)));
  315. attack->meleeDamage = attack_obj["meleeDamage"].toInt(0);
  316. attack->meleeCooldown =
  317. static_cast<float>(attack_obj["meleeCooldown"].toDouble());
  318. attack->preferredMode =
  319. combatModeFromString(attack_obj["preferredMode"].toString());
  320. attack->currentMode =
  321. combatModeFromString(attack_obj["currentMode"].toString());
  322. attack->canMelee = attack_obj["canMelee"].toBool(true);
  323. attack->canRanged = attack_obj["canRanged"].toBool(false);
  324. attack->max_heightDifference =
  325. static_cast<float>(attack_obj["max_heightDifference"].toDouble(
  326. static_cast<double>(Defaults::kAttackHeightTolerance)));
  327. attack->inMeleeLock = attack_obj["inMeleeLock"].toBool(false);
  328. attack->meleeLockTargetId = static_cast<EntityID>(
  329. attack_obj["meleeLockTargetId"].toVariant().toULongLong());
  330. }
  331. if (json.contains("attack_target")) {
  332. const auto attack_target_obj = json["attack_target"].toObject();
  333. auto *attack_target = entity->addComponent<AttackTargetComponent>();
  334. attack_target->target_id = static_cast<EntityID>(
  335. attack_target_obj["target_id"].toVariant().toULongLong());
  336. attack_target->shouldChase = attack_target_obj["shouldChase"].toBool(false);
  337. }
  338. if (json.contains("patrol")) {
  339. const auto patrol_obj = json["patrol"].toObject();
  340. auto *patrol = entity->addComponent<PatrolComponent>();
  341. patrol->currentWaypoint =
  342. static_cast<size_t>(std::max(0, patrol_obj["currentWaypoint"].toInt()));
  343. patrol->patrolling = patrol_obj["patrolling"].toBool(false);
  344. patrol->waypoints.clear();
  345. const auto waypoints_array = patrol_obj["waypoints"].toArray();
  346. patrol->waypoints.reserve(waypoints_array.size());
  347. for (const auto &value : waypoints_array) {
  348. const auto waypoint_obj = value.toObject();
  349. patrol->waypoints.emplace_back(
  350. static_cast<float>(waypoint_obj["x"].toDouble()),
  351. static_cast<float>(waypoint_obj["y"].toDouble()));
  352. }
  353. }
  354. if (json.contains("building") && json["building"].toBool()) {
  355. entity->addComponent<BuildingComponent>();
  356. }
  357. if (json.contains("production")) {
  358. const auto production_obj = json["production"].toObject();
  359. auto *production = entity->addComponent<ProductionComponent>();
  360. production->inProgress = production_obj["inProgress"].toBool(false);
  361. production->buildTime =
  362. static_cast<float>(production_obj["buildTime"].toDouble());
  363. production->timeRemaining =
  364. static_cast<float>(production_obj["timeRemaining"].toDouble());
  365. production->producedCount = production_obj["producedCount"].toInt(0);
  366. production->maxUnits = production_obj["maxUnits"].toInt(0);
  367. production->product_type = Game::Units::troop_typeFromString(
  368. production_obj["product_type"].toString().toStdString());
  369. production->rallyX =
  370. static_cast<float>(production_obj["rallyX"].toDouble());
  371. production->rallyZ =
  372. static_cast<float>(production_obj["rallyZ"].toDouble());
  373. production->rallySet = production_obj["rallySet"].toBool(false);
  374. production->villagerCost = production_obj["villagerCost"].toInt(1);
  375. production->productionQueue.clear();
  376. const auto queue_array = production_obj["queue"].toArray();
  377. production->productionQueue.reserve(queue_array.size());
  378. for (const auto &value : queue_array) {
  379. production->productionQueue.push_back(
  380. Game::Units::troop_typeFromString(value.toString().toStdString()));
  381. }
  382. }
  383. if (json.contains("aiControlled") && json["aiControlled"].toBool()) {
  384. entity->addComponent<AIControlledComponent>();
  385. }
  386. if (json.contains("capture")) {
  387. const auto capture_obj = json["capture"].toObject();
  388. auto *capture = entity->addComponent<CaptureComponent>();
  389. capture->capturing_player_id = capture_obj["capturing_player_id"].toInt(-1);
  390. capture->captureProgress =
  391. static_cast<float>(capture_obj["captureProgress"].toDouble(0.0));
  392. capture->requiredTime =
  393. static_cast<float>(capture_obj["requiredTime"].toDouble(
  394. static_cast<double>(Defaults::kCaptureRequiredTime)));
  395. capture->isBeingCaptured = capture_obj["isBeingCaptured"].toBool(false);
  396. }
  397. }
  398. auto Serialization::serializeTerrain(
  399. const Game::Map::TerrainHeightMap *height_map,
  400. const Game::Map::BiomeSettings &biome) -> QJsonObject {
  401. QJsonObject terrain_obj;
  402. if (height_map == nullptr) {
  403. return terrain_obj;
  404. }
  405. terrain_obj["width"] = height_map->getWidth();
  406. terrain_obj["height"] = height_map->getHeight();
  407. terrain_obj["tile_size"] = height_map->getTileSize();
  408. QJsonArray heights_array;
  409. const auto &heights = height_map->getHeightData();
  410. for (float const h : heights) {
  411. heights_array.append(h);
  412. }
  413. terrain_obj["heights"] = heights_array;
  414. QJsonArray terrain_types_array;
  415. const auto &terrain_types = height_map->getTerrainTypes();
  416. for (auto type : terrain_types) {
  417. terrain_types_array.append(static_cast<int>(type));
  418. }
  419. terrain_obj["terrain_types"] = terrain_types_array;
  420. QJsonArray rivers_array;
  421. const auto &rivers = height_map->getRiverSegments();
  422. for (const auto &river : rivers) {
  423. QJsonObject river_obj;
  424. river_obj["startX"] = river.start.x();
  425. river_obj["startY"] = river.start.y();
  426. river_obj["startZ"] = river.start.z();
  427. river_obj["endX"] = river.end.x();
  428. river_obj["endY"] = river.end.y();
  429. river_obj["endZ"] = river.end.z();
  430. river_obj["width"] = river.width;
  431. rivers_array.append(river_obj);
  432. }
  433. terrain_obj["rivers"] = rivers_array;
  434. QJsonArray bridges_array;
  435. const auto &bridges = height_map->getBridges();
  436. for (const auto &bridge : bridges) {
  437. QJsonObject bridge_obj;
  438. bridge_obj["startX"] = bridge.start.x();
  439. bridge_obj["startY"] = bridge.start.y();
  440. bridge_obj["startZ"] = bridge.start.z();
  441. bridge_obj["endX"] = bridge.end.x();
  442. bridge_obj["endY"] = bridge.end.y();
  443. bridge_obj["endZ"] = bridge.end.z();
  444. bridge_obj["width"] = bridge.width;
  445. bridge_obj["height"] = bridge.height;
  446. bridges_array.append(bridge_obj);
  447. }
  448. terrain_obj["bridges"] = bridges_array;
  449. QJsonObject biome_obj;
  450. biome_obj["grassPrimaryR"] = biome.grassPrimary.x();
  451. biome_obj["grassPrimaryG"] = biome.grassPrimary.y();
  452. biome_obj["grassPrimaryB"] = biome.grassPrimary.z();
  453. biome_obj["grassSecondaryR"] = biome.grassSecondary.x();
  454. biome_obj["grassSecondaryG"] = biome.grassSecondary.y();
  455. biome_obj["grassSecondaryB"] = biome.grassSecondary.z();
  456. biome_obj["grassDryR"] = biome.grassDry.x();
  457. biome_obj["grassDryG"] = biome.grassDry.y();
  458. biome_obj["grassDryB"] = biome.grassDry.z();
  459. biome_obj["soilColorR"] = biome.soilColor.x();
  460. biome_obj["soilColorG"] = biome.soilColor.y();
  461. biome_obj["soilColorB"] = biome.soilColor.z();
  462. biome_obj["rockLowR"] = biome.rockLow.x();
  463. biome_obj["rockLowG"] = biome.rockLow.y();
  464. biome_obj["rockLowB"] = biome.rockLow.z();
  465. biome_obj["rockHighR"] = biome.rockHigh.x();
  466. biome_obj["rockHighG"] = biome.rockHigh.y();
  467. biome_obj["rockHighB"] = biome.rockHigh.z();
  468. biome_obj["patchDensity"] = biome.patchDensity;
  469. biome_obj["patchJitter"] = biome.patchJitter;
  470. biome_obj["backgroundBladeDensity"] = biome.backgroundBladeDensity;
  471. biome_obj["bladeHeightMin"] = biome.bladeHeightMin;
  472. biome_obj["bladeHeightMax"] = biome.bladeHeightMax;
  473. biome_obj["bladeWidthMin"] = biome.bladeWidthMin;
  474. biome_obj["bladeWidthMax"] = biome.bladeWidthMax;
  475. biome_obj["sway_strength"] = biome.sway_strength;
  476. biome_obj["sway_speed"] = biome.sway_speed;
  477. biome_obj["heightNoiseAmplitude"] = biome.heightNoiseAmplitude;
  478. biome_obj["heightNoiseFrequency"] = biome.heightNoiseFrequency;
  479. biome_obj["terrainMacroNoiseScale"] = biome.terrainMacroNoiseScale;
  480. biome_obj["terrainDetailNoiseScale"] = biome.terrainDetailNoiseScale;
  481. biome_obj["terrainSoilHeight"] = biome.terrainSoilHeight;
  482. biome_obj["terrainSoilSharpness"] = biome.terrainSoilSharpness;
  483. biome_obj["terrainRockThreshold"] = biome.terrainRockThreshold;
  484. biome_obj["terrainRockSharpness"] = biome.terrainRockSharpness;
  485. biome_obj["terrainAmbientBoost"] = biome.terrainAmbientBoost;
  486. biome_obj["terrainRockDetailStrength"] = biome.terrainRockDetailStrength;
  487. biome_obj["backgroundSwayVariance"] = biome.backgroundSwayVariance;
  488. biome_obj["backgroundScatterRadius"] = biome.backgroundScatterRadius;
  489. biome_obj["plant_density"] = biome.plant_density;
  490. biome_obj["spawnEdgePadding"] = biome.spawnEdgePadding;
  491. biome_obj["seed"] = static_cast<qint64>(biome.seed);
  492. terrain_obj["biome"] = biome_obj;
  493. return terrain_obj;
  494. }
  495. void Serialization::deserializeTerrain(Game::Map::TerrainHeightMap *height_map,
  496. Game::Map::BiomeSettings &biome,
  497. const QJsonObject &json) {
  498. if ((height_map == nullptr) || json.isEmpty()) {
  499. return;
  500. }
  501. if (json.contains("biome")) {
  502. const auto biome_obj = json["biome"].toObject();
  503. const Game::Map::BiomeSettings default_biome{};
  504. const auto read_color = [&](const QString &base,
  505. const QVector3D &fallback) -> QVector3D {
  506. const auto r_key = base + QStringLiteral("R");
  507. const auto g_key = base + QStringLiteral("G");
  508. const auto b_key = base + QStringLiteral("B");
  509. const float r = static_cast<float>(
  510. biome_obj[r_key].toDouble(static_cast<double>(fallback.x())));
  511. const float g = static_cast<float>(
  512. biome_obj[g_key].toDouble(static_cast<double>(fallback.y())));
  513. const float b = static_cast<float>(
  514. biome_obj[b_key].toDouble(static_cast<double>(fallback.z())));
  515. return {r, g, b};
  516. };
  517. biome.grassPrimary =
  518. read_color(QStringLiteral("grassPrimary"), default_biome.grassPrimary);
  519. biome.grassSecondary = read_color(QStringLiteral("grassSecondary"),
  520. default_biome.grassSecondary);
  521. biome.grassDry =
  522. read_color(QStringLiteral("grassDry"), default_biome.grassDry);
  523. biome.soilColor =
  524. read_color(QStringLiteral("soilColor"), default_biome.soilColor);
  525. biome.rockLow =
  526. read_color(QStringLiteral("rockLow"), default_biome.rockLow);
  527. biome.rockHigh =
  528. read_color(QStringLiteral("rockHigh"), default_biome.rockHigh);
  529. biome.patchDensity = static_cast<float>(
  530. biome_obj["patchDensity"].toDouble(default_biome.patchDensity));
  531. biome.patchJitter = static_cast<float>(
  532. biome_obj["patchJitter"].toDouble(default_biome.patchJitter));
  533. biome.backgroundBladeDensity =
  534. static_cast<float>(biome_obj["backgroundBladeDensity"].toDouble(
  535. default_biome.backgroundBladeDensity));
  536. biome.bladeHeightMin = static_cast<float>(
  537. biome_obj["bladeHeightMin"].toDouble(default_biome.bladeHeightMin));
  538. biome.bladeHeightMax = static_cast<float>(
  539. biome_obj["bladeHeightMax"].toDouble(default_biome.bladeHeightMax));
  540. biome.bladeWidthMin = static_cast<float>(
  541. biome_obj["bladeWidthMin"].toDouble(default_biome.bladeWidthMin));
  542. biome.bladeWidthMax = static_cast<float>(
  543. biome_obj["bladeWidthMax"].toDouble(default_biome.bladeWidthMax));
  544. biome.sway_strength = static_cast<float>(
  545. biome_obj["sway_strength"].toDouble(default_biome.sway_strength));
  546. biome.sway_speed = static_cast<float>(
  547. biome_obj["sway_speed"].toDouble(default_biome.sway_speed));
  548. biome.heightNoiseAmplitude =
  549. static_cast<float>(biome_obj["heightNoiseAmplitude"].toDouble(
  550. default_biome.heightNoiseAmplitude));
  551. biome.heightNoiseFrequency =
  552. static_cast<float>(biome_obj["heightNoiseFrequency"].toDouble(
  553. default_biome.heightNoiseFrequency));
  554. biome.terrainMacroNoiseScale =
  555. static_cast<float>(biome_obj["terrainMacroNoiseScale"].toDouble(
  556. default_biome.terrainMacroNoiseScale));
  557. biome.terrainDetailNoiseScale =
  558. static_cast<float>(biome_obj["terrainDetailNoiseScale"].toDouble(
  559. default_biome.terrainDetailNoiseScale));
  560. biome.terrainSoilHeight =
  561. static_cast<float>(biome_obj["terrainSoilHeight"].toDouble(
  562. default_biome.terrainSoilHeight));
  563. biome.terrainSoilSharpness =
  564. static_cast<float>(biome_obj["terrainSoilSharpness"].toDouble(
  565. default_biome.terrainSoilSharpness));
  566. biome.terrainRockThreshold =
  567. static_cast<float>(biome_obj["terrainRockThreshold"].toDouble(
  568. default_biome.terrainRockThreshold));
  569. biome.terrainRockSharpness =
  570. static_cast<float>(biome_obj["terrainRockSharpness"].toDouble(
  571. default_biome.terrainRockSharpness));
  572. biome.terrainAmbientBoost =
  573. static_cast<float>(biome_obj["terrainAmbientBoost"].toDouble(
  574. default_biome.terrainAmbientBoost));
  575. biome.terrainRockDetailStrength =
  576. static_cast<float>(biome_obj["terrainRockDetailStrength"].toDouble(
  577. default_biome.terrainRockDetailStrength));
  578. biome.backgroundSwayVariance =
  579. static_cast<float>(biome_obj["backgroundSwayVariance"].toDouble(
  580. default_biome.backgroundSwayVariance));
  581. biome.backgroundScatterRadius =
  582. static_cast<float>(biome_obj["backgroundScatterRadius"].toDouble(
  583. default_biome.backgroundScatterRadius));
  584. biome.plant_density = static_cast<float>(
  585. biome_obj["plant_density"].toDouble(default_biome.plant_density));
  586. biome.spawnEdgePadding = static_cast<float>(
  587. biome_obj["spawnEdgePadding"].toDouble(default_biome.spawnEdgePadding));
  588. if (biome_obj.contains("seed")) {
  589. biome.seed = static_cast<std::uint32_t>(
  590. biome_obj["seed"].toVariant().toULongLong());
  591. } else {
  592. biome.seed = default_biome.seed;
  593. }
  594. }
  595. std::vector<float> heights;
  596. if (json.contains("heights")) {
  597. const auto heights_array = json["heights"].toArray();
  598. heights.reserve(heights_array.size());
  599. for (const auto &val : heights_array) {
  600. heights.push_back(static_cast<float>(val.toDouble(0.0)));
  601. }
  602. }
  603. std::vector<Game::Map::TerrainType> terrain_types;
  604. if (json.contains("terrain_types")) {
  605. const auto types_array = json["terrain_types"].toArray();
  606. terrain_types.reserve(types_array.size());
  607. for (const auto &val : types_array) {
  608. terrain_types.push_back(
  609. static_cast<Game::Map::TerrainType>(val.toInt(0)));
  610. }
  611. }
  612. std::vector<Game::Map::RiverSegment> rivers;
  613. if (json.contains("rivers")) {
  614. const auto rivers_array = json["rivers"].toArray();
  615. rivers.reserve(rivers_array.size());
  616. const Game::Map::RiverSegment default_river{};
  617. for (const auto &val : rivers_array) {
  618. const auto river_obj = val.toObject();
  619. Game::Map::RiverSegment river;
  620. river.start =
  621. QVector3D(static_cast<float>(river_obj["startX"].toDouble(0.0)),
  622. static_cast<float>(river_obj["startY"].toDouble(0.0)),
  623. static_cast<float>(river_obj["startZ"].toDouble(0.0)));
  624. river.end =
  625. QVector3D(static_cast<float>(river_obj["endX"].toDouble(0.0)),
  626. static_cast<float>(river_obj["endY"].toDouble(0.0)),
  627. static_cast<float>(river_obj["endZ"].toDouble(0.0)));
  628. river.width = static_cast<float>(river_obj["width"].toDouble(
  629. static_cast<double>(default_river.width)));
  630. rivers.push_back(river);
  631. }
  632. }
  633. std::vector<Game::Map::Bridge> bridges;
  634. if (json.contains("bridges")) {
  635. const auto bridges_array = json["bridges"].toArray();
  636. bridges.reserve(bridges_array.size());
  637. const Game::Map::Bridge default_bridge{};
  638. for (const auto &val : bridges_array) {
  639. const auto bridge_obj = val.toObject();
  640. Game::Map::Bridge bridge;
  641. bridge.start =
  642. QVector3D(static_cast<float>(bridge_obj["startX"].toDouble(0.0)),
  643. static_cast<float>(bridge_obj["startY"].toDouble(0.0)),
  644. static_cast<float>(bridge_obj["startZ"].toDouble(0.0)));
  645. bridge.end =
  646. QVector3D(static_cast<float>(bridge_obj["endX"].toDouble(0.0)),
  647. static_cast<float>(bridge_obj["endY"].toDouble(0.0)),
  648. static_cast<float>(bridge_obj["endZ"].toDouble(0.0)));
  649. bridge.width = static_cast<float>(bridge_obj["width"].toDouble(
  650. static_cast<double>(default_bridge.width)));
  651. bridge.height = static_cast<float>(bridge_obj["height"].toDouble(
  652. static_cast<double>(default_bridge.height)));
  653. bridges.push_back(bridge);
  654. }
  655. }
  656. height_map->restoreFromData(heights, terrain_types, rivers, bridges);
  657. }
  658. auto Serialization::serializeWorld(const World *world) -> QJsonDocument {
  659. QJsonObject world_obj;
  660. QJsonArray entities_array;
  661. const auto &entities = world->getEntities();
  662. for (const auto &[id, entity] : entities) {
  663. QJsonObject const entity_obj = serializeEntity(entity.get());
  664. entities_array.append(entity_obj);
  665. }
  666. world_obj["entities"] = entities_array;
  667. world_obj["nextEntityId"] = static_cast<qint64>(world->getNextEntityId());
  668. world_obj["schemaVersion"] = 1;
  669. world_obj["owner_registry"] =
  670. Game::Systems::OwnerRegistry::instance().toJson();
  671. const auto &terrain_service = Game::Map::TerrainService::instance();
  672. if (terrain_service.isInitialized() &&
  673. (terrain_service.getHeightMap() != nullptr)) {
  674. world_obj["terrain"] = serializeTerrain(terrain_service.getHeightMap(),
  675. terrain_service.biomeSettings());
  676. }
  677. return QJsonDocument(world_obj);
  678. }
  679. void Serialization::deserializeWorld(World *world, const QJsonDocument &doc) {
  680. auto world_obj = doc.object();
  681. auto entities_array = world_obj["entities"].toArray();
  682. for (const auto &value : entities_array) {
  683. auto entity_obj = value.toObject();
  684. const auto entity_id =
  685. static_cast<EntityID>(entity_obj["id"].toVariant().toULongLong());
  686. auto *entity = entity_id == NULL_ENTITY
  687. ? world->createEntity()
  688. : world->createEntityWithId(entity_id);
  689. if (entity != nullptr) {
  690. deserializeEntity(entity, entity_obj);
  691. }
  692. }
  693. if (world_obj.contains("nextEntityId")) {
  694. const auto next_id = static_cast<EntityID>(
  695. world_obj["nextEntityId"].toVariant().toULongLong());
  696. world->setNextEntityId(next_id);
  697. }
  698. if (world_obj.contains("owner_registry")) {
  699. Game::Systems::OwnerRegistry::instance().fromJson(
  700. world_obj["owner_registry"].toObject());
  701. }
  702. if (world_obj.contains("terrain")) {
  703. const auto terrain_obj = world_obj["terrain"].toObject();
  704. const int width = terrain_obj["width"].toInt(50);
  705. const int height = terrain_obj["height"].toInt(50);
  706. const float tile_size =
  707. static_cast<float>(terrain_obj["tile_size"].toDouble(1.0));
  708. Game::Map::BiomeSettings biome;
  709. std::vector<float> const heights;
  710. std::vector<Game::Map::TerrainType> const terrain_types;
  711. std::vector<Game::Map::RiverSegment> const rivers;
  712. std::vector<Game::Map::Bridge> const bridges;
  713. auto temp_height_map =
  714. std::make_unique<Game::Map::TerrainHeightMap>(width, height, tile_size);
  715. deserializeTerrain(temp_height_map.get(), biome, terrain_obj);
  716. auto &terrain_service = Game::Map::TerrainService::instance();
  717. terrain_service.restoreFromSerialized(
  718. width, height, tile_size, temp_height_map->getHeightData(),
  719. temp_height_map->getTerrainTypes(), temp_height_map->getRiverSegments(),
  720. temp_height_map->getBridges(), biome);
  721. }
  722. }
  723. auto Serialization::saveToFile(const QString &filename,
  724. const QJsonDocument &doc) -> bool {
  725. QFile file(filename);
  726. if (!file.open(QIODevice::WriteOnly)) {
  727. qWarning() << "Could not open file for writing:" << filename;
  728. return false;
  729. }
  730. file.write(doc.toJson());
  731. return true;
  732. }
  733. auto Serialization::loadFromFile(const QString &filename) -> QJsonDocument {
  734. QFile file(filename);
  735. if (!file.open(QIODevice::ReadOnly)) {
  736. qWarning() << "Could not open file for reading:" << filename;
  737. return {};
  738. }
  739. const QByteArray data = file.readAll();
  740. return QJsonDocument::fromJson(data);
  741. }
  742. } // namespace Engine::Core