Game.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. #include "Game.h"
  2. #include <Datei.h>
  3. #include <Logging.h>
  4. #include "Chat.h"
  5. #include "Dimension.h"
  6. #include "Entity.h"
  7. #include "ItemEntity.h"
  8. #include "JsonUtils.h"
  9. #include "MultiblockTree.h"
  10. #include "NetworkMessage.h"
  11. #include "NoBlock.h"
  12. #include "Player.h"
  13. #include "PlayerHand.h"
  14. #include "PlayerRegister.h"
  15. #include "Quest.h"
  16. #include "RecipieLoader.h"
  17. #include "Server.h"
  18. #include "TickOrganizer.h"
  19. #include "UIController.h"
  20. #include "WorldGenerator.h"
  21. #include "WorldLoader.h"
  22. #include "Zeit.h"
  23. using namespace Framework;
  24. Framework::ConsoleHandler* Game::consoleHandler = 0;
  25. Framework::InputLine* Game::consoleInput = 0;
  26. Game::Game(Framework::Text name, Framework::Text worldsDir)
  27. : Thread(),
  28. name(name),
  29. typeRegistry(new TypeRegistry()),
  30. blockTypeNameFactory(new BlockTypeNameFactory()),
  31. itemTypeNameFactory(new ItemTypeNameFactory()),
  32. dimensions(new RCArray<Dimension>()),
  33. clients(new RCArray<GameClient>()),
  34. questManager(new QuestManager()),
  35. ticker(new TickOrganizer()),
  36. path((const char*)(worldsDir + "/" + name)),
  37. stop(0),
  38. tickId(0),
  39. nextEntityId(0),
  40. generator(0),
  41. loader(0),
  42. recipies(new RecipieLoader()),
  43. chat(0),
  44. playerRegister(new PlayerRegister(path)),
  45. uiController(new UIController()),
  46. totalTickTime(0),
  47. tickCounter(0),
  48. averageTickTime(0),
  49. ticksPerSecond(0),
  50. totalTime(0),
  51. blockTypes(0),
  52. blockTypeCount(0),
  53. itemTypes(0),
  54. itemTypeCount(0),
  55. entityTypes(0),
  56. entityTypeCount(0),
  57. multiblockStructureTypes(0),
  58. multiblockStructureTypeCount(0)
  59. {
  60. typeRegistry->registerType(
  61. BlockTypeNameFactory::TYPE_ID, blockTypeNameFactory);
  62. typeRegistry->registerType(
  63. ItemTypeNameFactory::TYPE_ID, itemTypeNameFactory);
  64. if (!DateiExistiert(path)) DateiPfadErstellen(path + "/");
  65. Datei d;
  66. d.setDatei(path + "/eid");
  67. if (d.existiert())
  68. {
  69. d.open(Datei::Style::lesen);
  70. d.lese((char*)&nextEntityId, 4);
  71. d.close();
  72. }
  73. start();
  74. }
  75. Game::~Game()
  76. {
  77. dimensions->release();
  78. clients->release();
  79. generator->release();
  80. loader->release();
  81. chat->release();
  82. playerRegister->release();
  83. typeRegistry->release();
  84. uiController->release();
  85. recipies->release();
  86. for (int i = 0; i < blockTypeCount; i++)
  87. {
  88. if (blockTypes[i]) blockTypes[i]->release();
  89. }
  90. delete[] blockTypes;
  91. for (int i = 0; i < itemTypeCount; i++)
  92. {
  93. if (itemTypes[i]) itemTypes[i]->release();
  94. }
  95. delete[] itemTypes;
  96. for (int i = 0; i < entityTypeCount; i++)
  97. {
  98. if (entityTypes[i]) entityTypes[i]->release();
  99. }
  100. delete[] entityTypes;
  101. for (int i = 0; i < multiblockStructureTypeCount; i++)
  102. {
  103. if (multiblockStructureTypes[i]) multiblockStructureTypes[i]->release();
  104. }
  105. delete[] multiblockStructureTypes;
  106. }
  107. void Game::initialize()
  108. {
  109. // TODO load mods libraries
  110. // load block types
  111. Framework::Logging::info() << "Loading block types";
  112. Framework::Array<BlockType*> blockTypeArray;
  113. Framework::Validator::DataValidator* validator
  114. = Framework::Validator::DataValidator::buildForArray()
  115. ->addAcceptedTypeInArray(typeRegistry->getValidator<BlockType>())
  116. ->removeInvalidEntries()
  117. ->finishArray();
  118. loadAllJsonsFromDirectory("data/blocks",
  119. [this, &blockTypeArray, validator](
  120. Framework::JSON::JSONValue* zValue, Framework::Text path) {
  121. Framework::RCArray<Framework::Validator::ValidationResult>
  122. validationResults;
  123. Framework::JSON::JSONValue* validParts
  124. = validator->getValidParts(zValue, &validationResults);
  125. for (Framework::Validator::ValidationResult* result :
  126. validationResults)
  127. {
  128. Framework::Logging::error() << result->getInvalidInfo();
  129. }
  130. if (validParts)
  131. {
  132. for (Framework::JSON::JSONValue* value : *validParts->asArray())
  133. {
  134. BlockType* blockType
  135. = typeRegistry->fromJson<BlockType>(value);
  136. if (blockType)
  137. {
  138. blockTypeArray.add(blockType);
  139. }
  140. }
  141. validParts->release();
  142. }
  143. });
  144. validator->release();
  145. Framework::Logging::info() << "Loaded " << blockTypeArray.getEintragAnzahl()
  146. << " block types from data/blocks";
  147. blockTypes = new BlockType*[2 + blockTypeArray.getEintragAnzahl()];
  148. blockTypes[0] = new NoBlockBlockType(
  149. dynamic_cast<Block*>(NoBlock::INSTANCE.getThis()),
  150. "__not_yet_generated");
  151. blockTypes[1] = new NoBlockBlockType(
  152. dynamic_cast<Block*>(AirBlock::INSTANCE.getThis()), "Air");
  153. blockTypeCount = 2;
  154. for (BlockType* blockType : blockTypeArray)
  155. {
  156. blockTypes[blockTypeCount++] = blockType;
  157. }
  158. Framework::RCArray<Framework::Text>* blockTypeNames
  159. = new Framework::RCArray<Framework::Text>();
  160. for (int i = 0; i < blockTypeCount; i++)
  161. {
  162. blockTypeNames->add(new Framework::Text(blockTypes[i]->getName()));
  163. blockTypes[i]->setTypeId(i);
  164. }
  165. blockTypeNameFactory->setBlockTypeNames(blockTypeNames);
  166. Framework::Logging::info() << "Loading item types";
  167. Framework::Array<ItemType*> itemTypeArray;
  168. validator
  169. = Framework::Validator::DataValidator::buildForArray()
  170. ->addAcceptedTypeInArray(typeRegistry->getValidator<ItemType>())
  171. ->removeInvalidEntries()
  172. ->finishArray();
  173. loadAllJsonsFromDirectory("data/items",
  174. [this, &itemTypeArray, validator](
  175. Framework::JSON::JSONValue* zValue, Framework::Text path) {
  176. Framework::RCArray<Framework::Validator::ValidationResult>
  177. validationResults;
  178. Framework::JSON::JSONValue* validParts
  179. = validator->getValidParts(zValue, &validationResults);
  180. for (Framework::Validator::ValidationResult* result :
  181. validationResults)
  182. {
  183. Framework::Logging::error() << result->getInvalidInfo();
  184. }
  185. if (validParts)
  186. {
  187. for (Framework::JSON::JSONValue* value : *validParts->asArray())
  188. {
  189. ItemType* itemType
  190. = typeRegistry->fromJson<ItemType>(value);
  191. if (itemType)
  192. {
  193. itemTypeArray.add(itemType);
  194. }
  195. }
  196. validParts->release();
  197. }
  198. });
  199. validator->release();
  200. Framework::Logging::info() << "Loaded " << itemTypeArray.getEintragAnzahl()
  201. << " item types from data/items";
  202. itemTypes
  203. = new ItemType*[blockTypeCount + itemTypeArray.getEintragAnzahl()];
  204. itemTypes[0] = new PlayerHandItemType();
  205. itemTypeCount = 1;
  206. for (int i = 0; i < blockTypeCount; i++)
  207. {
  208. ItemType* itemType = blockTypes[i]->createItemType();
  209. if (itemType)
  210. {
  211. itemTypes[itemTypeCount++] = itemType;
  212. }
  213. }
  214. for (ItemType* itemType : itemTypeArray)
  215. {
  216. itemTypes[itemTypeCount++] = itemType;
  217. }
  218. Framework::RCArray<Framework::Text>* itemTypeNames
  219. = new Framework::RCArray<Framework::Text>();
  220. for (int i = 0; i < itemTypeCount; i++)
  221. {
  222. itemTypes[i]->setTypeId(i);
  223. itemTypeNames->add(new Framework::Text(itemTypes[i]->getName()));
  224. }
  225. itemTypeNameFactory->setItemTypeNames(itemTypeNames);
  226. Framework::Logging::info() << "Loading entity types";
  227. Framework::Array<EntityType*> entityTypeArray;
  228. validator
  229. = Framework::Validator::DataValidator::buildForArray()
  230. ->addAcceptedTypeInArray(typeRegistry->getValidator<EntityType>())
  231. ->removeInvalidEntries()
  232. ->finishArray();
  233. loadAllJsonsFromDirectory("data/entities",
  234. [this, &entityTypeArray, validator](
  235. Framework::JSON::JSONValue* zValue, Framework::Text path) {
  236. Framework::RCArray<Framework::Validator::ValidationResult>
  237. validationResults;
  238. Framework::JSON::JSONValue* validParts
  239. = validator->getValidParts(zValue, &validationResults);
  240. for (Framework::Validator::ValidationResult* result :
  241. validationResults)
  242. {
  243. Framework::Logging::error() << result->getInvalidInfo();
  244. }
  245. if (validParts)
  246. {
  247. for (Framework::JSON::JSONValue* value : *validParts->asArray())
  248. {
  249. EntityType* entityType
  250. = typeRegistry->fromJson<EntityType>(value);
  251. if (entityType)
  252. {
  253. entityTypeArray.add(entityType);
  254. }
  255. }
  256. validParts->release();
  257. }
  258. });
  259. validator->release();
  260. Framework::Logging::info()
  261. << "Loaded " << entityTypeArray.getEintragAnzahl()
  262. << " entity types from data/entities";
  263. entityTypes = new EntityType*[2 + entityTypeArray.getEintragAnzahl()];
  264. entityTypes[0] = new PlayerEntityType();
  265. entityTypes[1] = new ItemEntityType();
  266. entityTypeCount = 2;
  267. for (EntityType* entityType : entityTypeArray)
  268. {
  269. entityTypes[entityTypeCount++] = entityType;
  270. }
  271. for (int i = 0; i < entityTypeCount; i++)
  272. {
  273. entityTypes[i]->setTypeId(i);
  274. }
  275. // initialize loaded types
  276. bool allInitialized = false;
  277. while (!allInitialized)
  278. {
  279. allInitialized = true;
  280. for (int i = 0; i < blockTypeCount; i++)
  281. {
  282. if (blockTypes[i] && !blockTypes[i]->initialize(this))
  283. {
  284. Framework::Logging::error()
  285. << "Could not initialize Block Type '"
  286. << blockTypes[i]->getName() << "'.";
  287. blockTypes[i]->release();
  288. blockTypes[i] = 0;
  289. allInitialized = false;
  290. }
  291. }
  292. }
  293. allInitialized = false;
  294. while (!allInitialized)
  295. {
  296. allInitialized = true;
  297. for (int i = 0; i < itemTypeCount; i++)
  298. {
  299. if (itemTypes[i] && !itemTypes[i]->initialize(this))
  300. {
  301. Framework::Logging::error()
  302. << "Could not initialize Item Type '"
  303. << itemTypes[i]->getName() << "'.";
  304. itemTypes[i]->release();
  305. itemTypes[i] = 0;
  306. allInitialized = false;
  307. }
  308. }
  309. }
  310. allInitialized = false;
  311. while (!allInitialized)
  312. {
  313. allInitialized = true;
  314. for (int i = 0; i < entityTypeCount; i++)
  315. {
  316. if (entityTypes[i] && !entityTypes[i]->initialize(this))
  317. {
  318. Framework::Logging::error()
  319. << "Could not initialize Entity Type '"
  320. << entityTypes[i]->getName() << "'.";
  321. entityTypes[i]->release();
  322. entityTypes[i] = 0;
  323. allInitialized = false;
  324. }
  325. }
  326. }
  327. for (int i = 0; i < blockTypeCount; i++)
  328. {
  329. if (blockTypes[i])
  330. {
  331. blockTypes[i]->initializeDefault();
  332. }
  333. }
  334. multiblockStructureTypes = new MultiblockStructureType*[1];
  335. multiblockStructureTypes[0] = new MultiblockTreeStructureType();
  336. multiblockStructureTypeCount = 1;
  337. // save syntax info
  338. Framework::DateiRemove("data/syntax");
  339. // typeRegistry->writeSyntaxInfo("data/syntax");
  340. validator
  341. = Framework::Validator::DataValidator::buildForArray()
  342. ->addAcceptedTypeInArray(typeRegistry->getValidator<BlockType>())
  343. ->finishArray();
  344. Framework::JSON::JSONObject* schema = validator->getJsonSchema();
  345. Framework::Datei syntaxFile;
  346. syntaxFile.setDatei("data/syntax/schema/blocks.json");
  347. syntaxFile.erstellen();
  348. syntaxFile.open(Framework::Datei::Style::schreiben);
  349. syntaxFile.schreibe(schema->toString(), schema->toString().getLength());
  350. syntaxFile.close();
  351. schema->release();
  352. validator->release();
  353. validator
  354. = Framework::Validator::DataValidator::buildForArray()
  355. ->addAcceptedTypeInArray(typeRegistry->getValidator<ItemType>())
  356. ->finishArray();
  357. schema = validator->getJsonSchema();
  358. syntaxFile.setDatei("data/syntax/schema/items.json");
  359. syntaxFile.erstellen();
  360. syntaxFile.open(Framework::Datei::Style::schreiben);
  361. syntaxFile.schreibe(schema->toString(), schema->toString().getLength());
  362. syntaxFile.close();
  363. schema->release();
  364. validator->release();
  365. validator
  366. = Framework::Validator::DataValidator::buildForArray()
  367. ->addAcceptedTypeInArray(typeRegistry->getValidator<EntityType>())
  368. ->finishArray();
  369. schema = validator->getJsonSchema();
  370. syntaxFile.setDatei("data/syntax/schema/entities.json");
  371. syntaxFile.erstellen();
  372. syntaxFile.open(Framework::Datei::Style::schreiben);
  373. syntaxFile.schreibe(schema->toString(), schema->toString().getLength());
  374. syntaxFile.close();
  375. schema->release();
  376. validator->release();
  377. // initialize world generator and world loader
  378. int seed = 0;
  379. int index = 0;
  380. for (const char* n = name; *n; n++)
  381. seed += (int)pow((float)*n * 31, (float)++index);
  382. generator = new WorldGenerator(seed);
  383. loader = new WorldLoader();
  384. // load recipies
  385. recipies->loadRecipies("data");
  386. // initialize chat
  387. chat = new Chat();
  388. // load quests
  389. questManager->loadQuests();
  390. }
  391. void Game::thread()
  392. {
  393. ZeitMesser waitForLock;
  394. ZeitMesser removeOldClients;
  395. ZeitMesser clientReply;
  396. ZeitMesser removeOldChunks;
  397. ZeitMesser m;
  398. ZeitMesser total;
  399. total.messungStart();
  400. double tickTime = 0;
  401. double sleepTime = 0;
  402. int nextTimeSync = MAX_TICKS_PER_SECOND;
  403. int ticktToNextUpdate = MAX_TICKS_PER_SECOND * 5;
  404. while (!stop)
  405. {
  406. ticktToNextUpdate--;
  407. if (ticktToNextUpdate <= 0)
  408. {
  409. questManager->processEvent(new QuestEventTimeUpdate());
  410. ticktToNextUpdate = MAX_TICKS_PER_SECOND * 5;
  411. }
  412. m.messungStart();
  413. ticker->nextTick();
  414. actionsCs.lock();
  415. while (actions.getEintragAnzahl() > 0)
  416. {
  417. actions.get(0)();
  418. actions.remove(0);
  419. }
  420. actionsCs.unlock();
  421. Array<int> removed;
  422. double waitTotal = 0;
  423. waitForLock.messungStart();
  424. cs.lock();
  425. waitForLock.messungEnde();
  426. waitTotal += waitForLock.getSekunden();
  427. removeOldClients.messungStart();
  428. int index = 0;
  429. nextTimeSync--;
  430. for (auto player : *clients)
  431. {
  432. if (!player->isOnline())
  433. {
  434. uiController->removePlayerDialogs(player->zEntity()->getId());
  435. chat->removeObserver(player->zEntity()->getId());
  436. chat->broadcastMessage(
  437. Framework::Text(player->zEntity()->getName())
  438. + " left the game.",
  439. Chat::CHANNEL_INFO);
  440. Datei pFile;
  441. pFile.setDatei(path + "/player/"
  442. + getPlayerId(player->zEntity()->getName()));
  443. pFile.erstellen();
  444. if (pFile.open(Datei::Style::schreiben))
  445. {
  446. zEntityType(EntityTypeEnum::PLAYER)
  447. ->saveEntity(player->zEntity(), &pFile);
  448. }
  449. pFile.close();
  450. Dimension* dim
  451. = zDimension(player->zEntity()->getDimensionId());
  452. Chunk* chunk = dim->zChunk(
  453. getChunkCenter((int)player->zEntity()->getLocation().x,
  454. (int)player->zEntity()->getLocation().y));
  455. if (chunk)
  456. {
  457. chunk->onEntityLeaves(player->zEntity(), 0);
  458. }
  459. dim->removeEntity(player->zEntity()->getId());
  460. removed.add(index, 0);
  461. dim->removeSubscriptions(player->zEntity());
  462. }
  463. else
  464. {
  465. if (nextTimeSync <= 0 && player->zEntity())
  466. {
  467. Dimension* zDim
  468. = zDimension(player->zEntity()->getDimensionId());
  469. if (zDim)
  470. {
  471. NetworkMessage* msg = new NetworkMessage();
  472. msg->syncTime(zDim->getCurrentDayTime(),
  473. zDim->getNightDuration(),
  474. zDim->getNightTransitionDuration(),
  475. zDim->getDayDuration());
  476. player->sendResponse(msg);
  477. }
  478. }
  479. }
  480. index++;
  481. }
  482. if (nextTimeSync <= 0)
  483. {
  484. consoleHandler->print();
  485. nextTimeSync = MAX_TICKS_PER_SECOND;
  486. }
  487. for (auto i : removed)
  488. clients->remove(i);
  489. removeOldClients.messungEnde();
  490. for (Dimension* dim : *dimensions)
  491. {
  492. dim->tick();
  493. }
  494. cs.unlock();
  495. clientReply.messungStart();
  496. for (auto client : *clients)
  497. client->reply();
  498. clientReply.messungEnde();
  499. waitForLock.messungStart();
  500. cs.lock();
  501. waitForLock.messungEnde();
  502. waitTotal += waitForLock.getSekunden();
  503. removeOldChunks.messungStart();
  504. for (auto dim : *dimensions)
  505. dim->removeOldChunks();
  506. removeOldChunks.messungEnde();
  507. cs.unlock();
  508. m.messungEnde();
  509. double sec = m.getSekunden();
  510. tickCounter++;
  511. totalTickTime += sec;
  512. sleepTime += 1.0 / MAX_TICKS_PER_SECOND - tickTime;
  513. if (sleepTime > 0)
  514. {
  515. Sleep((int)(sleepTime * 1000));
  516. }
  517. total.messungEnde();
  518. total.messungStart();
  519. tickTime = total.getSekunden();
  520. totalTime += tickTime;
  521. if (totalTime >= 1)
  522. {
  523. averageTickTime = totalTickTime / tickCounter;
  524. ticksPerSecond = tickCounter;
  525. totalTickTime = 0;
  526. tickCounter = 0;
  527. totalTime = 0;
  528. }
  529. else if (sec > 1)
  530. {
  531. Framework::Logging::warning()
  532. << "tick needed " << sec
  533. << " seconds. The game will run sower then normal.\n";
  534. Framework::Logging::trace()
  535. << "waiting: " << waitTotal
  536. << "\nremoveOldClients: " << removeOldClients.getSekunden()
  537. << "\nclientReply: " << clientReply.getSekunden()
  538. << "\nremoveOldChunks:" << removeOldChunks.getSekunden();
  539. }
  540. }
  541. save();
  542. generator->exitAndWait();
  543. loader->exitAndWait();
  544. ticker->exitAndWait();
  545. for (Dimension* dim : *dimensions)
  546. dim->requestStopAndWait();
  547. Framework::Logging::info() << "Game thread exited";
  548. }
  549. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  550. {
  551. char type;
  552. zRequest->lese(&type, 1);
  553. NetworkMessage* response = new NetworkMessage();
  554. switch (type)
  555. {
  556. case 1: // world
  557. {
  558. Dimension* dim = zDimension(zOrigin->zEntity()->getDimensionId());
  559. if (!dim)
  560. {
  561. dim = generator->createDimension(
  562. zOrigin->zEntity()->getDimensionId());
  563. if (!dim)
  564. {
  565. Framework::Logging::error()
  566. << "could not create dimension "
  567. << zOrigin->zEntity()->getDimensionId()
  568. << ". No Factory was provided.";
  569. return;
  570. }
  571. addDimension(dim);
  572. }
  573. dim->api(zRequest, response, zOrigin->zEntity());
  574. break;
  575. }
  576. case 2: // player
  577. zOrigin->zEntity()->playerApi(zRequest, response);
  578. break;
  579. case 3: // entity
  580. {
  581. int id;
  582. zRequest->lese((char*)&id, 4);
  583. for (Dimension* dim : *dimensions)
  584. {
  585. Entity* entity = dim->zEntity(id);
  586. if (entity)
  587. {
  588. entity->api(zRequest, response, zOrigin->zEntity());
  589. break;
  590. }
  591. }
  592. break;
  593. }
  594. case 4:
  595. { // inventory
  596. bool isEntity;
  597. zRequest->lese((char*)&isEntity, 1);
  598. Inventory* target;
  599. if (isEntity)
  600. {
  601. int id;
  602. zRequest->lese((char*)&id, 4);
  603. target = zEntity(id);
  604. }
  605. else
  606. {
  607. int dim;
  608. Vec3<int> pos;
  609. zRequest->lese((char*)&dim, 4);
  610. zRequest->lese((char*)&pos.x, 4);
  611. zRequest->lese((char*)&pos.y, 4);
  612. zRequest->lese((char*)&pos.z, 4);
  613. target = zBlockAt(pos, dim, 0);
  614. }
  615. if (target)
  616. target->inventoryApi(zRequest, response, zOrigin->zEntity());
  617. break;
  618. }
  619. case 5:
  620. { // crafting uiml request
  621. int id;
  622. zRequest->lese((char*)&id, 4);
  623. Framework::XML::Element* uiml = recipies->getCrafingUIML(id);
  624. Text dialogId = "crafting_";
  625. dialogId += id;
  626. uiController->addDialog(
  627. new UIDialog(dialogId, zOrigin->zEntity()->getId(), uiml));
  628. break;
  629. }
  630. case 6:
  631. { // chat message
  632. chat->chatApi(zRequest, zOrigin->zEntity(), response);
  633. break;
  634. }
  635. case 7: // other dimension
  636. {
  637. int dimensionId;
  638. zRequest->lese((char*)&dimensionId, 4);
  639. Dimension* dim = zDimension(dimensionId);
  640. if (dim)
  641. {
  642. dim->api(zRequest, response, zOrigin->zEntity());
  643. }
  644. break;
  645. }
  646. case 8: // ui message
  647. {
  648. uiController->api(zRequest, response, zOrigin->zEntity());
  649. break;
  650. }
  651. default:
  652. Framework::Logging::warning()
  653. << "received unknown api request in game with type " << (int)type;
  654. }
  655. if (!response->isEmpty())
  656. {
  657. if (response->isBroadcast())
  658. broadcastMessage(response);
  659. else
  660. zOrigin->sendResponse(response);
  661. }
  662. else
  663. {
  664. response->release();
  665. }
  666. }
  667. void Game::updateLightning(int dimensionId, Vec3<int> location)
  668. {
  669. Dimension* zDim = zDimension(dimensionId);
  670. if (zDim) zDim->updateLightning(location);
  671. }
  672. void Game::updateLightningWithoutWait(int dimensionId, Vec3<int> location)
  673. {
  674. Dimension* zDim = zDimension(dimensionId);
  675. if (zDim) zDim->updateLightningWithoutWait(location);
  676. }
  677. void Game::broadcastMessage(NetworkMessage* response)
  678. {
  679. for (auto client : *clients)
  680. client->sendResponse(
  681. dynamic_cast<NetworkMessage*>(response->getThis()));
  682. response->release();
  683. }
  684. void Game::sendMessage(NetworkMessage* response, Entity* zTargetPlayer)
  685. {
  686. for (auto client : *clients)
  687. {
  688. if (client->zEntity()->getId() == zTargetPlayer->getId())
  689. {
  690. client->sendResponse(response);
  691. return;
  692. }
  693. }
  694. response->release();
  695. }
  696. bool Game::checkPlayer(Framework::Text name, Framework::Text secret)
  697. {
  698. if (playerRegister->checkSecret(name, secret))
  699. return 1;
  700. else
  701. {
  702. Framework::Logging::warning()
  703. << "player " << name.getText()
  704. << " tryed to connect with an invalid secret.";
  705. return 0;
  706. }
  707. }
  708. bool Game::existsPlayer(Framework::Text name)
  709. {
  710. return playerRegister->hasPlayer(name);
  711. }
  712. Framework::Text Game::createPlayer(Framework::Text name)
  713. {
  714. return playerRegister->addPlayer(name);
  715. }
  716. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  717. {
  718. cs.lock();
  719. int id = playerRegister->getPlayerId(name);
  720. Datei pFile;
  721. pFile.setDatei(path + "/player/" + id);
  722. Player* player;
  723. bool isNew = 0;
  724. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  725. {
  726. player = (Player*)zEntityType(EntityTypeEnum::PLAYER)
  727. ->createEntityAt(
  728. Vec3<float>(0.5, 0.5, 0), DimensionEnum::OVERWORLD);
  729. player->setName(name);
  730. isNew = 1;
  731. }
  732. else
  733. {
  734. player
  735. = (Player*)zEntityType(EntityTypeEnum::PLAYER)->loadEntity(&pFile);
  736. pFile.close();
  737. }
  738. if (player->getId() >= nextEntityId)
  739. {
  740. nextEntityId = player->getId() + 1;
  741. }
  742. GameClient* gameClient = new GameClient(player, client);
  743. gameClient->sendTypes();
  744. clients->add(gameClient);
  745. if (!zDimension(player->getDimensionId()))
  746. {
  747. Dimension* dim = generator->createDimension(player->getDimensionId());
  748. if (!dim)
  749. {
  750. Framework::Logging::error() << "could not create dimension "
  751. << (int)player->getDimensionId()
  752. << ". No Factory was provided.";
  753. return 0;
  754. }
  755. NetworkMessage* msg = new NetworkMessage();
  756. msg->syncTime(dim->getCurrentDayTime(),
  757. dim->getNightDuration(),
  758. dim->getNightTransitionDuration(),
  759. dim->getDayDuration());
  760. gameClient->sendResponse(msg);
  761. this->addDimension(dim);
  762. }
  763. // subscribe the new player as an observer of the new chunk
  764. Dimension* dim = zDimension(player->getDimensionId());
  765. InMemoryBuffer* buffer = new InMemoryBuffer();
  766. buffer->schreibe("\0", 1);
  767. Punkt center = getChunkCenter(
  768. (int)player->getPosition().x, (int)player->getPosition().y);
  769. buffer->schreibe((char*)&center.x, 4);
  770. buffer->schreibe((char*)&center.y, 4);
  771. buffer->schreibe("\0", 1);
  772. dim->api(buffer, 0, player);
  773. buffer->release();
  774. while (!dim->zChunk(getChunkCenter(
  775. (int)player->getPosition().x, (int)player->getPosition().y)))
  776. {
  777. cs.unlock();
  778. Sleep(1000);
  779. cs.lock();
  780. }
  781. if (isNew)
  782. {
  783. Either<Block*, int> b = BlockTypeEnum::AIR;
  784. int h = WORLD_HEIGHT;
  785. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable()))
  786. || (b.isB() && zBlockType(b)->zDefault()->isPassable()))
  787. && h > 0)
  788. b = zBlockAt({(int)player->getPosition().x,
  789. (int)player->getPosition().y,
  790. --h},
  791. player->getDimensionId(),
  792. 0);
  793. player->setPosition(
  794. {player->getPosition().x, player->getPosition().y, (float)h + 2.f});
  795. }
  796. dim->addEntity(player);
  797. chat->addObserver(gameClient->zEntity()->getId());
  798. chat->broadcastMessage(name + " joined the game.", Chat::CHANNEL_INFO);
  799. cs.unlock();
  800. return dynamic_cast<GameClient*>(gameClient->getThis());
  801. }
  802. bool Game::isChunkLoaded(int x, int y, int dimension) const
  803. {
  804. Dimension* dim = zDimension(dimension);
  805. return (dim && dim->hasChunck(x, y));
  806. }
  807. bool Game::doesChunkExist(int x, int y, int dimension)
  808. {
  809. cs.lock();
  810. bool result = isChunkLoaded(x, y, dimension)
  811. || loader->existsChunk(x, y, dimension);
  812. cs.unlock();
  813. return result;
  814. }
  815. void Game::blockTargetChanged(Block* zBlock)
  816. {
  817. for (GameClient* client : *this->clients)
  818. {
  819. if (client->zEntity()->zTarget()
  820. && client->zEntity()->zTarget()->isBlock(
  821. zBlock->getPos(), NO_DIRECTION))
  822. {
  823. client->zEntity()->onTargetChange();
  824. }
  825. }
  826. }
  827. void Game::entityTargetChanged(Entity* zEntity)
  828. {
  829. for (GameClient* client : *this->clients)
  830. {
  831. if (client->zEntity()->zTarget()
  832. && client->zEntity()->zTarget()->isEntity(zEntity->getId()))
  833. {
  834. client->zEntity()->onTargetChange();
  835. }
  836. }
  837. }
  838. void Game::spawnItem(
  839. Framework::Vec3<float> location, int dimensionId, Item* stack)
  840. {
  841. spawnItem(location, dimensionId, new ItemStack(stack, 1));
  842. }
  843. void Game::spawnItem(
  844. Framework::Vec3<float> location, int dimensionId, ItemStack* stack)
  845. {
  846. if (stack->getSize() == 0)
  847. {
  848. Logging::error() << "spawn item was called with empty stack";
  849. return;
  850. }
  851. ItemEntity* itemEntity = (ItemEntity*)zEntityType(EntityTypeEnum::ITEM)
  852. ->createEntityAt(location, dimensionId);
  853. itemEntity->unsaveAddItem(stack, NO_DIRECTION, 0);
  854. if (stack->getSize() > 0)
  855. {
  856. Logging::error() << "could not add item to item entity";
  857. }
  858. stack->release();
  859. Dimension* dim = zDimension(dimensionId);
  860. if (dim)
  861. {
  862. Punkt center = Game::getChunkCenter(
  863. (int)itemEntity->getLocation().x, (int)itemEntity->getLocation().y);
  864. dim->zChunk(center)
  865. ->onEntityEnters(itemEntity, 0);
  866. itemEntity->setLastChunk(dimensionId, center);
  867. dim->addEntity(itemEntity);
  868. }
  869. else
  870. {
  871. Framework::Logging::error()
  872. << "could not spawn item entity in dimension " << dimensionId
  873. << ". Dimension not loaded.";
  874. itemEntity->release();
  875. return;
  876. }
  877. }
  878. Framework::Either<Block*, int> Game::zBlockAt(
  879. Framework::Vec3<int> location, int dimension, OUT Chunk** zChunk) const
  880. {
  881. Dimension* dim = zDimension(dimension);
  882. if (dim) return dim->zBlock(location, zChunk);
  883. return 0;
  884. }
  885. Block* Game::zRealBlockInstance(
  886. Framework::Vec3<int> location, int dimension) const
  887. {
  888. Dimension* dim = zDimension(dimension);
  889. if (dim) return dim->zRealBlockInstance(location);
  890. return 0;
  891. }
  892. const Block* Game::zConstBlock(
  893. Framework::Vec3<int> location, int dimension) const
  894. {
  895. Dimension* dim = zDimension(dimension);
  896. if (dim) return dim->zBlockOrDefault(location);
  897. return 0;
  898. }
  899. int Game::getBlockType(Framework::Vec3<int> location, int dimension) const
  900. {
  901. Dimension* dim = zDimension(dimension);
  902. if (dim) return dim->getBlockType(location);
  903. return 0;
  904. }
  905. Dimension* Game::zDimension(int id) const
  906. {
  907. for (auto dim : *dimensions)
  908. {
  909. if (dim->getDimensionId() == id) return dim;
  910. }
  911. return 0;
  912. }
  913. Framework::Punkt Game::getChunkCenter(int x, int y)
  914. {
  915. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  916. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  917. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  918. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  919. }
  920. Area Game::getChunckArea(Punkt center) const
  921. {
  922. return {center.x - CHUNK_SIZE / 2,
  923. center.y - CHUNK_SIZE / 2,
  924. center.x + CHUNK_SIZE / 2 - 1,
  925. center.y + CHUNK_SIZE / 2 - 1,
  926. 0};
  927. }
  928. Framework::Text Game::getWorldDirectory() const
  929. {
  930. return path;
  931. }
  932. void Game::requestArea(Area area)
  933. {
  934. generator->requestGeneration(area);
  935. loader->requestLoading(area);
  936. }
  937. void Game::save() const
  938. {
  939. questManager->saveQuests();
  940. Datei d;
  941. d.setDatei(path + "/eid");
  942. d.open(Datei::Style::schreiben);
  943. d.schreibe((char*)&nextEntityId, 4);
  944. d.close();
  945. playerRegister->save();
  946. for (auto dim : *dimensions)
  947. dim->save(path);
  948. chat->save();
  949. Framework::Logging::info() << "Game was saved";
  950. }
  951. void Game::requestStop()
  952. {
  953. stop = 1;
  954. warteAufThread(1000000);
  955. }
  956. void Game::addDimension(Dimension* d)
  957. {
  958. dimensions->add(d);
  959. }
  960. int Game::getNextEntityId()
  961. {
  962. neidl.lock();
  963. int result = nextEntityId++;
  964. neidl.unlock();
  965. return result;
  966. }
  967. WorldGenerator* Game::zGenerator() const
  968. {
  969. return generator;
  970. }
  971. Game* Game::INSTANCE = 0;
  972. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  973. {
  974. if (!Game::INSTANCE)
  975. {
  976. Game::INSTANCE = new Game(name, worldsDir);
  977. Game::INSTANCE->initialize();
  978. }
  979. }
  980. Entity* Game::zEntity(int id, int dimensionId) const
  981. {
  982. Dimension* d = zDimension(dimensionId);
  983. if (d) return d->zEntity(id);
  984. return 0;
  985. }
  986. Entity* Game::zEntity(int id) const
  987. {
  988. for (Dimension* d : *dimensions)
  989. {
  990. Entity* e = d->zEntity(id);
  991. if (e) return e;
  992. }
  993. // for new players that are currently loading
  994. for (GameClient* client : *clients)
  995. {
  996. if (client->zEntity()->getId() == id)
  997. {
  998. return client->zEntity();
  999. }
  1000. }
  1001. return 0;
  1002. }
  1003. Entity* Game::zNearestEntity(int dimensionId,
  1004. Framework::Vec3<float> pos,
  1005. std::function<bool(Entity*)> filter) const
  1006. {
  1007. Dimension* d = zDimension(dimensionId);
  1008. if (!d) return 0;
  1009. return d->zNearestEntity(pos, filter);
  1010. }
  1011. RecipieLoader* Game::zRecipies() const
  1012. {
  1013. return recipies;
  1014. }
  1015. void Game::doLater(std::function<void()> action)
  1016. {
  1017. actionsCs.lock();
  1018. actions.add(action);
  1019. actionsCs.unlock();
  1020. }
  1021. TickOrganizer* Game::zTickOrganizer() const
  1022. {
  1023. return ticker;
  1024. }
  1025. Chat* Game::zChat() const
  1026. {
  1027. return chat;
  1028. }
  1029. Player* Game::zPlayerByName(const char* name) const
  1030. {
  1031. for (GameClient* client : *clients)
  1032. {
  1033. if (strcmp(client->zEntity()->getName(), name) == 0)
  1034. {
  1035. return client->zEntity();
  1036. }
  1037. }
  1038. return 0;
  1039. }
  1040. void Game::listPlayerNames(Framework::RCArray<Framework::Text>& names)
  1041. {
  1042. for (GameClient* client : *clients)
  1043. {
  1044. names.add(new Framework::Text(client->zEntity()->getName()));
  1045. }
  1046. }
  1047. TypeRegistry* Game::zTypeRegistry() const
  1048. {
  1049. return typeRegistry;
  1050. }
  1051. int Game::getPlayerId(const char* name) const
  1052. {
  1053. return playerRegister->getPlayerId(name);
  1054. }
  1055. QuestManager* Game::zQuestManager() const
  1056. {
  1057. return questManager;
  1058. }
  1059. UIController* Game::zUIController() const
  1060. {
  1061. return uiController;
  1062. }
  1063. double Game::getAverageTickTime() const
  1064. {
  1065. return averageTickTime;
  1066. }
  1067. int Game::getTicksPerSecond() const
  1068. {
  1069. return ticksPerSecond;
  1070. }
  1071. int Game::getPlayerCount() const
  1072. {
  1073. return clients->getEintragAnzahl();
  1074. }
  1075. int Game::getChunkCount() const
  1076. {
  1077. int result = 0;
  1078. for (Dimension* dim : *dimensions)
  1079. {
  1080. result += dim->getChunkCount();
  1081. }
  1082. return result;
  1083. }
  1084. const BlockType* Game::zBlockType(int id) const
  1085. {
  1086. return blockTypes[id];
  1087. }
  1088. const ItemType* Game::zItemType(int id) const
  1089. {
  1090. return itemTypes[id];
  1091. }
  1092. const EntityType* Game::zEntityType(int id) const
  1093. {
  1094. return entityTypes[id];
  1095. }
  1096. int Game::getEntityTypeId(const char* name) const
  1097. {
  1098. for (int i = 0; i < entityTypeCount; i++)
  1099. {
  1100. if (entityTypes[i]
  1101. && Framework::Text(entityTypes[i]->getName()).istGleich(name))
  1102. {
  1103. return i;
  1104. }
  1105. }
  1106. Framework::Logging::warning()
  1107. << "no entity type with name '" << name << "' found.";
  1108. return -1;
  1109. }
  1110. int Game::getBlockTypeId(const char* name) const
  1111. {
  1112. for (int i = 0; i < blockTypeCount; i++)
  1113. {
  1114. if (blockTypes[i]
  1115. && Framework::Text(blockTypes[i]->getName()).istGleich(name))
  1116. {
  1117. return i;
  1118. }
  1119. }
  1120. Framework::Logging::warning()
  1121. << "no block type with name '" << name << "' found.";
  1122. return -1;
  1123. }
  1124. int Game::getItemTypeId(const char* name) const
  1125. {
  1126. for (int i = 0; i < itemTypeCount; i++)
  1127. {
  1128. if (itemTypes[i]
  1129. && Framework::Text(itemTypes[i]->getName()).istGleich(name))
  1130. {
  1131. return i;
  1132. }
  1133. }
  1134. Framework::Logging::warning()
  1135. << "no item type with name '" << name << "' found.";
  1136. return -1;
  1137. }
  1138. int Game::getBlockTypeCount() const
  1139. {
  1140. return blockTypeCount;
  1141. }
  1142. int Game::getItemTypeCount() const
  1143. {
  1144. return itemTypeCount;
  1145. }
  1146. int Game::getEntityTypeCount() const
  1147. {
  1148. return entityTypeCount;
  1149. }
  1150. const MultiblockStructureType* Game::zMultiblockStructureType(int id) const
  1151. {
  1152. return multiblockStructureTypes[id];
  1153. }
  1154. int Game::getMultiblockStructureTypeCount() const
  1155. {
  1156. return multiblockStructureTypeCount;
  1157. }