Game.cpp 13 KB

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