World.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. #include "World.h"
  2. #include <AsynchronCall.h>
  3. #include <DX12Buffer.h>
  4. #include <GraphicsApi.h>
  5. #include <iostream>
  6. #include <Network.h>
  7. #include <Welt3D.h>
  8. #include "Constants.h"
  9. #include "Game.h"
  10. #include "Globals.h"
  11. using namespace Network;
  12. using namespace Framework;
  13. World* World::INSTANCE = 0;
  14. World::World(Bildschirm3D* zScreen, FactoryClient* client)
  15. : Thread(),
  16. client(client)
  17. {
  18. renderedWorld = new Welt3D();
  19. renderedWorld->addDiffuseLight(DiffuseLight{
  20. Vec3<float>(0.5f, 0.5f, -1.f), Vec3<float>(1.f, 1.f, 1.f)});
  21. currentDimension = new Dimension();
  22. renderedWorld->addCollection(
  23. dynamic_cast<Model3DCollection*>(currentDimension->getThis()));
  24. zScreenPtr = zScreen;
  25. kam = new PlayerKam(zScreen);
  26. kam->setWelt(renderedWorld);
  27. zScreen->addKamera(kam);
  28. firstMessage = 1;
  29. ownEntityId = -1;
  30. currentTarget = 0;
  31. dayLightFactor = 1;
  32. time = 0;
  33. dayLength = 1000;
  34. transitionLength = 0;
  35. nightLength = 0;
  36. fallbackVertexLightBuffer
  37. = zScreen->zGraphicsApi()->createStructuredBuffer(16);
  38. char data[16];
  39. memset(data, 0, 16);
  40. *(int*)data = 0xFFFFFF00;
  41. fallbackVertexLightBuffer->setData(data);
  42. fallbackVertexLightBuffer->setLength(16);
  43. fallbackVertexLightBuffer->copieren();
  44. selectionModel = new FactoryCraftModel();
  45. selectionModel->setModelDaten(zScreen->zGraphicsApi()->getModel("cube"));
  46. selectionModel->setSize(1.005f);
  47. selectionModel->setVisible(0);
  48. unsigned char light[3] = {0xff, 0xff, 0xff};
  49. selectionModel->setAverageLight(light);
  50. selectionModel->setModelTextur(new Model3DTextur());
  51. for (int i = 0; i < 6; i++)
  52. {
  53. selectionModel->zTextur()->setPolygonTextur(i,
  54. zScreen->zGraphicsApi()->createOrGetTextur(
  55. "blocks.ltdb/selectedblock.p"));
  56. }
  57. selectionModel->setAlpha(1);
  58. selectionModel->setUseEffectAlpha(1);
  59. renderedWorld->addZeichnung(selectionModel);
  60. start();
  61. }
  62. World::~World()
  63. {
  64. zScreenPtr->removeKamera(kam);
  65. currentDimension->release();
  66. if (currentTarget) currentTarget->release();
  67. client->release();
  68. World::INSTANCE = 0;
  69. }
  70. void World::update(bool background)
  71. {
  72. if (background && currentDimension->getId() < 0) return;
  73. NetworkReader* serverMessageReader = 0;
  74. unsigned char type = 0;
  75. while (background
  76. ? serverMessageReader = client->getNextBackgroundMessage()
  77. : serverMessageReader = client->getNextForegroundMessage())
  78. {
  79. serverMessageReader->lese((char*)&type, 1);
  80. if (type == 3) // API MESSAGE
  81. {
  82. int length;
  83. serverMessageReader->lese((char*)&length, 4);
  84. char* data = new char[length];
  85. serverMessageReader->lese(data, length);
  86. switch (data[0])
  87. {
  88. case 1: // dimension message
  89. {
  90. int dimId = *(int*)(data + 1);
  91. if (dimId == currentDimension->getId())
  92. {
  93. currentDimension->api(data + 5);
  94. }
  95. break;
  96. }
  97. case 2: // gui message
  98. ((Game*)(Menu*)menuRegister->get("game"))->api(data + 1);
  99. break;
  100. case 3: // set target
  101. {
  102. switch (data[1])
  103. {
  104. case 0:
  105. setTarget(0);
  106. ((Game*)(Menu*)menuRegister->get("game"))
  107. ->setTargetUIML("");
  108. break;
  109. case 1:
  110. setTarget(zEntity(*(int*)(data + 2)));
  111. ((Game*)(Menu*)menuRegister->get("game"))
  112. ->setTargetUIML("");
  113. break;
  114. case 2:
  115. setTarget(zBlockAt(Vec3<int>(*(int*)(data + 2),
  116. *(int*)(data + 6),
  117. *(int*)(data + 10))));
  118. int side = *(int*)(data + 14);
  119. short len = *(short*)(data + 18);
  120. char* uiml = new char[len + 1];
  121. memcpy(uiml, data + 20, len);
  122. uiml[len] = 0;
  123. ((Game*)(Menu*)menuRegister->get("game"))
  124. ->setTargetUIML(uiml);
  125. delete[] uiml;
  126. break;
  127. }
  128. break;
  129. }
  130. case 4: // chat message
  131. {
  132. ((Game*)(Menu*)menuRegister->get("game"))
  133. ->zChat()
  134. ->addMessage(data + 1);
  135. break;
  136. }
  137. case 5: // chat options
  138. {
  139. ((Game*)(Menu*)menuRegister->get("game"))
  140. ->zChat()
  141. ->initOptions(data + 1);
  142. break;
  143. }
  144. case 6: // map data
  145. {
  146. ByteArrayReader reader(data + 1, length - 1, 0);
  147. ChunkMap* map = new ChunkMap(&reader);
  148. ((Game*)(Menu*)menuRegister->get("game"))
  149. ->zMap()
  150. ->addChunk(map);
  151. break;
  152. }
  153. case 7: // map player data
  154. {
  155. ((Game*)(Menu*)menuRegister->get("game"))
  156. ->zMap()
  157. ->updatePlayerData(data + 1);
  158. break;
  159. }
  160. case 8: // time sync
  161. {
  162. nightLength = *(double*)(data + 9);
  163. transitionLength = *(double*)(data + 17);
  164. dayLength = *(double*)(data + 25);
  165. time = *(double*)(data + 1);
  166. break;
  167. }
  168. }
  169. delete[] data;
  170. }
  171. if (type == 4) // POSITION UPDATE
  172. {
  173. int old = ownEntityId;
  174. serverMessageReader->lese((char*)&ownEntityId, 4);
  175. int dimensionId = 0;
  176. serverMessageReader->lese((char*)&dimensionId, 4);
  177. currentDimension->setId(dimensionId);
  178. kam->setEntityId(ownEntityId);
  179. Entity* p = zEntity(ownEntityId);
  180. if (p) p->setPlayerControlled();
  181. if (old != ownEntityId) client->sendPlayerAction("\5", 1);
  182. }
  183. client->endMessageReading(background);
  184. }
  185. client->endMessageReading(background);
  186. Entity* player = getCurrentPlayerEntity();
  187. if (player)
  188. {
  189. renderedWorld->lock();
  190. currentDimension->removeDistantChunks(
  191. {(int)player->getPos().x, (int)player->getPos().y});
  192. Punkt currentChunk
  193. = getChunkCenter((int)player->getX(), (int)player->getY());
  194. for (int x = 0; x <= CHUNK_VISIBILITY_RANGE; x++)
  195. {
  196. for (int y = 0; y <= CHUNK_VISIBILITY_RANGE; y++)
  197. {
  198. std::function<void(Punkt)> requestChunk = [this](Punkt center) {
  199. Chunk* zC = currentDimension->zChunk(center);
  200. if (!zC)
  201. {
  202. char msg[1];
  203. msg[0] = 0; // add observer and request chaunk data
  204. Punkt pos = center;
  205. subLock.lock();
  206. bool found = 0;
  207. for (Punkt p : subscriptions)
  208. {
  209. if (p == pos)
  210. {
  211. found = 1;
  212. break;
  213. }
  214. }
  215. if (!found)
  216. {
  217. client->chunkAPIRequest(pos, msg, 1);
  218. subscriptions.add(pos);
  219. }
  220. subLock.unlock();
  221. }
  222. };
  223. requestChunk(
  224. currentChunk + Punkt(x * CHUNK_SIZE, y * CHUNK_SIZE));
  225. if (y > 0)
  226. requestChunk(
  227. currentChunk + Punkt(x * CHUNK_SIZE, -y * CHUNK_SIZE));
  228. if (x > 0)
  229. {
  230. requestChunk(
  231. currentChunk + Punkt(-x * CHUNK_SIZE, y * CHUNK_SIZE));
  232. if (y > 0)
  233. requestChunk(currentChunk
  234. + Punkt(-x * CHUNK_SIZE, -y * CHUNK_SIZE));
  235. }
  236. }
  237. }
  238. renderedWorld->unlock();
  239. }
  240. }
  241. void World::onTick(double time)
  242. {
  243. selectionModel->tick(0.1);
  244. this->time += time;
  245. if (this->time >= dayLength + nightLength + transitionLength * 2)
  246. {
  247. this->time -= dayLength + nightLength + transitionLength * 2;
  248. }
  249. if (this->time > dayLength && this->time < dayLength + transitionLength)
  250. {
  251. dayLightFactor
  252. = 1.f
  253. - (float)((this->time - dayLength) / transitionLength) * 0.95f;
  254. }
  255. else if (this->time > dayLength + transitionLength
  256. && this->time < dayLength + transitionLength + nightLength)
  257. {
  258. // night
  259. dayLightFactor = 0.05f;
  260. if (renderedWorld->getDiffuseLightCount() > 0)
  261. {
  262. renderedWorld->removeDiffuseLight(0);
  263. }
  264. }
  265. else if (this->time > dayLength + transitionLength + nightLength)
  266. {
  267. dayLightFactor
  268. = (float)((this->time - dayLength - nightLength - transitionLength)
  269. / transitionLength)
  270. * 0.95f
  271. + 0.05f;
  272. }
  273. else
  274. {
  275. dayLightFactor = 1.f;
  276. }
  277. if (this->time < dayLength + transitionLength
  278. || this->time > dayLength + transitionLength + nightLength)
  279. {
  280. float currentDayTime
  281. = (float)(this->time < dayLength + transitionLength
  282. ? this->time + transitionLength
  283. : this->time - dayLength + transitionLength
  284. + nightLength);
  285. Vec3<float> sunPos = Vec3<float>(-200.f, 50.f, 0.f);
  286. sunPos.rotateY((
  287. float)((currentDayTime / (dayLength + transitionLength * 2)) * PI));
  288. sunPos.normalize();
  289. if (!renderedWorld->getDiffuseLightCount())
  290. {
  291. renderedWorld->addDiffuseLight(
  292. {-sunPos, Vec3<float>(1.0, 1.0, 1.0)});
  293. }
  294. else
  295. {
  296. renderedWorld->getDiffuseLight(0).direction = -sunPos;
  297. }
  298. }
  299. }
  300. void World::setChunk(Chunk* chunk)
  301. {
  302. zScreenPtr->lock();
  303. renderedWorld->lock();
  304. currentDimension->setChunk(chunk, chunk->getCenter());
  305. renderedWorld->unlock();
  306. zScreenPtr->unlock();
  307. }
  308. void World::thread()
  309. {
  310. new AsynchronCall("World Update", [this]() {
  311. while (client->isConnected())
  312. {
  313. zScreenPtr->lock();
  314. if (World::INSTANCE != this)
  315. {
  316. zScreenPtr->unlock();
  317. return;
  318. }
  319. zScreenPtr->unlock();
  320. update(0);
  321. Sleep(10);
  322. }
  323. std::cout << "foreground connection lost\n";
  324. });
  325. while (client->isConnected())
  326. {
  327. zScreenPtr->lock();
  328. if (World::INSTANCE != this)
  329. {
  330. zScreenPtr->unlock();
  331. return;
  332. }
  333. zScreenPtr->unlock();
  334. update(1);
  335. Sleep(10);
  336. }
  337. Sleep(1000);
  338. zScreenPtr->lock();
  339. std::cout << "background connection lost\n";
  340. menuRegister->get("game")->hide();
  341. menuRegister->get("serverSelection")->show();
  342. zScreenPtr->unlock();
  343. zScreenPtr->postAction([this]() {
  344. if (World::INSTANCE == this)
  345. {
  346. World::INSTANCE = 0;
  347. release();
  348. }
  349. });
  350. }
  351. Block* World::zBlockAt(Framework::Vec3<int> location) const
  352. {
  353. return currentDimension->zBlock(location);
  354. }
  355. Block* World::getBlockAt(Framework::Vec3<int> location) const
  356. {
  357. return currentDimension->getBlock(location);
  358. }
  359. Dimension* World::zDimension() const
  360. {
  361. return currentDimension;
  362. }
  363. void World::setVisibility(Entity* zEntity, bool visible)
  364. {
  365. renderedWorld->lock();
  366. if (visible)
  367. renderedWorld->addZeichnung(
  368. dynamic_cast<Framework::Model3D*>(zEntity->getThis()));
  369. else
  370. renderedWorld->removeZeichnung(zEntity);
  371. renderedWorld->unlock();
  372. }
  373. Framework::Punkt World::getChunkCenter(int x, int y) const
  374. {
  375. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  376. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  377. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  378. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  379. }
  380. Entity* World::zEntity(int id) const
  381. {
  382. Entity* e = currentDimension->zEntity(id);
  383. if (e) return e;
  384. return 0;
  385. }
  386. Entity* World::getEntity(int id) const
  387. {
  388. Entity* e = currentDimension->getEntity(id);
  389. if (e) return e;
  390. return 0;
  391. }
  392. void World::removeEntity(int id)
  393. {
  394. currentDimension->removeEntity(id);
  395. }
  396. PlayerKam* World::zKamera() const
  397. {
  398. return kam;
  399. }
  400. int World::getCurrentPlayerId() const
  401. {
  402. return ownEntityId;
  403. }
  404. Entity* World::getCurrentPlayerEntity() const
  405. {
  406. return zEntity(ownEntityId);
  407. }
  408. void World::setTarget(Framework::Model3D* zTarget)
  409. {
  410. if (zTarget != currentTarget)
  411. {
  412. targetLock.lock();
  413. if (!zTarget)
  414. {
  415. selectionModel->setVisible(0);
  416. }
  417. else
  418. {
  419. selectionModel->setPosition(
  420. zTarget->getPos().x, zTarget->getPos().y, zTarget->getPos().z);
  421. Block* b = dynamic_cast<Block*>(zTarget);
  422. if (b && b->getPartOfModels())
  423. {
  424. selectionModel->setDestroyedState(b->getEffectPercentage());
  425. }
  426. else
  427. {
  428. selectionModel->setDestroyedState(0);
  429. }
  430. selectionModel->setVisible(1);
  431. }
  432. if (currentTarget)
  433. {
  434. currentTarget->setAmbientFactor(
  435. currentTarget->getAmbientFactor() - 0.2f);
  436. currentTarget->release();
  437. currentTarget = 0;
  438. }
  439. if (zTarget)
  440. {
  441. currentTarget
  442. = dynamic_cast<Framework::Model3D*>(zTarget->getThis());
  443. if (currentTarget)
  444. currentTarget->setAmbientFactor(
  445. currentTarget->getAmbientFactor() + 0.2f);
  446. }
  447. targetLock.unlock();
  448. }
  449. }
  450. void World::lockWorld()
  451. {
  452. renderedWorld->lock();
  453. }
  454. void World::unlockWorld()
  455. {
  456. renderedWorld->unlock();
  457. }
  458. void World::onChunkAdded(Punkt pos)
  459. {
  460. subLock.lock();
  461. int index = 0;
  462. for (Punkt p : subscriptions)
  463. {
  464. if (p == pos)
  465. {
  466. subscriptions.remove(index);
  467. break;
  468. }
  469. index++;
  470. }
  471. subLock.unlock();
  472. }
  473. Framework::Model3D* World::getCurrentTarget() const
  474. {
  475. while (targetLock.isLocked())
  476. Sleep(1);
  477. return currentTarget
  478. ? dynamic_cast<Framework::Model3D*>(currentTarget->getThis())
  479. : 0;
  480. }
  481. FactoryCraftModel* World::zSelectedEffectModel() const
  482. {
  483. return selectionModel;
  484. }
  485. Chunk* World::zChunk(Punkt center)
  486. {
  487. return currentDimension->zChunk(center);
  488. }
  489. FactoryClient* World::zClient() const
  490. {
  491. return client;
  492. }
  493. float World::getDayLightFactor() const
  494. {
  495. return dayLightFactor;
  496. }
  497. Framework::DXBuffer* World::zFallbackVertexLightBuffer()
  498. {
  499. return fallbackVertexLightBuffer;
  500. }