World.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. {
  111. setTarget(zEntity(*(int*)(data + 2)));
  112. short len = *(short*)(data + 6);
  113. char* uiml = new char[len + 8];
  114. memcpy(uiml, data + 8, len);
  115. uiml[len] = 0;
  116. ((Game*)(Menu*)menuRegister->get("game"))
  117. ->setTargetUIML(uiml);
  118. delete[] uiml;
  119. break;
  120. }
  121. case 2:
  122. {
  123. setTarget(zBlockAt(Vec3<int>(*(int*)(data + 2),
  124. *(int*)(data + 6),
  125. *(int*)(data + 10))));
  126. int side = *(int*)(data + 14);
  127. short len = *(short*)(data + 18);
  128. char* uiml = new char[len + 1];
  129. memcpy(uiml, data + 20, len);
  130. uiml[len] = 0;
  131. ((Game*)(Menu*)menuRegister->get("game"))
  132. ->setTargetUIML(uiml);
  133. delete[] uiml;
  134. break;
  135. }
  136. }
  137. break;
  138. }
  139. case 4: // chat message
  140. {
  141. ((Game*)(Menu*)menuRegister->get("game"))
  142. ->zChat()
  143. ->addMessage(data + 1);
  144. break;
  145. }
  146. case 5: // chat options
  147. {
  148. ((Game*)(Menu*)menuRegister->get("game"))
  149. ->zChat()
  150. ->initOptions(data + 1);
  151. break;
  152. }
  153. case 6: // map data
  154. {
  155. ByteArrayReader reader(data + 1, length - 1, 0);
  156. ChunkMap* map = new ChunkMap(&reader);
  157. ((Game*)(Menu*)menuRegister->get("game"))
  158. ->zMap()
  159. ->addChunk(map);
  160. break;
  161. }
  162. case 7: // map player data
  163. {
  164. ((Game*)(Menu*)menuRegister->get("game"))
  165. ->zMap()
  166. ->updatePlayerData(data + 1);
  167. break;
  168. }
  169. case 8: // time sync
  170. {
  171. nightLength = *(double*)(data + 9);
  172. transitionLength = *(double*)(data + 17);
  173. dayLength = *(double*)(data + 25);
  174. time = *(double*)(data + 1);
  175. break;
  176. }
  177. }
  178. delete[] data;
  179. }
  180. if (type == 4) // POSITION UPDATE
  181. {
  182. int old = ownEntityId;
  183. serverMessageReader->lese((char*)&ownEntityId, 4);
  184. int dimensionId = 0;
  185. serverMessageReader->lese((char*)&dimensionId, 4);
  186. currentDimension->setId(dimensionId);
  187. kam->setEntityId(ownEntityId);
  188. Entity* p = zEntity(ownEntityId);
  189. if (p) p->setPlayerControlled();
  190. if (old != ownEntityId) client->sendPlayerAction("\5", 1);
  191. }
  192. client->endMessageReading(background);
  193. }
  194. client->endMessageReading(background);
  195. Entity* player = getCurrentPlayerEntity();
  196. if (player)
  197. {
  198. renderedWorld->lock();
  199. currentDimension->removeDistantChunks(
  200. {(int)player->getPos().x, (int)player->getPos().y});
  201. Punkt currentChunk
  202. = getChunkCenter((int)player->getX(), (int)player->getY());
  203. for (int x = 0; x <= CHUNK_VISIBILITY_RANGE; x++)
  204. {
  205. for (int y = 0; y <= CHUNK_VISIBILITY_RANGE; y++)
  206. {
  207. std::function<void(Punkt)> requestChunk = [this](Punkt center) {
  208. Chunk* zC = currentDimension->zChunk(center);
  209. if (!zC)
  210. {
  211. char msg[1];
  212. msg[0] = 0; // add observer and request chaunk data
  213. Punkt pos = center;
  214. subLock.lock();
  215. bool found = 0;
  216. for (Punkt p : subscriptions)
  217. {
  218. if (p == pos)
  219. {
  220. found = 1;
  221. break;
  222. }
  223. }
  224. if (!found)
  225. {
  226. client->chunkAPIRequest(pos, msg, 1);
  227. subscriptions.add(pos);
  228. }
  229. subLock.unlock();
  230. }
  231. };
  232. requestChunk(
  233. currentChunk + Punkt(x * CHUNK_SIZE, y * CHUNK_SIZE));
  234. if (y > 0)
  235. requestChunk(
  236. currentChunk + Punkt(x * CHUNK_SIZE, -y * CHUNK_SIZE));
  237. if (x > 0)
  238. {
  239. requestChunk(
  240. currentChunk + Punkt(-x * CHUNK_SIZE, y * CHUNK_SIZE));
  241. if (y > 0)
  242. requestChunk(currentChunk
  243. + Punkt(-x * CHUNK_SIZE, -y * CHUNK_SIZE));
  244. }
  245. }
  246. }
  247. renderedWorld->unlock();
  248. }
  249. }
  250. void World::onTick(double time)
  251. {
  252. selectionModel->tick(0.1);
  253. this->time += time;
  254. if (this->time >= dayLength + nightLength + transitionLength * 2)
  255. {
  256. this->time -= dayLength + nightLength + transitionLength * 2;
  257. }
  258. if (this->time > dayLength && this->time < dayLength + transitionLength)
  259. {
  260. dayLightFactor
  261. = 1.f
  262. - (float)((this->time - dayLength) / transitionLength) * 0.95f;
  263. }
  264. else if (this->time > dayLength + transitionLength
  265. && this->time < dayLength + transitionLength + nightLength)
  266. {
  267. // night
  268. dayLightFactor = 0.05f;
  269. if (renderedWorld->getDiffuseLightCount() > 0)
  270. {
  271. renderedWorld->removeDiffuseLight(0);
  272. }
  273. }
  274. else if (this->time > dayLength + transitionLength + nightLength)
  275. {
  276. dayLightFactor
  277. = (float)((this->time - dayLength - nightLength - transitionLength)
  278. / transitionLength)
  279. * 0.95f
  280. + 0.05f;
  281. }
  282. else
  283. {
  284. dayLightFactor = 1.f;
  285. }
  286. if (this->time < dayLength + transitionLength
  287. || this->time > dayLength + transitionLength + nightLength)
  288. {
  289. float currentDayTime
  290. = (float)(this->time < dayLength + transitionLength
  291. ? this->time + transitionLength
  292. : this->time - dayLength + transitionLength
  293. + nightLength);
  294. Vec3<float> sunPos = Vec3<float>(-200.f, 50.f, 0.f);
  295. sunPos.rotateY((
  296. float)((currentDayTime / (dayLength + transitionLength * 2)) * PI));
  297. sunPos.normalize();
  298. if (!renderedWorld->getDiffuseLightCount())
  299. {
  300. renderedWorld->addDiffuseLight(
  301. {-sunPos, Vec3<float>(1.0, 1.0, 1.0)});
  302. }
  303. else
  304. {
  305. renderedWorld->getDiffuseLight(0).direction = -sunPos;
  306. }
  307. }
  308. }
  309. void World::setChunk(Chunk* chunk)
  310. {
  311. zScreenPtr->lock();
  312. renderedWorld->lock();
  313. currentDimension->setChunk(chunk, chunk->getCenter());
  314. renderedWorld->unlock();
  315. zScreenPtr->unlock();
  316. }
  317. void World::thread()
  318. {
  319. new AsynchronCall("World Update", [this]() {
  320. while (client->isConnected())
  321. {
  322. zScreenPtr->lock();
  323. if (World::INSTANCE != this)
  324. {
  325. zScreenPtr->unlock();
  326. return;
  327. }
  328. zScreenPtr->unlock();
  329. update(0);
  330. Sleep(10);
  331. }
  332. std::cout << "foreground connection lost\n";
  333. });
  334. while (client->isConnected())
  335. {
  336. zScreenPtr->lock();
  337. if (World::INSTANCE != this)
  338. {
  339. zScreenPtr->unlock();
  340. return;
  341. }
  342. zScreenPtr->unlock();
  343. update(1);
  344. Sleep(10);
  345. }
  346. Sleep(1000);
  347. zScreenPtr->lock();
  348. std::cout << "background connection lost\n";
  349. menuRegister->get("game")->hide();
  350. menuRegister->get("serverSelection")->show();
  351. zScreenPtr->unlock();
  352. zScreenPtr->postAction([this]() {
  353. if (World::INSTANCE == this)
  354. {
  355. World::INSTANCE = 0;
  356. release();
  357. }
  358. });
  359. }
  360. Block* World::zBlockAt(Framework::Vec3<int> location) const
  361. {
  362. return currentDimension->zBlock(location);
  363. }
  364. Block* World::getBlockAt(Framework::Vec3<int> location) const
  365. {
  366. return currentDimension->getBlock(location);
  367. }
  368. Dimension* World::zDimension() const
  369. {
  370. return currentDimension;
  371. }
  372. void World::setVisibility(Entity* zEntity, bool visible)
  373. {
  374. renderedWorld->lock();
  375. if (visible)
  376. renderedWorld->addZeichnung(
  377. dynamic_cast<Framework::Model3D*>(zEntity->getThis()));
  378. else
  379. renderedWorld->removeZeichnung(zEntity);
  380. renderedWorld->unlock();
  381. }
  382. Framework::Punkt World::getChunkCenter(int x, int y) const
  383. {
  384. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  385. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  386. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  387. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  388. }
  389. Entity* World::zEntity(int id) const
  390. {
  391. Entity* e = currentDimension->zEntity(id);
  392. if (e) return e;
  393. return 0;
  394. }
  395. Entity* World::getEntity(int id) const
  396. {
  397. Entity* e = currentDimension->getEntity(id);
  398. if (e) return e;
  399. return 0;
  400. }
  401. void World::removeEntity(int id)
  402. {
  403. currentDimension->removeEntity(id);
  404. }
  405. PlayerKam* World::zKamera() const
  406. {
  407. return kam;
  408. }
  409. int World::getCurrentPlayerId() const
  410. {
  411. return ownEntityId;
  412. }
  413. Entity* World::getCurrentPlayerEntity() const
  414. {
  415. return zEntity(ownEntityId);
  416. }
  417. void World::setTarget(Framework::Model3D* zTarget)
  418. {
  419. if (zTarget != currentTarget)
  420. {
  421. targetLock.lock();
  422. if (!zTarget)
  423. {
  424. selectionModel->setVisible(0);
  425. }
  426. else
  427. {
  428. selectionModel->setPosition(
  429. zTarget->getPos().x, zTarget->getPos().y, zTarget->getPos().z);
  430. Block* b = dynamic_cast<Block*>(zTarget);
  431. if (b && b->getPartOfModels())
  432. {
  433. selectionModel->setDestroyedState(b->getEffectPercentage());
  434. }
  435. else
  436. {
  437. selectionModel->setDestroyedState(0);
  438. }
  439. selectionModel->setVisible(1);
  440. }
  441. if (currentTarget)
  442. {
  443. currentTarget->setAmbientFactor(
  444. currentTarget->getAmbientFactor() - 0.2f);
  445. currentTarget->release();
  446. currentTarget = 0;
  447. }
  448. if (zTarget)
  449. {
  450. currentTarget
  451. = dynamic_cast<Framework::Model3D*>(zTarget->getThis());
  452. if (currentTarget)
  453. currentTarget->setAmbientFactor(
  454. currentTarget->getAmbientFactor() + 0.2f);
  455. }
  456. targetLock.unlock();
  457. }
  458. }
  459. void World::lockWorld()
  460. {
  461. renderedWorld->lock();
  462. }
  463. void World::unlockWorld()
  464. {
  465. renderedWorld->unlock();
  466. }
  467. void World::onChunkAdded(Punkt pos)
  468. {
  469. subLock.lock();
  470. int index = 0;
  471. for (Punkt p : subscriptions)
  472. {
  473. if (p == pos)
  474. {
  475. subscriptions.remove(index);
  476. break;
  477. }
  478. index++;
  479. }
  480. subLock.unlock();
  481. }
  482. Framework::Model3D* World::getCurrentTarget() const
  483. {
  484. while (targetLock.isLocked())
  485. Sleep(1);
  486. return currentTarget
  487. ? dynamic_cast<Framework::Model3D*>(currentTarget->getThis())
  488. : 0;
  489. }
  490. FactoryCraftModel* World::zSelectedEffectModel() const
  491. {
  492. return selectionModel;
  493. }
  494. Chunk* World::zChunk(Punkt center)
  495. {
  496. return currentDimension->zChunk(center);
  497. }
  498. FactoryClient* World::zClient() const
  499. {
  500. return client;
  501. }
  502. float World::getDayLightFactor() const
  503. {
  504. return dayLightFactor;
  505. }
  506. Framework::DXBuffer* World::zFallbackVertexLightBuffer()
  507. {
  508. return fallbackVertexLightBuffer;
  509. }