Game.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. #include "Game.h"
  2. #include "Zeit.h"
  3. #include "Player.h"
  4. #include "OverworldDimension.h"
  5. #include "AddChunkUpdate.h"
  6. #include "NoBlock.h"
  7. #include "AsynchronCall.h"
  8. using namespace Framework;
  9. GameClient::GameClient( Player* zPlayer, FCKlient* client )
  10. : ReferenceCounter(),
  11. zPlayer( zPlayer ),
  12. client( client ),
  13. viewDistance( DEFAULT_VIEW_DISTANCE ),
  14. first( 1 ),
  15. online( 1 ),
  16. finished( 0 )
  17. {
  18. new AsynchronCall( [this]() {
  19. while( online )
  20. {
  21. other.lock();
  22. if( updateQueue.hat( 0 ) )
  23. {
  24. WorldUpdate* update = updateQueue.get( 0 );
  25. updateQueue.remove( 0 );
  26. other.unlock();
  27. background.lock();
  28. this->client->zBackgroundWriter()->schreibe( (char*)&Message::WORLD_UPDATE, 1 );
  29. update->write( this->client->zBackgroundWriter() );
  30. background.unlock();
  31. update->release();
  32. }
  33. else
  34. {
  35. other.unlock();
  36. updateSync.wait();
  37. }
  38. }
  39. finished = 1;
  40. } );
  41. }
  42. GameClient::~GameClient()
  43. {
  44. online = 0;
  45. updateSync.notify();
  46. while( !finished )
  47. Sleep( 100 );
  48. client->release();
  49. }
  50. void GameClient::sendWorldUpdate( WorldUpdate* update )
  51. {
  52. bool add = 0;
  53. if( zPlayer->getCurrentDimensionId() == update->getAffectedDimension() )
  54. {
  55. auto pos = (Vec3<int>)zPlayer->getPosition();
  56. int dist = update->distanceTo( pos.x, pos.y );
  57. if( dist < viewDistance * CHUNK_SIZE )
  58. {
  59. other.lock();
  60. int index = 0;
  61. for( auto update2 : updateQueue )
  62. {
  63. int dist2 = update2->distanceTo( pos.x, pos.y );
  64. if( dist2 >= dist )
  65. break;
  66. index++;
  67. }
  68. updateQueue.add( update, index );
  69. other.unlock();
  70. updateSync.notify();
  71. add = 1;
  72. }
  73. }
  74. if( !add )
  75. update->release();
  76. }
  77. void GameClient::reply( Game* zGame )
  78. {
  79. other.lock();
  80. for( auto req : requests )
  81. zGame->api( req, this );
  82. requests.leeren();
  83. other.unlock();
  84. int x = (int)zPlayer->getPosition().x;
  85. int y = (int)zPlayer->getPosition().y;
  86. int d = zPlayer->getCurrentDimensionId();
  87. foreground.lock();
  88. client->zForegroundWriter()->schreibe( (char*)&Message::POSITION_UPDATE, 1 );
  89. float f = zPlayer->getPosition().x;
  90. client->zForegroundWriter()->schreibe( (char*)&f, 4 );
  91. f = zPlayer->getPosition().y;
  92. client->zForegroundWriter()->schreibe( (char*)&f, 4 );
  93. f = zPlayer->getPosition().z;
  94. client->zForegroundWriter()->schreibe( (char*)&f, 4 );
  95. f = zPlayer->getFaceDir().x;
  96. client->zForegroundWriter()->schreibe( (char*)&f, 4 );
  97. f = zPlayer->getFaceDir().y;
  98. client->zForegroundWriter()->schreibe( (char*)&f, 4 );
  99. foreground.unlock();
  100. // send world to client
  101. if( first )
  102. {
  103. first = 0;
  104. for( int xP = x - CHUNK_SIZE * viewDistance; xP <= x + CHUNK_SIZE * viewDistance; xP += CHUNK_SIZE )
  105. {
  106. for( int yP = y - CHUNK_SIZE * viewDistance; yP <= y + CHUNK_SIZE * viewDistance; yP += CHUNK_SIZE )
  107. {
  108. Chunk* chunk = zGame->zDimension( d )->zChunk( zGame->getChunkCenter( xP, yP ) );
  109. if( chunk )
  110. sendWorldUpdate( new AddChunkUpdate( dynamic_cast<Chunk*>(chunk->getThis()) ) );
  111. }
  112. }
  113. zGame->requestArea( { x - CHUNK_SIZE * viewDistance, y - CHUNK_SIZE * viewDistance, x + CHUNK_SIZE * viewDistance, y + CHUNK_SIZE * viewDistance, d } );
  114. }
  115. else
  116. {
  117. Punkt lastMin = zGame->getChunkCenter( (int)lastPos.x - CHUNK_SIZE * viewDistance, (int)lastPos.y - CHUNK_SIZE * viewDistance );
  118. Punkt curMin = zGame->getChunkCenter( x - CHUNK_SIZE * viewDistance, y - CHUNK_SIZE * viewDistance );
  119. Punkt lastMax = zGame->getChunkCenter( (int)lastPos.x + CHUNK_SIZE * viewDistance, (int)lastPos.y + CHUNK_SIZE * viewDistance );
  120. Punkt curMax = zGame->getChunkCenter( x + CHUNK_SIZE * viewDistance, y + CHUNK_SIZE * viewDistance );
  121. for( int xP = curMin.x; xP <= curMax.x; xP += CHUNK_SIZE )
  122. {
  123. for( int yP = curMin.y; yP <= curMax.y; yP += CHUNK_SIZE )
  124. {
  125. if( xP < lastMin.x || xP > lastMax.x || yP < lastMin.y || yP > lastMax.y )
  126. {
  127. Chunk* chunk = zGame->zDimension( d )->zChunk( zGame->getChunkCenter( xP, yP ) );
  128. if( chunk )
  129. sendWorldUpdate( new AddChunkUpdate( dynamic_cast<Chunk*>(chunk->getThis()) ) );
  130. else
  131. zGame->requestArea( zGame->getChunckArea( zGame->getChunkCenter( xP, yP ) ) );
  132. }
  133. }
  134. }
  135. }
  136. lastPos = zPlayer->getPosition();
  137. }
  138. void GameClient::logout()
  139. {
  140. online = 0;
  141. }
  142. void GameClient::addMessage( StreamReader* reader )
  143. {
  144. short len = 0;
  145. reader->lese( (char*)&len, 2 );
  146. InMemoryBuffer* buffer = new InMemoryBuffer();
  147. char* tmp = new char[ len ];
  148. reader->lese( tmp, len );
  149. buffer->schreibe( tmp, len );
  150. delete[]tmp;
  151. other.lock();
  152. requests.add( buffer );
  153. other.unlock();
  154. }
  155. bool GameClient::isOnline() const
  156. {
  157. return online;
  158. }
  159. void GameClient::sendResponse( NetworkResponse* zResponse )
  160. {
  161. if( zResponse->isAreaAffected( { lastPos.x - (float)CHUNK_SIZE * (float)viewDistance, lastPos.y - (float)CHUNK_SIZE * (float)viewDistance, 0.f }, { lastPos.x + (float)CHUNK_SIZE * (float)viewDistance, lastPos.y + (float)CHUNK_SIZE * (float)viewDistance, (float)WORLD_HEIGHT } ) )
  162. {
  163. if( zResponse->isUseBackground() )
  164. {
  165. background.unlock();
  166. client->zBackgroundWriter()->schreibe( (char*)&Message::API_MESSAGE, 1 );
  167. zResponse->writeTo( client->zBackgroundWriter() );
  168. background.unlock();
  169. }
  170. else
  171. {
  172. foreground.unlock();
  173. client->zForegroundWriter()->schreibe( (char*)&Message::API_MESSAGE, 1 );
  174. zResponse->writeTo( client->zForegroundWriter() );
  175. foreground.unlock();
  176. }
  177. }
  178. }
  179. Player* GameClient::zEntity() const
  180. {
  181. return zPlayer;
  182. }
  183. Game::Game( Framework::Text name, Framework::Text worldsDir )
  184. : Thread(),
  185. name( name ),
  186. dimensions( new RCArray<Dimension>() ),
  187. updates( new RCArray<WorldUpdate>() ),
  188. clients( new RCArray<GameClient>() ),
  189. ticker( new TickOrganizer() ),
  190. path( (const char*)(worldsDir + "/" + name) ),
  191. stop( 0 ),
  192. tickId( 0 ),
  193. nextEntityId( 0 ),
  194. generator( 0 ),
  195. loader( 0 )
  196. {
  197. if( !DateiExistiert( worldsDir + "/" + name ) )
  198. DateiPfadErstellen( worldsDir + "/" + name + "/" );
  199. Datei d;
  200. d.setDatei( path + "/eid" );
  201. if( d.existiert() )
  202. {
  203. d.open( Datei::Style::lesen );
  204. d.lese( (char*)&nextEntityId, 4 );
  205. d.close();
  206. }
  207. int seed = 0;
  208. int index = 0;
  209. for( char* n = name; *n; n++ )
  210. seed += (int)pow( (float)*n * 31, (float)++index );
  211. generator = new WorldGenerator( seed, this );
  212. loader = new WorldLoader( this );
  213. start();
  214. }
  215. Game::~Game()
  216. {
  217. dimensions->release();
  218. updates->release();
  219. clients->release();
  220. generator->release();
  221. loader->release();
  222. }
  223. void Game::thread()
  224. {
  225. ZeitMesser m;
  226. while( !stop )
  227. {
  228. m.messungStart();
  229. ticker->nextTick();
  230. Array<int> removed;
  231. cs.lock();
  232. int index = 0;
  233. for( auto player : *clients )
  234. {
  235. if( !player->isOnline() )
  236. {
  237. Datei pFile;
  238. pFile.setDatei( path + "/player/" + player->zEntity()->getName() );
  239. if( pFile.open( Datei::Style::schreiben ) )
  240. PlayerEntityType::INSTANCE->saveEntity( player->zEntity(), &pFile );
  241. removed.add( index, 0 );
  242. }
  243. index++;
  244. }
  245. for( auto i : removed )
  246. clients->remove( i );
  247. cs.unlock();
  248. for( auto dim : *dimensions )
  249. dim->tickEntities( this );
  250. cs.lock();
  251. while( updates->hat( 0 ) )
  252. {
  253. WorldUpdate* update = updates->z( 0 );
  254. for( auto client : *clients )
  255. client->sendWorldUpdate( dynamic_cast<WorldUpdate*>(update->getThis()) );
  256. if( !zDimension( update->getAffectedDimension() ) )
  257. addDimension( new Dimension( update->getAffectedDimension() ) );
  258. update->onUpdate( zDimension( update->getAffectedDimension() ) );
  259. updates->remove( 0 );
  260. }
  261. cs.unlock();
  262. for( auto client : *clients )
  263. client->reply( this );
  264. m.messungEnde();
  265. double sec = m.getSekunden();
  266. if( sec < 0.05 )
  267. Sleep( (int)((0.05 - sec) * 1000) );
  268. }
  269. save();
  270. }
  271. void Game::api( Framework::StreamReader* zRequest, GameClient* zOrigin )
  272. {
  273. char type;
  274. zRequest->lese( &type, 1 );
  275. NetworkResponse response;
  276. switch( type )
  277. {
  278. case 1: // world
  279. {
  280. int dimensionId;
  281. zRequest->lese( (char*)&dimensionId, 4 );
  282. Dimension* dim = zDimension( dimensionId );
  283. if( !dim )
  284. {
  285. dim = new Dimension( dimensionId );
  286. addDimension( dim );
  287. }
  288. dim->api( zRequest, &response );
  289. break;
  290. }
  291. case 2: // player
  292. zOrigin->zEntity()->api( zRequest, &response );
  293. break;
  294. default:
  295. std::cout << "received unknown api request in game with type " << (int)type << "\n";
  296. }
  297. if( !response.isEmpty() )
  298. {
  299. if( response.isBroadcast() )
  300. distributeResponse( &response );
  301. else
  302. zOrigin->sendResponse( &response );
  303. }
  304. }
  305. void Game::distributeResponse( NetworkResponse* zResponse )
  306. {
  307. for( auto client : *clients )
  308. client->sendResponse( zResponse );
  309. }
  310. void Game::requestWorldUpdate( WorldUpdate* update )
  311. {
  312. cs.lock();
  313. updates->add( update );
  314. cs.unlock();
  315. }
  316. GameClient* Game::addPlayer( FCKlient* client, Framework::Text name )
  317. {
  318. cs.lock();
  319. Datei pFile;
  320. pFile.setDatei( path + "/player/" + name );
  321. Player* player;
  322. bool isNew = 0;
  323. if( !pFile.existiert() || !pFile.open( Datei::Style::lesen ) )
  324. {
  325. player = (Player*)PlayerEntityType::INSTANCE->createEntityAt( Vec3<float>( 0, 0, 0 ), OverworldDimension::ID, this );
  326. player->setName( name );
  327. isNew = 1;
  328. }
  329. else
  330. {
  331. player = (Player*)PlayerEntityType::INSTANCE->loadEntity( this, &pFile );
  332. pFile.close();
  333. }
  334. requestArea( { (int)player->getPosition().x - DEFAULT_VIEW_DISTANCE * CHUNK_SIZE, (int)player->getPosition().y - DEFAULT_VIEW_DISTANCE * CHUNK_SIZE, (int)player->getPosition().x + DEFAULT_VIEW_DISTANCE * CHUNK_SIZE, (int)player->getPosition().y + DEFAULT_VIEW_DISTANCE * CHUNK_SIZE, player->getCurrentDimensionId() } );
  335. while( !zDimension( OverworldDimension::ID ) || (isNew && !zDimension( OverworldDimension::ID )->zChunk( getChunkCenter( (int)player->getPosition().x, (int)player->getPosition().y ) )) )
  336. {
  337. cs.unlock();
  338. Sleep( 1000 );
  339. cs.lock();
  340. }
  341. if( isNew )
  342. {
  343. Either<Block*, int> b = AirBlockBlockType::ID;
  344. int h = WORLD_HEIGHT;
  345. while( ((b.isA() && (!(Block*)b || ((Block*)b)->isPassable())) || (b.isB() && StaticRegistry<BlockType>::INSTANCE.zElement( b )->zDefault()->isPassable())) && h > 0 )
  346. b = zBlockAt( { (int)player->getPosition().x, (int)player->getPosition().y, --h }, player->getCurrentDimensionId() );
  347. player->setPosition( { player->getPosition().x, player->getPosition().y, (float)h + 1.f } );
  348. }
  349. zDimension( OverworldDimension::ID )->addEntity( player );
  350. GameClient* gameClient = new GameClient( player, client );
  351. clients->add( gameClient );
  352. cs.unlock();
  353. return dynamic_cast<GameClient*>(gameClient->getThis());
  354. }
  355. bool Game::isChunkLoaded( int x, int y, int dimension ) const
  356. {
  357. Dimension* dim = zDimension( dimension );
  358. return (dim && dim->hasChunck( x, y ));
  359. }
  360. bool Game::doesChunkExist( int x, int y, int dimension )
  361. {
  362. cs.lock();
  363. bool result = isChunkLoaded( x, y, dimension ) || loader->existsChunk( x, y, dimension );
  364. if( !result )
  365. {
  366. for( WorldUpdate* update : *updates )
  367. {
  368. if( update->getType() == AddChunkUpdateType::ID )
  369. result |= ((AddChunkUpdate*)update)->zChunk()->getClock() == Framework::Punkt( x, y );
  370. }
  371. }
  372. cs.unlock();
  373. return result;
  374. }
  375. Framework::Either<Block*, int> Game::zBlockAt( Framework::Vec3<int> location, int dimension ) const
  376. {
  377. Dimension* dim = zDimension( dimension );
  378. if( dim )
  379. return dim->zBlock( location, this );
  380. return 0;
  381. }
  382. Dimension* Game::zDimension( int id ) const
  383. {
  384. for( auto dim : *dimensions )
  385. {
  386. if( dim->getDimensionId() == id )
  387. return dim;
  388. }
  389. return 0;
  390. }
  391. Framework::Punkt Game::getChunkCenter( int x, int y ) const
  392. {
  393. return Punkt( ((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2, ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2 );
  394. }
  395. Area Game::getChunckArea( Punkt center ) const
  396. {
  397. return { center.x - CHUNK_SIZE / 2, center.y - CHUNK_SIZE / 2, center.x + CHUNK_SIZE / 2 - 1, center.y + CHUNK_SIZE / 2 - 1, 0 };
  398. }
  399. Framework::Text Game::getWorldDirectory() const
  400. {
  401. return path;
  402. }
  403. void Game::requestArea( Area area )
  404. {
  405. generator->requestGeneration( area );
  406. loader->requestLoading( area );
  407. }
  408. void Game::save() const
  409. {
  410. Datei d;
  411. d.setDatei( path + "/eid" );
  412. d.open( Datei::Style::schreiben );
  413. d.schreibe( (char*)&nextEntityId, 4 );
  414. d.close();
  415. for( auto dim : *dimensions )
  416. dim->save( path );
  417. }
  418. void Game::requestStop()
  419. {
  420. stop = 1;
  421. warteAufThread( 1000000 );
  422. }
  423. void Game::addDimension( Dimension* d )
  424. {
  425. dimensions->add( d );
  426. }
  427. int Game::getNextEntityId()
  428. {
  429. cs.lock();
  430. int result = nextEntityId++;
  431. cs.unlock();
  432. return result;
  433. }
  434. WorldGenerator* Game::zGenerator() const
  435. {
  436. return generator;
  437. }