Game.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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. while (!stop)
  404. {
  405. m.messungStart();
  406. ticker->nextTick();
  407. actionsCs.lock();
  408. while (actions.getEintragAnzahl() > 0)
  409. {
  410. actions.get(0)();
  411. actions.remove(0);
  412. }
  413. actionsCs.unlock();
  414. Array<int> removed;
  415. double waitTotal = 0;
  416. waitForLock.messungStart();
  417. cs.lock();
  418. waitForLock.messungEnde();
  419. waitTotal += waitForLock.getSekunden();
  420. removeOldClients.messungStart();
  421. int index = 0;
  422. nextTimeSync--;
  423. for (auto player : *clients)
  424. {
  425. if (!player->isOnline())
  426. {
  427. uiController->removePlayerDialogs(player->zEntity()->getId());
  428. chat->removeObserver(player->zEntity()->getId());
  429. chat->broadcastMessage(
  430. Framework::Text(player->zEntity()->getName())
  431. + " left the game.",
  432. Chat::CHANNEL_INFO);
  433. Datei pFile;
  434. pFile.setDatei(path + "/player/"
  435. + getPlayerId(player->zEntity()->getName()));
  436. pFile.erstellen();
  437. if (pFile.open(Datei::Style::schreiben))
  438. {
  439. zEntityType(EntityTypeEnum::PLAYER)
  440. ->saveEntity(player->zEntity(), &pFile);
  441. }
  442. pFile.close();
  443. Dimension* dim
  444. = zDimension(player->zEntity()->getDimensionId());
  445. Chunk* chunk = dim->zChunk(
  446. getChunkCenter((int)player->zEntity()->getLocation().x,
  447. (int)player->zEntity()->getLocation().y));
  448. if (chunk)
  449. {
  450. chunk->onEntityLeaves(player->zEntity(), 0);
  451. }
  452. dim->removeEntity(player->zEntity()->getId());
  453. removed.add(index, 0);
  454. dim->removeSubscriptions(player->zEntity());
  455. }
  456. else
  457. {
  458. if (nextTimeSync <= 0 && player->zEntity())
  459. {
  460. Dimension* zDim
  461. = zDimension(player->zEntity()->getDimensionId());
  462. if (zDim)
  463. {
  464. NetworkMessage* msg = new NetworkMessage();
  465. msg->syncTime(zDim->getCurrentDayTime(),
  466. zDim->getNightDuration(),
  467. zDim->getNightTransitionDuration(),
  468. zDim->getDayDuration());
  469. player->sendResponse(msg);
  470. }
  471. }
  472. }
  473. index++;
  474. }
  475. if (nextTimeSync <= 0)
  476. {
  477. consoleHandler->print();
  478. nextTimeSync = MAX_TICKS_PER_SECOND;
  479. }
  480. for (auto i : removed)
  481. clients->remove(i);
  482. removeOldClients.messungEnde();
  483. for (Dimension* dim : *dimensions)
  484. {
  485. dim->tick();
  486. }
  487. cs.unlock();
  488. clientReply.messungStart();
  489. for (auto client : *clients)
  490. client->reply();
  491. clientReply.messungEnde();
  492. waitForLock.messungStart();
  493. cs.lock();
  494. waitForLock.messungEnde();
  495. waitTotal += waitForLock.getSekunden();
  496. removeOldChunks.messungStart();
  497. for (auto dim : *dimensions)
  498. dim->removeOldChunks();
  499. removeOldChunks.messungEnde();
  500. cs.unlock();
  501. m.messungEnde();
  502. double sec = m.getSekunden();
  503. tickCounter++;
  504. totalTickTime += sec;
  505. sleepTime += 1.0 / MAX_TICKS_PER_SECOND - tickTime;
  506. if (sleepTime > 0)
  507. {
  508. Sleep((int)(sleepTime * 1000));
  509. }
  510. total.messungEnde();
  511. total.messungStart();
  512. tickTime = total.getSekunden();
  513. totalTime += tickTime;
  514. if (totalTime >= 1)
  515. {
  516. averageTickTime = totalTickTime / tickCounter;
  517. ticksPerSecond = tickCounter;
  518. totalTickTime = 0;
  519. tickCounter = 0;
  520. totalTime = 0;
  521. }
  522. else if (sec > 1)
  523. {
  524. Framework::Logging::warning()
  525. << "tick needed " << sec
  526. << " seconds. The game will run sower then normal.\n";
  527. Framework::Logging::trace()
  528. << "waiting: " << waitTotal
  529. << "\nremoveOldClients: " << removeOldClients.getSekunden()
  530. << "\nclientReply: " << clientReply.getSekunden()
  531. << "\nremoveOldChunks:" << removeOldChunks.getSekunden();
  532. }
  533. }
  534. save();
  535. generator->exitAndWait();
  536. loader->exitAndWait();
  537. ticker->exitAndWait();
  538. for (Dimension* dim : *dimensions)
  539. dim->requestStopAndWait();
  540. Framework::Logging::info() << "Game thread exited";
  541. }
  542. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  543. {
  544. char type;
  545. zRequest->lese(&type, 1);
  546. NetworkMessage* response = new NetworkMessage();
  547. switch (type)
  548. {
  549. case 1: // world
  550. {
  551. Dimension* dim = zDimension(zOrigin->zEntity()->getDimensionId());
  552. if (!dim)
  553. {
  554. dim = generator->createDimension(
  555. zOrigin->zEntity()->getDimensionId());
  556. if (!dim)
  557. {
  558. Framework::Logging::error()
  559. << "could not create dimension "
  560. << zOrigin->zEntity()->getDimensionId()
  561. << ". No Factory was provided.";
  562. return;
  563. }
  564. addDimension(dim);
  565. }
  566. dim->api(zRequest, response, zOrigin->zEntity());
  567. break;
  568. }
  569. case 2: // player
  570. zOrigin->zEntity()->playerApi(zRequest, response);
  571. break;
  572. case 3: // entity
  573. {
  574. int id;
  575. zRequest->lese((char*)&id, 4);
  576. for (Dimension* dim : *dimensions)
  577. {
  578. Entity* entity = dim->zEntity(id);
  579. if (entity)
  580. {
  581. entity->api(zRequest, response, zOrigin->zEntity());
  582. break;
  583. }
  584. }
  585. break;
  586. }
  587. case 4:
  588. { // inventory
  589. bool isEntity;
  590. zRequest->lese((char*)&isEntity, 1);
  591. Inventory* target;
  592. if (isEntity)
  593. {
  594. int id;
  595. zRequest->lese((char*)&id, 4);
  596. target = zEntity(id);
  597. }
  598. else
  599. {
  600. int dim;
  601. Vec3<int> pos;
  602. zRequest->lese((char*)&dim, 4);
  603. zRequest->lese((char*)&pos.x, 4);
  604. zRequest->lese((char*)&pos.y, 4);
  605. zRequest->lese((char*)&pos.z, 4);
  606. target = zBlockAt(pos, dim, 0);
  607. }
  608. if (target)
  609. target->inventoryApi(zRequest, response, zOrigin->zEntity());
  610. break;
  611. }
  612. case 5:
  613. { // crafting uiml request
  614. int id;
  615. zRequest->lese((char*)&id, 4);
  616. Text uiml = recipies->getCrafingUIML(id);
  617. Text dialogId = "crafting_";
  618. dialogId += id;
  619. uiController->addDialog(new UIDialog(dialogId,
  620. zOrigin->zEntity()->getId(),
  621. new Framework::XML::Element(uiml)));
  622. break;
  623. }
  624. case 6:
  625. { // chat message
  626. chat->chatApi(zRequest, zOrigin->zEntity(), response);
  627. break;
  628. }
  629. case 7: // other dimension
  630. {
  631. int dimensionId;
  632. zRequest->lese((char*)&dimensionId, 4);
  633. Dimension* dim = zDimension(dimensionId);
  634. if (dim)
  635. {
  636. dim->api(zRequest, response, zOrigin->zEntity());
  637. }
  638. break;
  639. }
  640. case 8: // ui message
  641. {
  642. uiController->api(zRequest, response, zOrigin->zEntity());
  643. break;
  644. }
  645. default:
  646. Framework::Logging::warning()
  647. << "received unknown api request in game with type " << (int)type;
  648. }
  649. if (!response->isEmpty())
  650. {
  651. if (response->isBroadcast())
  652. broadcastMessage(response);
  653. else
  654. zOrigin->sendResponse(response);
  655. }
  656. else
  657. {
  658. response->release();
  659. }
  660. }
  661. void Game::updateLightning(int dimensionId, Vec3<int> location)
  662. {
  663. Dimension* zDim = zDimension(dimensionId);
  664. if (zDim) zDim->updateLightning(location);
  665. }
  666. void Game::updateLightningWithoutWait(int dimensionId, Vec3<int> location)
  667. {
  668. Dimension* zDim = zDimension(dimensionId);
  669. if (zDim) zDim->updateLightningWithoutWait(location);
  670. }
  671. void Game::broadcastMessage(NetworkMessage* response)
  672. {
  673. for (auto client : *clients)
  674. client->sendResponse(
  675. dynamic_cast<NetworkMessage*>(response->getThis()));
  676. response->release();
  677. }
  678. void Game::sendMessage(NetworkMessage* response, Entity* zTargetPlayer)
  679. {
  680. for (auto client : *clients)
  681. {
  682. if (client->zEntity()->getId() == zTargetPlayer->getId())
  683. {
  684. client->sendResponse(response);
  685. return;
  686. }
  687. }
  688. response->release();
  689. }
  690. bool Game::checkPlayer(Framework::Text name, Framework::Text secret)
  691. {
  692. if (playerRegister->checkSecret(name, secret))
  693. return 1;
  694. else
  695. {
  696. Framework::Logging::warning()
  697. << "player " << name.getText()
  698. << " tryed to connect with an invalid secret.";
  699. return 0;
  700. }
  701. }
  702. bool Game::existsPlayer(Framework::Text name)
  703. {
  704. return playerRegister->hasPlayer(name);
  705. }
  706. Framework::Text Game::createPlayer(Framework::Text name)
  707. {
  708. return playerRegister->addPlayer(name);
  709. }
  710. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  711. {
  712. cs.lock();
  713. int id = playerRegister->getPlayerId(name);
  714. Datei pFile;
  715. pFile.setDatei(path + "/player/" + id);
  716. Player* player;
  717. bool isNew = 0;
  718. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  719. {
  720. player = (Player*)zEntityType(EntityTypeEnum::PLAYER)
  721. ->createEntityAt(
  722. Vec3<float>(0.5, 0.5, 0), DimensionEnum::OVERWORLD);
  723. player->setName(name);
  724. isNew = 1;
  725. }
  726. else
  727. {
  728. player
  729. = (Player*)zEntityType(EntityTypeEnum::PLAYER)->loadEntity(&pFile);
  730. pFile.close();
  731. }
  732. if (player->getId() >= nextEntityId)
  733. {
  734. nextEntityId = player->getId() + 1;
  735. }
  736. GameClient* gameClient = new GameClient(player, client);
  737. gameClient->sendTypes();
  738. clients->add(gameClient);
  739. if (!zDimension(player->getDimensionId()))
  740. {
  741. Dimension* dim = generator->createDimension(player->getDimensionId());
  742. if (!dim)
  743. {
  744. Framework::Logging::error() << "could not create dimension "
  745. << (int)player->getDimensionId()
  746. << ". No Factory was provided.";
  747. return 0;
  748. }
  749. NetworkMessage* msg = new NetworkMessage();
  750. msg->syncTime(dim->getCurrentDayTime(),
  751. dim->getNightDuration(),
  752. dim->getNightTransitionDuration(),
  753. dim->getDayDuration());
  754. gameClient->sendResponse(msg);
  755. this->addDimension(dim);
  756. }
  757. // subscribe the new player as an observer of the new chunk
  758. Dimension* dim = zDimension(player->getDimensionId());
  759. InMemoryBuffer* buffer = new InMemoryBuffer();
  760. buffer->schreibe("\0", 1);
  761. Punkt center = getChunkCenter(
  762. (int)player->getPosition().x, (int)player->getPosition().y);
  763. buffer->schreibe((char*)&center.x, 4);
  764. buffer->schreibe((char*)&center.y, 4);
  765. buffer->schreibe("\0", 1);
  766. dim->api(buffer, 0, player);
  767. buffer->release();
  768. while (!dim->zChunk(getChunkCenter(
  769. (int)player->getPosition().x, (int)player->getPosition().y)))
  770. {
  771. cs.unlock();
  772. Sleep(1000);
  773. cs.lock();
  774. }
  775. if (isNew)
  776. {
  777. Either<Block*, int> b = BlockTypeEnum::AIR;
  778. int h = WORLD_HEIGHT;
  779. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable()))
  780. || (b.isB() && zBlockType(b)->zDefault()->isPassable()))
  781. && h > 0)
  782. b = zBlockAt({(int)player->getPosition().x,
  783. (int)player->getPosition().y,
  784. --h},
  785. player->getDimensionId(),
  786. 0);
  787. player->setPosition(
  788. {player->getPosition().x, player->getPosition().y, (float)h + 2.f});
  789. }
  790. dim->addEntity(player);
  791. chat->addObserver(gameClient->zEntity()->getId());
  792. chat->broadcastMessage(name + " joined the game.", Chat::CHANNEL_INFO);
  793. cs.unlock();
  794. return dynamic_cast<GameClient*>(gameClient->getThis());
  795. }
  796. bool Game::isChunkLoaded(int x, int y, int dimension) const
  797. {
  798. Dimension* dim = zDimension(dimension);
  799. return (dim && dim->hasChunck(x, y));
  800. }
  801. bool Game::doesChunkExist(int x, int y, int dimension)
  802. {
  803. cs.lock();
  804. bool result = isChunkLoaded(x, y, dimension)
  805. || loader->existsChunk(x, y, dimension);
  806. cs.unlock();
  807. return result;
  808. }
  809. void Game::blockTargetChanged(Block* zBlock)
  810. {
  811. for (GameClient* client : *this->clients)
  812. {
  813. if (client->zEntity()->zTarget()
  814. && client->zEntity()->zTarget()->isBlock(
  815. zBlock->getPos(), NO_DIRECTION))
  816. {
  817. client->zEntity()->onTargetChange();
  818. }
  819. }
  820. }
  821. void Game::entityTargetChanged(Entity* zEntity)
  822. {
  823. for (GameClient* client : *this->clients)
  824. {
  825. if (client->zEntity()->zTarget()
  826. && client->zEntity()->zTarget()->isEntity(zEntity->getId()))
  827. {
  828. client->zEntity()->onTargetChange();
  829. }
  830. }
  831. }
  832. void Game::spawnItem(
  833. Framework::Vec3<float> location, int dimensionId, Item* stack)
  834. {
  835. spawnItem(location, dimensionId, new ItemStack(stack, 1));
  836. }
  837. void Game::spawnItem(
  838. Framework::Vec3<float> location, int dimensionId, ItemStack* stack)
  839. {
  840. ItemEntity* itemEntity = (ItemEntity*)zEntityType(EntityTypeEnum::ITEM)
  841. ->createEntityAt(location, dimensionId);
  842. itemEntity->unsaveAddItem(stack, NO_DIRECTION, 0);
  843. stack->release();
  844. Dimension* dim = zDimension(dimensionId);
  845. if (dim)
  846. {
  847. dim->addEntity(itemEntity);
  848. dim->zChunk(Game::getChunkCenter((int)itemEntity->getLocation().x,
  849. (int)itemEntity->getLocation().y))
  850. ->onEntityEnters(itemEntity, 0);
  851. }
  852. else
  853. {
  854. Framework::Logging::error()
  855. << "could not spawn item entity in dimension " << dimensionId
  856. << ". Dimension not loaded.";
  857. itemEntity->release();
  858. return;
  859. }
  860. }
  861. Framework::Either<Block*, int> Game::zBlockAt(
  862. Framework::Vec3<int> location, int dimension, OUT Chunk** zChunk) const
  863. {
  864. Dimension* dim = zDimension(dimension);
  865. if (dim) return dim->zBlock(location, zChunk);
  866. return 0;
  867. }
  868. Block* Game::zRealBlockInstance(
  869. Framework::Vec3<int> location, int dimension) const
  870. {
  871. Dimension* dim = zDimension(dimension);
  872. if (dim) return dim->zRealBlockInstance(location);
  873. return 0;
  874. }
  875. const Block* Game::zConstBlock(
  876. Framework::Vec3<int> location, int dimension) const
  877. {
  878. Dimension* dim = zDimension(dimension);
  879. if (dim) return dim->zBlockOrDefault(location);
  880. return 0;
  881. }
  882. int Game::getBlockType(Framework::Vec3<int> location, int dimension) const
  883. {
  884. Dimension* dim = zDimension(dimension);
  885. if (dim) return dim->getBlockType(location);
  886. return 0;
  887. }
  888. Dimension* Game::zDimension(int id) const
  889. {
  890. for (auto dim : *dimensions)
  891. {
  892. if (dim->getDimensionId() == id) return dim;
  893. }
  894. return 0;
  895. }
  896. Framework::Punkt Game::getChunkCenter(int x, int y)
  897. {
  898. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  899. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  900. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  901. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  902. }
  903. Area Game::getChunckArea(Punkt center) const
  904. {
  905. return {center.x - CHUNK_SIZE / 2,
  906. center.y - CHUNK_SIZE / 2,
  907. center.x + CHUNK_SIZE / 2 - 1,
  908. center.y + CHUNK_SIZE / 2 - 1,
  909. 0};
  910. }
  911. Framework::Text Game::getWorldDirectory() const
  912. {
  913. return path;
  914. }
  915. void Game::requestArea(Area area)
  916. {
  917. generator->requestGeneration(area);
  918. loader->requestLoading(area);
  919. }
  920. void Game::save() const
  921. {
  922. questManager->saveQuests();
  923. Datei d;
  924. d.setDatei(path + "/eid");
  925. d.open(Datei::Style::schreiben);
  926. d.schreibe((char*)&nextEntityId, 4);
  927. d.close();
  928. playerRegister->save();
  929. for (auto dim : *dimensions)
  930. dim->save(path);
  931. chat->save();
  932. Framework::Logging::info() << "Game was saved";
  933. }
  934. void Game::requestStop()
  935. {
  936. stop = 1;
  937. warteAufThread(1000000);
  938. }
  939. void Game::addDimension(Dimension* d)
  940. {
  941. dimensions->add(d);
  942. }
  943. int Game::getNextEntityId()
  944. {
  945. neidl.lock();
  946. int result = nextEntityId++;
  947. neidl.unlock();
  948. return result;
  949. }
  950. WorldGenerator* Game::zGenerator() const
  951. {
  952. return generator;
  953. }
  954. Game* Game::INSTANCE = 0;
  955. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  956. {
  957. if (!Game::INSTANCE)
  958. {
  959. Game::INSTANCE = new Game(name, worldsDir);
  960. Game::INSTANCE->initialize();
  961. }
  962. }
  963. Entity* Game::zEntity(int id, int dimensionId) const
  964. {
  965. Dimension* d = zDimension(dimensionId);
  966. if (d) return d->zEntity(id);
  967. return 0;
  968. }
  969. Entity* Game::zEntity(int id) const
  970. {
  971. for (Dimension* d : *dimensions)
  972. {
  973. Entity* e = d->zEntity(id);
  974. if (e) return e;
  975. }
  976. // for new players that are currently loading
  977. for (GameClient* client : *clients)
  978. {
  979. if (client->zEntity()->getId() == id)
  980. {
  981. return client->zEntity();
  982. }
  983. }
  984. return 0;
  985. }
  986. Entity* Game::zNearestEntity(int dimensionId,
  987. Framework::Vec3<float> pos,
  988. std::function<bool(Entity*)> filter) const
  989. {
  990. Dimension* d = zDimension(dimensionId);
  991. if (!d) return 0;
  992. return d->zNearestEntity(pos, filter);
  993. }
  994. RecipieLoader* Game::zRecipies() const
  995. {
  996. return recipies;
  997. }
  998. void Game::doLater(std::function<void()> action)
  999. {
  1000. actionsCs.lock();
  1001. actions.add(action);
  1002. actionsCs.unlock();
  1003. }
  1004. TickOrganizer* Game::zTickOrganizer() const
  1005. {
  1006. return ticker;
  1007. }
  1008. Chat* Game::zChat() const
  1009. {
  1010. return chat;
  1011. }
  1012. Player* Game::zPlayerByName(const char* name) const
  1013. {
  1014. for (GameClient* client : *clients)
  1015. {
  1016. if (strcmp(client->zEntity()->getName(), name) == 0)
  1017. {
  1018. return client->zEntity();
  1019. }
  1020. }
  1021. return 0;
  1022. }
  1023. void Game::listPlayerNames(Framework::RCArray<Framework::Text>& names)
  1024. {
  1025. for (GameClient* client : *clients)
  1026. {
  1027. names.add(new Framework::Text(client->zEntity()->getName()));
  1028. }
  1029. }
  1030. TypeRegistry* Game::zTypeRegistry() const
  1031. {
  1032. return typeRegistry;
  1033. }
  1034. int Game::getPlayerId(const char* name) const
  1035. {
  1036. return playerRegister->getPlayerId(name);
  1037. }
  1038. QuestManager* Game::zQuestManager() const
  1039. {
  1040. return questManager;
  1041. }
  1042. UIController* Game::zUIController() const
  1043. {
  1044. return uiController;
  1045. }
  1046. double Game::getAverageTickTime() const
  1047. {
  1048. return averageTickTime;
  1049. }
  1050. int Game::getTicksPerSecond() const
  1051. {
  1052. return ticksPerSecond;
  1053. }
  1054. int Game::getPlayerCount() const
  1055. {
  1056. return clients->getEintragAnzahl();
  1057. }
  1058. int Game::getChunkCount() const
  1059. {
  1060. int result = 0;
  1061. for (Dimension* dim : *dimensions)
  1062. {
  1063. result += dim->getChunkCount();
  1064. }
  1065. return result;
  1066. }
  1067. const BlockType* Game::zBlockType(int id) const
  1068. {
  1069. return blockTypes[id];
  1070. }
  1071. const ItemType* Game::zItemType(int id) const
  1072. {
  1073. return itemTypes[id];
  1074. }
  1075. const EntityType* Game::zEntityType(int id) const
  1076. {
  1077. return entityTypes[id];
  1078. }
  1079. int Game::getEntityTypeId(const char* name) const
  1080. {
  1081. for (int i = 0; i < entityTypeCount; i++)
  1082. {
  1083. if (entityTypes[i]
  1084. && Framework::Text(entityTypes[i]->getName()).istGleich(name))
  1085. {
  1086. return i;
  1087. }
  1088. }
  1089. Framework::Logging::warning()
  1090. << "no entity type with name '" << name << "' found.";
  1091. return -1;
  1092. }
  1093. int Game::getBlockTypeId(const char* name) const
  1094. {
  1095. for (int i = 0; i < blockTypeCount; i++)
  1096. {
  1097. if (blockTypes[i]
  1098. && Framework::Text(blockTypes[i]->getName()).istGleich(name))
  1099. {
  1100. return i;
  1101. }
  1102. }
  1103. Framework::Logging::warning()
  1104. << "no block type with name '" << name << "' found.";
  1105. return -1;
  1106. }
  1107. int Game::getItemTypeId(const char* name) const
  1108. {
  1109. for (int i = 0; i < itemTypeCount; i++)
  1110. {
  1111. if (itemTypes[i]
  1112. && Framework::Text(itemTypes[i]->getName()).istGleich(name))
  1113. {
  1114. return i;
  1115. }
  1116. }
  1117. Framework::Logging::warning()
  1118. << "no item type with name '" << name << "' found.";
  1119. return -1;
  1120. }
  1121. int Game::getBlockTypeCount() const
  1122. {
  1123. return blockTypeCount;
  1124. }
  1125. int Game::getItemTypeCount() const
  1126. {
  1127. return itemTypeCount;
  1128. }
  1129. int Game::getEntityTypeCount() const
  1130. {
  1131. return entityTypeCount;
  1132. }
  1133. const MultiblockStructureType* Game::zMultiblockStructureType(int id) const
  1134. {
  1135. return multiblockStructureTypes[id];
  1136. }
  1137. int Game::getMultiblockStructureTypeCount() const
  1138. {
  1139. return multiblockStructureTypeCount;
  1140. }