diff options
| author | void_17 <61356189+void2012@users.noreply.github.com> | 2026-03-06 02:11:18 +0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-03-06 02:11:18 +0700 |
| commit | 55231bb8d3e1a4e2752ac3d444c4287eb0ca4e8b (patch) | |
| tree | 953c537a5c66e328e9f4ab29626cf738112d53c0 | |
| parent | 7d6658fe5b3095f35093701b5ab669ffc291e875 (diff) | |
Remove AUTO_VAR macro and _toString function (#592)
294 files changed, 5032 insertions, 5738 deletions
diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 00000000..3ad11404 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,18 @@ +--- +# Enable all modernize checks, but explicitly exclude trailing return types +Checks: > + -*, + modernize-*, + google-readability-casting, + cppcoreguidelines-pro-type-cstyle-cast, + -modernize-use-trailing-return-type + +# Pass the C++14 flag to the internal Clang compiler +ExtraArgs: ['-std=c++14'] + +CheckOptions: + - key: modernize-loop-convert.MinConfidence + value: reasonable + - key: modernize-use-auto.MinTypeNameLength + value: 5 +... diff --git a/Minecraft.Client/.clangd b/Minecraft.Client/.clangd new file mode 100644 index 00000000..f6b7f8ad --- /dev/null +++ b/Minecraft.Client/.clangd @@ -0,0 +1,30 @@ +CompileFlags: + Add: [-std=c++14, + -m64, + -Wno-unused-includes + ] + Remove: [-W*] + +Index: + StandardLibrary: true + +Diagnostics: + Suppress: unused-includes + UnusedIncludes: None + ClangTidy: + Add: [modernize-loop-convert] + +Completion: + AllScopes: Yes + ArgumentLists: Delimiters + HeaderInsertion: Never + +InlayHints: + BlockEnd: true + ParameterNames: false + DeducedTypes: false + Designators: false + DefaultArguments: false + +Hover: + ShowAKA: true diff --git a/Minecraft.Client/AbstractContainerScreen.cpp b/Minecraft.Client/AbstractContainerScreen.cpp index 2b3e0837..fbf1331d 100644 --- a/Minecraft.Client/AbstractContainerScreen.cpp +++ b/Minecraft.Client/AbstractContainerScreen.cpp @@ -52,12 +52,9 @@ void AbstractContainerScreen::render(int xm, int ym, float a) glEnable(GL_RESCALE_NORMAL); Slot *hoveredSlot = NULL; - - AUTO_VAR(itEnd, menu->slots->end()); - for (AUTO_VAR(it, menu->slots->begin()); it != itEnd; it++) - { - Slot *slot = *it; //menu->slots->at(i); + for ( Slot *slot : *menu->slots ) + { renderSlot(slot); if (isHovering(slot, xm, ym)) @@ -150,10 +147,8 @@ void AbstractContainerScreen::renderSlot(Slot *slot) Slot *AbstractContainerScreen::findSlot(int x, int y) { - AUTO_VAR(itEnd, menu->slots->end()); - for (AUTO_VAR(it, menu->slots->begin()); it != itEnd; it++) + for (Slot* slot : menu->slots ) { - Slot *slot = *it; //menu->slots->at(i); if (isHovering(slot, x, y)) return slot; } return NULL; diff --git a/Minecraft.Client/AchievementScreen.cpp b/Minecraft.Client/AchievementScreen.cpp index 26f20326..902aed17 100644 --- a/Minecraft.Client/AchievementScreen.cpp +++ b/Minecraft.Client/AchievementScreen.cpp @@ -261,12 +261,10 @@ void AchievementScreen::renderBg(int xm, int ym, float a) glDepthFunc(GL_LEQUAL); glDisable(GL_TEXTURE_2D); - - AUTO_VAR(itEnd, Achievements::achievements->end()); - for (AUTO_VAR(it, Achievements::achievements->begin()); it != itEnd; it++) + + for ( Achievement *ach : *Achievements::achievements ) { - Achievement *ach = *it; //Achievements::achievements->at(i); - if (ach->requires == NULL) continue; + if ( ach == nullptr || ach->requires == nullptr) continue; int x1 = ach->x * ACHIEVEMENT_COORD_SCALE - (int) xScroll + 11 + xBigMap; int y1 = ach->y * ACHIEVEMENT_COORD_SCALE - (int) yScroll + 11 + yBigMap; @@ -298,12 +296,9 @@ void AchievementScreen::renderBg(int xm, int ym, float a) glDisable(GL_LIGHTING); glEnable(GL_RESCALE_NORMAL); glEnable(GL_COLOR_MATERIAL); - - itEnd = Achievements::achievements->end(); - for (AUTO_VAR(it, Achievements::achievements->begin()); it != itEnd; it++) - { - Achievement *ach = *it; //Achievements::achievements->at(i); + for ( Achievement *ach : *Achievements::achievements ) + { int x = ach->x * ACHIEVEMENT_COORD_SCALE - (int) xScroll; int y = ach->y * ACHIEVEMENT_COORD_SCALE - (int) yScroll; diff --git a/Minecraft.Client/ArchiveFile.cpp b/Minecraft.Client/ArchiveFile.cpp index 642471a4..2e57a5bb 100644 --- a/Minecraft.Client/ArchiveFile.cpp +++ b/Minecraft.Client/ArchiveFile.cpp @@ -78,11 +78,8 @@ vector<wstring> *ArchiveFile::getFileList() { vector<wstring> *out = new vector<wstring>(); - for ( AUTO_VAR(it, m_index.begin()); - it != m_index.end(); - it++ ) - - out->push_back( it->first ); + for ( const auto& it : m_index ) + out->push_back( it.first ); return out; } @@ -100,7 +97,7 @@ int ArchiveFile::getFileSize(const wstring &filename) byteArray ArchiveFile::getFile(const wstring &filename) { byteArray out; - AUTO_VAR(it,m_index.find(filename)); + auto it = m_index.find(filename); if(it == m_index.end()) { diff --git a/Minecraft.Client/BufferedImage.cpp b/Minecraft.Client/BufferedImage.cpp index 37662d8a..89e37e4f 100644 --- a/Minecraft.Client/BufferedImage.cpp +++ b/Minecraft.Client/BufferedImage.cpp @@ -1,4 +1,4 @@ -#include "stdafx.h" +#include "stdafx.h" #include "..\Minecraft.World\StringHelpers.h" #include "Textures.h" #include "..\Minecraft.World\ArrayWithLength.h" @@ -46,7 +46,7 @@ void BufferedImage::ByteFlip4(unsigned int &data) } // Loads a bitmap into a buffered image - only currently supports the 2 types of 32-bit image that we've made so far // and determines which of these is which by the compression method. Compression method 3 is a 32-bit image with only -// 24-bits used (ie no alpha channel) whereas method 0 is a full 32-bit image with a valid alpha channel. +// 24-bits used (ie no alpha channel) whereas method 0 is a full 32-bit image with a valid alpha channel. BufferedImage::BufferedImage(const wstring& File, bool filenameHasExtension /*=false*/, bool bTitleUpdateTexture /*=false*/, const wstring &drive /*=L""*/) { HRESULT hr; @@ -149,7 +149,7 @@ BufferedImage::BufferedImage(const wstring& File, bool filenameHasExtension /*=f wstring mipMapPath = L""; if( l != 0 ) { - mipMapPath = L"MipMapLevel" + _toString<int>(l+1); + mipMapPath = L"MipMapLevel" + std::to_wstring(l+1); } if( filenameHasExtension ) { @@ -171,7 +171,7 @@ BufferedImage::BufferedImage(const wstring& File, bool filenameHasExtension /*=f hr=RenderManager.LoadTextureData(pchTextureName,&ImageInfo,&data[l]); - if(hr!=ERROR_SUCCESS) + if(hr!=ERROR_SUCCESS) { // 4J - If we haven't loaded the non-mipmap version then exit the game if( l == 0 ) @@ -179,7 +179,7 @@ BufferedImage::BufferedImage(const wstring& File, bool filenameHasExtension /*=f app.FatalLoadError(); } return; - } + } if( l == 0 ) { @@ -207,7 +207,7 @@ BufferedImage::BufferedImage(DLCPack *dlcPack, const wstring& File, bool filenam wstring mipMapPath = L""; if( l != 0 ) { - mipMapPath = L"MipMapLevel" + _toString<int>(l+1); + mipMapPath = L"MipMapLevel" + std::to_wstring(l+1); } if( filenameHasExtension ) { @@ -231,7 +231,7 @@ BufferedImage::BufferedImage(DLCPack *dlcPack, const wstring& File, bool filenam DLCFile *dlcFile = dlcPack->getFile(DLCManager::e_DLCType_All, name); pbData = dlcFile->getData(dwBytes); if(pbData == NULL || dwBytes == 0) - { + { // 4J - If we haven't loaded the non-mipmap version then exit the game if( l == 0 ) { @@ -245,7 +245,7 @@ BufferedImage::BufferedImage(DLCPack *dlcPack, const wstring& File, bool filenam hr=RenderManager.LoadTextureData(pbData,dwBytes,&ImageInfo,&data[l]); - if(hr!=ERROR_SUCCESS) + if(hr!=ERROR_SUCCESS) { // 4J - If we haven't loaded the non-mipmap version then exit the game if( l == 0 ) @@ -253,7 +253,7 @@ BufferedImage::BufferedImage(DLCPack *dlcPack, const wstring& File, bool filenam app.FatalLoadError(); } return; - } + } if( l == 0 ) { @@ -276,7 +276,7 @@ BufferedImage::BufferedImage(BYTE *pbData, DWORD dwBytes) ZeroMemory(&ImageInfo,sizeof(D3DXIMAGE_INFO)); HRESULT hr=RenderManager.LoadTextureData(pbData,dwBytes,&ImageInfo,&data[0]); - if(hr==ERROR_SUCCESS) + if(hr==ERROR_SUCCESS) { width=ImageInfo.Width; height=ImageInfo.Height; diff --git a/Minecraft.Client/Chunk.cpp b/Minecraft.Client/Chunk.cpp index 63cd0501..850b79fb 100644 --- a/Minecraft.Client/Chunk.cpp +++ b/Minecraft.Client/Chunk.cpp @@ -105,7 +105,7 @@ void Chunk::setPos(int x, int y, int z) { bb = shared_ptr<AABB>(AABB::newPermanent(-g, -g, -g, XZSIZE+g, SIZE+g, XZSIZE+g)); } - else + else { // 4J MGH - bounds are relative to the position now, so the AABB will be setup already, either above, or from the tesselator bounds. // bb->set(-g, -g, -g, SIZE+g, SIZE+g, SIZE+g); @@ -143,7 +143,7 @@ void Chunk::setPos(int x, int y, int z) LeaveCriticalSection(&levelRenderer->m_csDirtyChunks); - + } void Chunk::translateToPos() @@ -176,7 +176,7 @@ void Chunk::makeCopyForRebuild(Chunk *source) this->clipChunk = NULL; this->id = source->id; this->globalRenderableTileEntities = source->globalRenderableTileEntities; - this->globalRenderableTileEntities_cs = source->globalRenderableTileEntities_cs; + this->globalRenderableTileEntities_cs = source->globalRenderableTileEntities_cs; } void Chunk::rebuild() @@ -189,7 +189,7 @@ void Chunk::rebuild() // if (!dirty) return; PIXBeginNamedEvent(0,"Rebuild section A"); - + #ifdef _LARGE_WORLDS Tesselator *t = Tesselator::getInstance(); #else @@ -226,7 +226,7 @@ void Chunk::rebuild() // Get the data for the level chunk that this render chunk is it (level chunk is 16 x 16 x 128, // render chunk is 16 x 16 x 16. We wouldn't have to actually get all of it if the data was ordered differently, but currently // it is ordered by x then z then y so just getting a small range of y out of it would involve getting the whole thing into - // the cache anyway. + // the cache anyway. #ifdef _LARGE_WORLDS unsigned char *tileIds = GetTileIdsStorage(); @@ -240,9 +240,9 @@ void Chunk::rebuild() TileRenderer *tileRenderer = new TileRenderer(region, this->x, this->y, this->z, tileIds); // AP - added a caching system for Chunk::rebuild to take advantage of - // Basically we're storing of copy of the tileIDs array inside the region so that calls to Region::getTile can grab data - // more quickly from this array rather than calling CompressedTileStorage. On the Vita the total thread time spent in - // Region::getTile went from 20% to 4%. + // Basically we're storing of copy of the tileIDs array inside the region so that calls to Region::getTile can grab data + // more quickly from this array rather than calling CompressedTileStorage. On the Vita the total thread time spent in + // Region::getTile went from 20% to 4%. #ifdef __PSVITA__ int xc = x >> 4; int zc = z >> 4; @@ -278,7 +278,7 @@ void Chunk::rebuild() if( yy == (Level::maxBuildHeight - 1) ) continue; if(( xx == 0 ) || ( xx == 15 )) continue; if(( zz == 0 ) || ( zz == 15 )) continue; - + // Establish whether this tile and its neighbours are all made of rock, dirt, unbreakable tiles, or have already // been determined to meet this criteria themselves and have a tile of 255 set. if( !( ( tileId == Tile::stone_Id ) || ( tileId == Tile::dirt_Id ) || ( tileId == Tile::unbreakable_Id ) || ( tileId == 255) ) ) continue; @@ -340,7 +340,7 @@ void Chunk::rebuild() PIXBeginNamedEvent(0,"Rebuild section C"); Tesselator::Bounds bounds; // 4J MGH - added { - // this was the old default clip bounds for the chunk, set in Chunk::setPos. + // this was the old default clip bounds for the chunk, set in Chunk::setPos. float g = 6.0f; bounds.boundingBox[0] = -g; bounds.boundingBox[1] = -g; @@ -401,7 +401,7 @@ void Chunk::rebuild() t->begin(); t->offset((float)(-this->x), (float)(-this->y), (float)(-this->z)); } - + Tile *tile = Tile::tiles[tileId]; if (currentLayer == 0 && tile->isEntityTile()) { @@ -468,7 +468,7 @@ void Chunk::rebuild() { levelRenderer->setGlobalChunkFlag(this->x, this->y, this->z, level, LevelRenderer::CHUNK_FLAG_EMPTY1); RenderManager.CBuffClear(lists + 1); - break; + break; } } @@ -484,7 +484,6 @@ void Chunk::rebuild() PIXEndNamedEvent(); PIXBeginNamedEvent(0,"Rebuild section D"); - // 4J - have rewritten the way that tile entities are stored globally to make it work more easily with split screen. Chunks are now // stored globally in the levelrenderer, in a hashmap with a special key made up from the dimension and chunk position (using same index // as is used for global flags) @@ -493,25 +492,25 @@ void Chunk::rebuild() EnterCriticalSection(globalRenderableTileEntities_cs); if( renderableTileEntities.size() ) { - AUTO_VAR(it, globalRenderableTileEntities->find(key)); - if( it != globalRenderableTileEntities->end() ) + auto it = globalRenderableTileEntities->find(key); + if( it != globalRenderableTileEntities->end() ) { // We've got some renderable tile entities that we want associated with this chunk, and an existing list of things that used to be. // We need to flag any that we don't need any more to be removed, keep those that we do, and add any new ones // First pass - flag everything already existing to be removed - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) + for(auto& it2 : it->second) { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); + it2->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); } // Now go through the current list. If these are already in the list, then unflag the remove flag. If they aren't, then add - for( int i = 0; i < renderableTileEntities.size(); i++ ) + for(const auto& it3 : renderableTileEntities) { - AUTO_VAR(it2, find( it->second.begin(), it->second.end(), renderableTileEntities[i] )); - if( it2 == it->second.end() ) + auto it2 = find(it->second.begin(), it->second.end(), it3); + if( it2 == it->second.end() ) { - (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); + (*globalRenderableTileEntities)[key].push_back(it3); } else { @@ -531,12 +530,12 @@ void Chunk::rebuild() else { // Another easy case - we don't want any renderable tile entities associated with this chunk. Flag all to be removed. - AUTO_VAR(it, globalRenderableTileEntities->find(key)); - if( it != globalRenderableTileEntities->end() ) + auto it = globalRenderableTileEntities->find(key); + if( it != globalRenderableTileEntities->end() ) { - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) + for(auto& it2 : it->second) { - (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); + it2->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); } } } @@ -555,11 +554,11 @@ void Chunk::rebuild() oldTileEntities.removeAll(renderableTileEntities); globalRenderableTileEntities.removeAll(oldTileEntities); */ - + unordered_set<shared_ptr<TileEntity> > newTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); - - AUTO_VAR(endIt, oldTileEntities.end()); + + auto endIt = oldTileEntities.end(); for( unordered_set<shared_ptr<TileEntity> >::iterator it = oldTileEntities.begin(); it != endIt; it++ ) { newTileEntities.erase(*it); @@ -576,7 +575,7 @@ void Chunk::rebuild() // 4J - All these new things added to globalRenderableTileEntities - AUTO_VAR(endItRTE, renderableTileEntities.end()); + auto endItRTE = renderableTileEntities.end(); for( vector<shared_ptr<TileEntity> >::iterator it = renderableTileEntities.begin(); it != endItRTE; it++ ) { oldTileEntities.erase(*it); @@ -680,13 +679,13 @@ void Chunk::rebuild_SPU() // Get the data for the level chunk that this render chunk is it (level chunk is 16 x 16 x 128, // render chunk is 16 x 16 x 16. We wouldn't have to actually get all of it if the data was ordered differently, but currently // it is ordered by x then z then y so just getting a small range of y out of it would involve getting the whole thing into - // the cache anyway. + // the cache anyway. ChunkRebuildData* pOutData = NULL; g_rebuildDataIn.buildForChunk(®ion, level, x0, y0, z0); Tesselator::Bounds bounds; { - // this was the old default clip bounds for the chunk, set in Chunk::setPos. + // this was the old default clip bounds for the chunk, set in Chunk::setPos. float g = 6.0f; bounds.boundingBox[0] = -g; bounds.boundingBox[1] = -g; @@ -814,14 +813,14 @@ void Chunk::rebuild_SPU() EnterCriticalSection(globalRenderableTileEntities_cs); if( renderableTileEntities.size() ) { - AUTO_VAR(it, globalRenderableTileEntities->find(key)); + auto it = globalRenderableTileEntities->find(key); if( it != globalRenderableTileEntities->end() ) { // We've got some renderable tile entities that we want associated with this chunk, and an existing list of things that used to be. // We need to flag any that we don't need any more to be removed, keep those that we do, and add any new ones // First pass - flag everything already existing to be removed - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) + for( auto it2 = it->second.begin(); it2 != it->second.end(); it2++ ) { (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); } @@ -829,7 +828,7 @@ void Chunk::rebuild_SPU() // Now go through the current list. If these are already in the list, then unflag the remove flag. If they aren't, then add for( int i = 0; i < renderableTileEntities.size(); i++ ) { - AUTO_VAR(it2, find( it->second.begin(), it->second.end(), renderableTileEntities[i] )); + auto it2 = find( it->second.begin(), it->second.end(), renderableTileEntities[i] ); if( it2 == it->second.end() ) { (*globalRenderableTileEntities)[key].push_back(renderableTileEntities[i]); @@ -852,10 +851,10 @@ void Chunk::rebuild_SPU() else { // Another easy case - we don't want any renderable tile entities associated with this chunk. Flag all to be removed. - AUTO_VAR(it, globalRenderableTileEntities->find(key)); + auto it = globalRenderableTileEntities->find(key); if( it != globalRenderableTileEntities->end() ) { - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++ ) + for( auto it2 = it->second.begin(); it2 != it->second.end(); it2++ ) { (*it2)->setRenderRemoveStage(TileEntity::e_RenderRemoveStageFlaggedAtChunk); } @@ -875,11 +874,11 @@ void Chunk::rebuild_SPU() oldTileEntities.removeAll(renderableTileEntities); globalRenderableTileEntities.removeAll(oldTileEntities); */ - + unordered_set<shared_ptr<TileEntity> > newTileEntities(renderableTileEntities.begin(),renderableTileEntities.end()); - - AUTO_VAR(endIt, oldTileEntities.end()); + + auto endIt = oldTileEntities.end(); for( unordered_set<shared_ptr<TileEntity> >::iterator it = oldTileEntities.begin(); it != endIt; it++ ) { newTileEntities.erase(*it); @@ -896,7 +895,7 @@ void Chunk::rebuild_SPU() // 4J - All these new things added to globalRenderableTileEntities - AUTO_VAR(endItRTE, renderableTileEntities.end()); + auto endItRTE = renderableTileEntities.end(); for( vector<shared_ptr<TileEntity> >::iterator it = renderableTileEntities.begin(); it != endItRTE; it++ ) { oldTileEntities.erase(*it); diff --git a/Minecraft.Client/ClientConnection.cpp b/Minecraft.Client/ClientConnection.cpp index 02a7837d..2270433d 100644 --- a/Minecraft.Client/ClientConnection.cpp +++ b/Minecraft.Client/ClientConnection.cpp @@ -168,9 +168,9 @@ void ClientConnection::handleLogin(shared_ptr<LoginPacket> packet) PlayerUID OnlineXuid; ProfileManager.GetXUID(m_userIndex,&OnlineXuid,true); // online xuid MOJANG_DATA *pMojangData = NULL; - + if(!g_NetworkManager.IsLocalGame()) - { + { pMojangData=app.GetMojangDataForXuid(OnlineXuid); } @@ -222,7 +222,7 @@ void ClientConnection::handleLogin(shared_ptr<LoginPacket> packet) // check the file is not already in bRes=app.IsFileInMemoryTextures(wstr); if(!bRes) - { + { #ifdef _XBOX C4JStorage::ETMSStatus eTMSStatus; eTMSStatus=StorageManager.ReadTMSFile(iUserID,C4JStorage::eGlobalStorage_Title,C4JStorage::eTMS_FileType_Graphic,pMojangData->wchSkin,&pBuffer, &dwSize); @@ -234,17 +234,17 @@ void ClientConnection::handleLogin(shared_ptr<LoginPacket> packet) if(bRes) { app.AddMemoryTextureFile(wstr,pBuffer,dwSize); - } + } } // a cloak? if(pMojangData->wchCape[0]!=0L) - { + { wstring wstr=pMojangData->wchCape; // check the file is not already in bRes=app.IsFileInMemoryTextures(wstr); if(!bRes) - { + { #ifdef _XBOX C4JStorage::ETMSStatus eTMSStatus; eTMSStatus=StorageManager.ReadTMSFile(iUserID,C4JStorage::eGlobalStorage_Title,C4JStorage::eTMS_FileType_Graphic,pMojangData->wchCape,&pBuffer, &dwSize); @@ -302,7 +302,7 @@ void ClientConnection::handleLogin(shared_ptr<LoginPacket> packet) app.DebugPrintf("ClientConnection - DIFFICULTY --- %d\n",packet->difficulty); level->difficulty = packet->difficulty; // 4J Added level->isClientSide = true; - minecraft->setLevel(level); + minecraft->setLevel(level); } minecraft->player->setPlayerIndex( packet->m_playerIndex ); @@ -362,7 +362,7 @@ void ClientConnection::handleLogin(shared_ptr<LoginPacket> packet) // 4J Stu - At time of writing ProfileManager.GetGamertag() does not always return the correct name, // if sign-ins are turned off while the player signed in. Using the qnetPlayer instead. // need to have a level before create extra local player - MultiPlayerLevel *levelpassedin=(MultiPlayerLevel *)level; + MultiPlayerLevel *levelpassedin=(MultiPlayerLevel *)level; player = minecraft->createExtraLocalPlayer(m_userIndex, networkPlayer->GetOnlineName(), m_userIndex, packet->dimension, this,levelpassedin); // need to have a player before the setlevel @@ -384,7 +384,7 @@ void ClientConnection::handleLogin(shared_ptr<LoginPacket> packet) player->setPlayerIndex( packet->m_playerIndex ); player->setCustomSkin( app.GetPlayerSkinId(m_userIndex) ); player->setCustomCape( app.GetPlayerCapeId(m_userIndex) ); - + BYTE networkSmallId = getSocket()->getSmallId(); app.UpdatePlayerInfo(networkSmallId, packet->m_playerIndex, packet->m_uiGamePrivileges); @@ -396,21 +396,21 @@ void ClientConnection::handleLogin(shared_ptr<LoginPacket> packet) displayPrivilegeChanges(minecraft->localplayers[m_userIndex],startingPrivileges); } - + maxPlayers = packet->maxPlayers; - + // need to have a player before the setLocalCreativeMode shared_ptr<MultiplayerLocalPlayer> lastPlayer = minecraft->player; minecraft->player = minecraft->localplayers[m_userIndex]; ((MultiPlayerGameMode *)minecraft->localgameModes[m_userIndex])->setLocalMode(GameType::byId(packet->gameType)); minecraft->player = lastPlayer; - + // make sure the UI offsets for this player are set correctly if(iUserID!=-1) { ui.UpdateSelectedItemPos(iUserID); } - + TelemetryManager->RecordLevelStart(m_userIndex, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, Minecraft::GetInstance()->getLevel(packet->dimension)->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); } @@ -448,7 +448,7 @@ void ClientConnection::handleAddEntity(shared_ptr<AddEntityPacket> packet) } } } - + if (owner != NULL && owner->instanceof(eTYPE_PLAYER)) { shared_ptr<Player> player = dynamic_pointer_cast<Player>(owner); @@ -574,7 +574,7 @@ void ClientConnection::handleAddEntity(shared_ptr<AddEntityPacket> packet) } packet->data = 0; } - + if (packet->type == AddEntityPacket::ARROW) e = shared_ptr<Entity>( new Arrow(level, x, y, z) ); if (packet->type == AddEntityPacket::SNOWBALL) e = shared_ptr<Entity>( new Snowball(level, x, y, z) ); if (packet->type == AddEntityPacket::THROWN_ENDERPEARL) e = shared_ptr<Entity>( new ThrownEnderpearl(level, x, y, z) ); @@ -620,22 +620,19 @@ void ClientConnection::handleAddEntity(shared_ptr<AddEntityPacket> packet) e->yRotp = packet->yRot; e->xRotp = packet->xRot; - if (setRot) + if (setRot) { e->yRot = 0.0f; e->xRot = 0.0f; } vector<shared_ptr<Entity> > *subEntities = e->getSubEntities(); - if (subEntities != NULL) + if (subEntities) { int offs = packet->id - e->entityId; - //for (int i = 0; i < subEntities.length; i++) - for(AUTO_VAR(it, subEntities->begin()); it != subEntities->end(); ++it) - { - (*it)->entityId += offs; - //subEntities[i].entityId += offs; - //System.out.println(subEntities[i].entityId); + for ( auto it : *subEntities ) + { + it->entityId += offs; } } @@ -685,10 +682,10 @@ void ClientConnection::handleAddEntity(shared_ptr<AddEntityPacket> packet) } } - e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); + e->lerpMotion(packet->xa / 8000.0, packet->ya / 8000.0, packet->za / 8000.0); } - // 4J: Check our deferred entity link packets + // 4J: Check our deferred entity link packets checkDeferredEntityLinkPackets(e->entityId); } } @@ -839,7 +836,7 @@ void ClientConnection::handleAddPlayer(shared_ptr<AddPlayerPacket> packet) player->setCustomSkin( packet->m_skinId ); player->setCustomCape( packet->m_capeId ); player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_All, packet->m_uiGamePrivileges); - + if(!player->customTextureUrl.empty() && player->customTextureUrl.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl)) { if( minecraft->addPendingClientTextureRequest(player->customTextureUrl) ) @@ -856,7 +853,7 @@ void ClientConnection::handleAddPlayer(shared_ptr<AddPlayerPacket> packet) } app.DebugPrintf("Custom skin for player %ls is %ls\n",player->name.c_str(),player->customTextureUrl.c_str()); - + if(!player->customTextureUrl2.empty() && player->customTextureUrl2.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(player->customTextureUrl2)) { if( minecraft->addPendingClientTextureRequest(player->customTextureUrl2) ) @@ -1034,7 +1031,7 @@ void ClientConnection::handleMovePlayer(shared_ptr<MovePlayerPacket> packet) packet->yView = player->y; connection->send(packet); if (!started) - { + { if(!g_NetworkManager.IsHost() ) { @@ -1050,7 +1047,7 @@ void ClientConnection::handleMovePlayer(shared_ptr<MovePlayerPacket> packet) started = true; minecraft->setScreen(NULL); - + // Fix for #105852 - TU12: Content: Gameplay: Local splitscreen Players are spawned at incorrect places after re-joining previously saved and loaded "Mass Effect World". // Move this check from Minecraft::createExtraLocalPlayer // 4J-PB - can't call this when this function is called from the qnet thread (GetGameStarted will be false) @@ -1124,7 +1121,7 @@ void ClientConnection::handleChunkTilesUpdate(shared_ptr<ChunkTilesUpdatePacket> // Don't bother setting this to dirty if it isn't going to visually change - we get a lot of // water changing from static to dynamic for instance if(!( ( ( prevTile == Tile::water_Id ) && ( tile == Tile::calmWater_Id ) ) || - ( ( prevTile == Tile::calmWater_Id ) && ( tile == Tile::water_Id ) ) || + ( ( prevTile == Tile::calmWater_Id ) && ( tile == Tile::water_Id ) ) || ( ( prevTile == Tile::lava_Id ) && ( tile == Tile::calmLava_Id ) ) || ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::calmLava_Id ) ) || ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::lava_Id ) ) ) ) @@ -1253,7 +1250,7 @@ void ClientConnection::handleDisconnect(shared_ptr<DisconnectPacket> packet) { connection->close(DisconnectPacket::eDisconnect_Kicked); done = true; - + Minecraft *pMinecraft = Minecraft::GetInstance(); pMinecraft->connectionDisconnected( m_userIndex , packet->reason ); app.SetDisconnectReason( packet->reason ); @@ -1337,7 +1334,7 @@ void ClientConnection::handleTakeItemEntity(shared_ptr<TakeItemEntityPacket> pac if (from != NULL) { - // If this is a local player, then we only want to do processing for it if this connection is associated with the player it is for. In + // If this is a local player, then we only want to do processing for it if this connection is associated with the player it is for. In // particular, we don't want to remove the item entity until we are processing it for the right connection, or else we won't have a valid // "from" reference if we've already removed the item for an earlier processed connection if( isLocalPlayer ) @@ -1422,7 +1419,7 @@ void ClientConnection::handleChat(shared_ptr<ChatPacket> packet) case ChatPacket::e_ChatBedMeSleep: message=app.GetString(IDS_TILE_BED_MESLEEP); break; - case ChatPacket::e_ChatPlayerJoinedGame: + case ChatPacket::e_ChatPlayerJoinedGame: message=app.GetString(IDS_PLAYER_JOINED); iPos=message.find(L"%s"); message.replace(iPos,2,playerDisplayName); @@ -1537,7 +1534,7 @@ void ClientConnection::handleChat(shared_ptr<ChatPacket> packet) replaceEntitySource = true; break; - + case ChatPacket::e_ChatDeathFellAccidentLadder: message=app.GetString(IDS_DEATH_FELL_ACCIDENT_LADDER); replacePlayer = true; @@ -1702,7 +1699,7 @@ void ClientConnection::handleChat(shared_ptr<ChatPacket> packet) message=app.GetString(IDS_MAX_WOLVES_BRED); break; - // can't shear the mooshroom + // can't shear the mooshroom case ChatPacket::e_ChatPlayerCantShearMooshroom: message=app.GetString(IDS_CANT_SHEAR_MOOSHROOM); break; @@ -1710,16 +1707,16 @@ void ClientConnection::handleChat(shared_ptr<ChatPacket> packet) // Paintings/Item Frames case ChatPacket::e_ChatPlayerMaxHangingEntities: message=app.GetString(IDS_MAX_HANGINGENTITIES); - break; + break; // Enemy spawn eggs in peaceful case ChatPacket::e_ChatPlayerCantSpawnInPeaceful: message=app.GetString(IDS_CANT_SPAWN_IN_PEACEFUL); - break; + break; // Enemy spawn eggs in peaceful case ChatPacket::e_ChatPlayerMaxBoats: message=app.GetString(IDS_MAX_BOATS); - break; + break; case ChatPacket::e_ChatCommandTeleportSuccess: message=app.GetString(IDS_COMMAND_TELEPORT_SUCCESS); @@ -1851,7 +1848,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) BOOL isAtLeastOneFriend = g_NetworkManager.IsHost(); BOOL isFriendsWithHost = TRUE; BOOL cantPlayContentRestricted = FALSE; - + if(!g_NetworkManager.IsHost()) { // set the game host settings @@ -1885,7 +1882,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) } if( playerXuid != INVALID_XUID ) { - // Is this user friends with the host player? + // Is this user friends with the host player? BOOL result; DWORD error; error = XUserAreUsersFriends(idx,&packet->m_playerXuids[packet->m_hostIndex],1,&result,NULL); @@ -1915,7 +1912,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) } if( playerXuid != INVALID_XUID ) { - // Is this user friends with the host player? + // Is this user friends with the host player? BOOL result; DWORD error; error = XUserAreUsersFriends(m_userIndex,&packet->m_playerXuids[packet->m_hostIndex],1,&result,NULL); @@ -2030,7 +2027,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) if(m_userIndex == ProfileManager.GetPrimaryPad() ) { - // Is this user friends with the host player? + // Is this user friends with the host player? bool isFriend = true; unsigned int friendCount = 0; #ifdef __PS3__ @@ -2060,7 +2057,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) requestParam.offset = 0; requestParam.userInfo.userId = ProfileManager.getUserID(ProfileManager.GetPrimaryPad()); - int ret = sce::Toolkit::NP::Friends::Interface::getFriendslist(&friendList, &requestParam, false); + int ret = sce::Toolkit::NP::Friends::Interface::getFriendslist(&friendList, &requestParam, false); if( ret == 0 ) { if( friendList.hasResult() ) @@ -2070,7 +2067,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) } #endif if( ret == 0 ) - { + { isFriend = false; SceNpId npid; for( unsigned int i = 0; i < friendCount; i++ ) @@ -2153,7 +2150,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) isAtLeastOneFriend = true; break; } - } + } } app.DebugPrintf("ClientConnection::handlePreLogin: User has at least one friend? %s\n", isAtLeastOneFriend ? "Yes" : "No"); @@ -2195,8 +2192,8 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) DisconnectPacket::eDisconnectReason reason = DisconnectPacket::eDisconnect_NoUGC_Remote; #else DisconnectPacket::eDisconnectReason reason = DisconnectPacket::eDisconnect_None; -#endif - if(m_userIndex == ProfileManager.GetPrimaryPad()) +#endif + if(m_userIndex == ProfileManager.GetPrimaryPad()) { if(!isFriendsWithHost) reason = DisconnectPacket::eDisconnect_NotFriendsWithHost; else if(!isAtLeastOneFriend) reason = DisconnectPacket::eDisconnect_NoFriendsInGame; @@ -2208,7 +2205,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) app.SetAction(ProfileManager.GetPrimaryPad(),eAppAction_ExitWorld,(void *)TRUE); } else - { + { if(!isFriendsWithHost) reason = DisconnectPacket::eDisconnect_NotFriendsWithHost; else if(!canPlayLocal) reason = DisconnectPacket::eDisconnect_NoUGC_Single_Local; else if(cantPlayContentRestricted) reason = DisconnectPacket::eDisconnect_ContentRestricted_Single_Local; @@ -2221,7 +2218,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) app.SetDisconnectReason( reason ); - // 4J-PB - this locks up on the read and write threads not closing down, because they are trying to lock the incoming critsec when it's already locked by this thread + // 4J-PB - this locks up on the read and write threads not closing down, because they are trying to lock the incoming critsec when it's already locked by this thread // Minecraft::GetInstance()->connectionDisconnected( m_userIndex , reason ); // done = true; // connection->flush(); @@ -2278,7 +2275,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) #endif // On PS3, all non-signed in players (even guests) can get a useful offlineXUID -#if !(defined __PS3__ || defined _DURANGO ) +#if !(defined __PS3__ || defined _DURANGO ) if( !ProfileManager.IsGuest( m_userIndex ) ) #endif { @@ -2287,7 +2284,7 @@ void ClientConnection::handlePreLogin(shared_ptr<PreLoginPacket> packet) } BOOL allAllowed, friendsAllowed; ProfileManager.AllowedPlayerCreatedContent(m_userIndex,true,&allAllowed,&friendsAllowed); - send( shared_ptr<LoginPacket>( new LoginPacket(minecraft->user->name, SharedConstants::NETWORK_PROTOCOL_VERSION, offlineXUID, onlineXUID, (allAllowed!=TRUE && friendsAllowed==TRUE), + send( shared_ptr<LoginPacket>( new LoginPacket(minecraft->user->name, SharedConstants::NETWORK_PROTOCOL_VERSION, offlineXUID, onlineXUID, (allAllowed!=TRUE && friendsAllowed==TRUE), packet->m_ugcPlayersVersion, app.GetPlayerSkinId(m_userIndex), app.GetPlayerCapeId(m_userIndex), ProfileManager.IsGuest( m_userIndex )))); if(!g_NetworkManager.IsHost() ) @@ -2345,14 +2342,12 @@ void ClientConnection::handleAddMob(shared_ptr<AddMobPacket> packet) mob->xRotp = packet->xRot; vector<shared_ptr<Entity> > *subEntities = mob->getSubEntities(); - if (subEntities != NULL) + if (subEntities) { int offs = packet->id - mob->entityId; - //for (int i = 0; i < subEntities.length; i++) - for(AUTO_VAR(it, subEntities->begin()); it != subEntities->end(); ++it) - { - //subEntities[i].entityId += offs; - (*it)->entityId += offs; + for (auto& it : *subEntities ) + { + it->entityId += offs; } } @@ -2438,7 +2433,7 @@ void ClientConnection::handleEntityLinkPacket(shared_ptr<SetEntityLinkPacket> pa minecraft.gui.setOverlayMessage(I18n.get("mount.onboard", Options.getTranslatedKeyMessage(options.keySneak.key)), false); } */ - } + } else if (packet->type == SetEntityLinkPacket::LEASH) { if ( (sourceEntity != NULL) && sourceEntity->instanceof(eTYPE_MOB) ) @@ -2508,7 +2503,7 @@ void ClientConnection::handleTexture(shared_ptr<TexturePacket> packet) wprintf(L"Client received request for custom texture %ls\n",packet->textureName.c_str()); #endif PBYTE pbData=NULL; - DWORD dwBytes=0; + DWORD dwBytes=0; app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); if(dwBytes!=0) @@ -2540,7 +2535,7 @@ void ClientConnection::handleTextureAndGeometry(shared_ptr<TextureAndGeometryPac wprintf(L"Client received request for custom texture and geometry %ls\n",packet->textureName.c_str()); #endif PBYTE pbData=NULL; - DWORD dwBytes=0; + DWORD dwBytes=0; app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); DLCSkinFile *pDLCSkinFile = app.m_dlcManager.getSkinFile(packet->textureName); @@ -2574,9 +2569,9 @@ void ClientConnection::handleTextureAndGeometry(shared_ptr<TextureAndGeometryPac // Add the texture data app.AddMemoryTextureFile(packet->textureName,packet->pbData,packet->dwTextureBytes); // Add the geometry data - if(packet->dwBoxC!=0) + if(packet->dwBoxC!=0) { - app.SetAdditionalSkinBoxes(packet->dwSkinID,packet->BoxDataA,packet->dwBoxC); + app.SetAdditionalSkinBoxes(packet->dwSkinID,packet->BoxDataA,packet->dwBoxC); } // Add the anim override app.SetAnimOverrideBitmask(packet->dwSkinID,packet->uiAnimOverrideBitmask); @@ -2622,7 +2617,7 @@ void ClientConnection::handleTextureChange(shared_ptr<TextureChangePacket> packe #endif break; } - + if(!packet->path.empty() && packet->path.substr(0,3).compare(L"def") != 0 && !app.IsFileInMemoryTextures(packet->path)) { if( minecraft->addPendingClientTextureRequest(packet->path) ) @@ -2728,7 +2723,7 @@ void ClientConnection::handleRespawn(shared_ptr<RespawnPacket> packet) level->removeEntity( shared_ptr<Entity>(minecraft->localplayers[m_userIndex]) ); level = dimensionLevel; - + // Whilst calling setLevel, make sure that minecraft::player is set up to be correct for this // connection shared_ptr<MultiplayerLocalPlayer> lastPlayer = minecraft->player; @@ -2737,7 +2732,7 @@ void ClientConnection::handleRespawn(shared_ptr<RespawnPacket> packet) minecraft->player = lastPlayer; TelemetryManager->RecordLevelExit(m_userIndex, eSen_LevelExitStatus_Succeeded); - + //minecraft->player->dimension = packet->dimension; minecraft->localplayers[m_userIndex]->dimension = packet->dimension; //minecraft->setScreen(new ReceivingLevelScreen(this)); @@ -2788,12 +2783,12 @@ void ClientConnection::handleRespawn(shared_ptr<RespawnPacket> packet) { ui.NavigateToScene(m_userIndex, eUIScene_ConnectingProgress, param); } - + app.SetAction( m_userIndex, eAppAction_WaitForDimensionChangeComplete); } //minecraft->respawnPlayer(minecraft->player->GetXboxPad(),true, packet->dimension); - + // Wrap respawnPlayer call up in code to set & restore the player/gamemode etc. as some things // in there assume that we are set up for the player that the respawn is coming in for int oldIndex = minecraft->getLocalPlayerIdx(); @@ -2818,7 +2813,7 @@ void ClientConnection::handleExplosion(shared_ptr<ExplodePacket> packet) MultiPlayerLevel *mpLevel = (MultiPlayerLevel *)minecraft->level; mpLevel->enableResetChanges(false); // 4J - now directly pass a pointer to the toBlow array in the packet rather than copying around - e->finalizeExplosion(true, &packet->toBlow); + e->finalizeExplosion(true, &packet->toBlow); mpLevel->enableResetChanges(true); PIXEndNamedEvent(); PIXEndNamedEvent(); @@ -2864,7 +2859,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -2878,7 +2873,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -2892,7 +2887,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -2907,7 +2902,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -2922,7 +2917,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -2937,7 +2932,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -2949,7 +2944,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -2961,7 +2956,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -2975,7 +2970,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -2990,7 +2985,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -3002,7 +2997,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -3025,7 +3020,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -3037,7 +3032,7 @@ void ClientConnection::handleContainerOpen(shared_ptr<ContainerOpenPacket> packe } else { - failed = true; + failed = true; } } break; @@ -3115,7 +3110,7 @@ void ClientConnection::handleContainerAck(shared_ptr<ContainerAckPacket> packet) void ClientConnection::handleContainerContent(shared_ptr<ContainerSetContentPacket> packet) { shared_ptr<MultiplayerLocalPlayer> player = minecraft->localplayers[m_userIndex]; - if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) + if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_INVENTORY) { player->inventoryMenu->setAll(&packet->items); } @@ -3195,7 +3190,7 @@ void ClientConnection::handleTileEntityData(shared_ptr<TileEntityDataPacket> pac else if (packet->type == TileEntityDataPacket::TYPE_BEACON && dynamic_pointer_cast<BeaconTileEntity>(te) != NULL) { dynamic_pointer_cast<BeaconTileEntity>(te)->load(packet->tag); - } + } else if (packet->type == TileEntityDataPacket::TYPE_SKULL && dynamic_pointer_cast<SkullTileEntity>(te) != NULL) { dynamic_pointer_cast<SkullTileEntity>(te)->load(packet->tag); @@ -3273,7 +3268,7 @@ void ClientConnection::handleGameEvent(shared_ptr<GameEventPacket> gameEventPack else if (event == GameEventPacket::WIN_GAME) { ui.SetWinUserIndex( (BYTE)gameEventPacket->param ); - + #ifdef _XBOX // turn off the gamertags in splitscreen for the primary player, since they are about to be made fullscreen @@ -3513,7 +3508,7 @@ void ClientConnection::displayPrivilegeChanges(shared_ptr<MultiplayerLocalPlayer case Player::ePlayerGamePrivilege_Invulnerable: if(privOn) message = app.GetString(IDS_PRIV_INVULNERABLE_TOGGLE_ON); else message = app.GetString(IDS_PRIV_INVULNERABLE_TOGGLE_OFF); - break; + break; case Player::ePlayerGamePrivilege_CanToggleInvisible: if(privOn) message = app.GetString(IDS_PRIV_CAN_INVISIBLE_TOGGLE_ON); else message = app.GetString(IDS_PRIV_CAN_INVISIBLE_TOGGLE_OFF); @@ -3587,7 +3582,7 @@ void ClientConnection::handleCustomPayload(shared_ptr<CustomPayloadPacket> custo UIScene_TradingMenu *screen = (UIScene_TradingMenu *)scene; trader = screen->getMerchant(); #endif - + MerchantRecipeList *recipeList = MerchantRecipeList::createFromStream(&input); trader->overrideOffers(recipeList); } @@ -3674,7 +3669,7 @@ int ClientConnection::HostDisconnectReturned(void *pParam,int iPad,C4JStorage::E DLCPack *pDLCPack=pDLCTexPack->getDLCInfoParentPack();//tPack->getDLCPack(); if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) - { + { // no upsell, we're about to quit MinecraftServer::getInstance()->setSaveOnExit( false ); // flag a app action of exit game @@ -3728,7 +3723,7 @@ int ClientConnection::HostDisconnectReturned(void *pParam,int iPad,C4JStorage::E int ClientConnection::ExitGameAndSaveReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { // results switched for this dialog - if(result==C4JStorage::EMessage_ResultDecline) + if(result==C4JStorage::EMessage_ResultDecline) { //INT saveOrCheckpointId = 0; //bool validSave = StorageManager.GetSaveUniqueNumber(&saveOrCheckpointId); @@ -3747,7 +3742,7 @@ int ClientConnection::ExitGameAndSaveReturned(void *pParam,int iPad,C4JStorage:: return 0; } -// +// wstring ClientConnection::GetDisplayNameByGamertag(wstring gamertag) { #ifdef _DURANGO @@ -3892,31 +3887,31 @@ void ClientConnection::handleUpdateAttributes(shared_ptr<UpdateAttributesPacket> if ( !entity->instanceof(eTYPE_LIVINGENTITY) ) { // Entity is not a living entity! - assert(0); + assert(0); } BaseAttributeMap *attributes = (dynamic_pointer_cast<LivingEntity>(entity))->getAttributes(); - unordered_set<UpdateAttributesPacket::AttributeSnapshot *> attributeSnapshots = packet->getValues(); - for (AUTO_VAR(it,attributeSnapshots.begin()); it != attributeSnapshots.end(); ++it) + unordered_set<UpdateAttributesPacket::AttributeSnapshot *> attributeSnapshots = packet->getValues(); + for ( UpdateAttributesPacket::AttributeSnapshot *attribute : attributeSnapshots ) { - UpdateAttributesPacket::AttributeSnapshot *attribute = *it; AttributeInstance *instance = attributes->getInstance(attribute->getId()); - if (instance == NULL) + if (instance) { // 4J - TODO: revisit, not familiar with the attribute system, why are we passing in MIN_NORMAL (Java's smallest non-zero value conforming to IEEE Standard 754 (?)) and MAX_VALUE instance = attributes->registerAttribute(new RangedAttribute(attribute->getId(), 0, Double::MIN_NORMAL, Double::MAX_VALUE)); - } - - instance->setBaseValue(attribute->getBase()); - instance->removeModifiers(); - - unordered_set<AttributeModifier *> *modifiers = attribute->getModifiers(); + instance->setBaseValue(attribute->getBase()); + instance->removeModifiers(); + + unordered_set<AttributeModifier *> *modifiers = attribute->getModifiers(); - for (AUTO_VAR(it2,modifiers->begin()); it2 != modifiers->end(); ++it2) - { - AttributeModifier* modifier = *it2; - instance->addModifier(new AttributeModifier(modifier->getId(), modifier->getAmount(), modifier->getOperation() ) ); + if ( modifiers ) + { + for ( AttributeModifier* modifier : *modifiers ) + { + instance->addModifier(new AttributeModifier(modifier->getId(), modifier->getAmount(), modifier->getOperation())); + } + } } } } diff --git a/Minecraft.Client/Common/Audio/Consoles_SoundEngine.cpp b/Minecraft.Client/Common/Audio/Consoles_SoundEngine.cpp index e440316d..54e9a1ef 100644 --- a/Minecraft.Client/Common/Audio/Consoles_SoundEngine.cpp +++ b/Minecraft.Client/Common/Audio/Consoles_SoundEngine.cpp @@ -42,7 +42,7 @@ void ConsoleSoundEngine::tick() return; } - for(AUTO_VAR(it,scheduledSounds.begin()); it != scheduledSounds.end();) + for (auto it = scheduledSounds.begin(); it != scheduledSounds.end();) { SoundEngine::ScheduledSound *next = *it; next->delay--; diff --git a/Minecraft.Client/Common/Colours/ColourTable.cpp b/Minecraft.Client/Common/Colours/ColourTable.cpp index 5c74d5ec..e4bfe732 100644 --- a/Minecraft.Client/Common/Colours/ColourTable.cpp +++ b/Minecraft.Client/Common/Colours/ColourTable.cpp @@ -355,7 +355,7 @@ void ColourTable::loadColoursFromData(PBYTE pbData, DWORD dwLength) wstring colourId = dis.readUTF(); int colourValue = dis.readInt(); setColour(colourId, colourValue); - AUTO_VAR(it,s_colourNamesMap.find(colourId)); + auto it = s_colourNamesMap.find(colourId); // ? } bais.reset(); @@ -363,7 +363,7 @@ void ColourTable::loadColoursFromData(PBYTE pbData, DWORD dwLength) void ColourTable::setColour(const wstring &colourName, int value) { - AUTO_VAR(it,s_colourNamesMap.find(colourName)); + auto it = s_colourNamesMap.find(colourName); if(it != s_colourNamesMap.end()) { m_colourValues[(int)it->second] = value; diff --git a/Minecraft.Client/Common/Consoles_App.cpp b/Minecraft.Client/Common/Consoles_App.cpp index b476ca90..d17d0678 100644 --- a/Minecraft.Client/Common/Consoles_App.cpp +++ b/Minecraft.Client/Common/Consoles_App.cpp @@ -1475,9 +1475,8 @@ void CMinecraftApp::ActionGameSettings(int iPad,eGameSetting eVal) app.SetXuiServerAction(iPad,eXuiServerAction_ServerSettingChanged_Gamertags); PlayerList *players = MinecraftServer::getInstance()->getPlayerList(); - for(AUTO_VAR(it3, players->players.begin()); it3 != players->players.end(); ++it3) + for( auto& decorationPlayer : players->players ) { - shared_ptr<ServerPlayer> decorationPlayer = *it3; decorationPlayer->setShowOnMaps((app.GetGameHostOption(eGameHostOption_Gamertags)!=0)?true:false); } } @@ -5641,7 +5640,7 @@ bool CMinecraftApp::isXuidNotch(PlayerUID xuid) bool CMinecraftApp::isXuidDeadmau5(PlayerUID xuid) { - AUTO_VAR(it, MojangData.find( xuid )); // 4J Stu - The .at and [] accessors insert elements if they don't exist + auto it = MojangData.find(xuid); // 4J Stu - The .at and [] accessors insert elements if they don't exist if (it != MojangData.end() ) { MOJANG_DATA *pMojangData=MojangData[xuid]; @@ -5659,7 +5658,7 @@ void CMinecraftApp::AddMemoryTextureFile(const wstring &wName,PBYTE pbData,DWORD EnterCriticalSection(&csMemFilesLock); // check it's not already in PMEMDATA pData=NULL; - AUTO_VAR(it, m_MEM_Files.find(wName)); + auto it = m_MEM_Files.find(wName); if(it != m_MEM_Files.end()) { #ifndef _CONTENT_PACKAGE @@ -5704,7 +5703,7 @@ void CMinecraftApp::RemoveMemoryTextureFile(const wstring &wName) { EnterCriticalSection(&csMemFilesLock); - AUTO_VAR(it, m_MEM_Files.find(wName)); + auto it = m_MEM_Files.find(wName); if(it != m_MEM_Files.end()) { #ifndef _CONTENT_PACKAGE @@ -5730,7 +5729,7 @@ bool CMinecraftApp::DefaultCapeExists() bool val = false; EnterCriticalSection(&csMemFilesLock); - AUTO_VAR(it, m_MEM_Files.find(wTex)); + auto it = m_MEM_Files.find(wTex); if(it != m_MEM_Files.end()) val = true; LeaveCriticalSection(&csMemFilesLock); @@ -5742,7 +5741,7 @@ bool CMinecraftApp::IsFileInMemoryTextures(const wstring &wName) bool val = false; EnterCriticalSection(&csMemFilesLock); - AUTO_VAR(it, m_MEM_Files.find(wName)); + auto it = m_MEM_Files.find(wName); if(it != m_MEM_Files.end()) val = true; LeaveCriticalSection(&csMemFilesLock); @@ -5752,7 +5751,7 @@ bool CMinecraftApp::IsFileInMemoryTextures(const wstring &wName) void CMinecraftApp::GetMemFileDetails(const wstring &wName,PBYTE *ppbData,DWORD *pdwBytes) { EnterCriticalSection(&csMemFilesLock); - AUTO_VAR(it, m_MEM_Files.find(wName)); + auto it = m_MEM_Files.find(wName); if(it != m_MEM_Files.end()) { PMEMDATA pData = (*it).second; @@ -5767,7 +5766,7 @@ void CMinecraftApp::AddMemoryTPDFile(int iConfig,PBYTE pbData,DWORD dwBytes) EnterCriticalSection(&csMemTPDLock); // check it's not already in PMEMDATA pData=NULL; - AUTO_VAR(it, m_MEM_TPD.find(iConfig)); + auto it = m_MEM_TPD.find(iConfig); if(it == m_MEM_TPD.end()) { pData = (PMEMDATA)new BYTE[sizeof(MEMDATA)]; @@ -5787,7 +5786,7 @@ void CMinecraftApp::RemoveMemoryTPDFile(int iConfig) EnterCriticalSection(&csMemTPDLock); // check it's not already in PMEMDATA pData=NULL; - AUTO_VAR(it, m_MEM_TPD.find(iConfig)); + auto it = m_MEM_TPD.find(iConfig); if(it != m_MEM_TPD.end()) { pData=m_MEM_TPD[iConfig]; @@ -5844,7 +5843,7 @@ bool CMinecraftApp::IsFileInTPD(int iConfig) bool val = false; EnterCriticalSection(&csMemTPDLock); - AUTO_VAR(it, m_MEM_TPD.find(iConfig)); + auto it = m_MEM_TPD.find(iConfig); if(it != m_MEM_TPD.end()) val = true; LeaveCriticalSection(&csMemTPDLock); @@ -5854,7 +5853,7 @@ bool CMinecraftApp::IsFileInTPD(int iConfig) void CMinecraftApp::GetTPD(int iConfig,PBYTE *ppbData,DWORD *pdwBytes) { EnterCriticalSection(&csMemTPDLock); - AUTO_VAR(it, m_MEM_TPD.find(iConfig)); + auto it = m_MEM_TPD.find(iConfig); if(it != m_MEM_TPD.end()) { PMEMDATA pData = (*it).second; @@ -6989,7 +6988,7 @@ HRESULT CMinecraftApp::RegisterDLCData(eDLCContentType eType, WCHAR *pwchBannerN // check if we already have this info from the local DLC file wstring wsTemp=wchUppercaseProductID; - AUTO_VAR(it, DLCInfo_Full.find(wsTemp)); + auto it = DLCInfo_Full.find(wsTemp); if( it == DLCInfo_Full.end() ) { // Not found @@ -7097,7 +7096,7 @@ HRESULT CMinecraftApp::RegisterDLCData(char *pchDLCName, unsigned int uiSortInde #if defined( __PS3__) || defined(__ORBIS__) || defined(__PSVITA__) bool CMinecraftApp::GetDLCFullOfferIDForSkinID(const wstring &FirstSkin,ULONGLONG *pullVal) { - AUTO_VAR(it, DLCInfo_SkinName.find(FirstSkin)); + auto it = DLCInfo_SkinName.find(FirstSkin); if( it == DLCInfo_SkinName.end() ) { return false; @@ -7110,7 +7109,7 @@ bool CMinecraftApp::GetDLCFullOfferIDForSkinID(const wstring &FirstSkin,ULONGLON } bool CMinecraftApp::GetDLCNameForPackID(const int iPackID,char **ppchKeyID) { - AUTO_VAR(it, DLCTextures_PackID.find(iPackID)); + auto it = DLCTextures_PackID.find(iPackID); if( it == DLCTextures_PackID.end() ) { *ppchKeyID=NULL; @@ -7128,7 +7127,7 @@ DLC_INFO *CMinecraftApp::GetDLCInfo(char *pchDLCName) if(DLCInfo.size()>0) { - AUTO_VAR(it, DLCInfo.find(tempString)); + auto it = DLCInfo.find(tempString); if( it == DLCInfo.end() ) { @@ -7185,7 +7184,7 @@ char *CMinecraftApp::GetDLCInfoTextures(int iIndex) #elif defined _XBOX_ONE bool CMinecraftApp::GetDLCFullOfferIDForSkinID(const wstring &FirstSkin,wstring &ProductId) { - AUTO_VAR(it, DLCInfo_SkinName.find(FirstSkin)); + auto it = DLCInfo_SkinName.find(FirstSkin); if( it == DLCInfo_SkinName.end() ) { return false; @@ -7198,7 +7197,7 @@ bool CMinecraftApp::GetDLCFullOfferIDForSkinID(const wstring &FirstSkin,wstring } bool CMinecraftApp::GetDLCFullOfferIDForPackID(const int iPackID,wstring &ProductId) { - AUTO_VAR(it, DLCTextures_PackID.find(iPackID)); + auto it = DLCTextures_PackID.find(iPackID); if( it == DLCTextures_PackID.end() ) { return false; @@ -7243,7 +7242,7 @@ wstring CMinecraftApp::GetDLCInfoTexturesFullOffer(int iIndex) #else bool CMinecraftApp::GetDLCFullOfferIDForSkinID(const wstring &FirstSkin,ULONGLONG *pullVal) { - AUTO_VAR(it, DLCInfo_SkinName.find(FirstSkin)); + auto it = DLCInfo_SkinName.find(FirstSkin); if( it == DLCInfo_SkinName.end() ) { return false; @@ -7256,15 +7255,15 @@ bool CMinecraftApp::GetDLCFullOfferIDForSkinID(const wstring &FirstSkin,ULONGLON } bool CMinecraftApp::GetDLCFullOfferIDForPackID(const int iPackID,ULONGLONG *pullVal) { - AUTO_VAR(it, DLCTextures_PackID.find(iPackID)); + auto it = DLCTextures_PackID.find(iPackID); if( it == DLCTextures_PackID.end() ) { - *pullVal=(ULONGLONG)0; + *pullVal=0ULL; return false; } else { - *pullVal=(ULONGLONG)it->second; + *pullVal=it->second; return true; } } @@ -7273,7 +7272,7 @@ DLC_INFO *CMinecraftApp::GetDLCInfoForTrialOfferID(ULONGLONG ullOfferID_Trial) //DLC_INFO *pDLCInfo=NULL; if(DLCInfo_Trial.size()>0) { - AUTO_VAR(it, DLCInfo_Trial.find(ullOfferID_Trial)); + auto it = DLCInfo_Trial.find(ullOfferID_Trial); if( it == DLCInfo_Trial.end() ) { @@ -7330,7 +7329,7 @@ DLC_INFO *CMinecraftApp::GetDLCInfoForFullOfferID(WCHAR *pwchProductID) wstring wsTemp = pwchProductID; if(DLCInfo_Full.size()>0) { - AUTO_VAR(it, DLCInfo_Full.find(wsTemp)); + auto it = DLCInfo_Full.find(wsTemp); if( it == DLCInfo_Full.end() ) { @@ -7370,7 +7369,7 @@ DLC_INFO *CMinecraftApp::GetDLCInfoForFullOfferID(ULONGLONG ullOfferID_Full) if(DLCInfo_Full.size()>0) { - AUTO_VAR(it, DLCInfo_Full.find(ullOfferID_Full)); + auto it = DLCInfo_Full.find(ullOfferID_Full); if( it == DLCInfo_Full.end() ) { @@ -7570,9 +7569,8 @@ void CMinecraftApp::AddLevelToBannedLevelList(int iPad, PlayerUID xuid, char *ps DWORD dwDataBytes=(DWORD)(sizeof(BANNEDLISTDATA)*m_vBannedListA[iPad]->size()); PBANNEDLISTDATA pBannedList = (BANNEDLISTDATA *)(new CHAR [dwDataBytes]); int iCount=0; - for(AUTO_VAR(it, m_vBannedListA[iPad]->begin()); it != m_vBannedListA[iPad]->end(); ++it) + for (PBANNEDLISTDATA pData : *m_vBannedListA[iPad] ) { - PBANNEDLISTDATA pData=*it; memcpy(&pBannedList[iCount++],pData,sizeof(BANNEDLISTDATA)); } @@ -7590,9 +7588,8 @@ void CMinecraftApp::AddLevelToBannedLevelList(int iPad, PlayerUID xuid, char *ps bool CMinecraftApp::IsInBannedLevelList(int iPad, PlayerUID xuid, char *pszLevelName) { - for(AUTO_VAR(it, m_vBannedListA[iPad]->begin()); it != m_vBannedListA[iPad]->end(); ++it) + for( PBANNEDLISTDATA pData : *m_vBannedListA[iPad] ) { - PBANNEDLISTDATA pData=*it; #ifdef _XBOX_ONE PlayerUID bannedPlayerUID = pData->wchPlayerUID; if(IsEqualXUID (bannedPlayerUID,xuid) && (strcmp(pData->pszLevelName,pszLevelName)==0)) @@ -7613,7 +7610,7 @@ void CMinecraftApp::RemoveLevelFromBannedLevelList(int iPad, PlayerUID xuid, cha //bool bRes; // we will have retrieved the banned level list from TMS, so remove this one from it and write it back to TMS - for(AUTO_VAR(it, m_vBannedListA[iPad]->begin()); it != m_vBannedListA[iPad]->end(); ) + for (auto it = m_vBannedListA[iPad]->begin(); it != m_vBannedListA[iPad]->end(); ) { PBANNEDLISTDATA pBannedListData = *it; @@ -8321,10 +8318,8 @@ unsigned int CMinecraftApp::CreateImageTextData(PBYTE bTextMetadata, __int64 see void CMinecraftApp::AddTerrainFeaturePosition(_eTerrainFeatureType eFeatureType,int x,int z) { // check we don't already have this in - for(AUTO_VAR(it, m_vTerrainFeatures.begin()); it < m_vTerrainFeatures.end(); ++it) + for( FEATURE_DATA *pFeatureData : m_vTerrainFeatures ) { - FEATURE_DATA *pFeatureData=*it; - if((pFeatureData->eTerrainFeature==eFeatureType) &&(pFeatureData->x==x) && (pFeatureData->z==z)) return; } @@ -8338,10 +8333,8 @@ void CMinecraftApp::AddTerrainFeaturePosition(_eTerrainFeatureType eFeatureType, _eTerrainFeatureType CMinecraftApp::IsTerrainFeature(int x,int z) { - for(AUTO_VAR(it, m_vTerrainFeatures.begin()); it < m_vTerrainFeatures.end(); ++it) + for(FEATURE_DATA *pFeatureData : m_vTerrainFeatures ) { - FEATURE_DATA *pFeatureData=*it; - if((pFeatureData->x==x) && (pFeatureData->z==z)) return pFeatureData->eTerrainFeature; } @@ -8350,10 +8343,8 @@ _eTerrainFeatureType CMinecraftApp::IsTerrainFeature(int x,int z) bool CMinecraftApp::GetTerrainFeaturePosition(_eTerrainFeatureType eType,int *pX, int *pZ) { - for(AUTO_VAR(it, m_vTerrainFeatures.begin()); it < m_vTerrainFeatures.end(); ++it) + for ( const FEATURE_DATA *pFeatureData : m_vTerrainFeatures ) { - FEATURE_DATA *pFeatureData=*it; - if(pFeatureData->eTerrainFeature==eType) { *pX=pFeatureData->x; @@ -8489,10 +8480,8 @@ unsigned int CMinecraftApp::AddDLCRequest(eDLCMarketplaceType eType, bool bPromo // If it's already in there, promote it to the top of the list int iPosition=0; - for(AUTO_VAR(it, m_DLCDownloadQueue.begin()); it != m_DLCDownloadQueue.end(); ++it) + for( DLCRequest *pCurrent : m_DLCDownloadQueue ) { - DLCRequest *pCurrent = *it; - if(pCurrent->dwType==m_dwContentTypeA[eType]) { // already got this in the list @@ -8543,7 +8532,7 @@ unsigned int CMinecraftApp::AddTMSPPFileTypeRequest(eDLCContentType eType, bool bool bPromoted=false; - for(AUTO_VAR(it, m_TMSPPDownloadQueue.begin()); it != m_TMSPPDownloadQueue.end(); ++it) + for ( TMSPPRequest *pCurrent : m_TMSPPDownloadQueue ) { TMSPPRequest *pCurrent = *it; @@ -8601,10 +8590,8 @@ unsigned int CMinecraftApp::AddTMSPPFileTypeRequest(eDLCContentType eType, bool // this may already be present in the vector because of a previous trial/full offer bool bAlreadyInQueue=false; - for(AUTO_VAR(it, m_TMSPPDownloadQueue.begin()); it != m_TMSPPDownloadQueue.end(); ++it) + for( TMSPPRequest *pCurrent : m_TMSPPDownloadQueue ) { - TMSPPRequest *pCurrent = *it; - if(wcscmp(pDLC->wchDataFile,pCurrent->wchFilename)==0) { bAlreadyInQueue=true; @@ -8664,10 +8651,8 @@ unsigned int CMinecraftApp::AddTMSPPFileTypeRequest(eDLCContentType eType, bool if(!bPresent) // retrieve it from TMSPP { bool bAlreadyInQueue=false; - for(AUTO_VAR(it, m_TMSPPDownloadQueue.begin()); it != m_TMSPPDownloadQueue.end(); ++it) + for( TMSPPRequest *pCurrent : m_TMSPPDownloadQueue ) { - TMSPPRequest *pCurrent = *it; - if(wcscmp(pDLC->wchBanner,pCurrent->wchFilename)==0) { bAlreadyInQueue=true; @@ -8721,10 +8706,8 @@ unsigned int CMinecraftApp::AddTMSPPFileTypeRequest(eDLCContentType eType, bool // this may already be present in the vector because of a previous trial/full offer bool bAlreadyInQueue=false; - for(AUTO_VAR(it, m_TMSPPDownloadQueue.begin()); it != m_TMSPPDownloadQueue.end(); ++it) + for( TMSPPRequest *pCurrent : m_TMSPPDownloadQueue ) { - TMSPPRequest *pCurrent = *it; - if(wcscmp(pDLC->wchBanner,pCurrent->wchFilename)==0) { bAlreadyInQueue=true; @@ -8767,10 +8750,8 @@ unsigned int CMinecraftApp::AddTMSPPFileTypeRequest(eDLCContentType eType, bool bool CMinecraftApp::CheckTMSDLCCanStop() { EnterCriticalSection(&csTMSPPDownloadQueue); - for(AUTO_VAR(it, m_TMSPPDownloadQueue.begin()); it != m_TMSPPDownloadQueue.end(); ++it) + for( TMSPPRequest *pCurrent : m_TMSPPDownloadQueue ) { - TMSPPRequest *pCurrent = *it; - if(pCurrent->eState==e_TMS_ContentState_Retrieving) { LeaveCriticalSection(&csTMSPPDownloadQueue); @@ -8796,10 +8777,8 @@ bool CMinecraftApp::RetrieveNextDLCContent() } EnterCriticalSection(&csDLCDownloadQueue); - for(AUTO_VAR(it, m_DLCDownloadQueue.begin()); it != m_DLCDownloadQueue.end(); ++it) + for( const DLCRequest* pCurrent : m_DLCDownloadQueue ) { - DLCRequest *pCurrent = *it; - if(pCurrent->eState==e_DLC_ContentState_Retrieving) { LeaveCriticalSection(&csDLCDownloadQueue); @@ -8808,10 +8787,8 @@ bool CMinecraftApp::RetrieveNextDLCContent() } // Now look for the next retrieval - for(AUTO_VAR(it, m_DLCDownloadQueue.begin()); it != m_DLCDownloadQueue.end(); ++it) + for( DLCRequest *pCurrent : m_DLCDownloadQueue ) { - DLCRequest *pCurrent = *it; - if(pCurrent->eState==e_DLC_ContentState_Idle) { #ifdef _DEBUG @@ -8853,9 +8830,8 @@ int CMinecraftApp::TMSPPFileReturned(LPVOID pParam,int iPad,int iUserData,C4JSto // find the right one in the vector EnterCriticalSection(&pClass->csTMSPPDownloadQueue); - for(AUTO_VAR(it, pClass->m_TMSPPDownloadQueue.begin()); it != pClass->m_TMSPPDownloadQueue.end(); ++it) + for( TMSPPRequest *pCurrent : pClass->m_TMSPPDownloadQueue ) { - TMSPPRequest *pCurrent = *it; #if defined(_XBOX) || defined(_WINDOWS64) char szFile[MAX_TMSFILENAME_SIZE]; wcstombs(szFile,pCurrent->wchFilename,MAX_TMSFILENAME_SIZE); @@ -8956,8 +8932,7 @@ bool CMinecraftApp::RetrieveNextTMSPPContent() if(ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())==false) return false; - EnterCriticalSection(&csTMSPPDownloadQueue); - for(AUTO_VAR(it, m_TMSPPDownloadQueue.begin()); it != m_TMSPPDownloadQueue.end(); ++it) + for( TMSPPRequest *pCurrent : m_TMSPPDownloadQueue ) { TMSPPRequest *pCurrent = *it; @@ -8970,7 +8945,7 @@ bool CMinecraftApp::RetrieveNextTMSPPContent() } // Now look for the next retrieval - for(AUTO_VAR(it, m_TMSPPDownloadQueue.begin()); it != m_TMSPPDownloadQueue.end(); ++it) + for( TMSPPRequest *pCurrent : m_TMSPPDownloadQueue ) { TMSPPRequest *pCurrent = *it; @@ -9074,11 +9049,10 @@ void CMinecraftApp::ClearAndResetDLCDownloadQueue() int iPosition=0; EnterCriticalSection(&csTMSPPDownloadQueue); - for(AUTO_VAR(it, m_DLCDownloadQueue.begin()); it != m_DLCDownloadQueue.end(); ++it) + for( DLCRequest *pCurrent : m_DLCDownloadQueue ) { - DLCRequest *pCurrent = *it; - - delete pCurrent; + if ( pCurrent ) + delete pCurrent; iPosition++; } m_DLCDownloadQueue.clear(); @@ -9100,11 +9074,10 @@ void CMinecraftApp::ClearTMSPPFilesRetrieved() { int iPosition=0; EnterCriticalSection(&csTMSPPDownloadQueue); - for(AUTO_VAR(it, m_TMSPPDownloadQueue.begin()); it != m_TMSPPDownloadQueue.end(); ++it) + for ( TMSPPRequest *pCurrent : m_TMSPPDownloadQueue ) { - TMSPPRequest *pCurrent = *it; - - delete pCurrent; + if ( pCurrent ) + delete pCurrent; iPosition++; } m_TMSPPDownloadQueue.clear(); @@ -9118,10 +9091,8 @@ int CMinecraftApp::DLCOffersReturned(void *pParam, int iOfferC, DWORD dwType, in // find the right one in the vector EnterCriticalSection(&pClass->csTMSPPDownloadQueue); - for(AUTO_VAR(it, pClass->m_DLCDownloadQueue.begin()); it != pClass->m_DLCDownloadQueue.end(); ++it) + for( DLCRequest *pCurrent : pClass->m_DLCDownloadQueue ) { - DLCRequest *pCurrent = *it; - // avatar items are coming back as type Content, so we can't trust the type setting if(pCurrent->dwType==dwType) { @@ -9151,10 +9122,8 @@ bool CMinecraftApp::DLCContentRetrieved(eDLCMarketplaceType eType) // If there's already a retrieve in progress, quit // we may have re-ordered the list, so need to check every item EnterCriticalSection(&csDLCDownloadQueue); - for(AUTO_VAR(it, m_DLCDownloadQueue.begin()); it != m_DLCDownloadQueue.end(); ++it) + for( DLCRequest *pCurrent : m_DLCDownloadQueue ) { - DLCRequest *pCurrent = *it; - if((pCurrent->dwType==m_dwContentTypeA[eType]) && (pCurrent->eState==e_DLC_ContentState_Retrieved)) { LeaveCriticalSection(&csDLCDownloadQueue); @@ -9208,17 +9177,17 @@ vector<ModelPart *> * CMinecraftApp::SetAdditionalSkinBoxes(DWORD dwSkinID, vect app.DebugPrintf("*** SetAdditionalSkinBoxes - Inserting model parts for skin %d from array of Skin Boxes\n",dwSkinID&0x0FFFFFFF); // convert the skin boxes into model parts, and add to the humanoid model - for(AUTO_VAR(it, pvSkinBoxA->begin());it != pvSkinBoxA->end(); ++it) + for( auto& it : *pvSkinBoxA ) { if(pModel) { - ModelPart *pModelPart=pModel->AddOrRetrievePart(*it); + ModelPart *pModelPart=pModel->AddOrRetrievePart(it); pvModelPart->push_back(pModelPart); } } - m_AdditionalModelParts.insert( std::pair<DWORD, vector<ModelPart *> *>(dwSkinID, pvModelPart) ); - m_AdditionalSkinBoxes.insert( std::pair<DWORD, vector<SKIN_BOX *> *>(dwSkinID, pvSkinBoxA) ); + m_AdditionalModelParts.emplace(dwSkinID, pvModelPart); + m_AdditionalSkinBoxes.emplace(dwSkinID, pvSkinBoxA); LeaveCriticalSection( &csAdditionalSkinBoxes ); LeaveCriticalSection( &csAdditionalModelParts ); @@ -9232,7 +9201,7 @@ vector<ModelPart *> *CMinecraftApp::GetAdditionalModelParts(DWORD dwSkinID) vector<ModelPart *> *pvModelParts=NULL; if(m_AdditionalModelParts.size()>0) { - AUTO_VAR(it, m_AdditionalModelParts.find(dwSkinID)); + auto it = m_AdditionalModelParts.find(dwSkinID); if(it!=m_AdditionalModelParts.end()) { pvModelParts = (*it).second; @@ -9249,7 +9218,7 @@ vector<SKIN_BOX *> *CMinecraftApp::GetAdditionalSkinBoxes(DWORD dwSkinID) vector<SKIN_BOX *> *pvSkinBoxes=NULL; if(m_AdditionalSkinBoxes.size()>0) { - AUTO_VAR(it,m_AdditionalSkinBoxes.find(dwSkinID)); + auto it = m_AdditionalSkinBoxes.find(dwSkinID); if(it!=m_AdditionalSkinBoxes.end()) { pvSkinBoxes = (*it).second; @@ -9267,7 +9236,7 @@ unsigned int CMinecraftApp::GetAnimOverrideBitmask(DWORD dwSkinID) if(m_AnimOverrides.size()>0) { - AUTO_VAR(it, m_AnimOverrides.find(dwSkinID)); + auto it = m_AnimOverrides.find(dwSkinID); if(it!=m_AnimOverrides.end()) { uiAnimOverrideBitmask = (*it).second; @@ -9285,7 +9254,7 @@ void CMinecraftApp::SetAnimOverrideBitmask(DWORD dwSkinID,unsigned int uiAnimOve if(m_AnimOverrides.size()>0) { - AUTO_VAR(it, m_AnimOverrides.find(dwSkinID)); + auto it = m_AnimOverrides.find(dwSkinID); if(it!=m_AnimOverrides.end()) { LeaveCriticalSection( &csAnimOverrideBitmask ); diff --git a/Minecraft.Client/Common/DLC/DLCAudioFile.cpp b/Minecraft.Client/Common/DLC/DLCAudioFile.cpp index 49ba52cd..6faf0c3b 100644 --- a/Minecraft.Client/Common/DLC/DLCAudioFile.cpp +++ b/Minecraft.Client/Common/DLC/DLCAudioFile.cpp @@ -178,7 +178,7 @@ bool DLCAudioFile::processDLCDataFile(PBYTE pbData, DWORD dwLength) { //EAudioParameterType paramType = e_AudioParamType_Invalid; - AUTO_VAR(it, parameterMapping.find( pParams->dwType )); + auto it = parameterMapping.find(pParams->dwType); if(it != parameterMapping.end() ) { diff --git a/Minecraft.Client/Common/DLC/DLCManager.cpp b/Minecraft.Client/Common/DLC/DLCManager.cpp index 17c9fc6d..36f4d7f7 100644 --- a/Minecraft.Client/Common/DLC/DLCManager.cpp +++ b/Minecraft.Client/Common/DLC/DLCManager.cpp @@ -32,10 +32,10 @@ DLCManager::DLCManager() DLCManager::~DLCManager() { - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for ( DLCPack *pack : m_packs ) { - DLCPack *pack = *it; - delete pack; + if ( pack ) + delete pack; } } @@ -60,10 +60,9 @@ DWORD DLCManager::getPackCount(EDLCType type /*= e_DLCType_All*/) DWORD packCount = 0; if( type != e_DLCType_All ) { - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *pack : m_packs ) { - DLCPack *pack = *it; - if( pack->getDLCItemsCount(type) > 0 ) + if( pack && pack->getDLCItemsCount(type) > 0 ) { ++packCount; } @@ -85,7 +84,7 @@ void DLCManager::removePack(DLCPack *pack) { if(pack != NULL) { - AUTO_VAR(it, find(m_packs.begin(),m_packs.end(),pack)); + auto it = find(m_packs.begin(), m_packs.end(), pack); if(it != m_packs.end() ) m_packs.erase(it); delete pack; } @@ -93,10 +92,10 @@ void DLCManager::removePack(DLCPack *pack) void DLCManager::removeAllPacks(void) { - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *pack : m_packs ) { - DLCPack *pack = (DLCPack *)*it; - delete pack; + if ( pack ) + delete pack; } m_packs.clear(); @@ -104,23 +103,19 @@ void DLCManager::removeAllPacks(void) void DLCManager::LanguageChanged(void) { - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *pack : m_packs ) { - DLCPack *pack = (DLCPack *)*it; // update the language pack->UpdateLanguage(); } - } DLCPack *DLCManager::getPack(const wstring &name) { DLCPack *pack = NULL; //DWORD currentIndex = 0; - DLCPack *currentPack = NULL; - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack * currentPack : m_packs ) { - currentPack = *it; wstring wsName=currentPack->getName(); if(wsName.compare(name) == 0) @@ -136,11 +131,8 @@ DLCPack *DLCManager::getPack(const wstring &name) DLCPack *DLCManager::getPackFromProductID(const wstring &productID) { DLCPack *pack = NULL; - //DWORD currentIndex = 0; - DLCPack *currentPack = NULL; - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *currentPack : m_packs ) { - currentPack = *it; wstring wsName=currentPack->getPurchaseOfferId(); if(wsName.compare(productID) == 0) @@ -159,10 +151,8 @@ DLCPack *DLCManager::getPack(DWORD index, EDLCType type /*= e_DLCType_All*/) if( type != e_DLCType_All ) { DWORD currentIndex = 0; - DLCPack *currentPack = NULL; - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *currentPack : m_packs ) { - currentPack = *it; if(currentPack->getDLCItemsCount(type)>0) { if(currentIndex == index) @@ -200,9 +190,8 @@ DWORD DLCManager::getPackIndex(DLCPack *pack, bool &found, EDLCType type /*= e_D if( type != e_DLCType_All ) { DWORD index = 0; - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *thisPack : m_packs ) { - DLCPack *thisPack = *it; if(thisPack->getDLCItemsCount(type)>0) { if(thisPack == pack) @@ -218,9 +207,8 @@ DWORD DLCManager::getPackIndex(DLCPack *pack, bool &found, EDLCType type /*= e_D else { DWORD index = 0; - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *thisPack : m_packs ) { - DLCPack *thisPack = *it; if(thisPack == pack) { found = true; @@ -238,9 +226,8 @@ DWORD DLCManager::getPackIndexContainingSkin(const wstring &path, bool &found) DWORD foundIndex = 0; found = false; DWORD index = 0; - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *pack : m_packs ) { - DLCPack *pack = *it; if(pack->getDLCItemsCount(e_DLCType_Skin)>0) { if(pack->doesPackContainSkin(path)) @@ -258,9 +245,8 @@ DWORD DLCManager::getPackIndexContainingSkin(const wstring &path, bool &found) DLCPack *DLCManager::getPackContainingSkin(const wstring &path) { DLCPack *foundPack = NULL; - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *pack : m_packs ) { - DLCPack *pack = *it; if(pack->getDLCItemsCount(e_DLCType_Skin)>0) { if(pack->doesPackContainSkin(path)) @@ -276,9 +262,8 @@ DLCPack *DLCManager::getPackContainingSkin(const wstring &path) DLCSkinFile *DLCManager::getSkinFile(const wstring &path) { DLCSkinFile *foundSkinfile = NULL; - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *pack : m_packs ) { - DLCPack *pack = *it; foundSkinfile=pack->getSkinFile(path); if(foundSkinfile!=NULL) { @@ -291,12 +276,10 @@ DLCSkinFile *DLCManager::getSkinFile(const wstring &path) DWORD DLCManager::checkForCorruptDLCAndAlert(bool showMessage /*= true*/) { DWORD corruptDLCCount = m_dwUnnamedCorruptDLCCount; - DLCPack *pack = NULL; DLCPack *firstCorruptPack = NULL; - for(AUTO_VAR(it, m_packs.begin()); it != m_packs.end(); ++it) + for( DLCPack *pack : m_packs ) { - pack = *it; if( pack->IsCorrupt() ) { ++corruptDLCCount; @@ -468,7 +451,7 @@ bool DLCManager::processDLCDataFile(DWORD &dwFilesProcessed, PBYTE pbData, DWORD { //DLCManager::EDLCParameterType paramType = DLCManager::e_DLCParamType_Invalid; - AUTO_VAR(it, parameterMapping.find( pParams->dwType )); + auto it = parameterMapping.find(pParams->dwType); if(it != parameterMapping.end() ) { @@ -658,7 +641,7 @@ DWORD DLCManager::retrievePackID(PBYTE pbData, DWORD dwLength, DLCPack *pack) pParams = (C4JStorage::DLC_FILE_PARAM *)pbTemp; for(unsigned int j=0;j<uiParameterCount;j++) { - AUTO_VAR(it, parameterMapping.find( pParams->dwType )); + auto it = parameterMapping.find(pParams->dwType); if(it != parameterMapping.end() ) { diff --git a/Minecraft.Client/Common/DLC/DLCPack.cpp b/Minecraft.Client/Common/DLC/DLCPack.cpp index 4a003d05..ea8a270f 100644 --- a/Minecraft.Client/Common/DLC/DLCPack.cpp +++ b/Minecraft.Client/Common/DLC/DLCPack.cpp @@ -54,16 +54,18 @@ DLCPack::DLCPack(const wstring &name,const wstring &productID,DWORD dwLicenseMas DLCPack::~DLCPack() { - for(AUTO_VAR(it, m_childPacks.begin()); it != m_childPacks.end(); ++it) + for( auto& it : m_childPacks ) { - delete *it; + if ( it ) + delete it; } for(unsigned int i = 0; i < DLCManager::e_DLCType_Max; ++i) { - for(AUTO_VAR(it,m_files[i].begin()); it != m_files[i].end(); ++it) + for (auto& it : m_files[i] ) { - delete *it; + if ( it ) + delete it; } } @@ -161,7 +163,7 @@ void DLCPack::addParameter(DLCManager::EDLCParameterType type, const wstring &va bool DLCPack::getParameterAsUInt(DLCManager::EDLCParameterType type, unsigned int ¶m) { - AUTO_VAR(it,m_parameters.find((int)type)); + auto it = m_parameters.find((int)type); if(it != m_parameters.end()) { switch(type) @@ -270,7 +272,7 @@ bool DLCPack::doesPackContainFile(DLCManager::EDLCType type, const wstring &path else { g_pathCmpString = &path; - AUTO_VAR(it, find_if( m_files[type].begin(), m_files[type].end(), pathCmp )); + auto it = find_if(m_files[type].begin(), m_files[type].end(), pathCmp); hasFile = it != m_files[type].end(); if(!hasFile && m_parentPack ) { @@ -316,7 +318,7 @@ DLCFile *DLCPack::getFile(DLCManager::EDLCType type, const wstring &path) else { g_pathCmpString = &path; - AUTO_VAR(it, find_if( m_files[type].begin(), m_files[type].end(), pathCmp )); + auto it = find_if(m_files[type].begin(), m_files[type].end(), pathCmp); if(it == m_files[type].end()) { @@ -368,9 +370,9 @@ DWORD DLCPack::getFileIndexAt(DLCManager::EDLCType type, const wstring &path, bo DWORD foundIndex = 0; found = false; DWORD index = 0; - for(AUTO_VAR(it, m_files[type].begin()); it != m_files[type].end(); ++it) + for( auto& it : m_files[type] ) { - if(path.compare((*it)->getPath()) == 0) + if(path.compare(it->getPath()) == 0) { foundIndex = index; found = true; diff --git a/Minecraft.Client/Common/GameRules/AddEnchantmentRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/AddEnchantmentRuleDefinition.cpp index eabc1401..555ed8b4 100644 --- a/Minecraft.Client/Common/GameRules/AddEnchantmentRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/AddEnchantmentRuleDefinition.cpp @@ -14,10 +14,10 @@ void AddEnchantmentRuleDefinition::writeAttributes(DataOutputStream *dos, UINT n GameRuleDefinition::writeAttributes(dos, numAttributes + 2); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_enchantmentId); - dos->writeUTF( _toString( m_enchantmentId ) ); + dos->writeUTF( std::to_wstring( m_enchantmentId ) ); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_enchantmentLevel); - dos->writeUTF( _toString( m_enchantmentLevel ) ); + dos->writeUTF( std::to_wstring( m_enchantmentLevel ) ); } void AddEnchantmentRuleDefinition::addAttribute(const wstring &attributeName, const wstring &attributeValue) @@ -50,7 +50,7 @@ bool AddEnchantmentRuleDefinition::enchantItem(shared_ptr<ItemInstance> item) { // 4J-JEV: Ripped code from enchantmenthelpers // Maybe we want to add an addEnchantment method to EnchantmentHelpers - if (item->id == Item::enchantedBook_Id) + if (item->id == Item::enchantedBook_Id) { Item::enchantedBook->addEnchantment( item, new EnchantmentInstance(m_enchantmentId, m_enchantmentLevel) ); } diff --git a/Minecraft.Client/Common/GameRules/AddItemRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/AddItemRuleDefinition.cpp index 0d14884a..801a2937 100644 --- a/Minecraft.Client/Common/GameRules/AddItemRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/AddItemRuleDefinition.cpp @@ -17,26 +17,26 @@ void AddItemRuleDefinition::writeAttributes(DataOutputStream *dos, UINT numAttrs GameRuleDefinition::writeAttributes(dos, numAttrs + 5); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_itemId); - dos->writeUTF( _toString( m_itemId ) ); + dos->writeUTF( std::to_wstring( m_itemId ) ); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_quantity); - dos->writeUTF( _toString( m_quantity ) ); + dos->writeUTF( std::to_wstring( m_quantity ) ); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_auxValue); - dos->writeUTF( _toString( m_auxValue ) ); + dos->writeUTF( std::to_wstring( m_auxValue ) ); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_dataTag); - dos->writeUTF( _toString( m_dataTag ) ); + dos->writeUTF( std::to_wstring( m_dataTag ) ); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_slot); - dos->writeUTF( _toString( m_slot ) ); + dos->writeUTF( std::to_wstring( m_slot ) ); } void AddItemRuleDefinition::getChildren(vector<GameRuleDefinition *> *children) { GameRuleDefinition::getChildren( children ); - for (AUTO_VAR(it, m_enchantments.begin()); it != m_enchantments.end(); it++) - children->push_back( *it ); + for ( const auto& it : m_enchantments ) + children->push_back( it ); } GameRuleDefinition *AddItemRuleDefinition::addChild(ConsoleGameRules::EGameRuleType ruleType) @@ -99,13 +99,13 @@ bool AddItemRuleDefinition::addItemToContainer(shared_ptr<Container> container, bool added = false; if(Item::items[m_itemId] != NULL) { - int quantity = min(m_quantity, Item::items[m_itemId]->getMaxStackSize()); + int quantity = std::min<int>(m_quantity, Item::items[m_itemId]->getMaxStackSize()); shared_ptr<ItemInstance> newItem = shared_ptr<ItemInstance>(new ItemInstance(m_itemId,quantity,m_auxValue) ); newItem->set4JData(m_dataTag); - for(AUTO_VAR(it, m_enchantments.begin()); it != m_enchantments.end(); ++it) + for( auto& it : m_enchantments ) { - (*it)->enchantItem(newItem); + it->enchantItem(newItem); } if(m_slot >= 0 && m_slot < container->getContainerSize() ) diff --git a/Minecraft.Client/Common/GameRules/ApplySchematicRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/ApplySchematicRuleDefinition.cpp index aa4a8fb2..a740a2be 100644 --- a/Minecraft.Client/Common/GameRules/ApplySchematicRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/ApplySchematicRuleDefinition.cpp @@ -37,19 +37,19 @@ void ApplySchematicRuleDefinition::writeAttributes(DataOutputStream *dos, UINT n ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_filename); dos->writeUTF(m_schematicName); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_x); - dos->writeUTF(_toString(m_location->x)); + dos->writeUTF(std::to_wstring(m_location->x)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_y); - dos->writeUTF(_toString(m_location->y)); + dos->writeUTF(std::to_wstring(m_location->y)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_z); - dos->writeUTF(_toString(m_location->z)); + dos->writeUTF(std::to_wstring(m_location->z)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_rot); switch (m_rotation) { - case ConsoleSchematicFile::eSchematicRot_0: dos->writeUTF(_toString( 0 )); break; - case ConsoleSchematicFile::eSchematicRot_90: dos->writeUTF(_toString( 90 )); break; - case ConsoleSchematicFile::eSchematicRot_180: dos->writeUTF(_toString( 180 )); break; - case ConsoleSchematicFile::eSchematicRot_270: dos->writeUTF(_toString( 270 )); break; + case ConsoleSchematicFile::eSchematicRot_0: dos->writeUTF(L"0"); break; + case ConsoleSchematicFile::eSchematicRot_90: dos->writeUTF(L"90"); break; + case ConsoleSchematicFile::eSchematicRot_180: dos->writeUTF(L"180"); break; + case ConsoleSchematicFile::eSchematicRot_270: dos->writeUTF(L"270"); break; } } @@ -113,7 +113,7 @@ void ApplySchematicRuleDefinition::addAttribute(const wstring &attributeName, co m_rotation = ConsoleSchematicFile::eSchematicRot_0; break; }; - + //app.DebugPrintf("ApplySchematicRuleDefinition: Adding parameter rot=%d\n",m_rotation); } else if(attributeName.compare(L"dim") == 0) @@ -160,7 +160,7 @@ void ApplySchematicRuleDefinition::processSchematic(AABB *chunkBox, LevelChunk * { if( m_completed ) return; if(chunk->level->dimension->id != m_dimension) return; - + PIXBeginNamedEvent(0, "Processing ApplySchematicRuleDefinition"); if(m_schematic == NULL) m_schematic = m_levelGenOptions->getSchematicFile(m_schematicName); @@ -199,7 +199,7 @@ void ApplySchematicRuleDefinition::processSchematicLighting(AABB *chunkBox, Leve { if( m_completed ) return; if(chunk->level->dimension->id != m_dimension) return; - + PIXBeginNamedEvent(0, "Processing ApplySchematicRuleDefinition (lighting)"); if(m_schematic == NULL) m_schematic = m_levelGenOptions->getSchematicFile(m_schematicName); diff --git a/Minecraft.Client/Common/GameRules/BiomeOverride.cpp b/Minecraft.Client/Common/GameRules/BiomeOverride.cpp index 22cc0c7a..155a6e2d 100644 --- a/Minecraft.Client/Common/GameRules/BiomeOverride.cpp +++ b/Minecraft.Client/Common/GameRules/BiomeOverride.cpp @@ -14,11 +14,11 @@ void BiomeOverride::writeAttributes(DataOutputStream *dos, UINT numAttrs) GameRuleDefinition::writeAttributes(dos, numAttrs + 3); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_biomeId); - dos->writeUTF(_toString(m_biomeId)); + dos->writeUTF(std::to_wstring(m_biomeId)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_tileId); - dos->writeUTF(_toString(m_tile)); + dos->writeUTF(std::to_wstring(m_tile)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_topTileId); - dos->writeUTF(_toString(m_topTile)); + dos->writeUTF(std::to_wstring(m_topTile)); } void BiomeOverride::addAttribute(const wstring &attributeName, const wstring &attributeValue) diff --git a/Minecraft.Client/Common/GameRules/CollectItemRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/CollectItemRuleDefinition.cpp index 66abefbb..f3b48445 100644 --- a/Minecraft.Client/Common/GameRules/CollectItemRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/CollectItemRuleDefinition.cpp @@ -22,13 +22,13 @@ void CollectItemRuleDefinition::writeAttributes(DataOutputStream *dos, UINT numA GameRuleDefinition::writeAttributes(dos, numAttributes + 3); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_itemId); - dos->writeUTF( _toString( m_itemId ) ); + dos->writeUTF( std::to_wstring( m_itemId ) ); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_auxValue); - dos->writeUTF( _toString( m_auxValue ) ); + dos->writeUTF( std::to_wstring( m_auxValue ) ); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_quantity); - dos->writeUTF( _toString( m_quantity ) ); + dos->writeUTF( std::to_wstring( m_quantity ) ); } void CollectItemRuleDefinition::addAttribute(const wstring &attributeName, const wstring &attributeValue) @@ -108,9 +108,9 @@ wstring CollectItemRuleDefinition::generateXml(shared_ptr<ItemInstance> item) wstring xml = L""; if(item != NULL) { - xml = L"<CollectItemRule itemId=\"" + _toString<int>(item->id) + L"\" quantity=\"SET\" descriptionName=\"OPTIONAL\" promptName=\"OPTIONAL\""; - if(item->getAuxValue() != 0) xml += L" auxValue=\"" + _toString<int>(item->getAuxValue()) + L"\""; - if(item->get4JData() != 0) xml += L" dataTag=\"" + _toString<int>(item->get4JData()) + L"\""; + xml = L"<CollectItemRule itemId=\"" + std::to_wstring(item->id) + L"\" quantity=\"SET\" descriptionName=\"OPTIONAL\" promptName=\"OPTIONAL\""; + if(item->getAuxValue() != 0) xml += L" auxValue=\"" + std::to_wstring(item->getAuxValue()) + L"\""; + if(item->get4JData() != 0) xml += L" dataTag=\"" + std::to_wstring(item->get4JData()) + L"\""; xml += L"/>\n"; } return xml; diff --git a/Minecraft.Client/Common/GameRules/CompleteAllRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/CompleteAllRuleDefinition.cpp index adaf70c8..b928b26c 100644 --- a/Minecraft.Client/Common/GameRules/CompleteAllRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/CompleteAllRuleDefinition.cpp @@ -28,12 +28,12 @@ void CompleteAllRuleDefinition::updateStatus(GameRule *rule) { int goal = 0; int progress = 0; - for(AUTO_VAR(it, rule->m_parameters.begin()); it != rule->m_parameters.end(); ++it) + for (auto& it : rule->m_parameters ) { - if(it->second.isPointer) + if(it.second.isPointer) { - goal += it->second.gr->getGameRuleDefinition()->getGoal(); - progress += it->second.gr->getGameRuleDefinition()->getProgress(it->second.gr); + goal += it.second.gr->getGameRuleDefinition()->getGoal(); + progress += it.second.gr->getGameRuleDefinition()->getProgress(it.second.gr); } } if(rule->getConnection() != NULL) @@ -44,9 +44,9 @@ void CompleteAllRuleDefinition::updateStatus(GameRule *rule) int icon = -1; int auxValue = 0; - + if(m_lastRuleStatusChanged != NULL) - { + { icon = m_lastRuleStatusChanged->getIcon(); auxValue = m_lastRuleStatusChanged->getAuxValue(); m_lastRuleStatusChanged = NULL; @@ -60,7 +60,7 @@ wstring CompleteAllRuleDefinition::generateDescriptionString(const wstring &desc { PacketData *values = (PacketData *)data; wstring newDesc = description; - newDesc = replaceAll(newDesc,L"{*progress*}",_toString<int>(values->progress)); - newDesc = replaceAll(newDesc,L"{*goal*}",_toString<int>(values->goal)); + newDesc = replaceAll(newDesc,L"{*progress*}",std::to_wstring(values->progress)); + newDesc = replaceAll(newDesc,L"{*goal*}",std::to_wstring(values->goal)); return newDesc; }
\ No newline at end of file diff --git a/Minecraft.Client/Common/GameRules/CompoundGameRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/CompoundGameRuleDefinition.cpp index 0481a54b..395b4eeb 100644 --- a/Minecraft.Client/Common/GameRules/CompoundGameRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/CompoundGameRuleDefinition.cpp @@ -11,17 +11,17 @@ CompoundGameRuleDefinition::CompoundGameRuleDefinition() CompoundGameRuleDefinition::~CompoundGameRuleDefinition() { - for(AUTO_VAR(it, m_children.begin()); it != m_children.end(); ++it) + for (auto it : m_children ) { - delete (*it); + delete it; } } void CompoundGameRuleDefinition::getChildren(vector<GameRuleDefinition *> *children) { GameRuleDefinition::getChildren(children); - for (AUTO_VAR(it, m_children.begin()); it != m_children.end(); it++) - children->push_back(*it); + for (auto& it : m_children ) + children->push_back(it); } GameRuleDefinition *CompoundGameRuleDefinition::addChild(ConsoleGameRules::EGameRuleType ruleType) @@ -40,7 +40,7 @@ GameRuleDefinition *CompoundGameRuleDefinition::addChild(ConsoleGameRules::EGame rule = new UseTileRuleDefinition(); } else if(ruleType == ConsoleGameRules::eGameRuleType_UpdatePlayerRule) - { + { rule = new UpdatePlayerRuleDefinition(); } else @@ -57,17 +57,17 @@ void CompoundGameRuleDefinition::populateGameRule(GameRulesInstance::EGameRulesI { GameRule *newRule = NULL; int i = 0; - for(AUTO_VAR(it, m_children.begin()); it != m_children.end(); ++it) + for (auto& it : m_children ) { - newRule = new GameRule(*it, rule->getConnection() ); - (*it)->populateGameRule(type,newRule); + newRule = new GameRule(it, rule->getConnection() ); + it->populateGameRule(type,newRule); GameRule::ValueType value; value.gr = newRule; value.isPointer = true; // Somehow add the newRule to the current rule - rule->setParameter(L"rule" + _toString<int>(i),value); + rule->setParameter(L"rule" + std::to_wstring(i),value); ++i; } GameRuleDefinition::populateGameRule(type, rule); @@ -76,14 +76,14 @@ void CompoundGameRuleDefinition::populateGameRule(GameRulesInstance::EGameRulesI bool CompoundGameRuleDefinition::onUseTile(GameRule *rule, int tileId, int x, int y, int z) { bool statusChanged = false; - for(AUTO_VAR(it, rule->m_parameters.begin()); it != rule->m_parameters.end(); ++it) + for (auto& it : rule->m_parameters ) { - if(it->second.isPointer) + if(it.second.isPointer) { - bool changed = it->second.gr->getGameRuleDefinition()->onUseTile(it->second.gr,tileId,x,y,z); + bool changed = it.second.gr->getGameRuleDefinition()->onUseTile(it.second.gr,tileId,x,y,z); if(!statusChanged && changed) { - m_lastRuleStatusChanged = it->second.gr->getGameRuleDefinition(); + m_lastRuleStatusChanged = it.second.gr->getGameRuleDefinition(); statusChanged = true; } } @@ -94,14 +94,14 @@ bool CompoundGameRuleDefinition::onUseTile(GameRule *rule, int tileId, int x, in bool CompoundGameRuleDefinition::onCollectItem(GameRule *rule, shared_ptr<ItemInstance> item) { bool statusChanged = false; - for(AUTO_VAR(it, rule->m_parameters.begin()); it != rule->m_parameters.end(); ++it) + for (auto& it : rule->m_parameters ) { - if(it->second.isPointer) + if(it.second.isPointer) { - bool changed = it->second.gr->getGameRuleDefinition()->onCollectItem(it->second.gr,item); + bool changed = it.second.gr->getGameRuleDefinition()->onCollectItem(it.second.gr,item); if(!statusChanged && changed) - { - m_lastRuleStatusChanged = it->second.gr->getGameRuleDefinition(); + { + m_lastRuleStatusChanged = it.second.gr->getGameRuleDefinition(); statusChanged = true; } } @@ -111,8 +111,8 @@ bool CompoundGameRuleDefinition::onCollectItem(GameRule *rule, shared_ptr<ItemIn void CompoundGameRuleDefinition::postProcessPlayer(shared_ptr<Player> player) { - for(AUTO_VAR(it, m_children.begin()); it != m_children.end(); ++it) + for (auto it : m_children ) { - (*it)->postProcessPlayer(player); + it->postProcessPlayer(player); } }
\ No newline at end of file diff --git a/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.cpp b/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.cpp index 0476b0e3..f505ce7a 100644 --- a/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.cpp +++ b/Minecraft.Client/Common/GameRules/ConsoleGenerateStructure.cpp @@ -17,10 +17,10 @@ ConsoleGenerateStructure::ConsoleGenerateStructure() : StructurePiece(0) void ConsoleGenerateStructure::getChildren(vector<GameRuleDefinition *> *children) { - GameRuleDefinition::getChildren(children); - - for(AUTO_VAR(it, m_actions.begin()); it != m_actions.end(); it++) - children->push_back( *it ); + GameRuleDefinition::getChildren(children); + + for ( auto& action : m_actions ) + children->push_back( action ); } GameRuleDefinition *ConsoleGenerateStructure::addChild(ConsoleGameRules::EGameRuleType ruleType) @@ -60,16 +60,16 @@ void ConsoleGenerateStructure::writeAttributes(DataOutputStream *dos, UINT numAt GameRuleDefinition::writeAttributes(dos, numAttrs + 5); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_x); - dos->writeUTF(_toString(m_x)); + dos->writeUTF(std::to_wstring(m_x)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_y); - dos->writeUTF(_toString(m_y)); + dos->writeUTF(std::to_wstring(m_y)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_z); - dos->writeUTF(_toString(m_z)); + dos->writeUTF(std::to_wstring(m_z)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_orientation); - dos->writeUTF(_toString(orientation)); + dos->writeUTF(std::to_wstring(orientation)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_dimension); - dos->writeUTF(_toString(m_dimension)); + dos->writeUTF(std::to_wstring(m_dimension)); } void ConsoleGenerateStructure::addAttribute(const wstring &attributeName, const wstring &attributeValue) @@ -117,27 +117,24 @@ BoundingBox* ConsoleGenerateStructure::getBoundingBox() // Find the max bounds int maxX, maxY, maxZ; maxX = maxY = maxZ = 1; - for(AUTO_VAR(it, m_actions.begin()); it != m_actions.end(); ++it) + for( ConsoleGenerateStructureAction *action : m_actions ) { - ConsoleGenerateStructureAction *action = *it; - maxX = max(maxX,action->getEndX()); - maxY = max(maxY,action->getEndY()); - maxZ = max(maxZ,action->getEndZ()); + maxX = std::max<int>(maxX,action->getEndX()); + maxY = std::max<int>(maxY,action->getEndY()); + maxZ = std::max<int>(maxZ,action->getEndZ()); } - + boundingBox = new BoundingBox(m_x, m_y, m_z, m_x + maxX, m_y + maxY, m_z + maxZ); } return boundingBox; } bool ConsoleGenerateStructure::postProcess(Level *level, Random *random, BoundingBox *chunkBB) -{ +{ if(level->dimension->id != m_dimension) return false; - for(AUTO_VAR(it, m_actions.begin()); it != m_actions.end(); ++it) + for( ConsoleGenerateStructureAction *action : m_actions ) { - ConsoleGenerateStructureAction *action = *it; - switch(action->getActionType()) { case ConsoleGameRules::eGameRuleType_GenerateBox: diff --git a/Minecraft.Client/Common/GameRules/ConsoleSchematicFile.cpp b/Minecraft.Client/Common/GameRules/ConsoleSchematicFile.cpp index 3b995000..01a8119e 100644 --- a/Minecraft.Client/Common/GameRules/ConsoleSchematicFile.cpp +++ b/Minecraft.Client/Common/GameRules/ConsoleSchematicFile.cpp @@ -167,18 +167,18 @@ void ConsoleSchematicFile::save_tags(DataOutputStream *dos) ListTag<CompoundTag> *tileEntityTags = new ListTag<CompoundTag>(); tag->put(L"TileEntities", tileEntityTags); - for (AUTO_VAR(it, m_tileEntities.begin()); it != m_tileEntities.end(); it++) + for ( auto& it : m_tileEntities ) { CompoundTag *cTag = new CompoundTag(); - (*it)->save(cTag); + it->save(cTag); tileEntityTags->add(cTag); } ListTag<CompoundTag> *entityTags = new ListTag<CompoundTag>(); tag->put(L"Entities", entityTags); - for (AUTO_VAR(it, m_entities.begin()); it != m_entities.end(); it++) - entityTags->add( (CompoundTag *)(*it).second->copy() ); + for (auto& it : m_entities ) + entityTags->add( (CompoundTag *)(it).second->copy() ); NbtIo::write(tag,dos); delete tag; @@ -186,15 +186,15 @@ void ConsoleSchematicFile::save_tags(DataOutputStream *dos) __int64 ConsoleSchematicFile::applyBlocksAndData(LevelChunk *chunk, AABB *chunkBox, AABB *destinationBox, ESchematicRotation rot) { - int xStart = max(destinationBox->x0, (double)chunk->x*16); - int xEnd = min(destinationBox->x1, (double)((xStart>>4)<<4) + 16); + int xStart = static_cast<int>(std::fmax<double>(destinationBox->x0, (double)chunk->x*16)); + int xEnd = static_cast<int>(std::fmin<double>(destinationBox->x1, (double)((xStart >> 4) << 4) + 16)); int yStart = destinationBox->y0; int yEnd = destinationBox->y1; if(yEnd > Level::maxBuildHeight) yEnd = Level::maxBuildHeight; - int zStart = max(destinationBox->z0, (double)chunk->z*16); - int zEnd = min(destinationBox->z1, (double)((zStart>>4)<<4) + 16); + int zStart = static_cast<int>(std::fmax<double>(destinationBox->z0, (double)chunk->z * 16)); + int zEnd = static_cast<int>(std::fmin<double>(destinationBox->z1, (double)((zStart >> 4) << 4) + 16)); #ifdef _DEBUG app.DebugPrintf("Range is (%d,%d,%d) to (%d,%d,%d)\n",xStart,yStart,zStart,xEnd-1,yEnd-1,zEnd-1); @@ -431,10 +431,8 @@ void ConsoleSchematicFile::schematicCoordToChunkCoord(AABB *destinationBox, doub void ConsoleSchematicFile::applyTileEntities(LevelChunk *chunk, AABB *chunkBox, AABB *destinationBox, ESchematicRotation rot) { - for(AUTO_VAR(it, m_tileEntities.begin()); it != m_tileEntities.end();++it) + for (auto& te : m_tileEntities ) { - shared_ptr<TileEntity> te = *it; - double targetX = te->x; double targetY = te->y + destinationBox->y0; double targetZ = te->z; @@ -477,7 +475,7 @@ void ConsoleSchematicFile::applyTileEntities(LevelChunk *chunk, AABB *chunkBox, teCopy->setChanged(); } } - for(AUTO_VAR(it, m_entities.begin()); it != m_entities.end();) + for (auto it = m_entities.begin(); it != m_entities.end();) { Vec3 *source = it->first; @@ -679,9 +677,8 @@ void ConsoleSchematicFile::generateSchematicFile(DataOutputStream *dos, Level *l for (int zc = zc0; zc <= zc1; zc++) { vector<shared_ptr<TileEntity> > *tileEntities = getTileEntitiesInRegion(level->getChunk(xc, zc), xStart, yStart, zStart, xStart + xSize, yStart + ySize, zStart + zSize); - for(AUTO_VAR(it, tileEntities->begin()); it != tileEntities->end(); ++it) + for( auto& te : *tileEntities ) { - shared_ptr<TileEntity> te = *it; CompoundTag *teTag = new CompoundTag(); shared_ptr<TileEntity> teCopy = te->clone(); @@ -701,10 +698,8 @@ void ConsoleSchematicFile::generateSchematicFile(DataOutputStream *dos, Level *l vector<shared_ptr<Entity> > *entities = level->getEntities(nullptr, bb); ListTag<CompoundTag> *entitiesTag = new ListTag<CompoundTag>(L"entities"); - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + for (auto& e : *entities ) { - shared_ptr<Entity> e = *it; - bool mobCanBeSaved = false; if (bSaveMobs) { @@ -1012,12 +1007,15 @@ void ConsoleSchematicFile::setBlocksAndData(LevelChunk *chunk, byteArray blockDa vector<shared_ptr<TileEntity> > *ConsoleSchematicFile::getTileEntitiesInRegion(LevelChunk *chunk, int x0, int y0, int z0, int x1, int y1, int z1) { vector<shared_ptr<TileEntity> > *result = new vector<shared_ptr<TileEntity> >; - for (AUTO_VAR(it, chunk->tileEntities.begin()); it != chunk->tileEntities.end(); ++it) + if ( result ) { - shared_ptr<TileEntity> te = it->second; - if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && te->y < y1 && te->z < z1) + for ( auto& it : chunk->tileEntities ) { - result->push_back(te); + shared_ptr<TileEntity> te = it.second; + if (te->x >= x0 && te->y >= y0 && te->z >= z0 && te->x < x1 && te->y < y1 && te->z < z1) + { + result->push_back(te); + } } } return result; diff --git a/Minecraft.Client/Common/GameRules/GameRule.cpp b/Minecraft.Client/Common/GameRules/GameRule.cpp index 34d6196c..b37df84d 100644 --- a/Minecraft.Client/Common/GameRules/GameRule.cpp +++ b/Minecraft.Client/Common/GameRules/GameRule.cpp @@ -9,11 +9,11 @@ GameRule::GameRule(GameRuleDefinition *definition, Connection *connection) GameRule::~GameRule() { - for(AUTO_VAR(it, m_parameters.begin()); it != m_parameters.end(); ++it) + for(auto& it : m_parameters ) { - if(it->second.isPointer) + if(it.second.isPointer) { - delete it->second.gr; + delete it.second.gr; } } } @@ -59,12 +59,12 @@ void GameRule::write(DataOutputStream *dos) { // Find required parameters. dos->writeInt(m_parameters.size()); - for (AUTO_VAR(it, m_parameters.begin()); it != m_parameters.end(); it++) + for ( const auto& parameter : m_parameters ) { - wstring pName = (*it).first; - ValueType vType = (*it).second; - - dos->writeUTF( (*it).first ); + wstring pName = parameter.first; + ValueType vType = parameter.second; + + dos->writeUTF( parameter.first ); dos->writeBoolean( vType.isPointer ); if (vType.isPointer) @@ -80,7 +80,7 @@ void GameRule::read(DataInputStream *dis) for (int i = 0; i < savedParams; i++) { wstring pNames = dis->readUTF(); - + ValueType vType = getParameter(pNames); if (dis->readBoolean()) diff --git a/Minecraft.Client/Common/GameRules/GameRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/GameRuleDefinition.cpp index b63687c2..80d02956 100644 --- a/Minecraft.Client/Common/GameRules/GameRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/GameRuleDefinition.cpp @@ -18,15 +18,15 @@ void GameRuleDefinition::write(DataOutputStream *dos) ConsoleGameRules::write(dos, eType); // stringID writeAttributes(dos, 0); - + // 4J-JEV: Get children. vector<GameRuleDefinition *> *children = new vector<GameRuleDefinition *>(); getChildren( children ); // Write children. dos->writeInt( children->size() ); - for (AUTO_VAR(it, children->begin()); it != children->end(); it++) - (*it)->write(dos); + for ( auto& it : *children ) + it->write(dos); } void GameRuleDefinition::writeAttributes(DataOutputStream *dos, UINT numAttributes) @@ -40,7 +40,7 @@ void GameRuleDefinition::writeAttributes(DataOutputStream *dos, UINT numAttribut dos->writeUTF(m_promptId); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_dataTag); - dos->writeUTF(_toString(m_4JDataValue)); + dos->writeUTF(std::to_wstring(m_4JDataValue)); } void GameRuleDefinition::getChildren(vector<GameRuleDefinition *> *children) {} @@ -116,13 +116,13 @@ vector<GameRuleDefinition *> *GameRuleDefinition::enumerate() unordered_map<GameRuleDefinition *, int> *GameRuleDefinition::enumerateMap() { - unordered_map<GameRuleDefinition *, int> *out + unordered_map<GameRuleDefinition *, int> *out = new unordered_map<GameRuleDefinition *, int>(); int i = 0; vector<GameRuleDefinition *> *gRules = enumerate(); - for (AUTO_VAR(it, gRules->begin()); it != gRules->end(); it++) - out->insert( pair<GameRuleDefinition *, int>( *it, i++ ) ); + for ( auto& it : *gRules ) + out->emplace(it, i++); return out; } diff --git a/Minecraft.Client/Common/GameRules/GameRuleManager.cpp b/Minecraft.Client/Common/GameRules/GameRuleManager.cpp index 6e5688cc..f18aa7ae 100644 --- a/Minecraft.Client/Common/GameRules/GameRuleManager.cpp +++ b/Minecraft.Client/Common/GameRules/GameRuleManager.cpp @@ -77,7 +77,7 @@ WCHAR *GameRuleManager::wchAttrNameA[] = L"spawnY", // eGameRuleAttr_spawnY L"spawnZ", // eGameRuleAttr_spawnZ L"orientation", - L"dimension", + L"dimension", L"topTileId", // eGameRuleAttr_topTileId L"biomeId", // eGameRuleAttr_biomeId L"feature", // eGameRuleAttr_feature @@ -127,7 +127,7 @@ void GameRuleManager::loadGameRules(DLCPack *pack) LevelGenerationOptions *createdLevelGenerationOptions = new LevelGenerationOptions(pack); // = loadGameRules(dData, dSize); //, strings); - + createdLevelGenerationOptions->setGrSource( new JustGrSource() ); createdLevelGenerationOptions->setSrc( LevelGenerationOptions::eSrc_tutorial ); @@ -164,7 +164,7 @@ void GameRuleManager::loadGameRules(LevelGenerationOptions *lgo, byte *dIn, UINT app.DebugPrintf("\tversion=%d.\n", version); for (int i = 0; i < 8; i++) dis.readByte(); - + BYTE compression_type = dis.readByte(); app.DebugPrintf("\tcompressionType=%d.\n", compression_type); @@ -174,11 +174,11 @@ void GameRuleManager::loadGameRules(LevelGenerationOptions *lgo, byte *dIn, UINT decomp_len = dis.readInt(); app.DebugPrintf("\tcompr_len=%d.\n\tdecomp_len=%d.\n", compr_len, decomp_len); - + // Decompress File Body - byteArray content(new BYTE[decomp_len], decomp_len), + byteArray content(new BYTE[decomp_len], decomp_len), compr_content(new BYTE[compr_len], compr_len); dis.read(compr_content); @@ -251,7 +251,7 @@ void GameRuleManager::saveGameRules(byte **dOut, UINT *dSize) // Initialise output stream. ByteArrayOutputStream baos; DataOutputStream dos(&baos); - + // Write header. // VERSION NUMBER @@ -279,7 +279,7 @@ void GameRuleManager::saveGameRules(byte **dOut, UINT *dSize) compr_dos.writeInt( 0 ); // XmlObjects.length } else - { + { StringTable *st = m_currentGameRuleDefinitions->getStringTable(); if (st == NULL) @@ -311,9 +311,9 @@ void GameRuleManager::saveGameRules(byte **dOut, UINT *dSize) dos.writeInt( compr_ba.length ); // Write length dos.writeInt( compr_baos.buf.length ); dos.write(compr_ba); - + delete [] compr_ba.data; - + compr_dos.close(); compr_baos.close(); // -- END COMPRESSED -- // @@ -323,7 +323,7 @@ void GameRuleManager::saveGameRules(byte **dOut, UINT *dSize) *dOut = baos.buf.data; baos.buf.data = NULL; - + dos.close(); baos.close(); } @@ -344,11 +344,10 @@ void GameRuleManager::writeRuleFile(DataOutputStream *dos) // Write schematic files. unordered_map<wstring, ConsoleSchematicFile *> *files; files = getLevelGenerationOptions()->getUnfinishedSchematicFiles(); - dos->writeInt( files->size() ); - for (AUTO_VAR(it, files->begin()); it != files->end(); it++) + for ( auto& it : *files ) { - wstring filename = it->first; - ConsoleSchematicFile *file = it->second; + const wstring& filename = it.first; + ConsoleSchematicFile *file = it.second; ByteArrayOutputStream fileBaos; DataOutputStream fileDos(&fileBaos); @@ -378,7 +377,7 @@ bool GameRuleManager::readRuleFile(LevelGenerationOptions *lgo, byte *dIn, UINT //DWORD dwLen = 0; //PBYTE pbData = dlcFile->getData(dwLen); //byteArray data(pbData,dwLen); - + byteArray data(dIn, dSize); ByteArrayInputStream bais(data); DataInputStream dis(&bais); @@ -497,7 +496,7 @@ bool GameRuleManager::readRuleFile(LevelGenerationOptions *lgo, byte *dIn, UINT } }*/ - // subfile + // subfile UINT numFiles = contentDis->readInt(); for (UINT i = 0; i < numFiles; i++) { @@ -519,7 +518,7 @@ bool GameRuleManager::readRuleFile(LevelGenerationOptions *lgo, byte *dIn, UINT { int tagId = contentDis->readInt(); ConsoleGameRules::EGameRuleType tagVal = ConsoleGameRules::eGameRuleType_Invalid; - AUTO_VAR(it,tagIdMap.find(tagId)); + auto it = tagIdMap.find(tagId); if(it != tagIdMap.end()) tagVal = it->second; GameRuleDefinition *rule = NULL; @@ -565,10 +564,10 @@ bool GameRuleManager::readRuleFile(LevelGenerationOptions *lgo, byte *dIn, UINT LevelGenerationOptions *GameRuleManager::readHeader(DLCGameRulesHeader *grh) { - LevelGenerationOptions *out = + LevelGenerationOptions *out = new LevelGenerationOptions(); - + out->setSrc(LevelGenerationOptions::eSrc_fromDLC); out->setGrSource(grh); addLevelGenerationOptions(out); @@ -595,7 +594,7 @@ void GameRuleManager::readChildren(DataInputStream *dis, vector<wstring> *tagsAn { int tagId = dis->readInt(); ConsoleGameRules::EGameRuleType tagVal = ConsoleGameRules::eGameRuleType_Invalid; - AUTO_VAR(it,tagIdMap->find(tagId)); + auto it = tagIdMap->find(tagId); if(it != tagIdMap->end()) tagVal = it->second; GameRuleDefinition *childRule = NULL; @@ -640,18 +639,6 @@ void GameRuleManager::loadDefaultGameRules() m_levelGenerators.getLevelGenerators()->at(0)->setDefaultSaveName(app.GetString(IDS_TUTORIALSAVENAME)); } -#ifndef _CONTENT_PACKAGE - // 4J Stu - Remove these just now - //File testRulesPath(L"GAME:\\GameRules"); - //vector<File *> *packFiles = testRulesPath.listFiles(); - - //for(AUTO_VAR(it,packFiles->begin()); it != packFiles->end(); ++it) - //{ - // loadGameRulesPack(*it); - //} - //delete packFiles; -#endif - #else // _XBOX #ifdef _WINDOWS64 @@ -741,7 +728,7 @@ LPCWSTR GameRuleManager::GetGameRulesString(const wstring &key) LEVEL_GEN_ID GameRuleManager::addLevelGenerationOptions(LevelGenerationOptions *lgo) { vector<LevelGenerationOptions *> *lgs = m_levelGenerators.getLevelGenerators(); - + for (int i = 0; i<lgs->size(); i++) if (lgs->at(i) == lgo) return i; @@ -761,7 +748,7 @@ void GameRuleManager::unloadCurrentGameRules() if (m_currentLevelGenerationOptions->isFromSave()) { m_levelGenerators.removeLevelGenerator( m_currentLevelGenerationOptions ); - + delete m_currentLevelGenerationOptions; } else if (m_currentLevelGenerationOptions->isFromDLC()) diff --git a/Minecraft.Client/Common/GameRules/LevelGenerationOptions.cpp b/Minecraft.Client/Common/GameRules/LevelGenerationOptions.cpp index 9ebd3428..e49ee293 100644 --- a/Minecraft.Client/Common/GameRules/LevelGenerationOptions.cpp +++ b/Minecraft.Client/Common/GameRules/LevelGenerationOptions.cpp @@ -59,7 +59,7 @@ LevelGenerationOptions::LevelGenerationOptions(DLCPack *parentPack) m_pbBaseSaveData = NULL; m_dwBaseSaveSize = 0; - m_parentDLCPack = parentPack; + m_parentDLCPack = parentPack; m_bLoadingData = false; } @@ -67,23 +67,24 @@ LevelGenerationOptions::~LevelGenerationOptions() { clearSchematics(); if(m_spawnPos != NULL) delete m_spawnPos; - for(AUTO_VAR(it, m_schematicRules.begin()); it != m_schematicRules.end(); ++it) + for (auto& it : m_schematicRules ) { - delete *it; + delete it; } - for(AUTO_VAR(it, m_structureRules.begin()); it != m_structureRules.end(); ++it) + + for (auto& it : m_structureRules ) { - delete *it; + delete it; } - for(AUTO_VAR(it, m_biomeOverrides.begin()); it != m_biomeOverrides.end(); ++it) + for (auto& it : m_biomeOverrides ) { - delete *it; + delete it; } - for(AUTO_VAR(it, m_features.begin()); it != m_features.end(); ++it) + for (auto& it : m_features ) { - delete *it; + delete it; } if (m_stringTable) @@ -100,16 +101,16 @@ void LevelGenerationOptions::writeAttributes(DataOutputStream *dos, UINT numAttr GameRuleDefinition::writeAttributes(dos, numAttrs + 5); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_spawnX); - dos->writeUTF(_toString(m_spawnPos->x)); + dos->writeUTF(std::to_wstring(m_spawnPos->x)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_spawnY); - dos->writeUTF(_toString(m_spawnPos->y)); + dos->writeUTF(std::to_wstring(m_spawnPos->y)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_spawnZ); - dos->writeUTF(_toString(m_spawnPos->z)); + dos->writeUTF(std::to_wstring(m_spawnPos->z)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_seed); - dos->writeUTF(_toString(m_seed)); + dos->writeUTF(std::to_wstring(m_seed)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_flatworld); - dos->writeUTF(_toString(m_useFlatWorld)); + dos->writeUTF(std::to_wstring(m_useFlatWorld)); } void LevelGenerationOptions::getChildren(vector<GameRuleDefinition *> *children) @@ -117,18 +118,25 @@ void LevelGenerationOptions::getChildren(vector<GameRuleDefinition *> *children) GameRuleDefinition::getChildren(children); vector<ApplySchematicRuleDefinition *> used_schematics; - for (AUTO_VAR(it, m_schematicRules.begin()); it != m_schematicRules.end(); it++) - if ( !(*it)->isComplete() ) - used_schematics.push_back( *it ); - - for(AUTO_VAR(it, m_structureRules.begin()); it!=m_structureRules.end(); it++) - children->push_back( *it ); - for(AUTO_VAR(it, used_schematics.begin()); it!=used_schematics.end(); it++) - children->push_back( *it ); - for(AUTO_VAR(it, m_biomeOverrides.begin()); it != m_biomeOverrides.end(); ++it) - children->push_back( *it ); - for(AUTO_VAR(it, m_features.begin()); it != m_features.end(); ++it) - children->push_back( *it ); + for (auto& it : m_schematicRules ) + if ( it && !it->isComplete() ) + used_schematics.push_back( it ); + + for (auto& it : m_structureRules) + if ( it ) + children->push_back( it ); + + for (auto& it : used_schematics) + if ( it ) + children->push_back( it ); + + for (auto& it : m_biomeOverrides) + if ( it ) + children->push_back( it ); + + for (auto& it : m_features) + if ( it ) + children->push_back( it ); } GameRuleDefinition *LevelGenerationOptions::addChild(ConsoleGameRules::EGameRuleType ruleType) @@ -195,7 +203,7 @@ void LevelGenerationOptions::addAttribute(const wstring &attributeName, const ws { if(attributeValue.compare(L"true") == 0) m_useFlatWorld = true; app.DebugPrintf("LevelGenerationOptions: Adding parameter flatworld=%s\n",m_useFlatWorld?"TRUE":"FALSE"); - } + } else if(attributeName.compare(L"saveName") == 0) { wstring string(attributeValue); @@ -218,7 +226,7 @@ void LevelGenerationOptions::addAttribute(const wstring &attributeName, const ws app.DebugPrintf("LevelGenerationOptions: Adding parameter displayName=%ls\n", getDisplayName()); } else if(attributeName.compare(L"texturePackId") == 0) - { + { setRequiredTexturePackId( _fromString<unsigned int>(attributeValue) ); setRequiresTexturePack( true ); app.DebugPrintf("LevelGenerationOptions: Adding parameter texturePackId=%0x\n", getRequiredTexturePackId()); @@ -249,19 +257,14 @@ void LevelGenerationOptions::processSchematics(LevelChunk *chunk) { PIXBeginNamedEvent(0,"Processing schematics for chunk (%d,%d)", chunk->x, chunk->z); AABB *chunkBox = AABB::newTemp(chunk->x*16,0,chunk->z*16,chunk->x*16 + 16,Level::maxBuildHeight,chunk->z*16 + 16); - for( AUTO_VAR(it, m_schematicRules.begin()); it != m_schematicRules.end();++it) - { - ApplySchematicRuleDefinition *rule = *it; + for( ApplySchematicRuleDefinition *rule : m_schematicRules ) rule->processSchematic(chunkBox, chunk); - } int cx = (chunk->x << 4); int cz = (chunk->z << 4); - for( AUTO_VAR(it, m_structureRules.begin()); it != m_structureRules.end(); it++ ) + for ( ConsoleGenerateStructure *structureStart : m_structureRules ) { - ConsoleGenerateStructure *structureStart = *it; - if (structureStart->getBoundingBox()->intersects(cx, cz, cx + 15, cz + 15)) { BoundingBox *bb = new BoundingBox(cx, cz, cx + 15, cz + 15); @@ -276,9 +279,8 @@ void LevelGenerationOptions::processSchematicsLighting(LevelChunk *chunk) { PIXBeginNamedEvent(0,"Processing schematics (lighting) for chunk (%d,%d)", chunk->x, chunk->z); AABB *chunkBox = AABB::newTemp(chunk->x*16,0,chunk->z*16,chunk->x*16 + 16,Level::maxBuildHeight,chunk->z*16 + 16); - for( AUTO_VAR(it, m_schematicRules.begin()); it != m_schematicRules.end();++it) + for ( ApplySchematicRuleDefinition *rule : m_schematicRules ) { - ApplySchematicRuleDefinition *rule = *it; rule->processSchematicLighting(chunkBox, chunk); } PIXEndNamedEvent(); @@ -292,16 +294,14 @@ bool LevelGenerationOptions::checkIntersects(int x0, int y0, int z0, int x1, int // a) ores generally being below ground/sea level and b) tutorial world additions generally being above ground/sea level if(!m_bHaveMinY) { - for(AUTO_VAR(it, m_schematicRules.begin()); it != m_schematicRules.end();++it) + for ( ApplySchematicRuleDefinition *rule : m_schematicRules ) { - ApplySchematicRuleDefinition *rule = *it; int minY = rule->getMinY(); if(minY < m_minY) m_minY = minY; } - for( AUTO_VAR(it, m_structureRules.begin()); it != m_structureRules.end(); it++ ) + for ( ConsoleGenerateStructure *structureStart : m_structureRules ) { - ConsoleGenerateStructure *structureStart = *it; int minY = structureStart->getMinY(); if(minY < m_minY) m_minY = minY; } @@ -313,18 +313,16 @@ bool LevelGenerationOptions::checkIntersects(int x0, int y0, int z0, int x1, int if( y1 < m_minY ) return false; bool intersects = false; - for(AUTO_VAR(it, m_schematicRules.begin()); it != m_schematicRules.end();++it) + for( ApplySchematicRuleDefinition *rule : m_schematicRules ) { - ApplySchematicRuleDefinition *rule = *it; intersects = rule->checkIntersects(x0,y0,z0,x1,y1,z1); if(intersects) break; } if(!intersects) { - for( AUTO_VAR(it, m_structureRules.begin()); it != m_structureRules.end(); it++ ) + for( ConsoleGenerateStructure *structureStart : m_structureRules ) { - ConsoleGenerateStructure *structureStart = *it; intersects = structureStart->checkIntersects(x0,y0,z0,x1,y1,z1); if(intersects) break; } @@ -335,9 +333,9 @@ bool LevelGenerationOptions::checkIntersects(int x0, int y0, int z0, int x1, int void LevelGenerationOptions::clearSchematics() { - for(AUTO_VAR(it, m_schematics.begin()); it != m_schematics.end(); ++it) + for ( auto& it : m_schematics ) { - delete it->second; + delete it.second; } m_schematics.clear(); } @@ -345,7 +343,7 @@ void LevelGenerationOptions::clearSchematics() ConsoleSchematicFile *LevelGenerationOptions::loadSchematicFile(const wstring &filename, PBYTE pbData, DWORD dwLen) { // If we have already loaded this, just return - AUTO_VAR(it, m_schematics.find(filename)); + auto it = m_schematics.find(filename); if(it != m_schematics.end()) { #ifndef _CONTENT_PACKAGE @@ -370,7 +368,7 @@ ConsoleSchematicFile *LevelGenerationOptions::getSchematicFile(const wstring &fi { ConsoleSchematicFile *schematic = NULL; // If we have already loaded this, just return - AUTO_VAR(it, m_schematics.find(filename)); + auto it = m_schematics.find(filename); if(it != m_schematics.end()) { schematic = it->second; @@ -381,7 +379,7 @@ ConsoleSchematicFile *LevelGenerationOptions::getSchematicFile(const wstring &fi void LevelGenerationOptions::releaseSchematicFile(const wstring &filename) { // 4J Stu - We don't want to delete them when done, but probably want to keep a set of active schematics for the current world - //AUTO_VAR(it, m_schematics.find(filename)); + // auto it = m_schematics.find(filename); //if(it != m_schematics.end()) //{ // ConsoleSchematicFile *schematic = it->second; @@ -413,10 +411,9 @@ LPCWSTR LevelGenerationOptions::getString(const wstring &key) void LevelGenerationOptions::getBiomeOverride(int biomeId, BYTE &tile, BYTE &topTile) { - for(AUTO_VAR(it, m_biomeOverrides.begin()); it != m_biomeOverrides.end(); ++it) + for ( BiomeOverride *bo : m_biomeOverrides ) { - BiomeOverride *bo = *it; - if(bo->isBiome(biomeId)) + if ( bo && bo->isBiome(biomeId) ) { bo->getTileValues(tile,topTile); break; @@ -428,9 +425,8 @@ bool LevelGenerationOptions::isFeatureChunk(int chunkX, int chunkZ, StructureFea { bool isFeature = false; - for(AUTO_VAR(it, m_features.begin()); it != m_features.end(); ++it) + for( StartFeature *sf : m_features ) { - StartFeature *sf = *it; if(sf->isFeatureChunk(chunkX, chunkZ, feature, orientation)) { isFeature = true; @@ -444,17 +440,17 @@ unordered_map<wstring, ConsoleSchematicFile *> *LevelGenerationOptions::getUnfin { // Clean schematic rules. unordered_set<wstring> usedFiles = unordered_set<wstring>(); - for (AUTO_VAR(it, m_schematicRules.begin()); it!=m_schematicRules.end(); it++) - if ( !(*it)->isComplete() ) - usedFiles.insert( (*it)->getSchematicName() ); + for ( auto& it : m_schematicRules ) + if ( !it->isComplete() ) + usedFiles.insert( it->getSchematicName() ); // Clean schematic files. - unordered_map<wstring, ConsoleSchematicFile *> *out + unordered_map<wstring, ConsoleSchematicFile *> *out = new unordered_map<wstring, ConsoleSchematicFile *>(); - for (AUTO_VAR(it, usedFiles.begin()); it!=usedFiles.end(); it++) - out->insert( pair<wstring, ConsoleSchematicFile *>(*it, getSchematicFile(*it)) ); + for ( auto& it : usedFiles ) + out->insert( pair<wstring, ConsoleSchematicFile *>(it, getSchematicFile(it)) ); - return out; + return out; } void LevelGenerationOptions::loadBaseSaveData() @@ -472,7 +468,7 @@ void LevelGenerationOptions::loadBaseSaveData() { // corrupt DLC setLoadedData(); - app.DebugPrintf("Failed to mount LGO DLC %d for pad %d\n",mountIndex,ProfileManager.GetPrimaryPad()); + app.DebugPrintf("Failed to mount LGO DLC %d for pad %d\n",mountIndex,ProfileManager.GetPrimaryPad()); } else { @@ -604,7 +600,7 @@ int LevelGenerationOptions::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD } } -#ifdef _DURANGO +#ifdef _DURANGO DWORD result = StorageManager.UnmountInstalledDLC(L"WPACK"); #else DWORD result = StorageManager.UnmountInstalledDLC("WPACK"); @@ -619,11 +615,10 @@ int LevelGenerationOptions::packMounted(LPVOID pParam,int iPad,DWORD dwErr,DWORD void LevelGenerationOptions::reset_start() { - for ( AUTO_VAR( it, m_schematicRules.begin()); - it != m_schematicRules.end(); - it++ ) + for ( auto& it : m_schematicRules ) { - (*it)->reset(); + if ( it ) + it->reset(); } } @@ -651,7 +646,7 @@ bool LevelGenerationOptions::requiresTexturePack() { return info()->requiresText UINT LevelGenerationOptions::getRequiredTexturePackId() { return info()->getRequiredTexturePackId(); } wstring LevelGenerationOptions::getDefaultSaveName() -{ +{ switch (getSrc()) { case eSrc_fromSave: return getString( info()->getDefaultSaveName() ); @@ -661,7 +656,7 @@ wstring LevelGenerationOptions::getDefaultSaveName() return L""; } LPCWSTR LevelGenerationOptions::getWorldName() -{ +{ switch (getSrc()) { case eSrc_fromSave: return getString( info()->getWorldName() ); diff --git a/Minecraft.Client/Common/GameRules/LevelRuleset.cpp b/Minecraft.Client/Common/GameRules/LevelRuleset.cpp index 1c7ecd47..658abe91 100644 --- a/Minecraft.Client/Common/GameRules/LevelRuleset.cpp +++ b/Minecraft.Client/Common/GameRules/LevelRuleset.cpp @@ -11,7 +11,7 @@ LevelRuleset::LevelRuleset() LevelRuleset::~LevelRuleset() { - for(AUTO_VAR(it, m_areas.begin()); it != m_areas.end(); ++it) + for (auto it = m_areas.begin(); it != m_areas.end(); ++it) { delete *it; } @@ -20,8 +20,8 @@ LevelRuleset::~LevelRuleset() void LevelRuleset::getChildren(vector<GameRuleDefinition *> *children) { CompoundGameRuleDefinition::getChildren(children); - for (AUTO_VAR(it, m_areas.begin()); it != m_areas.end(); it++) - children->push_back(*it); + for (const auto& area : m_areas) + children->push_back(area); } GameRuleDefinition *LevelRuleset::addChild(ConsoleGameRules::EGameRuleType ruleType) @@ -58,12 +58,12 @@ LPCWSTR LevelRuleset::getString(const wstring &key) AABB *LevelRuleset::getNamedArea(const wstring &areaName) { - AABB *area = NULL; - for(AUTO_VAR(it, m_areas.begin()); it != m_areas.end(); ++it) + AABB *area = nullptr; + for(auto& it : m_areas) { - if( (*it)->getName().compare(areaName) == 0 ) + if( it->getName().compare(areaName) == 0 ) { - area = (*it)->getArea(); + area = it->getArea(); break; } } diff --git a/Minecraft.Client/Common/GameRules/NamedAreaRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/NamedAreaRuleDefinition.cpp index 41ff15e8..2294c579 100644 --- a/Minecraft.Client/Common/GameRules/NamedAreaRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/NamedAreaRuleDefinition.cpp @@ -22,18 +22,18 @@ void NamedAreaRuleDefinition::writeAttributes(DataOutputStream *dos, UINT numAtt dos->writeUTF(m_name); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_x0); - dos->writeUTF(_toString(m_area->x0)); + dos->writeUTF(std::to_wstring(m_area->x0)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_y0); - dos->writeUTF(_toString(m_area->y0)); + dos->writeUTF(std::to_wstring(m_area->y0)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_z0); - dos->writeUTF(_toString(m_area->z0)); + dos->writeUTF(std::to_wstring(m_area->z0)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_x1); - dos->writeUTF(_toString(m_area->x1)); + dos->writeUTF(std::to_wstring(m_area->x1)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_y1); - dos->writeUTF(_toString(m_area->y1)); + dos->writeUTF(std::to_wstring(m_area->y1)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_z1); - dos->writeUTF(_toString(m_area->z1)); + dos->writeUTF(std::to_wstring(m_area->z1)); } void NamedAreaRuleDefinition::addAttribute(const wstring &attributeName, const wstring &attributeValue) diff --git a/Minecraft.Client/Common/GameRules/StartFeature.cpp b/Minecraft.Client/Common/GameRules/StartFeature.cpp index 7f0c8b5c..904bce73 100644 --- a/Minecraft.Client/Common/GameRules/StartFeature.cpp +++ b/Minecraft.Client/Common/GameRules/StartFeature.cpp @@ -15,13 +15,13 @@ void StartFeature::writeAttributes(DataOutputStream *dos, UINT numAttrs) GameRuleDefinition::writeAttributes(dos, numAttrs + 4); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_chunkX); - dos->writeUTF(_toString(m_chunkX)); + dos->writeUTF(std::to_wstring(m_chunkX)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_chunkZ); - dos->writeUTF(_toString(m_chunkZ)); + dos->writeUTF(std::to_wstring(m_chunkZ)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_feature); - dos->writeUTF(_toString((int)m_feature)); + dos->writeUTF(std::to_wstring((int)m_feature)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_orientation); - dos->writeUTF(_toString(m_orientation)); + dos->writeUTF(std::to_wstring(m_orientation)); } void StartFeature::addAttribute(const wstring &attributeName, const wstring &attributeValue) diff --git a/Minecraft.Client/Common/GameRules/UpdatePlayerRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/UpdatePlayerRuleDefinition.cpp index 6e55cd45..ec218c7a 100644 --- a/Minecraft.Client/Common/GameRules/UpdatePlayerRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/UpdatePlayerRuleDefinition.cpp @@ -11,16 +11,16 @@ UpdatePlayerRuleDefinition::UpdatePlayerRuleDefinition() { m_bUpdateHealth = m_bUpdateFood = m_bUpdateYRot = false;; m_health = 0; - m_food = 0; + m_food = 0; m_spawnPos = NULL; m_yRot = 0.0f; } UpdatePlayerRuleDefinition::~UpdatePlayerRuleDefinition() { - for(AUTO_VAR(it, m_items.begin()); it != m_items.end(); ++it) + for(auto& item : m_items) { - delete *it; + delete item; } } @@ -33,34 +33,34 @@ void UpdatePlayerRuleDefinition::writeAttributes(DataOutputStream *dos, UINT num GameRuleDefinition::writeAttributes(dos, numAttributes + attrCount ); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_spawnX); - dos->writeUTF(_toString(m_spawnPos->x)); + dos->writeUTF(std::to_wstring(m_spawnPos->x)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_spawnY); - dos->writeUTF(_toString(m_spawnPos->y)); + dos->writeUTF(std::to_wstring(m_spawnPos->y)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_spawnZ); - dos->writeUTF(_toString(m_spawnPos->z)); + dos->writeUTF(std::to_wstring(m_spawnPos->z)); if(m_bUpdateYRot) { ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_yRot); - dos->writeUTF(_toString(m_yRot)); + dos->writeUTF(std::to_wstring(m_yRot)); } if(m_bUpdateHealth) { ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_food); - dos->writeUTF(_toString(m_health)); + dos->writeUTF(std::to_wstring(m_health)); } if(m_bUpdateFood) { ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_health); - dos->writeUTF(_toString(m_food)); + dos->writeUTF(std::to_wstring(m_food)); } } void UpdatePlayerRuleDefinition::getChildren(vector<GameRuleDefinition *> *children) { GameRuleDefinition::getChildren(children); - for(AUTO_VAR(it, m_items.begin()); it!=m_items.end(); it++) - children->push_back(*it); + for(auto& item : m_items) + children->push_back(item); } GameRuleDefinition *UpdatePlayerRuleDefinition::addChild(ConsoleGameRules::EGameRuleType ruleType) @@ -162,10 +162,8 @@ void UpdatePlayerRuleDefinition::postProcessPlayer(shared_ptr<Player> player) if(m_spawnPos != NULL || m_bUpdateYRot) player->absMoveTo(x,y,z,yRot,xRot); - for(AUTO_VAR(it, m_items.begin()); it != m_items.end(); ++it) + for(auto& addItem : m_items) { - AddItemRuleDefinition *addItem = *it; - addItem->addItemToContainer(player->inventory, -1); } }
\ No newline at end of file diff --git a/Minecraft.Client/Common/GameRules/UseTileRuleDefinition.cpp b/Minecraft.Client/Common/GameRules/UseTileRuleDefinition.cpp index 965405ae..49cc0e9c 100644 --- a/Minecraft.Client/Common/GameRules/UseTileRuleDefinition.cpp +++ b/Minecraft.Client/Common/GameRules/UseTileRuleDefinition.cpp @@ -13,19 +13,19 @@ void UseTileRuleDefinition::writeAttributes(DataOutputStream *dos, UINT numAttri GameRuleDefinition::writeAttributes(dos, numAttributes + 5); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_tileId); - dos->writeUTF(_toString(m_tileId)); + dos->writeUTF(std::to_wstring(m_tileId)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_useCoords); - dos->writeUTF(_toString(m_useCoords)); + dos->writeUTF(std::to_wstring(m_useCoords)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_x); - dos->writeUTF(_toString(m_coordinates.x)); + dos->writeUTF(std::to_wstring(m_coordinates.x)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_y); - dos->writeUTF(_toString(m_coordinates.y)); + dos->writeUTF(std::to_wstring(m_coordinates.y)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_z); - dos->writeUTF(_toString(m_coordinates.z)); + dos->writeUTF(std::to_wstring(m_coordinates.z)); } void UseTileRuleDefinition::addAttribute(const wstring &attributeName, const wstring &attributeValue) diff --git a/Minecraft.Client/Common/GameRules/XboxStructureActionGenerateBox.cpp b/Minecraft.Client/Common/GameRules/XboxStructureActionGenerateBox.cpp index 6d687b36..6d949fc0 100644 --- a/Minecraft.Client/Common/GameRules/XboxStructureActionGenerateBox.cpp +++ b/Minecraft.Client/Common/GameRules/XboxStructureActionGenerateBox.cpp @@ -14,25 +14,25 @@ void XboxStructureActionGenerateBox::writeAttributes(DataOutputStream *dos, UINT ConsoleGenerateStructureAction::writeAttributes(dos, numAttrs + 9); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_x0); - dos->writeUTF(_toString(m_x0)); + dos->writeUTF(std::to_wstring(m_x0)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_y0); - dos->writeUTF(_toString(m_y0)); + dos->writeUTF(std::to_wstring(m_y0)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_z0); - dos->writeUTF(_toString(m_z0)); + dos->writeUTF(std::to_wstring(m_z0)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_x1); - dos->writeUTF(_toString(m_x1)); + dos->writeUTF(std::to_wstring(m_x1)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_y1); - dos->writeUTF(_toString(m_y1)); + dos->writeUTF(std::to_wstring(m_y1)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_z1); - dos->writeUTF(_toString(m_z1)); + dos->writeUTF(std::to_wstring(m_z1)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_edgeTile); - dos->writeUTF(_toString(m_edgeTile)); + dos->writeUTF(std::to_wstring(m_edgeTile)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_fillTile); - dos->writeUTF(_toString(m_fillTile)); + dos->writeUTF(std::to_wstring(m_fillTile)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_skipAir); - dos->writeUTF(_toString(m_skipAir)); + dos->writeUTF(std::to_wstring(m_skipAir)); } void XboxStructureActionGenerateBox::addAttribute(const wstring &attributeName, const wstring &attributeValue) diff --git a/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceBlock.cpp b/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceBlock.cpp index b816d5b6..f8ac1d44 100644 --- a/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceBlock.cpp +++ b/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceBlock.cpp @@ -13,16 +13,16 @@ void XboxStructureActionPlaceBlock::writeAttributes(DataOutputStream *dos, UINT ConsoleGenerateStructureAction::writeAttributes(dos, numAttrs + 5); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_x); - dos->writeUTF(_toString(m_x)); + dos->writeUTF(std::to_wstring(m_x)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_y); - dos->writeUTF(_toString(m_y)); + dos->writeUTF(std::to_wstring(m_y)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_z); - dos->writeUTF(_toString(m_z)); + dos->writeUTF(std::to_wstring(m_z)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_data); - dos->writeUTF(_toString(m_data)); + dos->writeUTF(std::to_wstring(m_data)); ConsoleGameRules::write(dos, ConsoleGameRules::eGameRuleAttr_block); - dos->writeUTF(_toString(m_tile)); + dos->writeUTF(std::to_wstring(m_tile)); } diff --git a/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceContainer.cpp b/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceContainer.cpp index d81a2b03..fa68ef6a 100644 --- a/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceContainer.cpp +++ b/Minecraft.Client/Common/GameRules/XboxStructureActionPlaceContainer.cpp @@ -14,21 +14,21 @@ XboxStructureActionPlaceContainer::XboxStructureActionPlaceContainer() XboxStructureActionPlaceContainer::~XboxStructureActionPlaceContainer() { - for(AUTO_VAR(it, m_items.begin()); it != m_items.end(); ++it) + for(auto& item : m_items) { - delete *it; + delete item; } } // 4J-JEV: Super class handles attr-facing fine. //void XboxStructureActionPlaceContainer::writeAttributes(DataOutputStream *dos, UINT numAttrs) - + void XboxStructureActionPlaceContainer::getChildren(vector<GameRuleDefinition *> *children) { XboxStructureActionPlaceBlock::getChildren(children); - for(AUTO_VAR(it, m_items.begin()); it!=m_items.end(); it++) - children->push_back( *it ); + for(auto & item : m_items) + children->push_back( item ); } GameRuleDefinition *XboxStructureActionPlaceContainer::addChild(ConsoleGameRules::EGameRuleType ruleType) @@ -79,15 +79,15 @@ bool XboxStructureActionPlaceContainer::placeContainerInLevel(StructurePiece *st level->setTileAndData( worldX, worldY, worldZ, m_tile, 0, Tile::UPDATE_ALL ); shared_ptr<Container> container = dynamic_pointer_cast<Container>(level->getTileEntity( worldX, worldY, worldZ )); - + app.DebugPrintf("XboxStructureActionPlaceContainer - placing a container at (%d,%d,%d)\n", worldX, worldY, worldZ); if ( container != NULL ) { level->setData( worldX, worldY, worldZ, m_data, Tile::UPDATE_CLIENTS); // Add items int slotId = 0; - for(AUTO_VAR(it, m_items.begin()); it != m_items.end() && (slotId < container->getContainerSize()); ++it, ++slotId ) - { + for (auto it = m_items.begin(); it != m_items.end() && (slotId < container->getContainerSize()); ++it, ++slotId) + { AddItemRuleDefinition *addItem = *it; addItem->addItemToContainer(container,slotId); diff --git a/Minecraft.Client/Common/Network/GameNetworkManager.cpp b/Minecraft.Client/Common/Network/GameNetworkManager.cpp index a65a61aa..dbae3010 100644 --- a/Minecraft.Client/Common/Network/GameNetworkManager.cpp +++ b/Minecraft.Client/Common/Network/GameNetworkManager.cpp @@ -75,7 +75,7 @@ void CGameNetworkManager::Initialise() #else s_pPlatformNetworkManager = new CPlatformNetworkManagerStub(); #endif - s_pPlatformNetworkManager->Initialise( this, flagIndexSize ); + s_pPlatformNetworkManager->Initialise( this, flagIndexSize ); m_bNetworkThreadRunning = false; m_bInitialised = true; } @@ -105,7 +105,7 @@ void CGameNetworkManager::DoWork() if((g_NetworkManager.GetLockedProfile()!=-1) && iPrimaryPlayer!=-1 && bConnected == false && g_NetworkManager.IsInSession() ) { app.SetAction(iPrimaryPlayer,eAppAction_EthernetDisconnected); - } + } } break; case XN_LIVE_INVITE_ACCEPTED: @@ -162,7 +162,7 @@ bool CGameNetworkManager::_RunNetworkGame(LPVOID lpParameter) success = s_pPlatformNetworkManager->_RunNetworkGame(); if(!success) - { + { app.SetAction(ProfileManager.GetPrimaryPad(),eAppAction_ExitWorld,(void *)TRUE); return true; } @@ -172,7 +172,7 @@ bool CGameNetworkManager::_RunNetworkGame(LPVOID lpParameter) // Client needs QNET_STATE_GAME_PLAY so that IsInGameplay() returns true s_pPlatformNetworkManager->SetGamePlayState(); } - + if( g_NetworkManager.IsLeavingGame() ) return false; app.SetGameStarted(true); @@ -199,7 +199,7 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame { NetworkGameInitData *param = (NetworkGameInitData *)lpParameter; seed = param->seed; - + app.setLevelGenerationOptions(param->levelGen); if(param->levelGen != NULL) { @@ -305,7 +305,7 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame ServerReadyWait(); ServerReadyDestroy(); - if( MinecraftServer::serverHalted() ) + if( MinecraftServer::serverHalted() ) return false; // printf("Server ready to go!\n"); @@ -316,7 +316,7 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame } #ifndef _XBOX - Minecraft *pMinecraft = Minecraft::GetInstance(); + Minecraft *pMinecraft = Minecraft::GetInstance(); // Make sure that we have transitioned through any joining/creating stages and are actually playing the game, so that we know the players should be valid bool changedMessage = false; while(!IsReadyToPlayOrIdle()) @@ -492,9 +492,10 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame do { // We need to keep ticking the connections for players that already logged in - for(AUTO_VAR(it, createdConnections.begin()); it < createdConnections.end(); ++it) - { - (*it)->tick(); + for (auto& it : createdConnections ) + { + if ( it ) + it->tick(); } // 4J Stu - We were ticking this way too fast which could cause the connection to time out @@ -522,8 +523,8 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame else { connection->close(); - AUTO_VAR(it, find( createdConnections.begin(), createdConnections.end(), connection )); - if(it != createdConnections.end() ) createdConnections.erase( it ); + auto it = find(createdConnections.begin(), createdConnections.end(), connection); + if(it != createdConnections.end() ) createdConnections.erase( it ); } } @@ -536,12 +537,12 @@ bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, LPVOID lpParame return false; } - + if(g_NetworkManager.IsLeavingGame() || !IsInSession() ) { - for(AUTO_VAR(it, createdConnections.begin()); it < createdConnections.end(); ++it) - { - (*it)->close(); + for (auto& it : createdConnections) + { + it->close(); } // assert(false); MinecraftServer::HaltServer(); @@ -832,7 +833,7 @@ int CGameNetworkManager::JoinFromInvite_SignInReturned(void *pParam,bool bContin ProfileManager.SetPrimaryPad(iPad); g_NetworkManager.SetLocalGame(false); - + // If the player was signed in before selecting play, we'll not have read the profile yet, so query the sign-in status to get this to happen ProfileManager.QuerySigninStatus(); @@ -848,7 +849,7 @@ int CGameNetworkManager::JoinFromInvite_SignInReturned(void *pParam,bool bContin pInviteInfo ); // pInviteInfo if( !success ) { - app.DebugPrintf( "Failed joining game from invite\n" ); + app.DebugPrintf( "Failed joining game from invite\n" ); } } } @@ -894,7 +895,7 @@ int CGameNetworkManager::RunNetworkGameThreadProc( void* lpParameter ) Compression::UseDefaultThreadStorage(); Tile::CreateNewThreadStorage(); IntCache::CreateNewThreadStorage(); - + g_NetworkManager.m_bNetworkThreadRunning = true; bool success = g_NetworkManager._RunNetworkGame(lpParameter); g_NetworkManager.m_bNetworkThreadRunning = false; @@ -906,7 +907,7 @@ int CGameNetworkManager::RunNetworkGameThreadProc( void* lpParameter ) Sleep(1); } ui.CleanUpSkinReload(); - if(app.GetDisconnectReason() == DisconnectPacket::eDisconnect_None) + if(app.GetDisconnectReason() == DisconnectPacket::eDisconnect_None) { app.SetDisconnectReason( DisconnectPacket::eDisconnect_ConnectionCreationFailed ); } @@ -949,7 +950,7 @@ int CGameNetworkManager::ServerThreadProc( void* lpParameter ) SetThreadName(-1, "Minecraft Server thread"); AABB::CreateNewThreadStorage(); Vec3::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); Compression::UseDefaultThreadStorage(); OldChunkStorage::UseDefaultThreadStorage(); Entity::useSmallIds(); @@ -958,7 +959,7 @@ int CGameNetworkManager::ServerThreadProc( void* lpParameter ) FireworksRecipe::CreateNewThreadStorage(); MinecraftServer::main(seed, lpParameter); //saveData, app.GetGameHostOption(eGameHostOption_All)); - + Tile::ReleaseThreadStorage(); AABB::ReleaseThreadStorage(); Vec3::ReleaseThreadStorage(); @@ -1012,7 +1013,7 @@ int CGameNetworkManager::ExitAndJoinFromInviteThreadProc( void* lpParam ) // The pair of methods MustSignInReturned_0 & PSNSignInReturned_0 handle this int CGameNetworkManager::MustSignInReturned_0(void *pParam,int iPad,C4JStorage::EMessageResult result) { - if(result==C4JStorage::EMessage_ResultAccept) + if(result==C4JStorage::EMessage_ResultAccept) { #ifdef __PS3__ SQRNetworkManager_PS3::AttemptPSNSignIn(&CGameNetworkManager::PSNSignInReturned_0, pParam,true); @@ -1072,7 +1073,7 @@ int CGameNetworkManager::PSNSignInReturned_0(void* pParam, bool bContinue, int i // The pair of methods MustSignInReturned_1 & PSNSignInReturned_1 handle this int CGameNetworkManager::MustSignInReturned_1(void *pParam,int iPad,C4JStorage::EMessageResult result) { - if(result==C4JStorage::EMessage_ResultAccept) + if(result==C4JStorage::EMessage_ResultAccept) { #ifdef __PS3__ SQRNetworkManager_PS3::AttemptPSNSignIn(&CGameNetworkManager::PSNSignInReturned_1, pParam,true); @@ -1104,7 +1105,7 @@ int CGameNetworkManager::PSNSignInReturned_1(void* pParam, bool bContinue, int i #elif defined __ORBIS__ // TODO: No Orbis equivalent (should there be?) #endif - + } } @@ -1129,7 +1130,7 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) Vec3::UseDefaultThreadStorage(); Compression::UseDefaultThreadStorage(); - Minecraft *pMinecraft = Minecraft::GetInstance(); + Minecraft *pMinecraft = Minecraft::GetInstance(); MinecraftServer *pServer = MinecraftServer::getInstance(); #if defined(__PS3__) || defined(__ORBIS__) || defined __PSVITA__ @@ -1168,7 +1169,7 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) pMinecraft->progressRenderer->progressStartNoAbort( g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT) ); pMinecraft->progressRenderer->progressStage( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); } - + #else pMinecraft->progressRenderer->progressStartNoAbort( g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT) ); pMinecraft->progressRenderer->progressStage( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); @@ -1182,7 +1183,7 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) // wait for the server to be in a non-ticking state pServer->m_serverPausedEvent->WaitForSignal(INFINITE); - + #if defined(__PS3__) || defined(__ORBIS__) || defined __PSVITA__ // Swap these two messages around as one is too long to display at 480 pMinecraft->progressRenderer->progressStartNoAbort( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); @@ -1218,9 +1219,8 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) if( pServer != NULL ) { PlayerList *players = pServer->getPlayers(); - for(AUTO_VAR(it, players->players.begin()); it < players->players.end(); ++it) + for(auto& servPlayer : players->players) { - shared_ptr<ServerPlayer> servPlayer = *it; if( servPlayer->connection->isLocal() && !servPlayer->connection->isGuest() ) { servPlayer->connection->connection->getSocket()->setPlayer(NULL); @@ -1244,7 +1244,7 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) { Sleep(1); } - + // Reset this flag as the we don't need to know that we only lost the room only from this point onwards, the behaviour is exactly the same g_NetworkManager.m_bLastDisconnectWasLostRoomOnly = false; g_NetworkManager.m_bFullSessionMessageOnNextSessionChange = false; @@ -1275,7 +1275,7 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) { Sleep(1); } - + // Restore the network player of all the server players that are local if( pServer != NULL ) { @@ -1286,9 +1286,8 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) PlayerUID localPlayerXuid = pMinecraft->localplayers[index]->getXuid(); PlayerList *players = pServer->getPlayers(); - for(AUTO_VAR(it, players->players.begin()); it < players->players.end(); ++it) + for(auto& servPlayer : players->players) { - shared_ptr<ServerPlayer> servPlayer = *it; if( servPlayer->getXuid() == localPlayerXuid ) { servPlayer->connection->connection->getSocket()->setPlayer( g_NetworkManager.GetLocalPlayerByUserIndex(index) ); @@ -1302,7 +1301,7 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) pMinecraft->m_pendingLocalConnections[index]->getConnection()->getSocket()->setPlayer(g_NetworkManager.GetLocalPlayerByUserIndex(index)); } else if ( pMinecraft->m_connectionFailed[index] && (pMinecraft->m_connectionFailedReason[index] == DisconnectPacket::eDisconnect_ConnectionCreationFailed) ) - { + { pMinecraft->removeLocalPlayerIdx(index); #ifdef _XBOX_ONE ProfileManager.RemoveGamepadFromGame(index); @@ -1311,7 +1310,7 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) } } } - + pMinecraft->progressRenderer->progressStagePercentage(100); #ifndef _XBOX @@ -1333,7 +1332,7 @@ int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) #endif // Start the game again - app.SetGameStarted(true); + app.SetGameStarted(true); app.SetXuiServerAction(ProfileManager.GetPrimaryPad(),eXuiServerAction_PauseServer,(void *)FALSE); app.SetChangingSessionType(false); app.SetReallyChangingSessionType(false); @@ -1387,7 +1386,7 @@ void CGameNetworkManager::StateChange_AnyToJoining() app.DebugPrintf("Disabling Guest Signin\n"); XEnableGuestSignin(FALSE); Minecraft::GetInstance()->clearPendingClientTextureRequests(); - + ConnectionProgressParams *param = new ConnectionProgressParams(); param->iPad = ProfileManager.GetPrimaryPad(); param->stringId = -1; @@ -1435,7 +1434,7 @@ void CGameNetworkManager::StateChange_AnyToStarting() completionData->type = e_ProgressCompletion_CloseAllPlayersUIScenes; completionData->iPad = ProfileManager.GetPrimaryPad(); loadingParams->completionData = completionData; - + ui.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_FullscreenProgress, loadingParams); } } @@ -1559,7 +1558,7 @@ void CGameNetworkManager::PlayerJoining( INetworkPlayer *pNetworkPlayer ) bool multiplayer = g_NetworkManager.GetPlayerCount() > 1, localgame = g_NetworkManager.IsLocalGame(); for (int iPad=0; iPad<XUSER_MAX_COUNT; ++iPad) { - INetworkPlayer *pNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(iPad); + INetworkPlayer *pNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(iPad); if (pNetworkPlayer == NULL) continue; app.SetRichPresenceContext(iPad,CONTEXT_GAME_STATE_BLANK); @@ -1584,7 +1583,7 @@ void CGameNetworkManager::PlayerJoining( INetworkPlayer *pNetworkPlayer ) else { if( !pNetworkPlayer->IsHost() ) - { + { for(int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { if(Minecraft::GetInstance()->localplayers[idx] != NULL) @@ -1640,7 +1639,7 @@ void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO * } // Need to check we're signed in to PSN - bool isSignedInLive = true; + bool isSignedInLive = true; bool isLocalMultiplayerAvailable = app.IsLocalMultiplayerAvailable(); int iPadNotSignedInLive = -1; for(unsigned int i = 0; i < XUSER_MAX_COUNT; i++) @@ -1680,7 +1679,7 @@ void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO * ui.RequestErrorMessage( IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, iPadNotSignedInLive); } else - { + { // Not signed in to PSN UINT uiIDA[1]; uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; @@ -1700,10 +1699,10 @@ void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO * { m_pInviteInfo = (INVITE_INFO *) pInviteInfo; m_iPlayerInvited = userIndex; - + m_pUpsell = new PsPlusUpsellWrapper(index); m_pUpsell->displayUpsell(); - + return; } } @@ -1723,9 +1722,9 @@ void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO * // 4J-PB we shouldn't bring any inactive players into the game, except for the invited player (who may be an inactive player) // 4J Stu - If we are not in a game, then bring in all players signed in if(index==userIndex || pMinecraft->localplayers[index]!=NULL ) - { + { ++joiningUsers; - if( !ProfileManager.AllowedToPlayMultiplayer(index) ) noPrivileges = true; + if( !ProfileManager.AllowedToPlayMultiplayer(index) ) noPrivileges = true; localUsersMask |= GetLocalPlayerMask( index ); } } @@ -1742,7 +1741,7 @@ void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO * ProfileManager.AllowedPlayerCreatedContent(ProfileManager.GetPrimaryPad(),false,&pccAllowed,&pccFriendsAllowed); if(!pccAllowed && !pccFriendsAllowed) noUGC = true; #endif - + #if defined(_XBOX) || defined(__PS3__) if(joiningUsers > 1 && !RenderManager.IsHiDef() && userIndex != ProfileManager.GetPrimaryPad()) { @@ -1796,10 +1795,10 @@ void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO * } #endif if( !g_NetworkManager.IsInSession() ) - { + { #if defined (__PS3__) || defined (__PSVITA__) // PS3 is more complicated here - we need to make sure that the player is online. If they are then we can do the same as the xbox, if not we need to try and get them online and then, if they do sign in, go down the same path - + // Determine why they're not "signed in live" // MGH - On Vita we need to add a new message at some point for connecting when already signed in if(ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())) @@ -1816,7 +1815,7 @@ void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO * #else - HandleInviteWhenInMenus(userIndex, pInviteInfo); + HandleInviteWhenInMenus(userIndex, pInviteInfo); #endif } else @@ -1856,7 +1855,7 @@ void CGameNetworkManager::HandleInviteWhenInMenus( int userIndex, const INVITE_I if(!ProfileManager.IsFullVersion()) { // The marketplace will fail with the primary player set to -1 - ProfileManager.SetPrimaryPad(userIndex); + ProfileManager.SetPrimaryPad(userIndex); app.SetAction(userIndex,eAppAction_DashboardTrialJoinFromInvite); } @@ -1900,7 +1899,7 @@ void CGameNetworkManager::HandleInviteWhenInMenus( int userIndex, const INVITE_I ProfileManager.QuerySigninStatus(); // 4J-PB - clear any previous connection errors - Minecraft::GetInstance()->clearConnectionFailed(); + Minecraft::GetInstance()->clearConnectionFailed(); g_NetworkManager.SetLocalGame(false); @@ -1910,7 +1909,7 @@ void CGameNetworkManager::HandleInviteWhenInMenus( int userIndex, const INVITE_I bool success = g_NetworkManager.JoinGameFromInviteInfo( userIndex, localUsersMask, pInviteInfo ); if( !success ) { - app.DebugPrintf( "Failed joining game from invite\n" ); + app.DebugPrintf( "Failed joining game from invite\n" ); } } } diff --git a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp index e5824bd4..6dd465d1 100644 --- a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp +++ b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp @@ -1,4 +1,4 @@ -#include "stdafx.h" +#include "stdafx.h" #include "..\..\..\Minecraft.World\Socket.h" #include "..\..\..\Minecraft.World\StringHelpers.h" #include "PlatformNetworkManagerStub.h" @@ -64,9 +64,8 @@ void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) { // Do we already have a primary player for this system? bool systemHasPrimaryPlayer = false; - for(AUTO_VAR(it, m_machineQNetPrimaryPlayers.begin()); it < m_machineQNetPrimaryPlayers.end(); ++it) - { - IQNetPlayer *pQNetPrimaryPlayer = *it; + for (auto& pQNetPrimaryPlayer : m_machineQNetPrimaryPlayers) + { if( pQNetPlayer->IsSameSystem(pQNetPrimaryPlayer) ) { systemHasPrimaryPlayer = true; @@ -78,7 +77,7 @@ void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) } } g_NetworkManager.PlayerJoining( networkPlayer ); - + if( createFakeSocket == true && !m_bHostChanged ) { g_NetworkManager.CreateSocket( networkPlayer, localPlayer ); @@ -98,7 +97,7 @@ void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) // g_NetworkManager.UpdateAndSetGameSessionData(); SystemFlagAddPlayer( networkPlayer ); } - + for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { if(playerChangedCallback[idx] != NULL) @@ -162,7 +161,7 @@ bool CPlatformNetworkManagerStub::Initialise(CGameNetworkManager *pGameNetworkMa { playerChangedCallback[ i ] = NULL; } - + m_bLeavingGame = false; m_bLeaveGameOnTick = false; m_bHostChanged = false; @@ -318,8 +317,8 @@ bool CPlatformNetworkManagerStub::LeaveGame(bool bMigrateHost) m_pIQNet->EndGame(); } - for (AUTO_VAR(it, currentNetworkPlayers.begin()); it != currentNetworkPlayers.end(); it++) - delete* it; + for (auto & it : currentNetworkPlayers) + delete it; currentNetworkPlayers.clear(); m_machineQNetPrimaryPlayers.clear(); SystemFlagReset(); @@ -473,7 +472,7 @@ void CPlatformNetworkManagerStub::UnRegisterPlayerChangedCallback(int iPad, void void CPlatformNetworkManagerStub::HandleSignInChange() { - return; + return; } bool CPlatformNetworkManagerStub::_RunNetworkGame() @@ -500,24 +499,24 @@ bool CPlatformNetworkManagerStub::_RunNetworkGame() void CPlatformNetworkManagerStub::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= NULL*/) { // DWORD playerCount = m_pIQNet->GetPlayerCount(); -// +// // if( this->m_bLeavingGame ) // return; -// +// // if( GetHostPlayer() == NULL ) // return; -// +// // for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) // { // if( i < playerCount ) // { // INetworkPlayer *pNetworkPlayer = GetPlayerByIndex(i); -// +// // // We can call this from NotifyPlayerLeaving but at that point the player is still considered in the session // if( pNetworkPlayer != pNetworkPlayerLeaving ) // { // m_hostGameSessionData.players[i] = ((NetworkPlayerXbox *)pNetworkPlayer)->GetUID(); -// +// // char *temp; // temp = (char *)wstringtofilename( pNetworkPlayer->GetOnlineName() ); // memcpy(m_hostGameSessionData.szPlayers[i],temp,XUSER_NAME_SIZE); @@ -534,7 +533,7 @@ void CPlatformNetworkManagerStub::UpdateAndSetGameSessionData(INetworkPlayer *pN // memset(m_hostGameSessionData.szPlayers[i],0,XUSER_NAME_SIZE); // } // } -// +// // m_hostGameSessionData.hostPlayerUID = ((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetXuid(); // m_hostGameSessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); } @@ -823,7 +822,7 @@ void CPlatformNetworkManagerStub::GetFullFriendSessionInfo( FriendSessionInfo *f void CPlatformNetworkManagerStub::ForceFriendsSessionRefresh() { app.DebugPrintf("Resetting friends session search data\n"); - + for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { m_searchResultsCount[i] = 0; @@ -844,8 +843,8 @@ INetworkPlayer *CPlatformNetworkManagerStub::addNetworkPlayer(IQNetPlayer *pQNet void CPlatformNetworkManagerStub::removeNetworkPlayer(IQNetPlayer *pQNetPlayer) { INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pQNetPlayer); - for( AUTO_VAR(it, currentNetworkPlayers.begin()); it != currentNetworkPlayers.end(); it++ ) - { + for (auto it = currentNetworkPlayers.begin(); it != currentNetworkPlayers.end(); it++) + { if( *it == pNetworkPlayer ) { currentNetworkPlayers.erase(it); @@ -862,7 +861,7 @@ INetworkPlayer *CPlatformNetworkManagerStub::getNetworkPlayer(IQNetPlayer *pQNet INetworkPlayer *CPlatformNetworkManagerStub::GetLocalPlayerByUserIndex(int userIndex ) { - return getNetworkPlayer(m_pIQNet->GetLocalPlayerByUserIndex(userIndex)); + return getNetworkPlayer(m_pIQNet->GetLocalPlayerByUserIndex(userIndex)); } INetworkPlayer *CPlatformNetworkManagerStub::GetPlayerByIndex(int playerIndex) diff --git a/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp b/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp index 67fd058c..a9799d26 100644 --- a/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp +++ b/Minecraft.Client/Common/Network/Sony/PlatformNetworkManagerSony.cpp @@ -7,21 +7,21 @@ CPlatformNetworkManagerSony *g_pPlatformNetworkManager; -bool CPlatformNetworkManagerSony::IsLocalGame() -{ - return m_bIsOfflineGame; +bool CPlatformNetworkManagerSony::IsLocalGame() +{ + return m_bIsOfflineGame; } -bool CPlatformNetworkManagerSony::IsPrivateGame() -{ - return m_bIsPrivateGame; +bool CPlatformNetworkManagerSony::IsPrivateGame() +{ + return m_bIsPrivateGame; } -bool CPlatformNetworkManagerSony::IsLeavingGame() -{ - return m_bLeavingGame; +bool CPlatformNetworkManagerSony::IsLeavingGame() +{ + return m_bLeavingGame; } -void CPlatformNetworkManagerSony::ResetLeavingGame() -{ - m_bLeavingGame = false; +void CPlatformNetworkManagerSony::ResetLeavingGame() +{ + m_bLeavingGame = false; } @@ -188,9 +188,8 @@ void CPlatformNetworkManagerSony::HandlePlayerJoined(SQRNetworkPlayer * { // Do we already have a primary player for this system? bool systemHasPrimaryPlayer = false; - for(AUTO_VAR(it, m_machineSQRPrimaryPlayers.begin()); it < m_machineSQRPrimaryPlayers.end(); ++it) + for( SQRNetworkPlayer *pQNetPrimaryPlayer : m_machineSQRPrimaryPlayers ) { - SQRNetworkPlayer *pQNetPrimaryPlayer = *it; if( pSQRPlayer->IsSameSystem(pQNetPrimaryPlayer) ) { systemHasPrimaryPlayer = true; @@ -202,7 +201,7 @@ void CPlatformNetworkManagerSony::HandlePlayerJoined(SQRNetworkPlayer * } } g_NetworkManager.PlayerJoining( networkPlayer ); - + if( createFakeSocket == true && !m_bHostChanged ) { g_NetworkManager.CreateSocket( networkPlayer, localPlayer ); @@ -224,7 +223,7 @@ void CPlatformNetworkManagerSony::HandlePlayerJoined(SQRNetworkPlayer * g_NetworkManager.UpdateAndSetGameSessionData(); SystemFlagAddPlayer( networkPlayer ); } - + for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { if(playerChangedCallback[idx] != NULL) @@ -293,7 +292,7 @@ void CPlatformNetworkManagerSony::HandlePlayerLeaving(SQRNetworkPlayer *pSQRPlay break; } } - AUTO_VAR(it, find( m_machineSQRPrimaryPlayers.begin(), m_machineSQRPrimaryPlayers.end(), pSQRPlayer)); + auto it = find( m_machineSQRPrimaryPlayers.begin(), m_machineSQRPrimaryPlayers.end(), pSQRPlayer); if( it != m_machineSQRPrimaryPlayers.end() ) { m_machineSQRPrimaryPlayers.erase( it ); @@ -309,7 +308,7 @@ void CPlatformNetworkManagerSony::HandlePlayerLeaving(SQRNetworkPlayer *pSQRPlay } g_NetworkManager.PlayerLeaving( networkPlayer ); - + for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { if(playerChangedCallback[idx] != NULL) @@ -374,7 +373,7 @@ bool CPlatformNetworkManagerSony::Initialise(CGameNetworkManager *pGameNetworkMa #ifdef __ORBIS__ m_pSQRNet = new SQRNetworkManager_Orbis(this); m_pSQRNet->Initialise(); -#elif defined __PS3__ +#elif defined __PS3__ m_pSQRNet = new SQRNetworkManager_PS3(this); m_pSQRNet->Initialise(); #else // __PSVITA__ @@ -405,7 +404,7 @@ bool CPlatformNetworkManagerSony::Initialise(CGameNetworkManager *pGameNetworkMa { playerChangedCallback[ i ] = NULL; } - + m_bLeavingGame = false; m_bLeaveGameOnTick = false; m_bHostChanged = false; @@ -419,7 +418,7 @@ bool CPlatformNetworkManagerSony::Initialise(CGameNetworkManager *pGameNetworkMa m_searchResultsCount = 0; m_pSearchResults = NULL; - + m_lastSearchStartTime = 0; // Success! @@ -458,7 +457,7 @@ int CPlatformNetworkManagerSony::CorrectErrorIDS(int IDS) bool preferSignoutError = false; int state; -#if defined __PSVITA__ // MGH - to fix devtrack #6258 +#if defined __PSVITA__ // MGH - to fix devtrack #6258 if(!ProfileManager.IsSignedInPSN(ProfileManager.GetPrimaryPad())) preferSignoutError = true; #elif defined __ORBIS__ @@ -529,9 +528,8 @@ int CPlatformNetworkManagerSony::CorrectErrorIDS(int IDS) bool CPlatformNetworkManagerSony::isSystemPrimaryPlayer(SQRNetworkPlayer *pSQRPlayer) { bool playerIsSystemPrimary = false; - for(AUTO_VAR(it, m_machineSQRPrimaryPlayers.begin()); it < m_machineSQRPrimaryPlayers.end(); ++it) + for( SQRNetworkPlayer *pSQRPrimaryPlayer : m_machineSQRPrimaryPlayers ) { - SQRNetworkPlayer *pSQRPrimaryPlayer = *it; if( pSQRPrimaryPlayer == pSQRPlayer ) { playerIsSystemPrimary = true; @@ -552,7 +550,7 @@ void CPlatformNetworkManagerSony::DoWork() m_notificationListener, 0, // Any notification &dwNotifyId, - &ulpNotifyParam) + &ulpNotifyParam) ) { @@ -650,7 +648,7 @@ bool CPlatformNetworkManagerSony::IsInStatsEnabledSession() DWORD dataSize = sizeof(QNET_LIVE_STATS_MODE); QNET_LIVE_STATS_MODE statsMode; m_pIQNet->GetOpt(QNET_OPTION_LIVE_STATS_MODE, &statsMode , &dataSize ); - + // Use QNET_LIVE_STATS_MODE_AUTO if there is another way to check if stats are enabled or not bool statsEnabled = statsMode == QNET_LIVE_STATS_MODE_ENABLED; return m_pIQNet->GetState() != QNET_STATE_IDLE && statsEnabled; @@ -732,7 +730,7 @@ bool CPlatformNetworkManagerSony::LeaveGame(bool bMigrateHost) // If we are the host wait for the game server to end if(m_pSQRNet->IsHost() && g_NetworkManager.ServerStoppedValid()) - { + { m_pSQRNet->EndGame(); g_NetworkManager.ServerStoppedWait(); g_NetworkManager.ServerStoppedDestroy(); @@ -887,7 +885,7 @@ void CPlatformNetworkManagerSony::UnRegisterPlayerChangedCallback(int iPad, void void CPlatformNetworkManagerSony::HandleSignInChange() { - return; + return; } bool CPlatformNetworkManagerSony::_RunNetworkGame() @@ -930,7 +928,7 @@ void CPlatformNetworkManagerSony::UpdateAndSetGameSessionData(INetworkPlayer *pN { m_hostGameSessionData.hostPlayerUID.setForAdhoc(); } -#endif +#endif m_hostGameSessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); @@ -1066,8 +1064,8 @@ bool CPlatformNetworkManagerSony::SystemFlagGet(INetworkPlayer *pNetworkPlayer, wstring CPlatformNetworkManagerSony::GatherStats() { #if 0 - return L"Queue messages: " + _toString(((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_MESSAGES ) ) - + L" Queue bytes: " + _toString( ((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_BYTES ) ); + return L"Queue messages: " + std::to_wstring(((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_MESSAGES ) ) + + L" Queue bytes: " + std::to_wstring( ((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_BYTES ) ); #else return L""; #endif @@ -1192,7 +1190,7 @@ bool CPlatformNetworkManagerSony::GetGameSessionInfo(int iPad, SessionID session bool foundSession = false; FriendSessionInfo *sessionInfo = NULL; - AUTO_VAR(itFriendSession, friendsSessions[iPad].begin()); + auto itFriendSession = friendsSessions[iPad].begin(); for(itFriendSession = friendsSessions[iPad].begin(); itFriendSession < friendsSessions[iPad].end(); ++itFriendSession) { sessionInfo = *itFriendSession; @@ -1224,7 +1222,7 @@ bool CPlatformNetworkManagerSony::GetGameSessionInfo(int iPad, SessionID session else { swprintf(sessionInfo->displayLabel,app.GetString(IDS_GAME_HOST_NAME_UNKNOWN)); - } + } sessionInfo->displayLabelLength = wcslen( sessionInfo->displayLabel ); // If this host wasn't disabled use this one. @@ -1283,7 +1281,7 @@ INetworkPlayer *CPlatformNetworkManagerSony::addNetworkPlayer(SQRNetworkPlayer * void CPlatformNetworkManagerSony::removeNetworkPlayer(SQRNetworkPlayer *pSQRPlayer) { INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pSQRPlayer); - for( AUTO_VAR(it, currentNetworkPlayers.begin()); it != currentNetworkPlayers.end(); it++ ) + for( auto it = currentNetworkPlayers.begin(); it != currentNetworkPlayers.end(); it++ ) { if( *it == pNetworkPlayer ) { @@ -1301,7 +1299,7 @@ INetworkPlayer *CPlatformNetworkManagerSony::getNetworkPlayer(SQRNetworkPlayer * INetworkPlayer *CPlatformNetworkManagerSony::GetLocalPlayerByUserIndex(int userIndex ) { - return getNetworkPlayer(m_pSQRNet->GetLocalPlayerByUserIndex(userIndex)); + return getNetworkPlayer(m_pSQRNet->GetLocalPlayerByUserIndex(userIndex)); } INetworkPlayer *CPlatformNetworkManagerSony::GetPlayerByIndex(int playerIndex) @@ -1400,7 +1398,7 @@ bool CPlatformNetworkManagerSony::setAdhocMode( bool bAdhoc ) { if(m_bUsingAdhocMode != bAdhoc) { - m_bUsingAdhocMode = bAdhoc; + m_bUsingAdhocMode = bAdhoc; if(m_bUsingAdhocMode) { // uninit the PSN, and init adhoc @@ -1419,14 +1417,14 @@ bool CPlatformNetworkManagerSony::setAdhocMode( bool bAdhoc ) else { if(m_pSQRNet_Vita_Adhoc->IsInitialised()) - { - int ret = sceNetCtlAdhocDisconnect(); + { + int ret = sceNetCtlAdhocDisconnect(); // uninit the adhoc, and init psn m_pSQRNet_Vita_Adhoc->UnInitialise(); } if(m_pSQRNet_Vita->IsInitialised()==false) - { + { m_pSQRNet_Vita->Initialise(); } diff --git a/Minecraft.Client/Common/Tutorial/AreaTask.cpp b/Minecraft.Client/Common/Tutorial/AreaTask.cpp index de29ab1b..88cd3d27 100644 --- a/Minecraft.Client/Common/Tutorial/AreaTask.cpp +++ b/Minecraft.Client/Common/Tutorial/AreaTask.cpp @@ -23,9 +23,8 @@ bool AreaTask::isCompleted() case eAreaTaskCompletion_CompleteOnConstraintsSatisfied: { bool allSatisfied = true; - for(AUTO_VAR(it, constraints.begin()); it != constraints.end(); ++it) + for( auto& constraint : constraints ) { - TutorialConstraint *constraint = *it; if(!constraint->isConstraintSatisfied(tutorial->getPad())) { allSatisfied = false; diff --git a/Minecraft.Client/Common/Tutorial/ControllerTask.cpp b/Minecraft.Client/Common/Tutorial/ControllerTask.cpp index c3a42120..379e117c 100644 --- a/Minecraft.Client/Common/Tutorial/ControllerTask.cpp +++ b/Minecraft.Client/Common/Tutorial/ControllerTask.cpp @@ -53,15 +53,15 @@ bool ControllerTask::isCompleted() if(m_bHasSouthpaw && app.GetGameSettings(pMinecraft->player->GetXboxPad(),eGameSetting_ControlSouthPaw)) { - for(AUTO_VAR(it, southpawCompletedMappings.begin()); it != southpawCompletedMappings.end(); ++it) + for (auto& it : southpawCompletedMappings ) { - bool current = (*it).second; + bool current = it.second; if(!current) { // TODO Use a different pad - if( InputManager.GetValue(pMinecraft->player->GetXboxPad(), (*it).first) > 0 ) + if( InputManager.GetValue(pMinecraft->player->GetXboxPad(), it.first) > 0 ) { - (*it).second = true; + it.second = true; m_uiCompletionMask|=1<<iCurrent; } else @@ -78,15 +78,15 @@ bool ControllerTask::isCompleted() } else { - for(AUTO_VAR(it, completedMappings.begin()); it != completedMappings.end(); ++it) + for (auto& it : completedMappings ) { - bool current = (*it).second; + bool current = it.second; if(!current) { // TODO Use a different pad - if( InputManager.GetValue(pMinecraft->player->GetXboxPad(), (*it).first) > 0 ) + if( InputManager.GetValue(pMinecraft->player->GetXboxPad(), it.first) > 0 ) { - (*it).second = true; + it.second = true; m_uiCompletionMask|=1<<iCurrent; } else diff --git a/Minecraft.Client/Common/Tutorial/InfoTask.cpp b/Minecraft.Client/Common/Tutorial/InfoTask.cpp index 748093e5..6a78ed92 100644 --- a/Minecraft.Client/Common/Tutorial/InfoTask.cpp +++ b/Minecraft.Client/Common/Tutorial/InfoTask.cpp @@ -37,7 +37,7 @@ bool InfoTask::isCompleted() return false; bool bAllComplete = true; - + Minecraft *pMinecraft = Minecraft::GetInstance(); // If the player is under water then allow all keypresses so they can jump out @@ -47,9 +47,9 @@ bool InfoTask::isCompleted() { // If a menu is displayed, then we use the handleUIInput to complete the task bAllComplete = true; - for(AUTO_VAR(it, completedMappings.begin()); it != completedMappings.end(); ++it) + for( auto& it : completedMappings ) { - bool current = (*it).second; + bool current = it.second; if(!current) { bAllComplete = false; @@ -61,18 +61,18 @@ bool InfoTask::isCompleted() { int iCurrent=0; - for(AUTO_VAR(it, completedMappings.begin()); it != completedMappings.end(); ++it) + for( auto& it : completedMappings ) { - bool current = (*it).second; + bool current = it.second; if(!current) { #ifdef _WINDOWS64 - if (InputManager.GetValue(pMinecraft->player->GetXboxPad(), (*it).first) > 0 || g_KBMInput.IsKeyDown(VK_SPACE)) + if (InputManager.GetValue(pMinecraft->player->GetXboxPad(), it.first) > 0 || g_KBMInput.IsKeyDown(VK_SPACE)) #else - if( InputManager.GetValue(pMinecraft->player->GetXboxPad(), (*it).first) > 0) + if( InputManager.GetValue(pMinecraft->player->GetXboxPad(), it.first) > 0) #endif { - (*it).second = true; + it.second = true; bAllComplete=true; } else @@ -111,11 +111,11 @@ void InfoTask::handleUIInput(int iAction) { if(bHasBeenActivated) { - for(AUTO_VAR(it, completedMappings.begin()); it != completedMappings.end(); ++it) + for( auto& it : completedMappings ) { - if( iAction == (*it).first ) + if( iAction == it.first ) { - (*it).second = true; + it.second = true; } } } diff --git a/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.cpp b/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.cpp index 8603f765..0e3b3e37 100644 --- a/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.cpp +++ b/Minecraft.Client/Common/Tutorial/ProcedureCompoundTask.cpp @@ -3,8 +3,8 @@ ProcedureCompoundTask::~ProcedureCompoundTask() { - for(AUTO_VAR(it, m_taskSequence.begin()); it < m_taskSequence.end(); ++it) - { + for (auto it = m_taskSequence.begin(); it < m_taskSequence.end(); ++it) + { delete (*it); } } @@ -24,10 +24,8 @@ int ProcedureCompoundTask::getDescriptionId() // Return the id of the first task not completed int descriptionId = -1; - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) - { - TutorialTask *task = *it; + for (auto& task : m_taskSequence) + { if(!task->isCompleted()) { task->setAsCurrentTask(true); @@ -50,10 +48,8 @@ int ProcedureCompoundTask::getPromptId() // Return the id of the first task not completed int promptId = -1; - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; if(!task->isCompleted()) { promptId = task->getPromptId(); @@ -69,11 +65,8 @@ bool ProcedureCompoundTask::isCompleted() bool allCompleted = true; bool isCurrentTask = true; - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; - if(allCompleted && isCurrentTask) { if(task->isCompleted()) @@ -99,11 +92,9 @@ bool ProcedureCompoundTask::isCompleted() if(allCompleted) { - //Disable all constraints - itEnd = m_taskSequence.end(); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + // Disable all constraints + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; task->enableConstraints(false); } } @@ -113,20 +104,16 @@ bool ProcedureCompoundTask::isCompleted() void ProcedureCompoundTask::onCrafted(shared_ptr<ItemInstance> item) { - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; task->onCrafted(item); } } void ProcedureCompoundTask::handleUIInput(int iAction) { - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto task : m_taskSequence) { - TutorialTask *task = *it; task->handleUIInput(iAction); } } @@ -135,10 +122,8 @@ void ProcedureCompoundTask::handleUIInput(int iAction) void ProcedureCompoundTask::setAsCurrentTask(bool active /*= true*/) { bool allCompleted = true; - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; if(allCompleted && !task->isCompleted()) { task->setAsCurrentTask(true); @@ -157,10 +142,8 @@ bool ProcedureCompoundTask::ShowMinimumTime() return false; bool showMinimumTime = false; - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; if(!task->isCompleted()) { showMinimumTime = task->ShowMinimumTime(); @@ -176,10 +159,8 @@ bool ProcedureCompoundTask::hasBeenActivated() return true; bool hasBeenActivated = false; - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; if(!task->isCompleted()) { hasBeenActivated = task->hasBeenActivated(); @@ -191,10 +172,8 @@ bool ProcedureCompoundTask::hasBeenActivated() void ProcedureCompoundTask::setShownForMinimumTime() { - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; if(!task->isCompleted()) { task->setShownForMinimumTime(); @@ -209,10 +188,8 @@ bool ProcedureCompoundTask::AllowFade() return true; bool allowFade = true; - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; if(!task->isCompleted()) { allowFade = task->AllowFade(); @@ -224,40 +201,32 @@ bool ProcedureCompoundTask::AllowFade() void ProcedureCompoundTask::useItemOn(Level *level, shared_ptr<ItemInstance> item, int x, int y, int z,bool bTestUseOnly) { - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; task->useItemOn(level, item, x, y, z, bTestUseOnly); } } void ProcedureCompoundTask::useItem(shared_ptr<ItemInstance> item, bool bTestUseOnly) { - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; task->useItem(item, bTestUseOnly); } } void ProcedureCompoundTask::onTake(shared_ptr<ItemInstance> item, unsigned int invItemCountAnyAux, unsigned int invItemCountThisAux) { - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; task->onTake(item, invItemCountAnyAux, invItemCountThisAux); } } void ProcedureCompoundTask::onStateChange(eTutorial_State newState) { - AUTO_VAR(itEnd, m_taskSequence.end()); - for(AUTO_VAR(it, m_taskSequence.begin()); it < itEnd; ++it) + for(auto& task : m_taskSequence) { - TutorialTask *task = *it; task->onStateChange(newState); } }
\ No newline at end of file diff --git a/Minecraft.Client/Common/Tutorial/Tutorial.cpp b/Minecraft.Client/Common/Tutorial/Tutorial.cpp index 057e2171..60feba11 100644 --- a/Minecraft.Client/Common/Tutorial/Tutorial.cpp +++ b/Minecraft.Client/Common/Tutorial/Tutorial.cpp @@ -41,7 +41,7 @@ bool Tutorial::PopupMessageDetails::isSameContent(PopupMessageDetails *other) void Tutorial::staticCtor() { - // + // /* ***** ***** @@ -72,7 +72,7 @@ void Tutorial::staticCtor() s_completableTasks.push_back( e_Tutorial_State_Enchanting ); s_completableTasks.push_back( e_Tutorial_Hint_Hold_To_Mine ); - s_completableTasks.push_back( e_Tutorial_Hint_Tool_Damaged ); + s_completableTasks.push_back( e_Tutorial_Hint_Tool_Damaged ); s_completableTasks.push_back( e_Tutorial_Hint_Swim_Up ); s_completableTasks.push_back( e_Tutorial_Hint_Unused_2 ); @@ -164,7 +164,7 @@ void Tutorial::staticCtor() s_completableTasks.push_back( e_Tutorial_Hint_Thin_Glass ); s_completableTasks.push_back( e_Tutorial_Hint_Melon ); s_completableTasks.push_back( e_Tutorial_Hint_Vine ); - s_completableTasks.push_back( e_Tutorial_Hint_Fence_Gate ); + s_completableTasks.push_back( e_Tutorial_Hint_Fence_Gate ); s_completableTasks.push_back( e_Tutorial_Hint_Mycel ); s_completableTasks.push_back( e_Tutorial_Hint_Water_Lily ); s_completableTasks.push_back( e_Tutorial_Hint_Nether_Brick ); @@ -319,7 +319,7 @@ void Tutorial::staticCtor() s_completableTasks.push_back( e_Tutorial_State_Enderchests ); s_completableTasks.push_back( e_Tutorial_State_Horse_Menu ); s_completableTasks.push_back( e_Tutorial_State_Hopper_Menu ); - + s_completableTasks.push_back( e_Tutorial_Hint_Wither ); s_completableTasks.push_back( e_Tutorial_Hint_Witch ); s_completableTasks.push_back( e_Tutorial_Hint_Bat ); @@ -470,7 +470,7 @@ Tutorial::Tutorial(int iPad, bool isFullTutorial /*= false*/) : m_iPad( iPad ) if(!isHintCompleted(e_Tutorial_Hint_Detector_Rail)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_Detector_Rail, this, detectorRailItems, 1 ) ); int tallGrassItems[] = {Tile::tallgrass_Id}; - if(!isHintCompleted(e_Tutorial_Hint_Tall_Grass)) + if(!isHintCompleted(e_Tutorial_Hint_Tall_Grass)) { addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_Tall_Grass, this, tallGrassItems, 1, -1, TallGrass::DEAD_SHRUB ) ); addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_Tall_Grass, this, tallGrassItems, 1, -1, TallGrass::TALL_GRASS ) ); @@ -753,46 +753,46 @@ Tutorial::Tutorial(int iPad, bool isFullTutorial /*= false*/) : m_iPad( iPad ) int potatoItems[] = {Tile::potatoes_Id}; if(!isHintCompleted(e_Tutorial_Hint_Potato)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_Potato, this, potatoItems, 1, -1, -1, 7 ) ); - + int carrotItems[] = {Tile::carrots_Id}; if(!isHintCompleted(e_Tutorial_Hint_Carrot)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_Carrot, this, carrotItems, 1, -1, -1, 7 ) ); - + int commandBlockItems[] = {Tile::commandBlock_Id}; if(!isHintCompleted(e_Tutorial_Hint_CommandBlock)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_CommandBlock, this, commandBlockItems, 1 ) ); - + int beaconItems[] = {Tile::beacon_Id}; if(!isHintCompleted(e_Tutorial_Hint_Beacon)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_Beacon, this, beaconItems, 1 ) ); - + int activatorRailItems[] = {Tile::activatorRail_Id}; if(!isHintCompleted(e_Tutorial_Hint_Activator_Rail)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_Activator_Rail, this, activatorRailItems, 1 ) ); - + int redstoneBlockItems[] = {Tile::redstoneBlock_Id}; if(!isHintCompleted(e_Tutorial_Hint_RedstoneBlock)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_RedstoneBlock, this, redstoneBlockItems, 1 ) ); - + int daylightDetectorItems[] = {Tile::daylightDetector_Id}; if(!isHintCompleted(e_Tutorial_Hint_DaylightDetector)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_DaylightDetector, this, daylightDetectorItems, 1 ) ); - + int dropperItems[] = {Tile::dropper_Id}; if(!isHintCompleted(e_Tutorial_Hint_Dropper)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_Dropper, this, dropperItems, 1 ) ); - + int hopperItems[] = {Tile::hopper_Id}; if(!isHintCompleted(e_Tutorial_Hint_Hopper)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_Hopper, this, hopperItems, 1 ) ); - + int comparatorItems[] = {Tile::comparator_off_Id, Tile::comparator_on_Id}; if(!isHintCompleted(e_Tutorial_Hint_Comparator)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_Comparator, this, comparatorItems, 2, Item::comparator_Id ) ); - + int trappedChestItems[] = {Tile::chest_trap_Id}; if(!isHintCompleted(e_Tutorial_Hint_ChestTrap)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_ChestTrap, this, trappedChestItems, 1 ) ); - + int hayBlockItems[] = {Tile::hayBlock_Id}; if(!isHintCompleted(e_Tutorial_Hint_HayBlock)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_HayBlock, this, hayBlockItems, 1 ) ); - + int clayHardenedItems[] = {Tile::clayHardened_Id}; if(!isHintCompleted(e_Tutorial_Hint_ClayHardened)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_ClayHardened, this, clayHardenedItems, 1 ) ); - + int clayHardenedColoredItems[] = {Tile::clayHardened_colored_Id}; if(!isHintCompleted(e_Tutorial_Hint_ClayHardenedColored)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_ClayHardenedColored, this, clayHardenedColoredItems, 1 ) ); - + int coalBlockItems[] = {Tile::coalBlock_Id}; if(!isHintCompleted(e_Tutorial_Hint_CoalBlock)) addHint(e_Tutorial_State_Gameplay, new LookAtTileHint(e_Tutorial_Hint_CoalBlock, this, coalBlockItems, 1 ) ); @@ -1000,9 +1000,9 @@ Tutorial::Tutorial(int iPad, bool isFullTutorial /*= false*/) : m_iPad( iPad ) * HORSE ENCOUNTER * */ - if(isFullTutorial || !isStateCompleted(e_Tutorial_State_Horse) ) + if(isFullTutorial || !isStateCompleted(e_Tutorial_State_Horse) ) { - addTask(e_Tutorial_State_Horse, + addTask(e_Tutorial_State_Horse, new HorseChoiceTask(this, IDS_TUTORIAL_TASK_HORSE_OVERVIEW, IDS_TUTORIAL_TASK_DONKEY_OVERVIEW, IDS_TUTORIAL_TASK_MULE_OVERVIEW, IDS_TUTORIAL_PROMPT_HORSE_OVERVIEW, true, ACTION_MENU_A, ACTION_MENU_B, e_Tutorial_Completion_Complete_State_Gameplay_Constraints, eTelemetryTutorial_Horse) ); @@ -1144,23 +1144,23 @@ Tutorial::Tutorial(int iPad, bool isFullTutorial /*= false*/) : m_iPad( iPad ) Tutorial::~Tutorial() { - for(AUTO_VAR(it, m_globalConstraints.begin()); it != m_globalConstraints.end(); ++it) + for(auto& it : m_globalConstraints) { - delete (*it); + delete it; } - for(unordered_map<int, TutorialMessage *>::iterator it = messages.begin(); it != messages.end(); ++it) + for(auto& message : messages) { - delete (*it).second; + delete message.second; } for(unsigned int i = 0; i < e_Tutorial_State_Max; ++i) { - for(AUTO_VAR(it, activeTasks[i].begin()); it < activeTasks[i].end(); ++it) + for(auto& it : activeTasks[i]) { - delete (*it); + delete it; } - for(AUTO_VAR(it, hints[i].begin()); it < hints[i].end(); ++it) + for(auto& it : hints[i]) { - delete (*it); + delete it; } currentTask[i] = NULL; @@ -1188,10 +1188,10 @@ void Tutorial::setCompleted( int completableId ) int completableIndex = -1; - for( AUTO_VAR(it, s_completableTasks.begin()); it < s_completableTasks.end(); ++it) - { + for (int task : s_completableTasks) + { ++completableIndex; - if( *it == completableId ) + if( task == completableId ) { break; } @@ -1220,10 +1220,10 @@ bool Tutorial::getCompleted( int completableId ) //} int completableIndex = -1; - for( AUTO_VAR(it, s_completableTasks.begin()); it < s_completableTasks.end(); ++it) - { + for (int it : s_completableTasks) + { ++completableIndex; - if( *it == completableId ) + if( it == completableId ) { break; } @@ -1318,8 +1318,8 @@ void Tutorial::tick() for(unsigned int state = 0; state < e_Tutorial_State_Max; ++state) { - AUTO_VAR(it, constraintsToRemove[state].begin()); - while(it < constraintsToRemove[state].end() ) + auto it = constraintsToRemove[state].begin(); + while(it != constraintsToRemove[state].end() ) { ++(*it).second; if( (*it).second > m_iTutorialConstraintDelayRemoveTicks ) @@ -1361,7 +1361,7 @@ void Tutorial::tick() } if(!m_allowShow) - { + { if( currentTask[m_CurrentState] != NULL && (!currentTask[m_CurrentState]->AllowFade() || (lastMessageTime + m_iTutorialDisplayMessageTime ) > GetTickCount() ) ) { uiTempDisabled = true; @@ -1397,7 +1397,7 @@ void Tutorial::tick() app.TutorialSceneNavigateBack(m_iPad); m_bSceneIsSplitscreen=app.GetLocalPlayerCount()>1; if(m_bSceneIsSplitscreen) - { + { app.NavigateToScene(m_iPad, eUIComponent_TutorialPopup,(void *)this, false, false, &m_hTutorialScene); } else @@ -1427,9 +1427,8 @@ void Tutorial::tick() } // Check constraints - for(AUTO_VAR(it, m_globalConstraints.begin()); it < m_globalConstraints.end(); ++it) - { - TutorialConstraint *constraint = *it; + for (auto& constraint : m_globalConstraints) + { constraint->tick(m_iPad); } @@ -1443,9 +1442,8 @@ void Tutorial::tick() if(hintsOn) { - for(AUTO_VAR(it, hints[m_CurrentState].begin()); it < hints[m_CurrentState].end(); ++it) - { - TutorialHint *hint = *it; + for (auto& hint : hints[m_CurrentState]) + { hintNeeded = hint->tick(); if(hintNeeded >= 0) { @@ -1469,9 +1467,8 @@ void Tutorial::tick() constraintChanged = true; currentFailedConstraint[m_CurrentState] = NULL; } - for(AUTO_VAR(it, constraints[m_CurrentState].begin()); it < constraints[m_CurrentState].end(); ++it) - { - TutorialConstraint *constraint = *it; + for (auto& constraint : constraints[m_CurrentState]) + { if( !constraint->isConstraintSatisfied(m_iPad) && constraint->isConstraintRestrictive(m_iPad) ) { constraintChanged = true; @@ -1484,15 +1481,15 @@ void Tutorial::tick() { // Update tasks bool isCurrentTask = true; - AUTO_VAR(it, activeTasks[m_CurrentState].begin()); - while(activeTasks[m_CurrentState].size() > 0 && it < activeTasks[m_CurrentState].end()) + auto it = activeTasks[m_CurrentState].begin(); + while(activeTasks[m_CurrentState].size() > 0 && it != activeTasks[m_CurrentState].end()) { TutorialTask *task = *it; if( isCurrentTask || task->isPreCompletionEnabled() ) { isCurrentTask = false; if( - ( !task->ShowMinimumTime() || ( task->hasBeenActivated() && (lastMessageTime + m_iTutorialMinimumDisplayMessageTime ) < GetTickCount() ) ) + ( !task->ShowMinimumTime() || ( task->hasBeenActivated() && (lastMessageTime + m_iTutorialMinimumDisplayMessageTime ) < GetTickCount() ) ) && task->isCompleted() ) { @@ -1509,8 +1506,8 @@ void Tutorial::tick() { // 4J Stu - Move the delayed constraints to the gameplay state so that they are in // effect for a bit longer - AUTO_VAR(itCon, constraintsToRemove[m_CurrentState].begin()); - while(itCon != constraintsToRemove[m_CurrentState].end() ) + auto itCon = constraintsToRemove[m_CurrentState].begin(); + while(itCon != constraintsToRemove[m_CurrentState].end() ) { constraints[e_Tutorial_State_Gameplay].push_back(itCon->first); constraintsToRemove[e_Tutorial_State_Gameplay].push_back( pair<TutorialConstraint *, unsigned char>(itCon->first, itCon->second) ); @@ -1521,9 +1518,9 @@ void Tutorial::tick() } // Fall through the the normal complete state case e_Tutorial_Completion_Complete_State: - for(AUTO_VAR(itRem, activeTasks[m_CurrentState].begin()); itRem < activeTasks[m_CurrentState].end(); ++itRem) - { - delete (*itRem); + for (auto& itRem : activeTasks[m_CurrentState]) + { + delete itRem; } activeTasks[m_CurrentState].clear(); break; @@ -1531,9 +1528,9 @@ void Tutorial::tick() { TutorialTask *lastTask = activeTasks[m_CurrentState].at( activeTasks[m_CurrentState].size() - 1 ); activeTasks[m_CurrentState].pop_back(); - for(AUTO_VAR(itRem, activeTasks[m_CurrentState].begin()); itRem < activeTasks[m_CurrentState].end(); ++itRem) + for(auto& itRem : activeTasks[m_CurrentState]) { - delete (*itRem); + delete itRem; } activeTasks[m_CurrentState].clear(); activeTasks[m_CurrentState].push_back( lastTask ); @@ -1636,7 +1633,7 @@ void Tutorial::tick() message->m_promptId = currentTask[m_CurrentState]->getPromptId(); message->m_allowFade = currentTask[m_CurrentState]->AllowFade(); setMessage( message ); - currentTask[m_CurrentState]->TaskReminders()? m_iTaskReminders = 1 : m_iTaskReminders = 0; + currentTask[m_CurrentState]->TaskReminders()? m_iTaskReminders = 1 : m_iTaskReminders = 0; } else { @@ -1697,8 +1694,8 @@ bool Tutorial::setMessage(PopupMessageDetails *message) } else { - AUTO_VAR(it, messages.find(message->m_messageId)); - if( it != messages.end() && it->second != NULL ) + auto it = messages.find(message->m_messageId); + if( it != messages.end() && it->second != NULL ) { TutorialMessage *messageString = it->second; text = wstring( messageString->getMessageForDisplay() ); @@ -1727,8 +1724,8 @@ bool Tutorial::setMessage(PopupMessageDetails *message) } else if(message->m_promptId >= 0) { - AUTO_VAR(it, messages.find(message->m_promptId)); - if(it != messages.end() && it->second != NULL) + auto it = messages.find(message->m_promptId); + if(it != messages.end() && it->second != NULL) { TutorialMessage *prompt = it->second; text.append( prompt->getMessageForDisplay() ); @@ -1781,7 +1778,7 @@ bool Tutorial::setMessage(TutorialHint *hint, PopupMessageDetails *message) bool messageShown = false; DWORD time = GetTickCount(); if(message != NULL && (message->m_forceDisplay || hintsOn) && - (!message->m_delay || + (!message->m_delay || ( (m_hintDisplayed && (time - m_lastHintDisplayedTime) > m_iTutorialHintDelayTime ) || (!m_hintDisplayed && (time - lastMessageTime) > m_iTutorialMinimumDisplayMessageTime ) @@ -1793,7 +1790,7 @@ bool Tutorial::setMessage(TutorialHint *hint, PopupMessageDetails *message) if(messageShown) { - m_lastHintDisplayedTime = time; + m_lastHintDisplayedTime = time; m_hintDisplayed = true; if(hint!=NULL) setHintCompleted( hint ); } @@ -1817,7 +1814,7 @@ void Tutorial::showTutorialPopup(bool show) m_allowShow = show; if(!show) - { + { if( currentTask[m_CurrentState] != NULL && (!currentTask[m_CurrentState]->AllowFade() || (lastMessageTime + m_iTutorialDisplayMessageTime ) > GetTickCount() ) ) { uiTempDisabled = true; @@ -1828,36 +1825,32 @@ void Tutorial::showTutorialPopup(bool show) void Tutorial::useItemOn(Level *level, shared_ptr<ItemInstance> item, int x, int y, int z, bool bTestUseOnly) { - for(AUTO_VAR(it, activeTasks[m_CurrentState].begin()); it < activeTasks[m_CurrentState].end(); ++it) + for(auto& task : activeTasks[m_CurrentState]) { - TutorialTask *task = *it; task->useItemOn(level, item, x, y, z, bTestUseOnly); } } void Tutorial::useItemOn(shared_ptr<ItemInstance> item, bool bTestUseOnly) { - for(AUTO_VAR(it, activeTasks[m_CurrentState].begin()); it < activeTasks[m_CurrentState].end(); ++it) + for(auto& task : activeTasks[m_CurrentState]) { - TutorialTask *task = *it; task->useItem(item, bTestUseOnly); } } void Tutorial::completeUsingItem(shared_ptr<ItemInstance> item) { - for(AUTO_VAR(it, activeTasks[m_CurrentState].begin()); it < activeTasks[m_CurrentState].end(); ++it) + for(auto task : activeTasks[m_CurrentState]) { - TutorialTask *task = *it; task->completeUsingItem(item); } // Fix for #46922 - TU5: UI: Player receives a reminder that he is hungry while "hunger bar" is full (triggered in split-screen mode) if(m_CurrentState != e_Tutorial_State_Gameplay) { - for(AUTO_VAR(it, activeTasks[e_Tutorial_State_Gameplay].begin()); it < activeTasks[e_Tutorial_State_Gameplay].end(); ++it) + for(auto task : activeTasks[e_Tutorial_State_Gameplay]) { - TutorialTask *task = *it; task->completeUsingItem(item); } } @@ -1866,9 +1859,8 @@ void Tutorial::completeUsingItem(shared_ptr<ItemInstance> item) void Tutorial::startDestroyBlock(shared_ptr<ItemInstance> item, Tile *tile) { int hintNeeded = -1; - for(AUTO_VAR(it, hints[m_CurrentState].begin()); it < hints[m_CurrentState].end(); ++it) + for(auto& hint : hints[m_CurrentState]) { - TutorialHint *hint = *it; hintNeeded = hint->startDestroyBlock(item, tile); if(hintNeeded >= 0) { @@ -1877,16 +1869,14 @@ void Tutorial::startDestroyBlock(shared_ptr<ItemInstance> item, Tile *tile) setMessage( hint, message ); break; } - } } void Tutorial::destroyBlock(Tile *tile) { int hintNeeded = -1; - for(AUTO_VAR(it, hints[m_CurrentState].begin()); it < hints[m_CurrentState].end(); ++it) + for(auto& hint : hints[m_CurrentState]) { - TutorialHint *hint = *it; hintNeeded = hint->destroyBlock(tile); if(hintNeeded >= 0) { @@ -1895,16 +1885,14 @@ void Tutorial::destroyBlock(Tile *tile) setMessage( hint, message ); break; } - } } void Tutorial::attack(shared_ptr<Player> player, shared_ptr<Entity> entity) { int hintNeeded = -1; - for(AUTO_VAR(it, hints[m_CurrentState].begin()); it < hints[m_CurrentState].end(); ++it) + for(auto& hint : hints[m_CurrentState]) { - TutorialHint *hint = *it; hintNeeded = hint->attack(player->inventory->getSelected(), entity); if(hintNeeded >= 0) { @@ -1920,9 +1908,8 @@ void Tutorial::attack(shared_ptr<Player> player, shared_ptr<Entity> entity) void Tutorial::itemDamaged(shared_ptr<ItemInstance> item) { int hintNeeded = -1; - for(AUTO_VAR(it, hints[m_CurrentState].begin()); it < hints[m_CurrentState].end(); ++it) + for(auto& hint : hints[m_CurrentState]) { - TutorialHint *hint = *it; hintNeeded = hint->itemDamaged(item); if(hintNeeded >= 0) { @@ -1939,11 +1926,6 @@ void Tutorial::handleUIInput(int iAction) { if( m_hintDisplayed ) return; - //for(AUTO_VAR(it, activeTasks[m_CurrentState].begin()); it < activeTasks[m_CurrentState].end(); ++it) - //{ - // TutorialTask *task = *it; - // task->handleUIInput(iAction); - //} if(currentTask[m_CurrentState] != NULL) currentTask[m_CurrentState]->handleUIInput(iAction); } @@ -1951,9 +1933,8 @@ void Tutorial::handleUIInput(int iAction) void Tutorial::createItemSelected(shared_ptr<ItemInstance> item, bool canMake) { int hintNeeded = -1; - for(AUTO_VAR(it, hints[m_CurrentState].begin()); it < hints[m_CurrentState].end(); ++it) + for(auto& hint : hints[m_CurrentState]) { - TutorialHint *hint = *it; hintNeeded = hint->createItemSelected(item, canMake); if(hintNeeded >= 0) { @@ -1968,11 +1949,10 @@ void Tutorial::createItemSelected(shared_ptr<ItemInstance> item, bool canMake) void Tutorial::onCrafted(shared_ptr<ItemInstance> item) { - for(unsigned int state = 0; state < e_Tutorial_State_Max; ++state) + for(auto& subtasks : activeTasks) { - for(AUTO_VAR(it, activeTasks[state].begin()); it < activeTasks[state].end(); ++it) + for(auto& task : subtasks) { - TutorialTask *task = *it; task->onCrafted(item); } } @@ -1983,23 +1963,20 @@ void Tutorial::onTake(shared_ptr<ItemInstance> item, unsigned int invItemCountAn if( !m_hintDisplayed ) { bool hintNeeded = false; - for(AUTO_VAR(it, hints[m_CurrentState].begin()); it < hints[m_CurrentState].end(); ++it) + for(auto hint : hints[m_CurrentState]) { - TutorialHint *hint = *it; hintNeeded = hint->onTake(item); if(hintNeeded) { break; } - } } - for(unsigned int state = 0; state < e_Tutorial_State_Max; ++state) + for(auto& subtasks : activeTasks) { - for(AUTO_VAR(it, activeTasks[state].begin()); it < activeTasks[state].end(); ++it) + for(auto& task : subtasks) { - TutorialTask *task = *it; task->onTake(item, invItemCountAnyAux, invItemCountThisAux); } } @@ -2035,9 +2012,8 @@ void Tutorial::onLookAt(int id, int iData) if( m_hintDisplayed ) return; bool hintNeeded = false; - for(AUTO_VAR(it, hints[m_CurrentState].begin()); it < hints[m_CurrentState].end(); ++it) + for(auto& hint : hints[m_CurrentState]) { - TutorialHint *hint = *it; hintNeeded = hint->onLookAt(id, iData); if(hintNeeded) { @@ -2066,9 +2042,8 @@ void Tutorial::onLookAtEntity(shared_ptr<Entity> entity) if( m_hintDisplayed ) return; bool hintNeeded = false; - for(AUTO_VAR(it, hints[m_CurrentState].begin()); it < hints[m_CurrentState].end(); ++it) + for(auto& hint : hints[m_CurrentState]) { - TutorialHint *hint = *it; hintNeeded = hint->onLookAtEntity(entity->GetType()); if(hintNeeded) { @@ -2081,9 +2056,9 @@ void Tutorial::onLookAtEntity(shared_ptr<Entity> entity) changeTutorialState(e_Tutorial_State_Horse); } - for (AUTO_VAR(it, activeTasks[m_CurrentState].begin()); it != activeTasks[m_CurrentState].end(); ++it) + for (auto& it : activeTasks[m_CurrentState]) { - (*it)->onLookAtEntity(entity); + it->onLookAtEntity(entity); } } @@ -2098,17 +2073,16 @@ void Tutorial::onRideEntity(shared_ptr<Entity> entity) } } - for (AUTO_VAR(it, activeTasks[m_CurrentState].begin()); it != activeTasks[m_CurrentState].end(); ++it) + for (auto& it : activeTasks[m_CurrentState]) { - (*it)->onRideEntity(entity); + it->onRideEntity(entity); } } void Tutorial::onEffectChanged(MobEffect *effect, bool bRemoved) { - for(AUTO_VAR(it, activeTasks[m_CurrentState].begin()); it < activeTasks[m_CurrentState].end(); ++it) + for(auto& task : activeTasks[m_CurrentState]) { - TutorialTask *task = *it; task->onEffectChanged(effect,bRemoved); } } @@ -2116,9 +2090,8 @@ void Tutorial::onEffectChanged(MobEffect *effect, bool bRemoved) bool Tutorial::canMoveToPosition(double xo, double yo, double zo, double xt, double yt, double zt) { bool allowed = true; - for(AUTO_VAR(it, constraints[m_CurrentState].begin()); it < constraints[m_CurrentState].end(); ++it) + for(auto& constraint : constraints[m_CurrentState]) { - TutorialConstraint *constraint = *it; if( !constraint->isConstraintSatisfied(m_iPad) && !constraint->canMoveToPosition(xo,yo,zo,xt,yt,zt) ) { allowed = false; @@ -2136,9 +2109,8 @@ bool Tutorial::isInputAllowed(int mapping) if( Minecraft::GetInstance()->localplayers[m_iPad]->isUnderLiquid(Material::water) ) return true; bool allowed = true; - for(AUTO_VAR(it, constraints[m_CurrentState].begin()); it < constraints[m_CurrentState].end(); ++it) + for(auto& constraint : constraints[m_CurrentState]) { - TutorialConstraint *constraint = *it; if( constraint->isMappingConstrained( m_iPad, mapping ) ) { allowed = false; @@ -2156,9 +2128,9 @@ vector<TutorialTask *> *Tutorial::getTasks() unsigned int Tutorial::getCurrentTaskIndex() { unsigned int index = 0; - for(AUTO_VAR(it, tasks.begin()); it < tasks.end(); ++it) + for(const auto& task : tasks) { - if(*it == currentTask[e_Tutorial_State_Gameplay]) + if(task == currentTask[e_Tutorial_State_Gameplay]) break; ++index; @@ -2184,11 +2156,11 @@ void Tutorial::RemoveConstraint(TutorialConstraint *c, bool delayedRemove /*= fa if( c->getQueuedForRemoval() ) { // If it is already queued for removal, remove it on the next tick - /*for(AUTO_VAR(it, constraintsToRemove[m_CurrentState].begin()); it < constraintsToRemove[m_CurrentState].end(); ++it) + /*for(auto& it : constraintsToRemove[m_CurrentState]) { - if( it->first == c ) + if( it.first == c ) { - it->second = m_iTutorialConstraintDelayRemoveTicks; + it.second = m_iTutorialConstraintDelayRemoveTicks; break; } }*/ @@ -2196,12 +2168,12 @@ void Tutorial::RemoveConstraint(TutorialConstraint *c, bool delayedRemove /*= fa else if(delayedRemove) { c->setQueuedForRemoval(true); - constraintsToRemove[m_CurrentState].push_back( pair<TutorialConstraint *, unsigned char>(c, 0) ); + constraintsToRemove[m_CurrentState].emplace_back(c, 0); } else { - for( AUTO_VAR(it, constraintsToRemove[m_CurrentState].begin()); it < constraintsToRemove[m_CurrentState].end(); ++it) - { + for (auto it = constraintsToRemove[m_CurrentState].begin(); it != constraintsToRemove[m_CurrentState].end(); ++it) + { if( it->first == c ) { constraintsToRemove[m_CurrentState].erase( it ); @@ -2209,8 +2181,8 @@ void Tutorial::RemoveConstraint(TutorialConstraint *c, bool delayedRemove /*= fa } } - AUTO_VAR(it, find( constraints[m_CurrentState].begin(), constraints[m_CurrentState].end(), c)); - if( it != constraints[m_CurrentState].end() ) constraints[m_CurrentState].erase( find( constraints[m_CurrentState].begin(), constraints[m_CurrentState].end(), c) ); + auto it = find(constraints[m_CurrentState].begin(), constraints[m_CurrentState].end(), c); + if( it != constraints[m_CurrentState].end() ) constraints[m_CurrentState].erase( find( constraints[m_CurrentState].begin(), constraints[m_CurrentState].end(), c) ); // It may be in the gameplay list, so remove it from there if it is it = find( constraints[e_Tutorial_State_Gameplay].begin(), constraints[e_Tutorial_State_Gameplay].end(), c); @@ -2271,7 +2243,7 @@ void Tutorial::changeTutorialState(eTutorial_State newState, UIScene *scene /*= // The action that caused the change of state may also have completed the current task if( currentTask[m_CurrentState] != NULL && currentTask[m_CurrentState]->isCompleted() ) { - activeTasks[m_CurrentState].erase( find( activeTasks[m_CurrentState].begin(), activeTasks[m_CurrentState].end(), currentTask[m_CurrentState]) ); + activeTasks[m_CurrentState].erase( find( activeTasks[m_CurrentState].begin(), activeTasks[m_CurrentState].end(), currentTask[m_CurrentState]) ); if( activeTasks[m_CurrentState].size() > 0 ) { @@ -2304,9 +2276,8 @@ void Tutorial::changeTutorialState(eTutorial_State newState, UIScene *scene /*= if( m_CurrentState != newState ) { - for(AUTO_VAR(it, activeTasks[newState].begin()); it < activeTasks[newState].end(); ++it) - { - TutorialTask *task = *it; + for (auto& task : activeTasks[newState] ) + { task->onStateChange(newState); } m_CurrentState = newState; diff --git a/Minecraft.Client/Common/Tutorial/TutorialTask.cpp b/Minecraft.Client/Common/Tutorial/TutorialTask.cpp index 2251ab07..53fdd275 100644 --- a/Minecraft.Client/Common/Tutorial/TutorialTask.cpp +++ b/Minecraft.Client/Common/Tutorial/TutorialTask.cpp @@ -3,7 +3,7 @@ #include "TutorialConstraints.h" #include "TutorialTask.h" -TutorialTask::TutorialTask(Tutorial *tutorial, int descriptionId, bool enablePreCompletion, vector<TutorialConstraint *> *inConstraints, +TutorialTask::TutorialTask(Tutorial *tutorial, int descriptionId, bool enablePreCompletion, vector<TutorialConstraint *> *inConstraints, bool bShowMinimumTime, bool bAllowFade, bool bTaskReminders) : tutorial( tutorial ), descriptionId( descriptionId ), m_promptId( -1 ), enablePreCompletion( enablePreCompletion ), areConstraintsEnabled( false ), bIsCompleted( false ), bHasBeenActivated( false ), @@ -11,9 +11,8 @@ TutorialTask::TutorialTask(Tutorial *tutorial, int descriptionId, bool enablePre { if(inConstraints != NULL) { - for(AUTO_VAR(it, inConstraints->begin()); it < inConstraints->end(); ++it) + for(auto& constraint : *inConstraints) { - TutorialConstraint *constraint = *it; constraints.push_back( constraint ); } delete inConstraints; @@ -26,10 +25,8 @@ TutorialTask::~TutorialTask() { enableConstraints(false); - for(AUTO_VAR(it, constraints.begin()); it < constraints.end(); ++it) + for(auto& constraint : constraints) { - TutorialConstraint *constraint = *it; - if( constraint->getQueuedForRemoval() ) { constraint->setDeleteOnDeactivate(true); @@ -52,9 +49,8 @@ void TutorialTask::enableConstraints(bool enable, bool delayRemove /*= false*/) if( !enable && (areConstraintsEnabled || !delayRemove) ) { // Remove - for(AUTO_VAR(it, constraints.begin()); it != constraints.end(); ++it) + for(auto& constraint : constraints) { - TutorialConstraint *constraint = *it; //app.DebugPrintf(">>>>>>>> %i\n", constraints.size()); tutorial->RemoveConstraint( constraint, delayRemove ); } @@ -63,9 +59,8 @@ void TutorialTask::enableConstraints(bool enable, bool delayRemove /*= false*/) else if( !areConstraintsEnabled && enable ) { // Add - for(AUTO_VAR(it, constraints.begin()); it != constraints.end(); ++it) + for(auto& constraint : constraints) { - TutorialConstraint *constraint = *it; tutorial->AddConstraint( constraint ); } areConstraintsEnabled = true; diff --git a/Minecraft.Client/Common/UI/IUIScene_CraftingMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_CraftingMenu.cpp index 05a44202..fc012be3 100644 --- a/Minecraft.Client/Common/UI/IUIScene_CraftingMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_CraftingMenu.cpp @@ -91,7 +91,7 @@ IUIScene_CraftingMenu::_eGroupTab IUIScene_CraftingMenu::m_GroupTabBkgMapping3x3 // eBaseItemType_bow, // eBaseItemType_pockettool, // eBaseItemType_utensil, -// +// // } // eBaseItemType; @@ -180,11 +180,11 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) UpdateTooltips(); break; case ACTION_MENU_PAUSEMENU: - case ACTION_MENU_B: + case ACTION_MENU_B: ui.ShowTooltip( iPad, eToolTipButtonX, false ); ui.ShowTooltip( iPad, eToolTipButtonB, false ); - ui.ShowTooltip( iPad, eToolTipButtonA, false ); - ui.ShowTooltip( iPad, eToolTipButtonRB, false ); + ui.ShowTooltip( iPad, eToolTipButtonA, false ); + ui.ShowTooltip( iPad, eToolTipButtonRB, false ); // kill the crafting xui //ui.PlayUISFX(eSFX_Back); ui.CloseUIScenes(iPad); @@ -197,14 +197,14 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) #endif // Do some crafting! if(m_pPlayer && m_pPlayer->inventory) - { + { //RecipyList *recipes = ((Recipes *)Recipes::getInstance())->getRecipies(); Recipy::INGREDIENTS_REQUIRED *pRecipeIngredientsRequired=Recipes::getInstance()->getRecipeIngredientsArray(); // Force a make if the debug is on if(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<<eDebugSetting_CraftAnything)) { if(CanBeMadeA[m_iCurrentSlotHIndex].iCount!=0) - { + { int iSlot=iVSlotIndexA[m_iCurrentSlotVIndex]; int iRecipe= CanBeMadeA[m_iCurrentSlotHIndex].iRecipeA[iSlot]; @@ -256,7 +256,7 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) } } - if(pRecipeIngredientsRequired[iRecipe].bCanMake[iPad]) + if(pRecipeIngredientsRequired[iRecipe].bCanMake[iPad]) { pTempItemInst->onCraftedBy(m_pPlayer->level, dynamic_pointer_cast<Player>( m_pPlayer->shared_from_this() ), pTempItemInst->count ); // TODO 4J Stu - handleCraftItem should do a lot more than what it does, loads of the "can we craft" code should also probably be @@ -340,7 +340,7 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) break; case ACTION_MENU_LEFT_SCROLL: - // turn off the old group tab + // turn off the old group tab showTabHighlight(m_iGroupIndex,false); if(m_iGroupIndex==0) @@ -434,7 +434,7 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) // clear the indices iVSlotIndexA[0]=CanBeMadeA[m_iCurrentSlotHIndex].iCount-1; iVSlotIndexA[1]=0; - iVSlotIndexA[2]=1; + iVSlotIndexA[2]=1; UpdateVerticalSlots(); UpdateHighlight(); @@ -485,13 +485,13 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) else { iVSlotIndexA[1]--; - } + } ui.PlayUISFX(eSFX_Focus); } else if(CanBeMadeA[m_iCurrentSlotHIndex].iCount>2) { - { + { if(m_iCurrentSlotVIndex!=0) { // just move the highlight @@ -499,11 +499,11 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) ui.PlayUISFX(eSFX_Focus); } else - { + { //move the slots iVSlotIndexA[2]=iVSlotIndexA[1]; iVSlotIndexA[1]=iVSlotIndexA[0]; - // on 0 and went up, so cycle the values + // on 0 and went up, so cycle the values if(iVSlotIndexA[0]==0) { iVSlotIndexA[0]=CanBeMadeA[m_iCurrentSlotHIndex].iCount-1; @@ -536,7 +536,7 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) if(CanBeMadeA[m_iCurrentSlotHIndex].iCount>1) { if(bNoScrollSlots) - { + { if(iVSlotIndexA[1]==(CanBeMadeA[m_iCurrentSlotHIndex].iCount-1)) { iVSlotIndexA[1]=0; @@ -577,7 +577,7 @@ bool IUIScene_CraftingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) { m_iCurrentSlotVIndex++; ui.PlayUISFX(eSFX_Focus); - } + } } UpdateVerticalSlots(); UpdateHighlight(); @@ -621,9 +621,9 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() RecipyList *recipes = ((Recipes *)Recipes::getInstance())->getRecipies(); Recipy::INGREDIENTS_REQUIRED *pRecipeIngredientsRequired=Recipes::getInstance()->getRecipeIngredientsArray(); int iRecipeC=(int)recipes->size(); - AUTO_VAR(itRecipe, recipes->begin()); + auto itRecipe = recipes->begin(); - // dump out the recipe products + // dump out the recipe products // for (int i = 0; i < iRecipeC; i++) // { @@ -631,7 +631,7 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() // if (pTempItemInst != NULL) // { // wstring itemstring=pTempItemInst->toString(); - // + // // printf("Recipe [%d] = ",i); // OutputDebugStringW(itemstring.c_str()); // if(pTempItemInst->id!=0) @@ -645,7 +645,7 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() // { // printf("ID\t%d\tAux val\t%d\tBase type\t%d\tMaterial\t%d Count=%d\n",pTempItemInst->id, pTempItemInst->getAuxValue(),pTempItemInst->getItem()->getBaseItemType(),pTempItemInst->getItem()->getMaterial(),pTempItemInst->GetCount()); // } - // + // // } // } // } @@ -686,9 +686,9 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() if (m_pPlayer->inventory->items[k] != NULL) { // do they have the ingredient, and the aux value matches, and enough off it? - if((m_pPlayer->inventory->items[k]->id == pRecipeIngredientsRequired[i].iIngIDA[j]) && + if((m_pPlayer->inventory->items[k]->id == pRecipeIngredientsRequired[i].iIngIDA[j]) && // check if the ingredient required doesn't care about the aux value, or if it does, does the inventory item aux match it - ((pRecipeIngredientsRequired[i].iIngAuxValA[j]==Recipes::ANY_AUX_VALUE) || (pRecipeIngredientsRequired[i].iIngAuxValA[j]==m_pPlayer->inventory->items[k]->getAuxValue())) + ((pRecipeIngredientsRequired[i].iIngAuxValA[j]==Recipes::ANY_AUX_VALUE) || (pRecipeIngredientsRequired[i].iIngAuxValA[j]==m_pPlayer->inventory->items[k]->getAuxValue())) ) { // do they have enough? We need to check the whole inventory, since they may have enough in different slots (milk isn't milkx3, but milk,milk,milk) @@ -724,18 +724,18 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() // 4J Stu - TU-1 hotfix // Fix for #13143 - Players are able to craft items they do not have enough ingredients for if they store the ingredients in multiple, smaller stacks break; - } + } } } // if bFoundA[j] is false, then we didn't have enough of the ingredient required by the recipe, so mark the grid items we're short of if(bFoundA[j]==false) - { + { int iMissing = pRecipeIngredientsRequired[i].iIngValA[j]-iTotalCount; int iGridIndex=0; while(iMissing!=0) { // need to check if there is an aux val and match that - if(((pRecipeIngredientsRequired[i].uiGridA[iGridIndex]&0x00FFFFFF)==pRecipeIngredientsRequired[i].iIngIDA[j]) && + if(((pRecipeIngredientsRequired[i].uiGridA[iGridIndex]&0x00FFFFFF)==pRecipeIngredientsRequired[i].iIngIDA[j]) && ((pRecipeIngredientsRequired[i].iIngAuxValA[j]==Recipes::ANY_AUX_VALUE) ||(pRecipeIngredientsRequired[i].iIngAuxValA[j]== ((pRecipeIngredientsRequired[i].uiGridA[iGridIndex]&0xFF000000)>>24))) ) { // this grid entry is the ingredient we don't have enough of @@ -780,7 +780,7 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() // ignore for the misc base type - these have not been placed in a base type group if(iBaseType!=Item::eBaseItemType_undefined) - { + { for(int k=0;k<iHSlotBrushControl;k++) { // if the item base type is the same as one already in, then add it to that list @@ -804,7 +804,7 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() if(!bFound) { if(iHSlotBrushControl<m_iCraftablesMaxHSlotC) - { + { // add to the list CanBeMadeA[iHSlotBrushControl].iItemBaseType=iBaseType; CanBeMadeA[iHSlotBrushControl].iRecipeA[CanBeMadeA[iHSlotBrushControl].iCount++]=i; @@ -827,7 +827,7 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() } delete [] bFoundA; - itRecipe++; + itRecipe++; } } @@ -847,7 +847,7 @@ void IUIScene_CraftingMenu::CheckRecipesAvailable() uiAlpha = 31; } else - { + { if(pRecipeIngredientsRequired[CanBeMadeA[iIndex].iRecipeA[0]].bCanMake[getPad()]) { uiAlpha = 31; @@ -936,10 +936,10 @@ void IUIScene_CraftingMenu::UpdateHighlight() { itemstring=app.GetString( IDS_ITEM_FIREBALLCOAL ); } - } + } break; default: - itemstring=app.GetString(id ); + itemstring=app.GetString(id ); break; } @@ -1004,7 +1004,7 @@ void IUIScene_CraftingMenu::UpdateVerticalSlots() uiAlpha = 31; } else - { + { if(pRecipeIngredientsRequired[CanBeMadeA[m_iCurrentSlotHIndex].iRecipeA[iVSlotIndexA[i]]].bCanMake[getPad()]) { uiAlpha = 31; @@ -1043,7 +1043,7 @@ void IUIScene_CraftingMenu::DisplayIngredients() hideAllIngredientsSlots(); if(CanBeMadeA[m_iCurrentSlotHIndex].iCount!=0) - { + { int iSlot,iRecipy; if(CanBeMadeA[m_iCurrentSlotHIndex].iCount>1) { @@ -1135,13 +1135,13 @@ void IUIScene_CraftingMenu::DisplayIngredients() } } - for (int x = 0; x < iBoxWidth; x++) + for (int x = 0; x < iBoxWidth; x++) { - for (int y = 0; y < iBoxWidth; y++) + for (int y = 0; y < iBoxWidth; y++) { int index = x+y*iBoxWidth; if(pRecipeIngredientsRequired[iRecipy].uiGridA[x+y*3]!=0) - { + { int id=pRecipeIngredientsRequired[iRecipy].uiGridA[x+y*3]&0x00FFFFFF; assert(id!=0); int iAuxVal=(pRecipeIngredientsRequired[iRecipy].uiGridA[x+y*3]&0xFF000000)>>24; @@ -1164,7 +1164,7 @@ void IUIScene_CraftingMenu::DisplayIngredients() setIngredientSlotRedBox(index, false); } else - { + { if((pRecipeIngredientsRequired[iRecipy].usBitmaskMissingGridIngredients[getPad()]&(1<<(x+y*3)))!=0) { setIngredientSlotRedBox(index, true); @@ -1179,7 +1179,7 @@ void IUIScene_CraftingMenu::DisplayIngredients() { setIngredientSlotRedBox(index, false); setIngredientSlotItem(getPad(),index,nullptr); - } + } } } } @@ -1203,7 +1203,7 @@ void IUIScene_CraftingMenu::DisplayIngredients() { setIngredientSlotRedBox(i, false); setIngredientSlotItem(getPad(),i,nullptr); - } + } } } @@ -1220,7 +1220,7 @@ void IUIScene_CraftingMenu::UpdateDescriptionText(bool bCanBeMade) Recipy::INGREDIENTS_REQUIRED *pRecipeIngredientsRequired=Recipes::getInstance()->getRecipeIngredientsArray(); if(bCanBeMade) - { + { int iSlot;//,iRecipy; if(CanBeMadeA[m_iCurrentSlotHIndex].iCount>1) { @@ -1293,13 +1293,13 @@ void IUIScene_CraftingMenu::UpdateDescriptionText(bool bCanBeMade) #ifdef _DEBUG setDescriptionText(L"This is some placeholder description text about the craftable item."); #else - setDescriptionText(L""); + setDescriptionText(L""); #endif - } + } } else { - setDescriptionText(L""); + setDescriptionText(L""); } } @@ -1323,7 +1323,7 @@ void IUIScene_CraftingMenu::UpdateTooltips() { iSlot=iVSlotIndexA[m_iCurrentSlotVIndex]; } - else + else { iSlot=0; } @@ -1363,7 +1363,7 @@ void IUIScene_CraftingMenu::UpdateTooltips() { iSlot=iVSlotIndexA[m_iCurrentSlotVIndex]; } - else + else { iSlot=0; } @@ -1396,7 +1396,7 @@ bool IUIScene_CraftingMenu::isItemSelected(int itemId) { bool isSelected = false; if(m_pPlayer && m_pPlayer->inventory) - { + { //RecipyList *recipes = ((Recipes *)Recipes::getInstance())->getRecipies(); Recipy::INGREDIENTS_REQUIRED *pRecipeIngredientsRequired=Recipes::getInstance()->getRecipeIngredientsArray(); diff --git a/Minecraft.Client/Common/UI/IUIScene_CreativeMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_CreativeMenu.cpp index 04852e97..0d3f7dac 100644 --- a/Minecraft.Client/Common/UI/IUIScene_CreativeMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_CreativeMenu.cpp @@ -60,7 +60,7 @@ void IUIScene_CreativeMenu::staticCtor() ITEM_AUX(Tile::treeTrunk_Id, 0) ITEM_AUX(Tile::treeTrunk_Id, TreeTile::DARK_TRUNK) ITEM_AUX(Tile::treeTrunk_Id, TreeTile::BIRCH_TRUNK) - ITEM_AUX(Tile::treeTrunk_Id, TreeTile::JUNGLE_TRUNK) + ITEM_AUX(Tile::treeTrunk_Id, TreeTile::JUNGLE_TRUNK) ITEM(Tile::gravel_Id) ITEM(Tile::redBrick_Id) ITEM(Tile::mossyCobblestone_Id) @@ -144,7 +144,7 @@ void IUIScene_CreativeMenu::staticCtor() ITEM(Tile::sponge_Id) ITEM(Tile::melon_Id) ITEM(Tile::pumpkin_Id) - ITEM(Tile::litPumpkin_Id) + ITEM(Tile::litPumpkin_Id) ITEM_AUX(Tile::sapling_Id, Sapling::TYPE_DEFAULT) ITEM_AUX(Tile::sapling_Id, Sapling::TYPE_EVERGREEN) ITEM_AUX(Tile::sapling_Id, Sapling::TYPE_BIRCH) @@ -321,7 +321,7 @@ void IUIScene_CreativeMenu::staticCtor() ITEM(Tile::anvil_Id); ITEM(Item::bed_Id) ITEM(Item::bucket_empty_Id) - ITEM(Item::bucket_lava_Id) + ITEM(Item::bucket_lava_Id) ITEM(Item::bucket_water_Id) ITEM(Item::bucket_milk_Id) ITEM(Item::cauldron_Id) @@ -408,7 +408,7 @@ void IUIScene_CreativeMenu::staticCtor() ITEM(Item::beef_cooked_Id) ITEM(Item::beef_raw_Id) ITEM(Item::chicken_raw_Id) - ITEM(Item::chicken_cooked_Id) + ITEM(Item::chicken_cooked_Id) ITEM(Item::rotten_flesh_Id) ITEM(Item::spiderEye_Id) ITEM(Item::potato_Id) @@ -430,7 +430,7 @@ void IUIScene_CreativeMenu::staticCtor() ITEM(Item::pickAxe_wood_Id) ITEM(Item::hatchet_wood_Id) ITEM(Item::hoe_wood_Id) - + ITEM(Item::emptyMap_Id) ITEM(Item::helmet_chain_Id) ITEM(Item::chestplate_chain_Id) @@ -441,7 +441,7 @@ void IUIScene_CreativeMenu::staticCtor() ITEM(Item::pickAxe_stone_Id) ITEM(Item::hatchet_stone_Id) ITEM(Item::hoe_stone_Id) - + ITEM(Item::bow_Id) ITEM(Item::helmet_iron_Id) ITEM(Item::chestplate_iron_Id) @@ -452,7 +452,7 @@ void IUIScene_CreativeMenu::staticCtor() ITEM(Item::pickAxe_iron_Id) ITEM(Item::hatchet_iron_Id) ITEM(Item::hoe_iron_Id) - + ITEM(Item::arrow_Id) ITEM(Item::helmet_gold_Id) ITEM(Item::chestplate_gold_Id) @@ -514,7 +514,7 @@ void IUIScene_CreativeMenu::staticCtor() ITEM(Item::brick_Id) ITEM(Item::netherbrick_Id) ITEM(Item::stick_Id) - ITEM(Item::bowl_Id) + ITEM(Item::bowl_Id) ITEM(Item::bone_Id) ITEM(Item::string_Id) ITEM(Item::feather_Id) @@ -523,13 +523,13 @@ void IUIScene_CreativeMenu::staticCtor() ITEM(Item::gunpowder_Id) ITEM(Item::clay_Id) ITEM(Item::yellowDust_Id) - ITEM(Item::seeds_wheat_Id) + ITEM(Item::seeds_wheat_Id) ITEM(Item::seeds_melon_Id) ITEM(Item::seeds_pumpkin_Id) ITEM(Item::wheat_Id) ITEM(Item::reeds_Id) ITEM(Item::egg_Id) - ITEM(Item::sugar_Id) + ITEM(Item::sugar_Id) ITEM(Item::slimeBall_Id) ITEM(Item::blazeRod_Id) ITEM(Item::goldNugget_Id) @@ -562,7 +562,7 @@ void IUIScene_CreativeMenu::staticCtor() ITEM(Item::magmaCream_Id) ITEM(Item::speckledMelon_Id) ITEM(Item::glassBottle_Id) - ITEM_AUX(Item::potion_Id,0) // Water bottle + ITEM_AUX(Item::potion_Id,0) // Water bottle //ITEM_AUX(Item::potion_Id,MACRO_MAKEPOTION_AUXVAL(0, 0, MASK_TYPE_AWKWARD)) // Awkward Potion @@ -594,7 +594,7 @@ void IUIScene_CreativeMenu::staticCtor() //ITEM_AUX(Item::potion_Id,MACRO_MAKEPOTION_AUXVAL(0, MASK_LEVEL2, MASK_INSTANTHEALTH)) //ITEM_AUX(Item::potion_Id,MACRO_MAKEPOTION_AUXVAL(0, MASK_LEVEL2, MASK_NIGHTVISION)) //ITEM_AUX(Item::potion_Id,MACRO_MAKEPOTION_AUXVAL(0, MASK_LEVEL2, MASK_INVISIBILITY)) - + ITEM_AUX(Item::potion_Id,MACRO_MAKEPOTION_AUXVAL(0, 0, MASK_WEAKNESS)) ITEM_AUX(Item::potion_Id,MACRO_MAKEPOTION_AUXVAL(0, MASK_LEVEL2, MASK_STRENGTH)) ITEM_AUX(Item::potion_Id,MACRO_MAKEPOTION_AUXVAL(0, 0, MASK_SLOWNESS)) @@ -669,7 +669,7 @@ void IUIScene_CreativeMenu::staticCtor() // Top Row ECreative_Inventory_Groups blocksGroup[] = {eCreativeInventory_BuildingBlocks}; specs[eCreativeInventoryTab_BuildingBlocks] = new TabSpec(L"Structures", IDS_GROUPNAME_BUILDING_BLOCKS, 1, blocksGroup); - + #ifndef _CONTENT_PACKAGE ECreative_Inventory_Groups decorationsGroup[] = {eCreativeInventory_Decoration}; ECreative_Inventory_Groups debugDecorationsGroup[] = {eCreativeInventory_ArtToolsDecorations}; @@ -720,7 +720,7 @@ IUIScene_CreativeMenu::IUIScene_CreativeMenu() m_creativeSlotX = m_creativeSlotY = m_inventorySlotX = m_inventorySlotY = 0; // 4J JEV - Settup Tabs - for (int i = 0; i < eCreativeInventoryTab_COUNT; i++) + for (int i = 0; i < eCreativeInventoryTab_COUNT; i++) { m_tabDynamicPos[i] = 0; m_tabPage[i] = 0; @@ -735,7 +735,7 @@ void IUIScene_CreativeMenu::switchTab(ECreativeInventoryTabs tab) if(tab != m_curTab) updateTabHighlightAndText(tab); m_curTab = tab; - + updateScrollCurrentPage(m_tabPage[m_curTab] + 1, specs[m_curTab]->getPageCount()); specs[tab]->populateMenu(itemPickerMenu,m_tabDynamicPos[m_curTab], m_tabPage[m_curTab]); @@ -769,7 +769,7 @@ void IUIScene_CreativeMenu::ScrollBar(UIVec2D pointerPos) IUIScene_CreativeMenu::TabSpec::TabSpec(LPCWSTR icon, int descriptionId, int staticGroupsCount, ECreative_Inventory_Groups *staticGroups, int dynamicGroupsCount, ECreative_Inventory_Groups *dynamicGroups, int debugGroupsCount /*= 0*/, ECreative_Inventory_Groups *debugGroups /*= NULL*/) : m_icon(icon), m_descriptionId(descriptionId), m_staticGroupsCount(staticGroupsCount), m_dynamicGroupsCount(dynamicGroupsCount), m_debugGroupsCount(debugGroupsCount) { - + m_pages = 0; m_staticGroupsA = NULL; @@ -828,8 +828,8 @@ void IUIScene_CreativeMenu::TabSpec::populateMenu(AbstractContainerMenu *menu, i // Fill the dynamic group if(m_dynamicGroupsCount > 0 && m_dynamicGroupsA != NULL) { - for(AUTO_VAR(it, categoryGroups[m_dynamicGroupsA[dynamicIndex]].rbegin()); it != categoryGroups[m_dynamicGroupsA[dynamicIndex]].rend() && lastSlotIndex < MAX_SIZE; ++it) - { + for (auto it = categoryGroups[m_dynamicGroupsA[dynamicIndex]].rbegin(); it != categoryGroups[m_dynamicGroupsA[dynamicIndex]].rend() && lastSlotIndex < MAX_SIZE; ++it) + { Slot *slot = menu->getSlot(++lastSlotIndex); slot->set( *it ); } @@ -953,7 +953,7 @@ unsigned int IUIScene_CreativeMenu::TabSpec::getPageCount() IUIScene_CreativeMenu::ItemPickerMenu::ItemPickerMenu( shared_ptr<SimpleContainer> smp, shared_ptr<Inventory> inv ) : AbstractContainerMenu() { inventory = inv; - creativeContainer = smp; + creativeContainer = smp; //int startLength = slots->size(); @@ -994,7 +994,7 @@ IUIScene_AbstractContainerMenu::ESceneSection IUIScene_CreativeMenu::GetSectionA switch( eSection ) { case eSectionInventoryCreativeSelector: - if (eTapDirection == eTapStateDown || eTapDirection == eTapStateUp) + if (eTapDirection == eTapStateDown || eTapDirection == eTapStateUp) { newSection = eSectionInventoryCreativeUsing; } @@ -1081,7 +1081,7 @@ void IUIScene_CreativeMenu::handleAdditionalKeyPress(int iAction) dir = -1; // Fall through intentional case ACTION_MENU_RIGHT_SCROLL: - { + { ECreativeInventoryTabs tab = (ECreativeInventoryTabs)(m_curTab + dir); if (tab < 0) tab = (ECreativeInventoryTabs)(eCreativeInventoryTab_COUNT - 1); if (tab >= eCreativeInventoryTab_COUNT) tab = eCreativeInventoryTab_BuildingBlocks; @@ -1375,7 +1375,7 @@ void IUIScene_CreativeMenu::BuildFirework(vector<shared_ptr<ItemInstance> > *lis itemTag->put(FireworksItem::TAG_FIREWORKS, fireTag); firework->setTag(itemTag); - } + } list->push_back(firework); } diff --git a/Minecraft.Client/Common/UI/IUIScene_TradingMenu.cpp b/Minecraft.Client/Common/UI/IUIScene_TradingMenu.cpp index 8cc04940..059f9b75 100644 --- a/Minecraft.Client/Common/UI/IUIScene_TradingMenu.cpp +++ b/Minecraft.Client/Common/UI/IUIScene_TradingMenu.cpp @@ -47,11 +47,11 @@ bool IUIScene_TradingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) switch(iAction) { - case ACTION_MENU_B: + case ACTION_MENU_B: ui.ShowTooltip( iPad, eToolTipButtonX, false ); ui.ShowTooltip( iPad, eToolTipButtonB, false ); - ui.ShowTooltip( iPad, eToolTipButtonA, false ); - ui.ShowTooltip( iPad, eToolTipButtonRB, false ); + ui.ShowTooltip( iPad, eToolTipButtonA, false ); + ui.ShowTooltip( iPad, eToolTipButtonRB, false ); // kill the crafting xui //ui.PlayUISFX(eSFX_Back); ui.CloseUIScenes(iPad); @@ -78,7 +78,7 @@ bool IUIScene_TradingMenu::handleKeyDown(int iPad, int iAction, bool bRepeat) int buyBMatches = player->inventory->countMatches(buyBItem); if( (buyAItem != NULL && buyAMatches >= buyAItem->count) && (buyBItem == NULL || buyBMatches >= buyBItem->count) ) { - // 4J-JEV: Fix for PS4 #7111: [PATCH 1.12] Trading Librarian villagers for multiple ‘Enchanted Books’ will cause the title to crash. + // 4J-JEV: Fix for PS4 #7111: [PATCH 1.12] Trading Librarian villagers for multiple �Enchanted Books� will cause the title to crash. int actualShopItem = m_activeOffers.at(selectedShopItem).second; m_merchant->notifyTrade(activeRecipe); @@ -186,13 +186,12 @@ void IUIScene_TradingMenu::updateDisplay() m_activeOffers.clear(); int unfilteredIndex = 0; int firstValidTrade = INT_MAX; - for(AUTO_VAR(it, unfilteredOffers->begin()); it != unfilteredOffers->end(); ++it) + for(auto& recipe : *unfilteredOffers) { - MerchantRecipe *recipe = *it; if(!recipe->isDeprecated()) { - m_activeOffers.push_back( pair<MerchantRecipe *,int>(recipe,unfilteredIndex)); - firstValidTrade = min(firstValidTrade,unfilteredIndex); + m_activeOffers.emplace_back(recipe,unfilteredIndex); + firstValidTrade = std::min<int>(firstValidTrade, unfilteredIndex); } ++unfilteredIndex; } @@ -249,7 +248,7 @@ void IUIScene_TradingMenu::updateDisplay() vector<HtmlString> *offerDescription = GetItemDescription(activeRecipe->getSellItem()); setOfferDescription(offerDescription); - + shared_ptr<ItemInstance> buyAItem = activeRecipe->getBuyAItem(); shared_ptr<ItemInstance> buyBItem = activeRecipe->getBuyBItem(); @@ -307,7 +306,7 @@ void IUIScene_TradingMenu::updateDisplay() setRequest1RedBox(false); setRequest2RedBox(false); setRequest1Item(nullptr); - setRequest2Item(nullptr); + setRequest2Item(nullptr); vector<HtmlString> offerDescription; setOfferDescription(&offerDescription); } diff --git a/Minecraft.Client/Common/UI/UIControl_EnchantmentButton.cpp b/Minecraft.Client/Common/UI/UIControl_EnchantmentButton.cpp index 37f8fcf6..f1e2735a 100644 --- a/Minecraft.Client/Common/UI/UIControl_EnchantmentButton.cpp +++ b/Minecraft.Client/Common/UI/UIControl_EnchantmentButton.cpp @@ -24,7 +24,7 @@ bool UIControl_EnchantmentButton::setupControl(UIScene *scene, IggyValuePath *pa UIControl::setControlType(UIControl::eEnchantmentButton); bool success = UIControl_Button::setupControl(scene,parent,controlName); - //Button specific initialisers + //Button specific initialisers m_funcChangeState = registerFastName(L"ChangeState"); return success; @@ -40,7 +40,7 @@ void UIControl_EnchantmentButton::ReInit() { UIControl_Button::ReInit(); - + m_lastState = eState_Inactive; m_lastCost = 0; m_bHasFocus = false; @@ -54,10 +54,10 @@ void UIControl_EnchantmentButton::tick() } void UIControl_EnchantmentButton::render(IggyCustomDrawCallbackRegion *region) -{ +{ UIScene_EnchantingMenu *enchantingScene = (UIScene_EnchantingMenu *)m_parentScene; EnchantmentMenu *menu = enchantingScene->getMenu(); - + float width = region->x1 - region->x0; float height = region->y1 - region->y0; float xo = width/2; @@ -101,7 +101,7 @@ void UIControl_EnchantmentButton::render(IggyCustomDrawCallbackRegion *region) glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.1f); Minecraft *pMinecraft = Minecraft::GetInstance(); - wstring line = _toString<int>(cost); + wstring line = std::to_wstring(cost); Font *font = pMinecraft->altFont; //int col = 0x685E4A; unsigned int col = m_textColour; @@ -143,7 +143,7 @@ void UIControl_EnchantmentButton::updateState() EState state = eState_Inactive; int cost = menu->costs[m_index]; - + Minecraft *pMinecraft = Minecraft::GetInstance(); if(cost > pMinecraft->localplayers[enchantingScene->getPad()]->experienceLevel && !pMinecraft->localplayers[enchantingScene->getPad()]->abilities.instabuild) { @@ -165,7 +165,7 @@ void UIControl_EnchantmentButton::updateState() if(cost != m_lastCost) { - setLabel( _toString<int>(cost) ); + setLabel( std::to_wstring(cost) ); m_lastCost = cost; m_enchantmentString = EnchantmentNames::instance.getRandomName(); } diff --git a/Minecraft.Client/Common/UI/UIControl_PlayerSkinPreview.cpp b/Minecraft.Client/Common/UI/UIControl_PlayerSkinPreview.cpp index 2d7c0224..d74bd185 100644 --- a/Minecraft.Client/Common/UI/UIControl_PlayerSkinPreview.cpp +++ b/Minecraft.Client/Common/UI/UIControl_PlayerSkinPreview.cpp @@ -175,14 +175,14 @@ void UIControl_PlayerSkinPreview::CycleNextAnimation() void UIControl_PlayerSkinPreview::CyclePreviousAnimation() { - m_currentAnimation = (ESkinPreviewAnimations)(m_currentAnimation - 1); + m_currentAnimation = (ESkinPreviewAnimations)(m_currentAnimation - 1); if(m_currentAnimation < e_SkinPreviewAnimation_Walking) m_currentAnimation = (ESkinPreviewAnimations)(e_SkinPreviewAnimation_Count - 1); m_swingTime = 0.0f; } void UIControl_PlayerSkinPreview::render(IggyCustomDrawCallbackRegion *region) -{ +{ Minecraft *pMinecraft=Minecraft::GetInstance(); glEnable(GL_RESCALE_NORMAL); @@ -193,7 +193,7 @@ void UIControl_PlayerSkinPreview::render(IggyCustomDrawCallbackRegion *region) float height = region->y1 - region->y0; float xo = width/2; float yo = height; - + glTranslatef(xo, yo - 3.5f, 50.0f); //glTranslatef(120.0f, 294, 0.0f); @@ -224,11 +224,9 @@ void UIControl_PlayerSkinPreview::render(IggyCustomDrawCallbackRegion *region) //vector<ModelPart *> *pAdditionalModelParts=mob->GetAdditionalModelParts(); if(m_pvAdditionalModelParts && m_pvAdditionalModelParts->size()!=0) - { - for(AUTO_VAR(it, m_pvAdditionalModelParts->begin()); it != m_pvAdditionalModelParts->end(); ++it) + { + for(auto& pModelPart : *m_pvAdditionalModelParts) { - ModelPart *pModelPart=*it; - pModelPart->visible=true; } } @@ -238,11 +236,9 @@ void UIControl_PlayerSkinPreview::render(IggyCustomDrawCallbackRegion *region) // hide the additional parts if(m_pvAdditionalModelParts && m_pvAdditionalModelParts->size()!=0) - { - for(AUTO_VAR(it, m_pvAdditionalModelParts->begin()); it != m_pvAdditionalModelParts->end(); ++it) + { + for(auto& pModelPart : *m_pvAdditionalModelParts) { - ModelPart *pModelPart=*it; - pModelPart->visible=false; } } diff --git a/Minecraft.Client/Common/UI/UIController.cpp b/Minecraft.Client/Common/UI/UIController.cpp index 01ab49ba..5375b784 100644 --- a/Minecraft.Client/Common/UI/UIController.cpp +++ b/Minecraft.Client/Common/UI/UIController.cpp @@ -182,7 +182,7 @@ UIController::UIController() { m_uiDebugConsole = NULL; m_reloadSkinThread = NULL; - + m_navigateToHomeOnReload = false; m_bCleanupOnReload = false; @@ -302,7 +302,7 @@ void UIController::postInit() IggySetTextureSubstitutionCallbacks ( &UIController::TextureSubstitutionCreateCallback , &UIController::TextureSubstitutionDestroyCallback, this ); SetupFont(); - // + // loadSkins(); for(unsigned int i = 0; i < eUIGroup_COUNT; ++i) @@ -383,7 +383,7 @@ void UIController::SetupFont() app.m_dlcManager.LanguageChanged(); app.loadStringTable(); // Switch to use new string table, - + if (m_eTargetFont == m_eCurrentFont) { // 4J-JEV: If we're ingame, reload the font to update all the text. @@ -458,12 +458,12 @@ bool UIController::UsingBitmapFont() void UIController::tick() { SetupFont(); // If necessary, change font. - + if ( (m_navigateToHomeOnReload || m_bCleanupOnReload) && !ui.IsReloadingSkin() ) { ui.CleanUpSkinReload(); - - if (m_navigateToHomeOnReload || !g_NetworkManager.IsInSession()) + + if (m_navigateToHomeOnReload || !g_NetworkManager.IsInSession()) { ui.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_MainMenu); } @@ -500,8 +500,8 @@ void UIController::tick() // Clear out the cached movie file data __int64 currentTime = System::currentTimeMillis(); - for(AUTO_VAR(it, m_cachedMovieData.begin()); it != m_cachedMovieData.end();) - { + for (auto it = m_cachedMovieData.begin(); it != m_cachedMovieData.end();) + { if(it->second.m_expiry < currentTime) { delete [] it->second.m_ba.data; @@ -730,7 +730,7 @@ void UIController::CleanUpSkinReload() { if(!Minecraft::GetInstance()->skins->getSelected()->hasAudio()) { -#ifdef _DURANGO +#ifdef _DURANGO DWORD result = StorageManager.UnmountInstalledDLC(L"TPACK"); #else DWORD result = StorageManager.UnmountInstalledDLC("TPACK"); @@ -738,9 +738,8 @@ void UIController::CleanUpSkinReload() } } - for(AUTO_VAR(it,m_queuedMessageBoxData.begin()); it != m_queuedMessageBoxData.end(); ++it) + for(auto queuedData : m_queuedMessageBoxData) { - QueuedMessageBoxData *queuedData = *it; ui.NavigateToScene(queuedData->iPad, eUIScene_MessageBox, &queuedData->info, queuedData->layer, eUIGroup_Fullscreen); delete queuedData->info.uiOptionA; delete queuedData; @@ -752,8 +751,8 @@ byteArray UIController::getMovieData(const wstring &filename) { // Cache everything we load in the current tick __int64 targetTime = System::currentTimeMillis() + (1000LL * 60); - AUTO_VAR(it,m_cachedMovieData.find(filename)); - if(it == m_cachedMovieData.end() ) + auto it = m_cachedMovieData.find(filename); + if(it == m_cachedMovieData.end() ) { byteArray baFile = app.getArchiveFile(filename); CachedMovieData cmd; @@ -959,7 +958,7 @@ void UIController::handleInput() { #ifdef _DURANGO // 4J-JEV: Added exception for primary play who migh've uttered speech commands. - if(iPad != ProfileManager.GetPrimaryPad() + if(iPad != ProfileManager.GetPrimaryPad() && (!InputManager.IsPadConnected(iPad) || !InputManager.IsPadLocked(iPad)) ) continue; #endif for(unsigned int key = 0; key <= ACTION_MAX_MENU; ++key) @@ -1035,7 +1034,7 @@ void UIController::handleKeyPress(unsigned int iPad, unsigned int key) { // no active touch? clear active and highlighted touch UI elements m_ActiveUIElement = NULL; - m_HighlightedUIElement = NULL; + m_HighlightedUIElement = NULL; // fullscreen first UIScene *pScene=m_groups[(int)eUIGroup_Fullscreen]->getCurrentScene(); @@ -1085,7 +1084,7 @@ void UIController::handleKeyPress(unsigned int iPad, unsigned int key) } } } - } + } else if(m_bTouchscreenPressed && pTouchData->reportNum==1) { // fullscreen first @@ -1337,8 +1336,8 @@ void UIController::handleKeyPress(unsigned int iPad, unsigned int key) app.DebugPrintf(app.USER_SR, "Total static: %d , Total dynamic: %d\n", totalStatic, totalDynamic); app.DebugPrintf(app.USER_SR, "\n\nEND TOTAL SWF MEMORY USAGE\n"); app.DebugPrintf(app.USER_SR, "********************************\n\n"); - } - else + } + else #endif #endif #endif @@ -1535,7 +1534,7 @@ void UIController::setupCustomDrawGameState() glLoadIdentity(); glOrtho(0, m_fScreenWidth, m_fScreenHeight, 0, 1000, 3000); glMatrixMode(GL_MODELVIEW); - glEnable(GL_ALPHA_TEST); + glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.1f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); @@ -1635,22 +1634,22 @@ void RADLINK UIController::CustomDrawCallback(void *user_callback_data, Iggy *pl //Description //Callback to create a user-defined texture to replace SWF-defined textures. //Parameters -//width - Input value: optional number of pixels wide specified from AS3, or -1 if not defined. Output value: the number of pixels wide to pretend to Iggy that the bitmap is. SWF and AS3 scales bitmaps based on their pixel dimensions, so you can use this to substitute a texture that is higher or lower resolution that ActionScript thinks it is. -//height - Input value: optional number of pixels high specified from AS3, or -1 if not defined. Output value: the number of pixels high to pretend to Iggy that the bitmap is. SWF and AS3 scales bitmaps based on their pixel dimensions, so you can use this to substitute a texture that is higher or lower resolution that ActionScript thinks it is. -//destroy_callback_data - Optional additional output value you can set; the value will be passed along to the corresponding Iggy_TextureSubstitutionDestroyCallback (e.g. you can store the pointer to your own internal structure here). -//return - A platform-independent wrapped texture handle provided by GDraw, or NULL (NULL with throw an ActionScript 3 ArgumentError that the Flash developer can catch) Use by calling IggySetTextureSubstitutionCallbacks. +//width - Input value: optional number of pixels wide specified from AS3, or -1 if not defined. Output value: the number of pixels wide to pretend to Iggy that the bitmap is. SWF and AS3 scales bitmaps based on their pixel dimensions, so you can use this to substitute a texture that is higher or lower resolution that ActionScript thinks it is. +//height - Input value: optional number of pixels high specified from AS3, or -1 if not defined. Output value: the number of pixels high to pretend to Iggy that the bitmap is. SWF and AS3 scales bitmaps based on their pixel dimensions, so you can use this to substitute a texture that is higher or lower resolution that ActionScript thinks it is. +//destroy_callback_data - Optional additional output value you can set; the value will be passed along to the corresponding Iggy_TextureSubstitutionDestroyCallback (e.g. you can store the pointer to your own internal structure here). +//return - A platform-independent wrapped texture handle provided by GDraw, or NULL (NULL with throw an ActionScript 3 ArgumentError that the Flash developer can catch) Use by calling IggySetTextureSubstitutionCallbacks. // //Discussion // //If your texture includes an alpha channel, you must use a premultiplied alpha (where the R,G, and B channels have been multiplied by the alpha value); all Iggy shaders assume premultiplied alpha (and it looks better anyway). GDrawTexture * RADLINK UIController::TextureSubstitutionCreateCallback ( void * user_callback_data , IggyUTF16 * texture_name , S32 * width , S32 * height , void * * destroy_callback_data ) { - UIController *uiController = (UIController *)user_callback_data; - AUTO_VAR(it,uiController->m_substitutionTextures.find((wchar_t *)texture_name)); + UIController *uiController = static_cast<UIController *>(user_callback_data); + auto it = uiController->m_substitutionTextures.find(texture_name); - if(it != uiController->m_substitutionTextures.end()) + if(it != uiController->m_substitutionTextures.end()) { - app.DebugPrintf("Found substitution texture %ls, with %d bytes\n", (wchar_t *)texture_name,it->second.length); + app.DebugPrintf("Found substitution texture %ls, with %d bytes\n", texture_name,it->second.length); BufferedImage image(it->second.data, it->second.length); if( image.getData() != NULL ) @@ -1711,9 +1710,9 @@ void UIController::registerSubstitutionTexture(const wstring &textureName, PBYTE void UIController::unregisterSubstitutionTexture(const wstring &textureName, bool deleteData) { - AUTO_VAR(it,m_substitutionTextures.find(textureName)); + auto it = m_substitutionTextures.find(textureName); - if(it != m_substitutionTextures.end()) + if(it != m_substitutionTextures.end()) { if(deleteData) delete [] it->second.data; m_substitutionTextures.erase(it); @@ -1854,7 +1853,7 @@ bool UIController::NavigateBack(int iPad, bool forceUsePad, EUIScene eScene, EUI void UIController::NavigateToHomeMenu() { ui.CloseAllPlayersScenes(); - + // Alert the app the we no longer want to be informed of ethernet connections app.SetLiveLinkRequired( false ); @@ -1953,8 +1952,8 @@ size_t UIController::RegisterForCallbackId(UIScene *scene) void UIController::UnregisterCallbackId(size_t id) { EnterCriticalSection(&m_registeredCallbackScenesCS); - AUTO_VAR(it, m_registeredCallbackScenes.find(id) ); - if(it != m_registeredCallbackScenes.end() ) + auto it = m_registeredCallbackScenes.find(id); + if(it != m_registeredCallbackScenes.end() ) { m_registeredCallbackScenes.erase(it); } @@ -1964,8 +1963,8 @@ void UIController::UnregisterCallbackId(size_t id) UIScene *UIController::GetSceneFromCallbackId(size_t id) { UIScene *scene = NULL; - AUTO_VAR(it, m_registeredCallbackScenes.find(id) ); - if(it != m_registeredCallbackScenes.end() ) + auto it = m_registeredCallbackScenes.find(id); + if(it != m_registeredCallbackScenes.end() ) { scene = it->second; } @@ -2017,7 +2016,7 @@ void UIController::CloseUIScenes(int iPad, bool forceIPad) m_groups[(int)group]->closeAllScenes(); m_groups[(int)group]->getTooltips()->SetTooltips(-1); - + // This should cause the popup to dissappear TutorialPopupInfo popupInfo; if(m_groups[(int)group]->getTutorialPopup()) m_groups[(int)group]->getTutorialPopup()->SetTutorialDescription(&popupInfo); @@ -2168,7 +2167,7 @@ void UIController::SetMenuDisplayed(int iPad,bool bVal) #ifdef _DURANGO // 4J-JEV: When in-game, allow player to toggle the 'Pause' and 'IngameInfo' menus via Kinnect. - if (Minecraft::GetInstance()->running) + if (Minecraft::GetInstance()->running) InputManager.SetEnabledGtcButtons(_360_GTC_MENU | _360_GTC_PAUSE | _360_GTC_VIEW); #endif } @@ -2341,7 +2340,7 @@ void UIController::PlayUISFX(ESoundEffect eSound) // Don't play multiple SFX on the same tick // (prevents horrible sounds when programmatically setting multiple checkboxes) if (time - m_lastUiSfx < 10) { return; } - m_lastUiSfx = time; + m_lastUiSfx = time; Minecraft::GetInstance()->soundEngine->playUI(eSound,1.0f,1.0f); } @@ -2588,7 +2587,7 @@ void UIController::SetTrialTimerLimitSecs(unsigned int uiSeconds) void UIController::UpdateTrialTimer(unsigned int iPad) { - WCHAR wcTime[20]; + WCHAR wcTime[20]; DWORD dwTimeTicks=(DWORD)app.getTrialTimer(); @@ -2650,7 +2649,7 @@ void UIController::ShowAutosaveCountdownTimer(bool show) void UIController::UpdateAutosaveCountdownTimer(unsigned int uiSeconds) { #if !(defined(_XBOX_ONE) || defined(__ORBIS__)) - WCHAR wcAutosaveCountdown[100]; + WCHAR wcAutosaveCountdown[100]; swprintf( wcAutosaveCountdown, 100, app.GetString(IDS_AUTOSAVE_COUNTDOWN),uiSeconds); if(m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()) m_groups[(int)eUIGroup_Fullscreen]->getPressStartToPlay()->setTrialTimer(wcAutosaveCountdown); #endif @@ -2820,7 +2819,7 @@ C4JStorage::EMessageResult UIController::RequestUGCMessageBox(UINT title/* = -1 #ifdef __ORBIS__ // Show the vague UGC system message in addition to our message ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_UGC_RESTRICTION, iPad ); - return C4JStorage::EMessage_ResultAccept; + return C4JStorage::EMessage_ResultAccept; #elif defined(__PSVITA__) ProfileManager.ShowSystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, iPad ); UINT uiIDA[1]; @@ -2857,7 +2856,7 @@ C4JStorage::EMessageResult UIController::RequestContentRestrictedMessageBox(UINT #ifdef __ORBIS__ // Show the vague UGC system message in addition to our message ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_UGC_RESTRICTION, iPad ); - return C4JStorage::EMessage_ResultAccept; + return C4JStorage::EMessage_ResultAccept; #elif defined(__PSVITA__) ProfileManager.ShowSystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_AGE_RESTRICTION, iPad ); return C4JStorage::EMessage_ResultAccept; @@ -2897,7 +2896,7 @@ void UIController::setFontCachingCalculationBuffer(int length) } } -// Returns the first scene of given type if it exists, NULL otherwise +// Returns the first scene of given type if it exists, NULL otherwise UIScene *UIController::FindScene(EUIScene sceneType) { UIScene *pScene = NULL; @@ -3002,11 +3001,8 @@ void UIController::TouchBoxRebuild(UIScene *pUIScene) ui.TouchBoxesClear(pUIScene); // rebuild boxes - AUTO_VAR(itEnd, pUIScene->GetControls()->end()); - for (AUTO_VAR(it, pUIScene->GetControls()->begin()); it != itEnd; it++) + for ( UIControl *control : *pUIScene->GetControls() ) { - UIControl *control=(UIControl *)*it; - if(control->getControlType() == UIControl::eButton || control->getControlType() == UIControl::eSlider || control->getControlType() == UIControl::eCheckBox || @@ -3035,11 +3031,9 @@ void UIController::TouchBoxesClear(UIScene *pUIScene) EUILayer eUILayer=pUIScene->GetParentLayer()->m_iLayer; EUIScene eUIscene=pUIScene->getSceneType(); - AUTO_VAR(itEnd, m_TouchBoxes[eUIGroup][eUILayer][eUIscene].end()); - for (AUTO_VAR(it, m_TouchBoxes[eUIGroup][eUILayer][eUIscene].begin()); it != itEnd; it++) + for ( UIELEMENT *element : m_TouchBoxes[eUIGroup][eUILayer][eUIscene] ) { - UIELEMENT *element=(UIELEMENT *)*it; - delete element; + delete element; } m_TouchBoxes[eUIGroup][eUILayer][eUIscene].clear(); } @@ -3056,10 +3050,8 @@ bool UIController::TouchBoxHit(UIScene *pUIScene,S32 x, S32 y) if(m_TouchBoxes[eUIGroup][eUILayer][eUIscene].size()>0) { - AUTO_VAR(itEnd, m_TouchBoxes[eUIGroup][eUILayer][eUIscene].end()); - for (AUTO_VAR(it, m_TouchBoxes[eUIGroup][eUILayer][eUIscene].begin()); it != itEnd; it++) + for ( UIELEMENT *element : m_TouchBoxes[eUIGroup][eUILayer][eUIscene] ) { - UIELEMENT *element=(UIELEMENT *)*it; if(element->pControl->getHidden() == false && element->pControl->getVisible()) // ignore removed controls { if((x>=element->x1) &&(x<=element->x2) && (y>=element->y1) && (y<=element->y2)) @@ -3075,7 +3067,7 @@ bool UIController::TouchBoxHit(UIScene *pUIScene,S32 x, S32 y) return true; } } - } + } } //app.DebugPrintf("MISS at x = %i y = %i\n", (int)x, (int)y); diff --git a/Minecraft.Client/Common/UI/UILayer.cpp b/Minecraft.Client/Common/UI/UILayer.cpp index 13b26c84..b3cf72a0 100644 --- a/Minecraft.Client/Common/UI/UILayer.cpp +++ b/Minecraft.Client/Common/UI/UILayer.cpp @@ -18,18 +18,16 @@ void UILayer::tick() { // Delete old scenes - deleting a scene can cause a new scene to be deleted, so we need to make a copy of the scenes that we are going to try and destroy this tick vector<UIScene *>scenesToDeleteCopy; - for( AUTO_VAR(it,m_scenesToDelete.begin()); it != m_scenesToDelete.end(); it++) + for(auto& scene : m_scenesToDelete) { - UIScene *scene = (*it); scenesToDeleteCopy.push_back(scene); } m_scenesToDelete.clear(); // Delete the scenes in our copy if they are ready to delete, otherwise add back to the ones that are still to be deleted. Actually deleting a scene might also add something back into m_scenesToDelete. - for( AUTO_VAR(it,scenesToDeleteCopy.begin()); it != scenesToDeleteCopy.end(); it++) + for(auto& scene : scenesToDeleteCopy) { - UIScene *scene = (*it); - if( scene->isReadyToDelete()) + if( scene && scene->isReadyToDelete()) { delete scene; } @@ -38,7 +36,7 @@ void UILayer::tick() m_scenesToDelete.push_back(scene); } } - + while (!m_scenesToDestroy.empty()) { UIScene *scene = m_scenesToDestroy.back(); @@ -46,14 +44,13 @@ void UILayer::tick() scene->destroyMovie(); } m_scenesToDestroy.clear(); - - for(AUTO_VAR(it,m_components.begin()); it != m_components.end(); ++it) + + for(auto & component : m_components) { - (*it)->tick(); + component->tick(); } // Note: reverse iterator, the last element is the top of the stack - int sceneIndex = m_sceneStack.size() - 1; - //for(AUTO_VAR(it,m_sceneStack.rbegin()); it != m_sceneStack.rend(); ++it) + int sceneIndex = m_sceneStack.size() - 1; while( sceneIndex >= 0 && sceneIndex < m_sceneStack.size() ) { //(*it)->tick(); @@ -68,20 +65,20 @@ void UILayer::render(S32 width, S32 height, C4JRender::eViewportType viewport) { if(!ui.IsExpectingOrReloadingSkin()) { - for(AUTO_VAR(it,m_components.begin()); it != m_components.end(); ++it) - { - AUTO_VAR(itRef,m_componentRefCount.find((*it)->getSceneType())); - if(itRef != m_componentRefCount.end() && itRef->second.second) + for(auto& it : m_components) { - if((*it)->isVisible() ) + auto itRef = m_componentRefCount.find(it->getSceneType()); + if(itRef != m_componentRefCount.end() && itRef->second.second) { - PIXBeginNamedEvent(0, "Rendering component %d", (*it)->getSceneType() ); - (*it)->render(width, height,viewport); - PIXEndNamedEvent(); + if(it->isVisible() ) + { + PIXBeginNamedEvent(0, "Rendering component %d", it->getSceneType() ); + it->render(width, height,viewport); + PIXEndNamedEvent(); + } } } } - } if(!m_sceneStack.empty()) { int lowestRenderable = m_sceneStack.size() - 1; @@ -139,9 +136,9 @@ bool UILayer::HasFocus(int iPad) bool UILayer::hidesLowerScenes() { bool hidesScenes = false; - for(AUTO_VAR(it,m_components.begin()); it != m_components.end(); ++it) + for(auto& it : m_components) { - if((*it)->hidesLowerScenes()) + if(it->hidesLowerScenes()) { hidesScenes = true; break; @@ -168,28 +165,27 @@ void UILayer::getRenderDimensions(S32 &width, S32 &height) void UILayer::DestroyAll() { - for(AUTO_VAR(it,m_components.begin()); it != m_components.end(); ++it) + for(auto& it : m_components) { - (*it)->destroyMovie(); + it->destroyMovie(); } - for(AUTO_VAR(it, m_sceneStack.begin()); it != m_sceneStack.end(); ++it) + for(auto& it : m_sceneStack) { - (*it)->destroyMovie(); + it->destroyMovie(); } } void UILayer::ReloadAll(bool force) { - for(AUTO_VAR(it,m_components.begin()); it != m_components.end(); ++it) + for(auto& it : m_components) { - (*it)->reloadMovie(force); + it->reloadMovie(force); } if(!m_sceneStack.empty()) { - int lowestRenderable = 0; - for(;lowestRenderable < m_sceneStack.size(); ++lowestRenderable) + for(auto& lowestRenderable : m_sceneStack) { - m_sceneStack[lowestRenderable]->reloadMovie(force); + lowestRenderable->reloadMovie(force); } } } @@ -440,9 +436,9 @@ bool UILayer::NavigateToScene(int iPad, EUIScene scene, void *initData) } m_sceneStack.push_back(newScene); - + updateFocusState(); - + newScene->tick(); return true; @@ -493,8 +489,8 @@ bool UILayer::NavigateBack(int iPad, EUIScene eScene) void UILayer::showComponent(int iPad, EUIScene scene, bool show) { - AUTO_VAR(it,m_componentRefCount.find(scene)); - if(it != m_componentRefCount.end()) + auto it = m_componentRefCount.find(scene); + if(it != m_componentRefCount.end()) { it->second.second = show; return; @@ -505,8 +501,8 @@ void UILayer::showComponent(int iPad, EUIScene scene, bool show) bool UILayer::isComponentVisible(EUIScene scene) { bool visible = false; - AUTO_VAR(it,m_componentRefCount.find(scene)); - if(it != m_componentRefCount.end()) + auto it = m_componentRefCount.find(scene); + if(it != m_componentRefCount.end()) { visible = it->second.second; } @@ -515,16 +511,16 @@ bool UILayer::isComponentVisible(EUIScene scene) UIScene *UILayer::addComponent(int iPad, EUIScene scene, void *initData) { - AUTO_VAR(it,m_componentRefCount.find(scene)); - if(it != m_componentRefCount.end()) + auto it = m_componentRefCount.find(scene); + if(it != m_componentRefCount.end()) { ++it->second.first; - for(AUTO_VAR(itComp,m_components.begin()); itComp != m_components.end(); ++itComp) + for(auto& itComp : m_components) { - if( (*itComp)->getSceneType() == scene ) + if( itComp->getSceneType() == scene ) { - return *itComp; + return itComp; } } return NULL; @@ -586,16 +582,16 @@ UIScene *UILayer::addComponent(int iPad, EUIScene scene, void *initData) void UILayer::removeComponent(EUIScene scene) { - AUTO_VAR(it,m_componentRefCount.find(scene)); - if(it != m_componentRefCount.end()) + auto it = m_componentRefCount.find(scene); + if(it != m_componentRefCount.end()) { --it->second.first; if(it->second.first <= 0) { m_componentRefCount.erase(it); - for(AUTO_VAR(compIt, m_components.begin()) ; compIt != m_components.end(); ) - { + for (auto compIt = m_components.begin(); compIt != m_components.end();) + { if( (*compIt)->getSceneType() == scene) { #ifdef __PSVITA__ @@ -622,8 +618,8 @@ void UILayer::removeScene(UIScene *scene) ui.TouchBoxesClear(scene); #endif - AUTO_VAR(newEnd, std::remove(m_sceneStack.begin(), m_sceneStack.end(), scene) ); - m_sceneStack.erase(newEnd, m_sceneStack.end()); + auto newEnd = std::remove(m_sceneStack.begin(), m_sceneStack.end(), scene); + m_sceneStack.erase(newEnd, m_sceneStack.end()); m_scenesToDelete.push_back(scene); @@ -645,14 +641,14 @@ void UILayer::closeAllScenes() vector<UIScene *> temp; temp.insert(temp.end(), m_sceneStack.begin(), m_sceneStack.end()); m_sceneStack.clear(); - for(AUTO_VAR(it, temp.begin()); it != temp.end(); ++it) + for(auto& it : temp) { #ifdef __PSVITA__ // remove any touchboxes - ui.TouchBoxesClear(*it); + ui.TouchBoxesClear(it); #endif - m_scenesToDelete.push_back(*it); - (*it)->handleDestroy(); // For anything that might require the pointer be valid + m_scenesToDelete.push_back(it); + it->handleDestroy(); // For anything that might require the pointer be valid } updateFocusState(); @@ -696,8 +692,8 @@ bool UILayer::updateFocusState(bool allowedFocus /* = false */) m_bIgnorePlayerJoinMenuDisplayed = false; bool layerFocusSet = false; - for(AUTO_VAR(it,m_sceneStack.rbegin()); it != m_sceneStack.rend(); ++it) - { + for (auto it = m_sceneStack.rbegin(); it != m_sceneStack.rend(); ++it) + { UIScene *scene = *it; // UPDATE FOCUS STATES @@ -730,12 +726,12 @@ bool UILayer::updateFocusState(bool allowedFocus /* = false */) // 4J-PB - this should just be true m_bMenuDisplayed=true; - + EUIScene sceneType = scene->getSceneType(); switch(sceneType) { case eUIScene_PauseMenu: - m_bPauseMenuDisplayed = true; + m_bPauseMenuDisplayed = true; break; case eUIScene_Crafting2x2Menu: case eUIScene_Crafting3x3Menu: @@ -757,7 +753,7 @@ bool UILayer::updateFocusState(bool allowedFocus /* = false */) // Intentional fall-through case eUIScene_DeathMenu: - case eUIScene_FullscreenProgress: + case eUIScene_FullscreenProgress: case eUIScene_SignEntryMenu: case eUIScene_EndPoem: m_bIgnoreAutosaveMenuDisplayed = true; @@ -766,7 +762,7 @@ bool UILayer::updateFocusState(bool allowedFocus /* = false */) switch(sceneType) { - case eUIScene_FullscreenProgress: + case eUIScene_FullscreenProgress: case eUIScene_EndPoem: case eUIScene_Credits: case eUIScene_LeaderboardsMenu: @@ -783,7 +779,7 @@ bool UILayer::updateFocusState(bool allowedFocus /* = false */) UIScene *UILayer::getCurrentScene() { // Note: reverse iterator, the last element is the top of the stack - for(AUTO_VAR(it,m_sceneStack.rbegin()); it != m_sceneStack.rend(); ++it) + for( auto it = m_sceneStack.rbegin(); it != m_sceneStack.rend(); ++it) { UIScene *scene = *it; // 4J-PB - only used on Vita, so iPad 0 is fine @@ -800,13 +796,13 @@ UIScene *UILayer::getCurrentScene() void UILayer::handleInput(int iPad, int key, bool repeat, bool pressed, bool released, bool &handled) { // Note: reverse iterator, the last element is the top of the stack - for(AUTO_VAR(it,m_sceneStack.rbegin()); it != m_sceneStack.rend(); ++it) - { + for (auto it = m_sceneStack.rbegin(); it != m_sceneStack.rend(); ++it) + { UIScene *scene = *it; if(scene->hasFocus(iPad) && scene->canHandleInput()) { - // 4J-PB - ignore repeats of action ABXY buttons - // fix for PS3 213 - [MAIN MENU] Holding down buttons will continue to activate every prompt. + // 4J-PB - ignore repeats of action ABXY buttons + // fix for PS3 213 - [MAIN MENU] Holding down buttons will continue to activate every prompt. // 4J Stu - Changed this slightly to add the allowRepeat function so we can allow repeats in the crafting menu if(repeat && !scene->allowRepeat(key) ) { @@ -814,8 +810,8 @@ void UILayer::handleInput(int iPad, int key, bool repeat, bool pressed, bool rel } scene->handleInput(iPad, key, repeat, pressed, released, handled); } - - // Fix for PS3 #444 - [IN GAME] If the user keeps pressing CROSS while on the 'Save Game' screen the title will crash. + + // Fix for PS3 #444 - [IN GAME] If the user keeps pressing CROSS while on the 'Save Game' screen the title will crash. handled = handled || scene->hidesLowerScenes() || scene->blocksInput(); if(handled ) break; } @@ -825,8 +821,8 @@ void UILayer::handleInput(int iPad, int key, bool repeat, bool pressed, bool rel void UILayer::HandleDLCMountingComplete() { - for(AUTO_VAR(it,m_sceneStack.rbegin()); it != m_sceneStack.rend(); ++it) - { + for (auto it = m_sceneStack.rbegin(); it != m_sceneStack.rend(); ++it) + { UIScene *topScene = *it; app.DebugPrintf("UILayer::HandleDLCMountingComplete - topScene\n"); topScene->HandleDLCMountingComplete(); @@ -835,8 +831,8 @@ void UILayer::HandleDLCMountingComplete() void UILayer::HandleDLCInstalled() { - for(AUTO_VAR(it,m_sceneStack.rbegin()); it != m_sceneStack.rend(); ++it) - { + for (auto it = m_sceneStack.rbegin(); it != m_sceneStack.rend(); ++it) + { UIScene *topScene = *it; topScene->HandleDLCInstalled(); } @@ -845,7 +841,7 @@ void UILayer::HandleDLCInstalled() #ifdef _XBOX_ONE void UILayer::HandleDLCLicenseChange() { - for(AUTO_VAR(it,m_sceneStack.rbegin()); it != m_sceneStack.rend(); ++it) + for( auto it = m_sceneStack.rbegin(); it != m_sceneStack.rend(); ++it) { UIScene *topScene = *it; topScene->HandleDLCLicenseChange(); @@ -855,8 +851,8 @@ void UILayer::HandleDLCLicenseChange() void UILayer::HandleMessage(EUIMessage message, void *data) { - for(AUTO_VAR(it,m_sceneStack.rbegin()); it != m_sceneStack.rend(); ++it) - { + for (auto it = m_sceneStack.rbegin(); it != m_sceneStack.rend(); ++it) + { UIScene *topScene = *it; topScene->HandleMessage(message, data); } @@ -875,9 +871,9 @@ C4JRender::eViewportType UILayer::getViewport() void UILayer::handleUnlockFullVersion() { - for(AUTO_VAR(it, m_sceneStack.begin()); it != m_sceneStack.end(); ++it) + for(auto& it : m_sceneStack) { - (*it)->handleUnlockFullVersion(); + it->handleUnlockFullVersion(); } } @@ -885,20 +881,20 @@ void UILayer::PrintTotalMemoryUsage(__int64 &totalStatic, __int64 &totalDynamic) { __int64 layerStatic = 0; __int64 layerDynamic = 0; - for(AUTO_VAR(it,m_components.begin()); it != m_components.end(); ++it) + for(auto& it : m_components) { - (*it)->PrintTotalMemoryUsage(layerStatic, layerDynamic); + it->PrintTotalMemoryUsage(layerStatic, layerDynamic); } - for(AUTO_VAR(it, m_sceneStack.begin()); it != m_sceneStack.end(); ++it) + for(auto& it : m_sceneStack) { - (*it)->PrintTotalMemoryUsage(layerStatic, layerDynamic); + it->PrintTotalMemoryUsage(layerStatic, layerDynamic); } app.DebugPrintf(app.USER_SR, " \\- Layer static: %d , Layer dynamic: %d\n", layerStatic, layerDynamic); totalStatic += layerStatic; totalDynamic += layerDynamic; } -// Returns the first scene of given type if it exists, NULL otherwise +// Returns the first scene of given type if it exists, NULL otherwise UIScene *UILayer::FindScene(EUIScene sceneType) { for (int i = 0; i < m_sceneStack.size(); i++) diff --git a/Minecraft.Client/Common/UI/UIScene.cpp b/Minecraft.Client/Common/UI/UIScene.cpp index ba253643..6ef6d0e8 100644 --- a/Minecraft.Client/Common/UI/UIScene.cpp +++ b/Minecraft.Client/Common/UI/UIScene.cpp @@ -13,7 +13,7 @@ UIScene::UIScene(int iPad, UILayer *parentLayer) m_iPad = iPad; swf = NULL; m_pItemRenderer = NULL; - + bHasFocus = false; m_hasTickedOnce = false; m_bFocussedOnce = false; @@ -27,7 +27,7 @@ UIScene::UIScene(int iPad, UILayer *parentLayer) m_bUpdateOpacity = false; m_backScene = NULL; - + m_cacheSlotRenders = false; m_needsCacheRendered = true; m_expectedCachedSlotCount = 0; @@ -39,9 +39,9 @@ UIScene::~UIScene() /* Destroy the Iggy player. */ IggyPlayerDestroy( swf ); - for(AUTO_VAR(it,m_registeredTextures.begin()); it != m_registeredTextures.end(); ++it) + for(auto & it : m_registeredTextures) { - ui.unregisterSubstitutionTexture( it->first, it->second ); + ui.unregisterSubstitutionTexture( it.first, it.second ); } if(m_callbackUniqueId != 0) @@ -88,14 +88,14 @@ void UIScene::reloadMovie(bool force) handlePreReload(); // Reload controls - for(AUTO_VAR(it, m_controls.begin()); it != m_controls.end(); ++it) + for(auto & it : m_controls) { - (*it)->ReInit(); + it->ReInit(); } updateComponents(); handleReload(); - + IggyDataValue result; IggyDataValue value[1]; @@ -332,7 +332,7 @@ void UIScene::loadMovie() __int64 beforeLoad = ui.iggyAllocCount; swf = IggyPlayerCreateFromMemory ( baFile.data , baFile.length, NULL); __int64 afterLoad = ui.iggyAllocCount; - IggyPlayerInitializeAndTickRS ( swf ); + IggyPlayerInitializeAndTickRS ( swf ); __int64 afterTick = ui.iggyAllocCount; if(!swf) @@ -344,7 +344,7 @@ void UIScene::loadMovie() app.FatalLoadError(); } app.DebugPrintf( app.USER_SR, "Loaded iggy movie %ls\n", moviePath.c_str() ); - IggyProperties *properties = IggyPlayerProperties ( swf ); + IggyProperties *properties = IggyPlayerProperties ( swf ); m_movieHeight = properties->movie_height_in_pixels; m_movieWidth = properties->movie_width_in_pixels; @@ -352,7 +352,7 @@ void UIScene::loadMovie() m_renderHeight = m_movieHeight; S32 width, height; - m_parentLayer->getRenderDimensions(width, height); + m_parentLayer->getRenderDimensions(width, height); IggyPlayerSetDisplaySize( swf, width, height ); IggyPlayerSetUserdata(swf,this); @@ -373,7 +373,7 @@ void UIScene::loadMovie() { totalStatic += memoryInfo.static_allocation_bytes; totalDynamic += memoryInfo.dynamic_allocation_bytes; - app.DebugPrintf(app.USER_SR, "%ls - %.*s static: %d ( %d ) dynamic: %d ( %d )\n", moviePath.c_str(), memoryInfo.subcategory_stringlen, memoryInfo.subcategory, + app.DebugPrintf(app.USER_SR, "%ls - %.*s static: %d ( %d ) dynamic: %d ( %d )\n", moviePath.c_str(), memoryInfo.subcategory_stringlen, memoryInfo.subcategory, memoryInfo.static_allocation_bytes, memoryInfo.static_allocation_count, memoryInfo.dynamic_allocation_bytes, memoryInfo.dynamic_allocation_count); ++iteration; //if(memoryInfo.static_allocation_bytes > 0) getDebugMemoryUseRecursive(moviePath, memoryInfo); @@ -399,7 +399,7 @@ void UIScene::getDebugMemoryUseRecursive(const wstring &moviePath, IggyMemoryUse internalIteration , &internalMemoryInfo )) { - app.DebugPrintf(app.USER_SR, "%ls - %.*s static: %d ( %d ) dynamic: %d ( %d )\n", moviePath.c_str(), internalMemoryInfo.subcategory_stringlen, internalMemoryInfo.subcategory, + app.DebugPrintf(app.USER_SR, "%ls - %.*s static: %d ( %d ) dynamic: %d ( %d )\n", moviePath.c_str(), internalMemoryInfo.subcategory_stringlen, internalMemoryInfo.subcategory, internalMemoryInfo.static_allocation_bytes, internalMemoryInfo.static_allocation_count, internalMemoryInfo.dynamic_allocation_bytes, internalMemoryInfo.dynamic_allocation_count); ++internalIteration; if(internalMemoryInfo.subcategory_stringlen > memoryInfo.subcategory_stringlen) getDebugMemoryUseRecursive(moviePath, internalMemoryInfo); @@ -440,9 +440,9 @@ void UIScene::tick() while(IggyPlayerReadyToTick( swf )) { tickTimers(); - for(AUTO_VAR(it, m_controls.begin()); it != m_controls.end(); ++it) + for(auto & it : m_controls) { - (*it)->tick(); + it->tick(); } IggyPlayerTickRS( swf ); m_hasTickedOnce = true; @@ -468,8 +468,8 @@ void UIScene::addTimer(int id, int ms) void UIScene::killTimer(int id) { - AUTO_VAR(it, m_timers.find(id)); - if(it != m_timers.end()) + auto it = m_timers.find(id); + if(it != m_timers.end()) { it->second.running = false; } @@ -478,13 +478,13 @@ void UIScene::killTimer(int id) void UIScene::tickTimers() { int currentTime = System::currentTimeMillis(); - for(AUTO_VAR(it, m_timers.begin()); it != m_timers.end();) - { + for (auto it = m_timers.begin(); it != m_timers.end();) + { if(!it->second.running) { it = m_timers.erase(it); } - else + else { if(currentTime > it->second.targetTime) { @@ -501,8 +501,8 @@ void UIScene::tickTimers() IggyName UIScene::registerFastName(const wstring &name) { IggyName var; - AUTO_VAR(it,m_fastNames.find(name)); - if(it != m_fastNames.end()) + auto it = m_fastNames.find(name); + if(it != m_fastNames.end()) { var = it->second; } @@ -635,17 +635,16 @@ void UIScene::customDrawSlotControl(IggyCustomDrawCallbackRegion *region, int iP if(useCommandBuffers) RenderManager.CBuffStart(list, true); #endif PIXBeginNamedEvent(0,"Draw uncached"); - ui.setupCustomDrawMatrices(this, customDrawRegion); + ui.setupCustomDrawMatrices(this, customDrawRegion); _customDrawSlotControl(customDrawRegion, iPad, item, fAlpha, isFoil, bDecorations, useCommandBuffers); delete customDrawRegion; PIXEndNamedEvent(); PIXBeginNamedEvent(0,"Draw all cache"); // Draw all the cached slots - for(AUTO_VAR(it, m_cachedSlotDraw.begin()); it != m_cachedSlotDraw.end(); ++it) + for(auto& drawData : m_cachedSlotDraw) { - CachedSlotDrawData *drawData = *it; - ui.setupCustomDrawMatrices(this, drawData->customDrawRegion); + ui.setupCustomDrawMatrices(this, drawData->customDrawRegion); _customDrawSlotControl(drawData->customDrawRegion, iPad, drawData->item, drawData->fAlpha, drawData->isFoil, drawData->bDecorations, useCommandBuffers); delete drawData->customDrawRegion; delete drawData; @@ -699,7 +698,7 @@ void UIScene::customDrawSlotControl(IggyCustomDrawCallbackRegion *region, int iP // Finish GDraw and anything else that needs to be finalised ui.endCustomDraw(region); } - } + } } void UIScene::_customDrawSlotControl(CustomDrawData *region, int iPad, shared_ptr<ItemInstance> item, float fAlpha, bool isFoil, bool bDecorations, bool usingCommandBuffer) @@ -717,7 +716,7 @@ void UIScene::_customDrawSlotControl(CustomDrawData *region, int iPad, shared_pt // we might want separate x & y scales here float scaleX = bwidth / 16.0f; - float scaleY = bheight / 16.0f; + float scaleY = bheight / 16.0f; glEnable(GL_RESCALE_NORMAL); glPushMatrix(); @@ -755,8 +754,8 @@ void UIScene::_customDrawSlotControl(CustomDrawData *region, int iPad, shared_pt if(bDecorations) { if((scaleX!=1.0f) ||(scaleY!=1.0f)) - { - glPushMatrix(); + { + glPushMatrix(); glScalef(scaleX, scaleY, 1.0f); int iX= (int)(0.5f+((float)x)/scaleX); int iY= (int)(0.5f+((float)y)/scaleY); @@ -991,8 +990,8 @@ int UIScene::convertGameActionToIggyKeycode(int action) bool UIScene::allowRepeat(int key) { - // 4J-PB - ignore repeats of action ABXY buttons - // fix for PS3 213 - [MAIN MENU] Holding down buttons will continue to activate every prompt. + // 4J-PB - ignore repeats of action ABXY buttons + // fix for PS3 213 - [MAIN MENU] Holding down buttons will continue to activate every prompt. switch(key) { case ACTION_MENU_OK: @@ -1185,9 +1184,9 @@ void UIScene::registerSubstitutionTexture(const wstring &textureName, PBYTE pbDa bool UIScene::hasRegisteredSubstitutionTexture(const wstring &textureName) { - AUTO_VAR(it, m_registeredTextures.find( textureName ) ); + auto it = m_registeredTextures.find(textureName); - return it != m_registeredTextures.end(); + return it != m_registeredTextures.end(); } void UIScene::_handleFocusChange(F64 controlId, F64 childId) @@ -1240,10 +1239,8 @@ UIScene *UIScene::getBackScene() #ifdef __PSVITA__ void UIScene::UpdateSceneControls() { - AUTO_VAR(itEnd, GetControls()->end()); - for (AUTO_VAR(it, GetControls()->begin()); it != itEnd; it++) + for ( UIControl *control : *GetControls() ) { - UIControl *control=(UIControl *)*it; control->UpdateControl(); } } diff --git a/Minecraft.Client/Common/UI/UIScene_DLCOffersMenu.cpp b/Minecraft.Client/Common/UI/UIScene_DLCOffersMenu.cpp index 65c1b6fc..c109ed62 100644 --- a/Minecraft.Client/Common/UI/UIScene_DLCOffersMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_DLCOffersMenu.cpp @@ -191,13 +191,13 @@ void UIScene_DLCOffersMenu::handleInput(int iPad, int key, bool repeat, bool pre switch(iTextC) { case 0: - m_labelHTMLSellText.init("Voici un fantastique mini-pack de 24 apparences pour personnaliser votre personnage Minecraft et vous mettre dans l'ambiance des fêtes de fin d'année.<br><br>1-4 joueurs<br>2-8 joueurs en réseau<br><br> Cet article fait l’objet d’une licence ou d’une sous-licence de Sony Computer Entertainment America, et est soumis aux conditions générales du service du réseau, au contrat d’utilisateur, aux restrictions d’utilisation de cet article et aux autres conditions applicables, disponibles sur le site www.us.playstation.com/support/useragreements. Si vous ne souhaitez pas accepter ces conditions, ne téléchargez pas ce produit. Cet article peut être utilisé avec un maximum de deux systèmes PlayStation®3 activés associés à ce compte Sony Entertainment Network. <br><br>'Minecraft' est une marque commerciale de Notch Development AB."); + m_labelHTMLSellText.init("Voici un fantastique mini-pack de 24 apparences pour personnaliser votre personnage Minecraft et vous mettre dans l'ambiance des f�tes de fin d'ann�e.<br><br>1-4 joueurs<br>2-8 joueurs en r�seau<br><br> Cet article fait l�objet d�une licence ou d�une sous-licence de Sony Computer Entertainment America, et est soumis aux conditions g�n�rales du service du r�seau, au contrat d�utilisateur, aux restrictions d�utilisation de cet article et aux autres conditions applicables, disponibles sur le site www.us.playstation.com/support/useragreements. Si vous ne souhaitez pas accepter ces conditions, ne t�l�chargez pas ce produit. Cet article peut �tre utilis� avec un maximum de deux syst�mes PlayStation�3 activ�s associ�s � ce compte Sony Entertainment Network.�<br><br>'Minecraft' est une marque commerciale de Notch Development AB."); break; case 1: - m_labelHTMLSellText.init("Un fabuloso minipack de 24 aspectos para personalizar tu personaje de Minecraft y ponerte a tono con las fiestas.<br><br>1-4 jugadores<br>2-8 jugadores en red<br><br> Sony Computer Entertainment America le concede la licencia o sublicencia de este artículo, que está sujeto a los términos de servicio y al acuerdo de usuario de la red. Las restricciones de uso de este artículo, así como otros términos aplicables, se encuentran en www.us.playstation.com/support/useragreements. Si no desea aceptar todos estos términos, no descargue este artículo. Este artículo puede usarse en hasta dos sistemas PlayStation®3 activados asociados con esta cuenta de Sony Entertainment Network. <br><br>'Minecraft' es una marca comercial de Notch Development AB."); + m_labelHTMLSellText.init("Un fabuloso minipack de 24 aspectos para personalizar tu personaje de Minecraft y ponerte a tono con las fiestas.<br><br>1-4 jugadores<br>2-8 jugadores en red<br><br> Sony Computer Entertainment America le concede la licencia o sublicencia de este art�culo, que est� sujeto a los t�rminos de servicio y al acuerdo de usuario de la red. Las restricciones de uso de este art�culo, as� como otros t�rminos aplicables, se encuentran en www.us.playstation.com/support/useragreements. Si no desea aceptar todos estos t�rminos, no descargue este art�culo. Este art�culo puede usarse en hasta dos sistemas PlayStation�3 activados asociados con esta cuenta de Sony Entertainment Network.�<br><br>'Minecraft' es una marca comercial de Notch Development AB."); break; case 2: - m_labelHTMLSellText.init("Este é um incrível pacote com 24 capas para personalizar seu personagem no Minecraft e entrar no clima de final de ano.<br><br>1-4 Jogadores<br>Jogadores em rede 2-8<br><br> Este item está sendo licenciado ou sublicenciado para você pela Sony Computer Entertainment America e está sujeito aos Termos de Serviço da Rede e Acordo do Usuário, as restrições de uso deste item e outros termos aplicáveis estão localizados em www.us.playstation.com/support/useragreements. Caso não queira aceitar todos esses termos, não baixe este item. Este item pode ser usado com até 2 sistemas PlayStation®3 ativados associados a esta Conta de Rede Sony Entertainment. <br><br>'Minecraft' é uma marca registrada da Notch Development AB"); + m_labelHTMLSellText.init("Este � um incr�vel pacote com 24 capas para personalizar seu personagem no Minecraft e entrar no clima de final de ano.<br><br>1-4 Jogadores<br>Jogadores em rede 2-8<br><br> Este item est� sendo licenciado ou sublicenciado para voc� pela Sony Computer Entertainment America e est� sujeito aos Termos de Servi�o da Rede e Acordo do Usu�rio, as restri��es de uso deste item e outros termos aplic�veis est�o localizados em www.us.playstation.com/support/useragreements. Caso n�o queira aceitar todos esses termos, n�o baixe este item. Este item pode ser usado com at� 2 sistemas PlayStation�3 ativados associados a esta Conta de Rede Sony Entertainment.�<br><br>'Minecraft' � uma marca registrada da Notch Development AB"); break; } iTextC++; @@ -208,7 +208,7 @@ void UIScene_DLCOffersMenu::handleInput(int iPad, int key, bool repeat, bool pre case ACTION_MENU_OTHER_STICK_DOWN: case ACTION_MENU_OTHER_STICK_UP: // don't pass down PageUp or PageDown because this will cause conflicts between the buttonlist and scrollable html text component - //case ACTION_MENU_PAGEUP: + //case ACTION_MENU_PAGEUP: //case ACTION_MENU_PAGEDOWN: sendInputToMovie(key, repeat, pressed, released); break; @@ -235,7 +235,7 @@ void UIScene_DLCOffersMenu::handlePress(F64 controlId, F64 childId) #ifdef __PS3__ // is the item purchasable? - if(info.purchasabilityFlag==1) + if(info.purchasabilityFlag==1) { // can be bought app.Checkout(info.skuId); @@ -249,7 +249,7 @@ void UIScene_DLCOffersMenu::handlePress(F64 controlId, F64 childId) } #else // __ORBIS__ // is the item purchasable? - if(info.purchasabilityFlag==SCE_TOOLKIT_NP_COMMERCE_NOT_PURCHASED) + if(info.purchasabilityFlag==SCE_TOOLKIT_NP_COMMERCE_NOT_PURCHASED) { // can be bought app.Checkout(info.skuId); @@ -280,7 +280,7 @@ void UIScene_DLCOffersMenu::handleSelectionChanged(F64 selectedId) } void UIScene_DLCOffersMenu::handleFocusChange(F64 controlId, F64 childId) -{ +{ app.DebugPrintf("UIScene_DLCOffersMenu::handleFocusChange\n"); #ifdef __PSVITA__ @@ -305,7 +305,7 @@ void UIScene_DLCOffersMenu::handleFocusChange(F64 controlId, F64 childId) #if defined __PSVITA__ || defined __ORBIS__ if(m_pvProductInfo) - { + { m_bIsSelected = true; vector<SonyCommerce::ProductInfo >::iterator it = m_pvProductInfo->begin(); string teststring; @@ -315,7 +315,7 @@ void UIScene_DLCOffersMenu::handleFocusChange(F64 controlId, F64 childId) } SonyCommerce::ProductInfo info = *it; - if(info.purchasabilityFlag==SCE_TOOLKIT_NP_COMMERCE_NOT_PURCHASED) + if(info.purchasabilityFlag==SCE_TOOLKIT_NP_COMMERCE_NOT_PURCHASED) { m_bHasPurchased=false; } @@ -379,7 +379,7 @@ void UIScene_DLCOffersMenu::tick() #ifdef __PS3__ // is the item purchasable? - if(info.purchasabilityFlag==1) + if(info.purchasabilityFlag==1) { // can be bought app.DebugPrintf("Adding DLC (%s) - not bought\n",teststring.c_str()); @@ -397,7 +397,7 @@ void UIScene_DLCOffersMenu::tick() } #else // __ORBIS__ // is the item purchasable? - if(info.purchasabilityFlag==SCE_TOOLKIT_NP_COMMERCE_NOT_PURCHASED) + if(info.purchasabilityFlag==SCE_TOOLKIT_NP_COMMERCE_NOT_PURCHASED) { // can be bought m_buttonListOffers.addItem(teststring,false,i); @@ -445,13 +445,13 @@ void UIScene_DLCOffersMenu::tick() // does the DLC info have an image? if(pSONYDLCInfo && pSONYDLCInfo->dwImageBytes!=0) - { + { pbImageData=pSONYDLCInfo->pbImageData; iImageDataBytes=pSONYDLCInfo->dwImageBytes; bDeleteData=false; // we'll clean up the local LDC images - } + } else -#endif +#endif if(info.imageUrl[0]!=0) { SonyHttp::getDataFromURL(info.imageUrl,(void **)&pbImageData,&iImageDataBytes); @@ -460,7 +460,7 @@ void UIScene_DLCOffersMenu::tick() if(iImageDataBytes!=0) { - // set the image + // set the image registerSubstitutionTexture(textureName,pbImageData,iImageDataBytes,bDeleteData); m_bitmapIconOfferImage.setTextureName(textureName); // 4J Stu - Don't delete this @@ -497,25 +497,25 @@ void UIScene_DLCOffersMenu::tick() m_labelOffers.setLabel(app.GetString(IDS_NO_DLCCATEGORIES)); } } - + m_Timer.setVisible(false); m_bProductInfoShown=true; } } else { -#ifdef __PSVITA__ +#ifdef __PSVITA__ // MGH - fixes bug 5768 on Vita - should be extended properly to work for other platforms if((SonyCommerce_Vita::getPurchasabilityUpdated()) && app.GetCommerceProductListRetrieved()&& app.GetCommerceProductListInfoRetrieved() && m_iTotalDLC > 0) { - - { + + { vector<SonyCommerce::ProductInfo >::iterator it = m_pvProductInfo->begin(); for(int i=0;i<m_iTotalDLC;i++) { SonyCommerce::ProductInfo info = *it; // is the item purchasable? - if(info.purchasabilityFlag==SCE_TOOLKIT_NP_COMMERCE_NOT_PURCHASED) + if(info.purchasabilityFlag==SCE_TOOLKIT_NP_COMMERCE_NOT_PURCHASED) { // can be bought m_buttonListOffers.showTick(i, false); @@ -577,11 +577,11 @@ void UIScene_DLCOffersMenu::tick() // does the DLC info have an image? if(pSONYDLCInfo->dwImageBytes!=0) - { + { pbImageData=pSONYDLCInfo->pbImageData; iImageDataBytes=pSONYDLCInfo->dwImageBytes; bDeleteData=false; // we'll clean up the local LDC images - } + } else #endif { @@ -601,7 +601,7 @@ void UIScene_DLCOffersMenu::tick() else { m_bitmapIconOfferImage.setTextureName(L""); - } + } } else { @@ -620,7 +620,7 @@ void UIScene_DLCOffersMenu::tick() { // DLCContentRetrieved is to see if the type of content has been retrieved - and on Durango there is only type 0 - XMARKETPLACE_OFFERING_TYPE_CONTENT if(app.DLCContentRetrieved(e_Marketplace_Content)) - { + { m_bDLCRequiredIsRetrieved=true; // Retrieve the info @@ -660,29 +660,10 @@ void UIScene_DLCOffersMenu::tick() } } } - -// if(m_bBitmapOfferIconDisplayed==false) -// { -// // do we have it yet? -// if -// } - // retrieve the icons for the DLC -// if(m_vIconRetrieval.size()>0) -// { -// // for each icon, request it, and remove it from the list -// // the callback for the retrieval will update the display if needed -// -// AUTO_VAR(itEnd, m_vIconRetrieval.end()); -// for (AUTO_VAR(it, m_vIconRetrieval.begin()); it != itEnd; it++) -// { -// -// } -// -// } #endif } -#if defined _XBOX_ONE +#if defined _XBOX_ONE void UIScene_DLCOffersMenu::GetDLCInfo( int iOfferC, bool bUpdateOnly ) { MARKETPLACE_CONTENTOFFER_INFO xOffer; @@ -719,7 +700,7 @@ void UIScene_DLCOffersMenu::GetDLCInfo( int iOfferC, bool bUpdateOnly ) app.DebugPrintf("Unknown offer - %ls\n",xOffer.wszOfferName); } } - + qsort( OrderA, uiDLCCount, sizeof(SORTINDEXSTRUCT), OrderSortFunction ); for(int i = 0; i < uiDLCCount; i++) @@ -737,7 +718,7 @@ void UIScene_DLCOffersMenu::GetDLCInfo( int iOfferC, bool bUpdateOnly ) } if(pDLC->eDLCType==(eDLCContentType)m_iProductInfoIndex) - { + { wstring wstrTemp=xOffer.wszOfferName; // 4J-PB - Rog requested we remove the Minecraft at the start of the name. It's required for the Bing search, but gets in the way here @@ -774,7 +755,7 @@ void UIScene_DLCOffersMenu::GetDLCInfo( int iOfferC, bool bUpdateOnly ) * We've filtered results out from the list, need to keep track * of the 'actual' list index. */ - iCount++; + iCount++; } } @@ -834,7 +815,7 @@ bool UIScene_DLCOffersMenu::UpdateDisplay(MARKETPLACE_CONTENTOFFER_INFO& xOffer) // is the file in the local DLC images? - // is the file in the TMS XZP? + // is the file in the TMS XZP? //int iIndex = app.GetLocalTMSFileIndex(cString, true); if(dlc->dwImageBytes!=0) @@ -862,7 +843,7 @@ bool UIScene_DLCOffersMenu::UpdateDisplay(MARKETPLACE_CONTENTOFFER_INFO& xOffer) else { if(hasRegisteredSubstitutionTexture(cString)==false) - { + { BYTE *pData=NULL; DWORD dwSize=0; app.GetMemFileDetails(cString,&pData,&dwSize); @@ -879,12 +860,12 @@ bool UIScene_DLCOffersMenu::UpdateDisplay(MARKETPLACE_CONTENTOFFER_INFO& xOffer) m_bitmapIconOfferImage.setTextureName(cString); } bImageAvailable=true; - } + } } m_labelHTMLSellText.setLabel(xOffer.wszSellText); - // set the price info + // set the price info m_labelPriceTag.setVisible(true); m_labelPriceTag.setLabel(xOffer.wszCurrencyPrice); @@ -923,7 +904,7 @@ void UIScene_DLCOffersMenu::HandleDLCInstalled() } // void UIScene_DLCOffersMenu::HandleDLCMountingComplete() -// { +// { // app.DebugPrintf(4,"UIScene_SkinSelectMenu::HandleDLCMountingComplete\n"); //} diff --git a/Minecraft.Client/Common/UI/UIScene_DebugOverlay.cpp b/Minecraft.Client/Common/UI/UIScene_DebugOverlay.cpp index 6514e6ec..af86d4b8 100644 --- a/Minecraft.Client/Common/UI/UIScene_DebugOverlay.cpp +++ b/Minecraft.Client/Common/UI/UIScene_DebugOverlay.cpp @@ -80,7 +80,7 @@ UIScene_DebugOverlay::UIScene_DebugOverlay(int iPad, void *initData, UILayer *pa for(unsigned int level = ench->getMinLevel(); level <= ench->getMaxLevel(); ++level) { m_enchantmentIdAndLevels.push_back(pair<int,int>(ench->id,level)); - m_buttonListEnchantments.addItem(app.GetString( ench->getDescriptionId() ) + _toString<int>(level) ); + m_buttonListEnchantments.addItem(app.GetString( ench->getDescriptionId() ) + std::to_wstring(level) ); } } @@ -196,7 +196,7 @@ void UIScene_DebugOverlay::handlePress(F64 controlId, F64 childId) { int id = childId; if(id<m_mobFactories.size()) - { + { app.SetXuiServerAction(ProfileManager.GetPrimaryPad(),eXuiServerAction_SpawnMob,(void *)m_mobFactories[id]); } } diff --git a/Minecraft.Client/Common/UI/UIScene_EndPoem.cpp b/Minecraft.Client/Common/UI/UIScene_EndPoem.cpp index c5a8e61a..2f43cada 100644 --- a/Minecraft.Client/Common/UI/UIScene_EndPoem.cpp +++ b/Minecraft.Client/Common/UI/UIScene_EndPoem.cpp @@ -61,13 +61,13 @@ UIScene_EndPoem::UIScene_EndPoem(int iPad, void *initData, UILayer *parentLayer) noNoiseString = replaceAll(noNoiseString,L"{*PLAYER*}",playerName); Random random(8124371); - int found=(int)noNoiseString.find(L"{*NOISE*}"); + size_t found=noNoiseString.find(L"{*NOISE*}"); int length; while (found!=string::npos) { length = random.nextInt(4) + 3; m_noiseLengths.push_back(length); - found=(int)noNoiseString.find(L"{*NOISE*}",found+1); + found=noNoiseString.find(L"{*NOISE*}",found+1); } updateNoise(); @@ -77,7 +77,7 @@ UIScene_EndPoem::UIScene_EndPoem(int iPad, void *initData, UILayer *parentLayer) m_paragraphs = vector<wstring>(); int lastIndex = 0; for ( int index = 0; - index != wstring::npos; + index != wstring::npos; index = noiseString.find(L"<br /><br />", index+12, 12) ) { @@ -198,7 +198,7 @@ void UIScene_EndPoem::updateNoise() { Minecraft *pMinecraft = Minecraft::GetInstance(); noiseString = noNoiseString; - + int length = 0; wchar_t replacements[64]; wstring replaceString = L""; @@ -209,8 +209,8 @@ void UIScene_EndPoem::updateNoise() wstring tag = L"{*NOISE*}"; - AUTO_VAR(it, m_noiseLengths.begin()); - int found=(int)noiseString.find(tag); + auto it = m_noiseLengths.begin(); + size_t found= noiseString.find(tag); while (found!=string::npos && it != m_noiseLengths.end() ) { length = *it; @@ -229,7 +229,7 @@ void UIScene_EndPoem::updateNoise() static wstring acceptableLetters = L"!\"#$%&'()*+,-./0123456789:;<=>?@[\\]^_'|}~"; randomChar = acceptableLetters[ random->nextInt((int)acceptableLetters.length()) ]; } - + wstring randomCharStr = L""; randomCharStr.push_back(randomChar); if(randomChar == L'<') @@ -275,6 +275,6 @@ void UIScene_EndPoem::updateNoise() //ib.put(listPos + 256 + random->nextInt(2) + 8 + (darken ? 16 : 0)); //ib.put(listPos + pos + 32); - found=(int)noiseString.find(tag,found+1); + found=noiseString.find(tag,found+1); } }
\ No newline at end of file diff --git a/Minecraft.Client/Common/UI/UIScene_InventoryMenu.cpp b/Minecraft.Client/Common/UI/UIScene_InventoryMenu.cpp index 723937d0..4a9dab43 100644 --- a/Minecraft.Client/Common/UI/UIScene_InventoryMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_InventoryMenu.cpp @@ -32,7 +32,7 @@ UIScene_InventoryMenu::UIScene_InventoryMenu(int iPad, void *_initData, UILayer m_previousTutorialState = gameMode->getTutorial()->getCurrentState(); gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Inventory_Menu, this); } - + InventoryMenu *menu = (InventoryMenu *)initData->player->inventoryMenu; initData->player->awardStat(GenericStats::openInventory(),GenericStats::param_openInventory()); @@ -261,10 +261,8 @@ void UIScene_InventoryMenu::updateEffectsDisplay() int iValue = 0; IggyDataValue *UpdateValue = new IggyDataValue[activeEffects->size()*2]; - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) - { - MobEffectInstance *effect = *it; - + for(auto& effect : *activeEffects) + { if(effect->getDuration() >= m_bEffectTime[effect->getId()]) { wstring effectString = app.GetString( effect->getDescriptionId() );//I18n.get(effect.getDescriptionId()).trim(); diff --git a/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp b/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp index d3cbe4c3..0c515ec0 100644 --- a/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp @@ -300,7 +300,7 @@ UIScene_LoadOrJoinMenu::UIScene_LoadOrJoinMenu(int iPad, void *initData, UILayer bool bTexturePackAlreadyListed; bool bNeedToGetTPD=false; Minecraft *pMinecraft = Minecraft::GetInstance(); - int texturePacksCount = pMinecraft->skins->getTexturePackCount(); + int texturePacksCount = pMinecraft->skins->getTexturePackCount(); for(unsigned int i = 0; i < app.GetDLCInfoTexturesOffersCount(); ++i) { @@ -407,7 +407,7 @@ void UIScene_LoadOrJoinMenu::updateTooltips() // update the tooltips // if the saves list has focus, then we should show the Delete Save tooltip // if the games list has focus, then we should the the View Gamercard tooltip - int iRB=-1; + int iRB=-1; int iY = -1; int iLB = -1; int iX=-1; @@ -418,7 +418,7 @@ void UIScene_LoadOrJoinMenu::updateTooltips() else if (DoesSavesListHaveFocus()) { if((m_iDefaultButtonsC > 0) && (m_iSaveListIndex >= m_iDefaultButtonsC)) - { + { if(StorageManager.GetSaveDisabled()) { iRB=IDS_TOOLTIPS_DELETESAVE; @@ -474,7 +474,7 @@ void UIScene_LoadOrJoinMenu::updateTooltips() // Is there a save from PS3 or PSVita available? // Sony asked that this be displayed at all times so users are aware of the functionality. We'll display some text when there's no save available //if(app.getRemoteStorage()->saveIsAvailable()) - { + { bool bSignedInLive = ProfileManager.IsSignedInLive(m_iPad); if(bSignedInLive) { @@ -489,7 +489,7 @@ void UIScene_LoadOrJoinMenu::updateTooltips() ui.SetTooltips( DEFAULT_XUI_MENU_USER, IDS_TOOLTIPS_SELECT, IDS_TOOLTIPS_BACK, iX, iY,-1,-1,iLB,iRB); } -// +// void UIScene_LoadOrJoinMenu::Initialise() { m_iSaveListIndex = 0; @@ -577,7 +577,7 @@ void UIScene_LoadOrJoinMenu::handleGainFocus(bool navBack) { app.SetLiveLinkRequired( true ); - m_bMultiplayerAllowed = ProfileManager.IsSignedInLive( m_iPad ) && ProfileManager.AllowedToPlayMultiplayer(m_iPad); + m_bMultiplayerAllowed = ProfileManager.IsSignedInLive( m_iPad ) && ProfileManager.AllowedToPlayMultiplayer(m_iPad); // re-enable button presses m_bIgnoreInput=false; @@ -661,7 +661,7 @@ void UIScene_LoadOrJoinMenu::tick() #ifdef SONY_REMOTE_STORAGE_DOWNLOAD // if the loadOrJoin menu has focus again, we can clear the saveTransfer flag now. Added so we can delay the ehternet disconnect till it's cleaned up if(m_eSaveTransferState == eSaveTransfer_Idle) - m_bSaveTransferRunning = false; + m_bSaveTransferRunning = false; #endif #if defined(_XBOX_ONE) || defined(__ORBIS__) if(m_bUpdateSaveSize) @@ -978,7 +978,7 @@ void UIScene_LoadOrJoinMenu::GetSaveInfo() m_pSaveDetails=StorageManager.ReturnSavesInfo(); if(m_pSaveDetails==NULL) { - C4JStorage::ESaveGameState eSGIStatus= StorageManager.GetSavesInfo(m_iPad,NULL,this,"save"); + C4JStorage::ESaveGameState eSGIStatus= StorageManager.GetSavesInfo(m_iPad,NULL,this,"save"); } #endif @@ -1027,7 +1027,7 @@ void UIScene_LoadOrJoinMenu::GetSaveInfo() m_pSaveDetails=StorageManager.ReturnSavesInfo(); if(m_pSaveDetails==NULL) { - C4JStorage::ESaveGameState eSGIStatus= StorageManager.GetSavesInfo(m_iPad,NULL,this,"save"); + C4JStorage::ESaveGameState eSGIStatus= StorageManager.GetSavesInfo(m_iPad,NULL,this,"save"); } #if TO_BE_IMPLEMENTED @@ -1054,10 +1054,8 @@ void UIScene_LoadOrJoinMenu::AddDefaultButtons() int i = 0; - for(AUTO_VAR(it, app.getLevelGenerators()->begin()); it != app.getLevelGenerators()->end(); ++it) + for ( LevelGenerationOptions *levelGen : *app.getLevelGenerators() ) { - LevelGenerationOptions *levelGen = *it; - // retrieve the save icon from the texture pack, if there is one unsigned int uiTexturePackID=levelGen->getRequiredTexturePackId(); @@ -1071,7 +1069,7 @@ void UIScene_LoadOrJoinMenu::AddDefaultButtons() continue; } } - + // 4J-JEV: For debug. Ignore worlds with no name. LPCWSTR wstr = levelGen->getWorldName(); m_buttonListSaves.addItem( wstr ); @@ -1124,7 +1122,7 @@ void UIScene_LoadOrJoinMenu::handleInput(int iPad, int key, bool repeat, bool pr case ACTION_MENU_X: #if TO_BE_IMPLEMENTED // Change device - // Fix for #12531 - TCR 001: BAS Game Stability: When a player selects to change a storage + // Fix for #12531 - TCR 001: BAS Game Stability: When a player selects to change a storage // device, and repeatedly backs out of the SD screen, disconnects from LIVE, and then selects a SD, the title crashes. m_bIgnoreInput=true; StorageManager.SetSaveDevice(&CScene_MultiGameJoinLoad::DeviceSelectReturned,this,true); @@ -1142,7 +1140,7 @@ void UIScene_LoadOrJoinMenu::handleInput(int iPad, int key, bool repeat, bool pr { bool bSignedInLive = ProfileManager.IsSignedInLive(iPad); if(bSignedInLive) - { + { LaunchSaveTransfer(); } } @@ -1334,7 +1332,7 @@ int UIScene_LoadOrJoinMenu::KeyboardCompleteWorldNameCallback(LPVOID lpParam,boo UIScene_LoadOrJoinMenu *pClass=(UIScene_LoadOrJoinMenu *)lpParam; pClass->m_bIgnoreInput=false; if (bRes) - { + { uint16_t ui16Text[128]; ZeroMemory(ui16Text, 128 * sizeof(uint16_t) ); InputManager.GetText(ui16Text); @@ -1347,13 +1345,13 @@ int UIScene_LoadOrJoinMenu::KeyboardCompleteWorldNameCallback(LPVOID lpParam,boo StorageManager.RenameSaveData(pClass->m_iSaveListIndex - pClass->m_iDefaultButtonsC, ui16Text,&UIScene_LoadOrJoinMenu::RenameSaveDataReturned,pClass); #endif } - else + else { pClass->m_bIgnoreInput=false; pClass->updateTooltips(); } - } - else + } + else { pClass->m_bIgnoreInput=false; pClass->updateTooltips(); @@ -1367,13 +1365,13 @@ void UIScene_LoadOrJoinMenu::handleInitFocus(F64 controlId, F64 childId) app.DebugPrintf(app.USER_SR, "UIScene_LoadOrJoinMenu::handleInitFocus - %d , %d\n", (int)controlId, (int)childId); } -void UIScene_LoadOrJoinMenu::handleFocusChange(F64 controlId, F64 childId) +void UIScene_LoadOrJoinMenu::handleFocusChange(F64 controlId, F64 childId) { app.DebugPrintf(app.USER_SR, "UIScene_LoadOrJoinMenu::handleFocusChange - %d , %d\n", (int)controlId, (int)childId); - + switch((int)controlId) { - case eControl_GamesList: + case eControl_GamesList: m_iGameListIndex = childId; m_buttonListGames.updateChildFocus( (int) childId ); break; @@ -1409,7 +1407,7 @@ void UIScene_LoadOrJoinMenu::handlePress(F64 controlId, F64 childId) ui.PlayUISFX(eSFX_Press); if((int)childId == JOIN_LOAD_CREATE_BUTTON_INDEX) - { + { app.SetTutorialMode( false ); m_controlJoinTimer.setVisible( false ); @@ -1461,7 +1459,7 @@ void UIScene_LoadOrJoinMenu::handlePress(F64 controlId, F64 childId) } else #endif - { + { app.SetTutorialMode( false ); if(app.DebugSettingsOn() && app.GetLoadSavesFromFolderEnabled()) @@ -1503,7 +1501,7 @@ void UIScene_LoadOrJoinMenu::handlePress(F64 controlId, F64 childId) case eControl_GamesList: { m_bIgnoreInput=true; - + m_eAction = eAction_JoinGame; //CD - Added for audio @@ -1538,7 +1536,7 @@ void UIScene_LoadOrJoinMenu::CheckAndJoinGame(int gameIndex) bool bPlayStationPlus=true; int iPadWithNoPlaystationPlus=0; - bool isSignedInLive = true; + bool isSignedInLive = true; int iPadNotSignedInLive = -1; for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { @@ -1631,7 +1629,7 @@ void UIScene_LoadOrJoinMenu::CheckAndJoinGame(int gameIndex) SceNpCommerceDialogParam param; sceNpCommerceDialogParamInitialize(¶m); param.mode=SCE_NP_COMMERCE_DIALOG_MODE_PLUS; - param.features = SCE_NP_PLUS_FEATURE_REALTIME_MULTIPLAY; + param.features = SCE_NP_PLUS_FEATURE_REALTIME_MULTIPLAY; param.userId = ProfileManager.getUserID(iPadWithNoPlaystationPlus); iResult=sceNpCommerceDialogOpen(¶m); @@ -1714,7 +1712,7 @@ void UIScene_LoadOrJoinMenu::CheckAndJoinGame(int gameIndex) } void UIScene_LoadOrJoinMenu::LoadLevelGen(LevelGenerationOptions *levelGen) -{ +{ // Load data from disc //File saveFile( L"Tutorial\\Tutorial" ); //LoadSaveFromDisk(&saveFile); @@ -1812,7 +1810,7 @@ void UIScene_LoadOrJoinMenu::UpdateGamesList() // if the saves list has focus, then we should show the Delete Save tooltip // if the games list has focus, then we should show the View Gamercard tooltip - int iRB=-1; + int iRB=-1; int iY = -1; int iX=-1; @@ -1859,10 +1857,8 @@ void UIScene_LoadOrJoinMenu::UpdateGamesList() unsigned int sessionIndex = 0; m_buttonListGames.setCurrentSelection(0); - for( AUTO_VAR(it, m_currentSessions->begin()); it < m_currentSessions->end(); ++it) + for( FriendSessionInfo *sessionInfo : *m_currentSessions ) { - FriendSessionInfo *sessionInfo = *it; - wchar_t textureName[64] = L"\0"; // Is this a default game or a texture pack game? @@ -2036,7 +2032,7 @@ void UIScene_LoadOrJoinMenu::handleTimerComplete(int id) if(iImageDataBytes!=0) { - // set the image + // set the image registerSubstitutionTexture(textureName,pbImageData,iImageDataBytes,true); m_iConfigA[i]=-1; } @@ -2049,7 +2045,7 @@ void UIScene_LoadOrJoinMenu::handleTimerComplete(int id) bool bAllDone=true; for(int i=0;i<m_iTexturePacksNotInstalled;i++) { - if(m_iConfigA[i]!=-1) + if(m_iConfigA[i]!=-1) { bAllDone = false; } @@ -2064,13 +2060,13 @@ void UIScene_LoadOrJoinMenu::handleTimerComplete(int id) } break; -#endif +#endif } } void UIScene_LoadOrJoinMenu::LoadSaveFromDisk(File *saveFile, ESavePlatform savePlatform /*= SAVE_FILE_PLATFORM_LOCAL*/) -{ +{ // we'll only be coming in here when the tutorial is loaded now StorageManager.ResetSaveData(); @@ -2128,7 +2124,7 @@ void UIScene_LoadOrJoinMenu::LoadSaveFromDisk(File *saveFile, ESavePlatform save #ifdef SONY_REMOTE_STORAGE_DOWNLOAD void UIScene_LoadOrJoinMenu::LoadSaveFromCloud() -{ +{ wchar_t wFileName[128]; mbstowcs(wFileName, app.getRemoteStorage()->getLocalFilename(), strlen(app.getRemoteStorage()->getLocalFilename())+1); // plus null @@ -2201,7 +2197,7 @@ int UIScene_LoadOrJoinMenu::DeleteSaveDialogReturned(void *pParam,int iPad,C4JSt // Check that we have a valid save selected (can get a bad index if the save list has been refreshed) bool validSelection= pClass->m_iDefaultButtonsC != 0 && pClass->m_iSaveListIndex >= pClass->m_iDefaultButtonsC; - if(result==C4JStorage::EMessage_ResultDecline && validSelection) + if(result==C4JStorage::EMessage_ResultDecline && validSelection) { if(app.DebugSettingsOn() && app.GetLoadSavesFromFolderEnabled()) { @@ -2231,7 +2227,7 @@ int UIScene_LoadOrJoinMenu::DeleteSaveDataReturned(LPVOID lpParam,bool bRes) if(bRes) { // wipe the list and repopulate it - pClass->m_iState=e_SavesRepopulateAfterDelete; + pClass->m_iState=e_SavesRepopulateAfterDelete; } else pClass->m_bIgnoreInput=false; @@ -2363,7 +2359,7 @@ int UIScene_LoadOrJoinMenu::MustSignInTexturePack(void *pParam,int iPad,C4JStora { UIScene_LoadOrJoinMenu* pClass = (UIScene_LoadOrJoinMenu*)pParam; - if(result==C4JStorage::EMessage_ResultAccept) + if(result==C4JStorage::EMessage_ResultAccept) { SQRNetworkManager_Vita::AttemptPSNSignIn(&UIScene_LoadOrJoinMenu::MustSignInReturnedTexturePack, pClass); } @@ -2391,7 +2387,7 @@ int UIScene_LoadOrJoinMenu::MustSignInReturnedTexturePack(void *pParam,bool bCon if(bContinue==true) { - SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo(pClass->m_initData->selectedSession->data.texturePackParentId); + SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo(pClass->m_initData->selectedSession->data.texturePackParentId); if(pSONYDLCInfo!=NULL) { char chName[42]; @@ -2420,7 +2416,7 @@ int UIScene_LoadOrJoinMenu::MustSignInReturnedTexturePack(void *pParam,bool bCon } else { - app.Checkout(chSkuID); + app.Checkout(chSkuID); } } } @@ -2436,7 +2432,7 @@ int UIScene_LoadOrJoinMenu::TexturePackDialogReturned(void *pParam,int iPad,C4JS UIScene_LoadOrJoinMenu *pClass = (UIScene_LoadOrJoinMenu *)pParam; // Exit with or without saving - if(result==C4JStorage::EMessage_ResultAccept) + if(result==C4JStorage::EMessage_ResultAccept) { // we need to enable background downloading for the DLC XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); @@ -2454,7 +2450,7 @@ int UIScene_LoadOrJoinMenu::TexturePackDialogReturned(void *pParam,int iPad,C4JS } #endif - SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo(pClass->m_initData->selectedSession->data.texturePackParentId); + SONYDLC *pSONYDLCInfo=app.GetSONYDLCInfo(pClass->m_initData->selectedSession->data.texturePackParentId); if(pSONYDLCInfo!=NULL) { char chName[42]; @@ -2483,16 +2479,16 @@ int UIScene_LoadOrJoinMenu::TexturePackDialogReturned(void *pParam,int iPad,C4JS } else { - app.Checkout(chSkuID); + app.Checkout(chSkuID); } } } #endif -#if defined _XBOX_ONE +#if defined _XBOX_ONE if(ProfileManager.IsSignedIn(iPad)) - { + { if (ProfileManager.IsSignedInLive(iPad)) { wstring ProductId; @@ -2501,13 +2497,13 @@ int UIScene_LoadOrJoinMenu::TexturePackDialogReturned(void *pParam,int iPad,C4JS StorageManager.InstallOffer(1,(WCHAR *)ProductId.c_str(),NULL,NULL); } else - { + { // 4J-JEV: Fix for XB1: #165863 - XR-074: Compliance: With no active network connection user is unable to convert from Trial to Full texture pack and is not messaged why. UINT uiIDA[1] = { IDS_CONFIRM_OK }; - ui.RequestErrorMessage(IDS_PRO_NOTONLINE_TITLE, IDS_PRO_XBOXLIVE_NOTIFICATION, uiIDA, 1, iPad); + ui.RequestErrorMessage(IDS_PRO_NOTONLINE_TITLE, IDS_PRO_XBOXLIVE_NOTIFICATION, uiIDA, 1, iPad); } } -#endif +#endif } pClass->m_bIgnoreInput=false; @@ -2519,7 +2515,7 @@ int UIScene_LoadOrJoinMenu::MustSignInReturnedPSN(void *pParam,int iPad,C4JStora { UIScene_LoadOrJoinMenu* pClass = (UIScene_LoadOrJoinMenu*)pParam; - if(result==C4JStorage::EMessage_ResultAccept) + if(result==C4JStorage::EMessage_ResultAccept) { #if defined(__PS3__) SQRNetworkManager_PS3::AttemptPSNSignIn(&UIScene_LoadOrJoinMenu::PSN_SignInReturned, pClass); @@ -2679,7 +2675,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter Compression::UseDefaultThreadStorage(); UIScene_LoadOrJoinMenu* pClass = (UIScene_LoadOrJoinMenu *) lpParameter; pClass->m_saveTransferDownloadCancelled = false; - m_bSaveTransferRunning = true; + m_bSaveTransferRunning = true; bool bAbortCalled = false; Minecraft *pMinecraft=Minecraft::GetInstance(); bool bSaveFileCreated = false; @@ -2728,7 +2724,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter ui.RequestAlertMessage(IDS_TOOLTIPS_SAVETRANSFER_DOWNLOAD, IDS_SAVE_TRANSFER_WRONG_VERSION, uiIDA, 1, ProfileManager.GetPrimaryPad(),RemoteSaveNotFoundCallback,pClass); } } - else + else { // no save available, inform the user about the functionality UINT uiIDA[1]; @@ -2752,7 +2748,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter DWORD dwDataSizeSaveImage=0; StorageManager.GetDefaultSaveImage(&pbDataSaveImage, &dwDataSizeSaveImage); // Get the default save thumbnail (as set by SetDefaultImages) for use on saving games t - StorageManager.GetDefaultSaveThumbnail(&pbThumbnailData,&dwThumbnailDataSize); // Get the default save image (as set by SetDefaultImages) for use on saving games that + StorageManager.GetDefaultSaveThumbnail(&pbThumbnailData,&dwThumbnailDataSize); // Get the default save image (as set by SetDefaultImages) for use on saving games that BYTE bTextMetadata[88]; ZeroMemory(bTextMetadata,88); @@ -2784,7 +2780,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter { // we can't cancel here, we need the saves info so we can delete the file if(pClass->m_saveTransferDownloadCancelled) - { + { WCHAR wcTemp[256]; swprintf(wcTemp,256, app.GetString(IDS_CANCEL)); // MGH - should change this string to "cancelling download" m_wstrStageText=wcTemp; @@ -2799,7 +2795,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter break; case eSaveTransfer_GettingSavesInfo: if(pClass->m_saveTransferDownloadCancelled) - { + { WCHAR wcTemp[256]; swprintf(wcTemp,256, app.GetString(IDS_CANCEL)); // MGH - should change this string to "cancelling download" m_wstrStageText=wcTemp; @@ -2916,7 +2912,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter DWORD dwDataSizeSaveImage=0; StorageManager.GetDefaultSaveImage(&pbDataSaveImage, &dwDataSizeSaveImage); // Get the default save thumbnail (as set by SetDefaultImages) for use on saving games t - StorageManager.GetDefaultSaveThumbnail(&pbThumbnailData,&dwThumbnailDataSize); // Get the default save image (as set by SetDefaultImages) for use on saving games that + StorageManager.GetDefaultSaveThumbnail(&pbThumbnailData,&dwThumbnailDataSize); // Get the default save image (as set by SetDefaultImages) for use on saving games that BYTE bTextMetadata[88]; ZeroMemory(bTextMetadata,88); @@ -2929,12 +2925,12 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter } -#ifdef SPLIT_SAVES +#ifdef SPLIT_SAVES ConsoleSaveFileOriginal oldFormatSave( wSaveName, ba.data, ba.length, false, app.getRemoteStorage()->getSavePlatform() ); pSave = new ConsoleSaveFileSplit( &oldFormatSave, false, pMinecraft->progressRenderer ); pMinecraft->progressRenderer->progressStage(IDS_SAVETRANSFER_STAGE_SAVING); - pSave->Flush(false,false); + pSave->Flush(false,false); pClass->m_eSaveTransferState = eSaveTransfer_Saving; #else pSave = new ConsoleSaveFileOriginal( wSaveName, ba.data, ba.length, false, app.getRemoteStorage()->getSavePlatform() ); @@ -2970,7 +2966,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter delete pSave; - + pMinecraft->progressRenderer->progressStage(IDS_PROGRESS_SAVING_TO_DISC); pClass->m_eSaveTransferState = eSaveTransfer_Succeeded; } @@ -2984,7 +2980,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; app.getRemoteStorage()->waitForStorageManagerIdle(); // wait for everything to complete before we hand control back to the player - ui.RequestErrorMessage( IDS_TOOLTIPS_SAVETRANSFER_DOWNLOAD, IDS_SAVE_TRANSFER_DOWNLOADCOMPLETE, uiIDA,1,ProfileManager.GetPrimaryPad(),CrossSaveFinishedCallback,pClass); + ui.RequestErrorMessage( IDS_TOOLTIPS_SAVETRANSFER_DOWNLOAD, IDS_SAVE_TRANSFER_DOWNLOADCOMPLETE, uiIDA,1,ProfileManager.GetPrimaryPad(),CrossSaveFinishedCallback,pClass); pClass->m_eSaveTransferState = eSaveTransfer_Finished; } break; @@ -2999,7 +2995,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter if(bSaveFileCreated) { if(pClass->m_saveTransferDownloadCancelled) - { + { WCHAR wcTemp[256]; swprintf(wcTemp,256, app.GetString(IDS_CANCEL)); // MGH - should change this string to "cancelling download" m_wstrStageText=wcTemp; @@ -3077,7 +3073,7 @@ int UIScene_LoadOrJoinMenu::DownloadSonyCrossSaveThreadProc( LPVOID lpParameter #endif } - ui.RequestErrorMessage( IDS_TOOLTIPS_SAVETRANSFER_DOWNLOAD, errorMessage, uiIDA,1,ProfileManager.GetPrimaryPad(),CrossSaveFinishedCallback,pClass); + ui.RequestErrorMessage( IDS_TOOLTIPS_SAVETRANSFER_DOWNLOAD, errorMessage, uiIDA,1,ProfileManager.GetPrimaryPad(),CrossSaveFinishedCallback,pClass); pClass->m_eSaveTransferState = eSaveTransfer_Finished; } if(bSaveFileCreated) // save file has been created, then deleted. @@ -3223,7 +3219,7 @@ int UIScene_LoadOrJoinMenu::UploadSonyCrossSaveThreadProc( LPVOID lpParameter ) { UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestErrorMessage( IDS_TOOLTIPS_SAVETRANSFER_UPLOAD, IDS_SAVE_TRANSFER_UPLOADCOMPLETE, uiIDA,1,ProfileManager.GetPrimaryPad(),CrossSaveUploadFinishedCallback,pClass); + ui.RequestErrorMessage( IDS_TOOLTIPS_SAVETRANSFER_UPLOAD, IDS_SAVE_TRANSFER_UPLOADCOMPLETE, uiIDA,1,ProfileManager.GetPrimaryPad(),CrossSaveUploadFinishedCallback,pClass); pClass->m_eSaveUploadState = esaveUpload_Finished; } break; @@ -3240,7 +3236,7 @@ int UIScene_LoadOrJoinMenu::UploadSonyCrossSaveThreadProc( LPVOID lpParameter ) { UINT uiIDA[1]; uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestErrorMessage( IDS_TOOLTIPS_SAVETRANSFER_UPLOAD, IDS_SAVE_TRANSFER_UPLOADFAILED, uiIDA,1,ProfileManager.GetPrimaryPad(),CrossSaveUploadFinishedCallback,pClass); + ui.RequestErrorMessage( IDS_TOOLTIPS_SAVETRANSFER_UPLOAD, IDS_SAVE_TRANSFER_UPLOADFAILED, uiIDA,1,ProfileManager.GetPrimaryPad(),CrossSaveUploadFinishedCallback,pClass); pClass->m_eSaveUploadState = esaveUpload_Finished; } } @@ -3289,7 +3285,7 @@ int UIScene_LoadOrJoinMenu::SaveTransferDialogReturned(void *pParam,int iPad,C4J { UIScene_LoadOrJoinMenu* pClass = (UIScene_LoadOrJoinMenu*)pParam; // results switched for this dialog - if(result==C4JStorage::EMessage_ResultAccept) + if(result==C4JStorage::EMessage_ResultAccept) { // upload the save pClass->LaunchSaveUpload(); @@ -3408,13 +3404,13 @@ int UIScene_LoadOrJoinMenu::DownloadXbox360SaveThreadProc( LPVOID lpParameter ) ByteArrayInputStream bais(UIScene_LoadOrJoinMenu::s_transferData); DataInputStream dis(&bais); - wstring saveTitle = dis.readUTF(); + wstring saveTitle = dis.readUTF(); StorageManager.SetSaveTitle(saveTitle.c_str()); wstring saveUniqueName = dis.readUTF(); // 4J Stu - Don't set this any more. We added it so that we could share the ban list data for this save - // However if the player downloads the same save multiple times, it will overwrite the previous version + // However if the player downloads the same save multiple times, it will overwrite the previous version // with that filname, and they could have made changes to it. //StorageManager.SetSaveUniqueFilename((wchar_t *)saveUniqueName.c_str()); @@ -3424,7 +3420,7 @@ int UIScene_LoadOrJoinMenu::DownloadXbox360SaveThreadProc( LPVOID lpParameter ) byteArray ba(thumbnailSize); dis.readFully(ba); - + // retrieve the seed value from the image metadata, we need to change to host options, then set it back again bool bHostOptionsRead = false; @@ -3458,13 +3454,13 @@ int UIScene_LoadOrJoinMenu::DownloadXbox360SaveThreadProc( LPVOID lpParameter ) case eSaveTransferFile_SaveData: { #ifdef SPLIT_SAVES - if(!pStateContainer->m_bSaveTransferCancelled) + if(!pStateContainer->m_bSaveTransferCancelled) { ConsoleSaveFileOriginal oldFormatSave( L"Temp name", UIScene_LoadOrJoinMenu::s_transferData.data, UIScene_LoadOrJoinMenu::s_transferData.length, false, SAVE_FILE_PLATFORM_X360 ); pSave = new ConsoleSaveFileSplit( &oldFormatSave, false, pMinecraft->progressRenderer ); pMinecraft->progressRenderer->progressStage(IDS_SAVETRANSFER_STAGE_SAVING); - if(!pStateContainer->m_bSaveTransferCancelled) pSave->Flush(false,false); + if(!pStateContainer->m_bSaveTransferCancelled) pSave->Flush(false,false); } pStateContainer->m_eSaveTransferState=C4JStorage::eSaveTransfer_Saving; @@ -3485,7 +3481,7 @@ int UIScene_LoadOrJoinMenu::DownloadXbox360SaveThreadProc( LPVOID lpParameter ) pSave->ConvertToLocalPlatform(); pMinecraft->progressRenderer->progressStage(IDS_SAVETRANSFER_STAGE_SAVING); - if(!pStateContainer->m_bSaveTransferCancelled) pSave->Flush(false,false); + if(!pStateContainer->m_bSaveTransferCancelled) pSave->Flush(false,false); pStateContainer->m_iProgress+=1; if(pStateContainer->m_iProgress==101) @@ -3501,8 +3497,8 @@ int UIScene_LoadOrJoinMenu::DownloadXbox360SaveThreadProc( LPVOID lpParameter ) // On Durango/Orbis, we need to wait for all the asynchronous saving processes to complete before destroying the levels, as that will ultimately delete // the directory level storage & therefore the ConsoleSaveSplit instance, which needs to be around until all the sub files have completed saving. #if defined(_DURANGO) || defined(__ORBIS__) - pMinecraft->progressRenderer->progressStage(IDS_PROGRESS_SAVING_TO_DISC); - + pMinecraft->progressRenderer->progressStage(IDS_PROGRESS_SAVING_TO_DISC); + while(StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle ) { Sleep(10); @@ -3517,9 +3513,9 @@ int UIScene_LoadOrJoinMenu::DownloadXbox360SaveThreadProc( LPVOID lpParameter ) #ifdef _XBOX_ONE pMinecraft->progressRenderer->progressStage(IDS_SAVE_TRANSFER_DOWNLOAD_AND_CONVERT_COMPLETE); #endif - + pStateContainer->m_eSaveTransferState=C4JStorage::eSaveTransfer_Idle; - + // wipe the list and repopulate it if(!pStateContainer->m_bSaveTransferCancelled) pStateContainer->m_pClass->m_iState=e_SavesRepopulateAfterTransferDownload; @@ -3559,7 +3555,7 @@ int UIScene_LoadOrJoinMenu::DownloadXbox360SaveThreadProc( LPVOID lpParameter ) } void UIScene_LoadOrJoinMenu::RequestFileSize( SaveTransferStateContainer *pClass, wchar_t *filename ) -{ +{ Minecraft *pMinecraft=Minecraft::GetInstance(); // get the save file size @@ -3665,7 +3661,7 @@ int UIScene_LoadOrJoinMenu::SaveTransferUpdateProgress(LPVOID lpParam,unsigned l if(pClass->m_bSaveTransferCancelled) // was cancelled { - pMinecraft->progressRenderer->progressStage(IDS_SAVE_TRANSFER_DOWNLOAD_CANCELLING); + pMinecraft->progressRenderer->progressStage(IDS_SAVE_TRANSFER_DOWNLOAD_CANCELLING); swprintf(wcTemp,app.GetString(IDS_SAVE_TRANSFER_DOWNLOAD_CANCELLING)); m_wstrStageText=wcTemp; pMinecraft->progressRenderer->progressStage( m_wstrStageText ); @@ -3740,7 +3736,7 @@ int UIScene_LoadOrJoinMenu::CopySaveDialogReturned(void *pParam,int iPad,C4JStor { UIScene_LoadOrJoinMenu* pClass = (UIScene_LoadOrJoinMenu*)pParam; - if(result==C4JStorage::EMessage_ResultAccept) + if(result==C4JStorage::EMessage_ResultAccept) { LoadingInputParams *loadingParams = new LoadingInputParams(); @@ -3785,7 +3781,7 @@ int UIScene_LoadOrJoinMenu::CopySaveThreadProc( LPVOID lpParameter ) ui.LeaveCallbackIdCriticalSection(); // Copy save data takes two callbacks - one for completion, and one for progress. The progress callback also lets us cancel the operation, if we return false. StorageManager.CopySaveData(&pClass->m_pSaveDetails->SaveInfoA[pClass->m_iSaveListIndex - pClass->m_iDefaultButtonsC],UIScene_LoadOrJoinMenu::CopySaveDataReturned,UIScene_LoadOrJoinMenu::CopySaveDataProgress,lpParameter); - + bool bContinue = true; do { @@ -3822,7 +3818,7 @@ int UIScene_LoadOrJoinMenu::CopySaveDataReturned(LPVOID lpParam, bool success, C { pClass->m_bCopying = false; // wipe the list and repopulate it - pClass->m_iState=e_SavesRepopulateAfterDelete; + pClass->m_iState=e_SavesRepopulateAfterDelete; ui.LeaveCallbackIdCriticalSection(); } else diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_4JList.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_4JList.cpp index 60c32909..4c615979 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_4JList.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_4JList.cpp @@ -15,7 +15,7 @@ HRESULT CXuiCtrl4JList::OnInit(XUIMessageInit *pInitData, BOOL& bHandled) void CXuiCtrl4JList::AddData( const LIST_ITEM_INFO& ItemInfo , int iSortListFromIndex, int iSortFunction) { // need to allocate memory for the structure and its strings - // and remap the string pointers + // and remap the string pointers DWORD dwBytes=0; DWORD dwLen1=0; DWORD dwLen2=0; @@ -37,7 +37,7 @@ void CXuiCtrl4JList::AddData( const LIST_ITEM_INFO& ItemInfo , int iSortListFrom ZeroMemory(pItemInfo,dwBytes); XMemCpy( pItemInfo, &ItemInfo, sizeof( LIST_ITEM_INFO ) ); - if(dwLen1!=0) + if(dwLen1!=0) { XMemCpy( &pItemInfo[1], ItemInfo.pwszText, dwLen1 ); pItemInfo->pwszText=(LPCWSTR)&pItemInfo[1]; @@ -68,13 +68,13 @@ void CXuiCtrl4JList::AddData( const LIST_ITEM_INFO& ItemInfo , int iSortListFrom // added to force a sort order for DLC //pItemInfo->iSortIndex=iSortIndex; - + m_vListData.push_back(pItemInfo); #ifdef _DEBUG int iCount=0; - for (AUTO_VAR(it, m_vListData.begin()); it != m_vListData.end(); it++) + for ( auto it : m_vListData ) { PLIST_ITEM_INFO pInfo=(PLIST_ITEM_INFO)*it; app.DebugPrintf("%d. ",iCount++); @@ -99,22 +99,10 @@ void CXuiCtrl4JList::AddData( const LIST_ITEM_INFO& ItemInfo , int iSortListFrom break; case eSortList_Index: sort(m_vListData.begin()+iSortListFromIndex, m_vListData.end(),CXuiCtrl4JList::IndexSortFn); - break; + break; } } LeaveCriticalSection(&m_AccessListData); -// #ifdef _DEBUG -// -// iCount=0; -// for (AUTO_VAR(it, m_vListData.begin()); it != m_vListData.end(); it++) -// { -// PLIST_ITEM_INFO pInfo=(PLIST_ITEM_INFO)*it; -// app.DebugPrintf("After Sort - %d. ",iCount++); -// OutputDebugStringW(pInfo->pwszText); -// app.DebugPrintf(" - %d\n",pInfo->iSortIndex); -// -// } -// #endif InsertItems( 0, 1 ); } @@ -162,13 +150,13 @@ int CXuiCtrl4JList::GetIndexByUserData(int iData) return 0; } -CXuiCtrl4JList::LIST_ITEM_INFO& CXuiCtrl4JList::GetData(DWORD dw) -{ - return *m_vListData[dw]; +CXuiCtrl4JList::LIST_ITEM_INFO& CXuiCtrl4JList::GetData(DWORD dw) +{ + return *m_vListData[dw]; } -CXuiCtrl4JList::LIST_ITEM_INFO& CXuiCtrl4JList::GetDataiData(int iData) -{ +CXuiCtrl4JList::LIST_ITEM_INFO& CXuiCtrl4JList::GetDataiData(int iData) +{ LIST_ITEM_INFO info; for(unsigned int i=0;i<m_vListData.size();i++) @@ -180,11 +168,11 @@ CXuiCtrl4JList::LIST_ITEM_INFO& CXuiCtrl4JList::GetDataiData(int iData) } } - return *m_vListData[0]; + return *m_vListData[0]; } -CXuiCtrl4JList::LIST_ITEM_INFO& CXuiCtrl4JList::GetData(FILETIME *pFileTime) -{ +CXuiCtrl4JList::LIST_ITEM_INFO& CXuiCtrl4JList::GetData(FILETIME *pFileTime) +{ LIST_ITEM_INFO info; for(unsigned int i=0;i<m_vListData.size();i++) @@ -196,13 +184,13 @@ CXuiCtrl4JList::LIST_ITEM_INFO& CXuiCtrl4JList::GetData(FILETIME *pFileTime) } } - return *m_vListData[0]; + return *m_vListData[0]; } bool CXuiCtrl4JList::TimeSortFn(const void *a, const void *b) { CXuiCtrl4JList::LIST_ITEM_INFO *SaveDetailsA=(CXuiCtrl4JList::LIST_ITEM_INFO *)a; - CXuiCtrl4JList::LIST_ITEM_INFO *SaveDetailsB=(CXuiCtrl4JList::LIST_ITEM_INFO *)b; + CXuiCtrl4JList::LIST_ITEM_INFO *SaveDetailsB=(CXuiCtrl4JList::LIST_ITEM_INFO *)b; if(SaveDetailsA->fTime.dwHighDateTime > SaveDetailsB->fTime.dwHighDateTime) { @@ -229,14 +217,14 @@ bool CXuiCtrl4JList::TimeSortFn(const void *a, const void *b) bool CXuiCtrl4JList::AlphabeticSortFn(const void *a, const void *b) { CXuiCtrl4JList::LIST_ITEM_INFO *SaveDetailsA=(CXuiCtrl4JList::LIST_ITEM_INFO *)a; - CXuiCtrl4JList::LIST_ITEM_INFO *SaveDetailsB=(CXuiCtrl4JList::LIST_ITEM_INFO *)b; + CXuiCtrl4JList::LIST_ITEM_INFO *SaveDetailsB=(CXuiCtrl4JList::LIST_ITEM_INFO *)b; wstring wstr1=SaveDetailsA->pwszText; wstring wstr2=SaveDetailsB->pwszText; if(wstr1.compare(wstr2)<0) { return true; - } + } return false; } @@ -244,14 +232,14 @@ bool CXuiCtrl4JList::AlphabeticSortFn(const void *a, const void *b) bool CXuiCtrl4JList::IndexSortFn(const void *a, const void *b) { CXuiCtrl4JList::LIST_ITEM_INFO *SaveDetailsA=(CXuiCtrl4JList::LIST_ITEM_INFO *)a; - CXuiCtrl4JList::LIST_ITEM_INFO *SaveDetailsB=(CXuiCtrl4JList::LIST_ITEM_INFO *)b; + CXuiCtrl4JList::LIST_ITEM_INFO *SaveDetailsB=(CXuiCtrl4JList::LIST_ITEM_INFO *)b; int iA=SaveDetailsA->iSortIndex; int iB=SaveDetailsB->iSortIndex; if(iA>iB) { return true; - } + } return false; } @@ -303,10 +291,10 @@ void CXuiCtrl4JList::UpdateGraphic(FILETIME *pfTime,HXUIBRUSH hXuiBrush ) // Gets called every frame HRESULT CXuiCtrl4JList::OnGetSourceDataText(XUIMessageGetSourceText *pGetSourceTextData,BOOL& bHandled) { - if( ( 0 == pGetSourceTextData->iData ) && ( ( pGetSourceTextData->bItemData ) ) ) + if( ( 0 == pGetSourceTextData->iData ) && ( ( pGetSourceTextData->bItemData ) ) ) { EnterCriticalSection(&m_AccessListData); - pGetSourceTextData->szText = + pGetSourceTextData->szText = GetData(pGetSourceTextData->iItem).pwszText; LeaveCriticalSection(&m_AccessListData); bHandled = TRUE; @@ -323,7 +311,7 @@ HRESULT CXuiCtrl4JList::OnGetItemCountAll(XUIMessageGetItemCount *pGetItemCountD HRESULT CXuiCtrl4JList::OnGetSourceDataImage(XUIMessageGetSourceImage *pGetSourceImageData,BOOL& bHandled) { - if( ( 0 == pGetSourceImageData->iData ) && ( pGetSourceImageData->bItemData ) ) + if( ( 0 == pGetSourceImageData->iData ) && ( pGetSourceImageData->bItemData ) ) { // Check for a brush EnterCriticalSection(&m_AccessListData); @@ -333,7 +321,7 @@ HRESULT CXuiCtrl4JList::OnGetSourceDataImage(XUIMessageGetSourceImage *pGetSourc } else { - pGetSourceImageData->szPath = + pGetSourceImageData->szPath = GetData(pGetSourceImageData->iItem).pwszImage; } LeaveCriticalSection(&m_AccessListData); @@ -347,7 +335,7 @@ HRESULT CXuiCtrl4JList::OnGetItemEnable(XUIMessageGetItemEnable *pGetItemEnableD if(m_vListData.size()!=0) { EnterCriticalSection(&m_AccessListData); - pGetItemEnableData->bEnabled = + pGetItemEnableData->bEnabled = GetData(pGetItemEnableData->iItem).fEnabled; LeaveCriticalSection(&m_AccessListData); } @@ -356,14 +344,14 @@ HRESULT CXuiCtrl4JList::OnGetItemEnable(XUIMessageGetItemEnable *pGetItemEnableD } -HRESULT CXuiCtrl4JList::SetBorder(DWORD dw,BOOL bShow) -{ +HRESULT CXuiCtrl4JList::SetBorder(DWORD dw,BOOL bShow) +{ CXuiControl Control; HXUIOBJ hVisual,hBorder; GetItemControl(dw,&Control); Control.GetVisual(&hVisual); XuiElementGetChildById(hVisual,L"Border",&hBorder); - return XuiElementSetShow(hBorder,bShow); + return XuiElementSetShow(hBorder,bShow); } void CXuiCtrl4JList::SetSelectionChangedHandle(HXUIOBJ hObj) diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantButton.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantButton.cpp index dfb9b5ca..6c7876c9 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantButton.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantButton.cpp @@ -69,7 +69,7 @@ HRESULT CXuiCtrlEnchantmentButton::OnGetSourceDataText(XUIMessageGetSourceText * // Light background and focus background SetEnable(TRUE); } - m_costString = _toString<int>(cost); + m_costString = std::to_wstring(cost); m_lastCost = cost; } if(cost == 0) @@ -79,7 +79,7 @@ HRESULT CXuiCtrlEnchantmentButton::OnGetSourceDataText(XUIMessageGetSourceText * pGetSourceTextData->bDisplay = FALSE; } else - { + { pGetSourceTextData->szText = m_costString.c_str(); pGetSourceTextData->bDisplay = TRUE; } diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentButtonText.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentButtonText.cpp index 702ef15d..60156a0a 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentButtonText.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_EnchantmentButtonText.cpp @@ -70,11 +70,11 @@ HRESULT CXuiCtrlEnchantmentButtonText::OnRender(XUIMessageRender *pRenderData, B D3DXMATRIX matrix; xuiControl.GetFullXForm(&matrix); float bwidth,bheight; - xuiControl.GetBounds(&bwidth,&bheight); + xuiControl.GetBounds(&bwidth,&bheight); // Annoyingly, XUI renders everything to a z of 0 so if we want to render anything that needs the z-buffer on top of it, then we need to clear it. // Clear just the region required for this control. - D3DRECT clearRect; + D3DRECT clearRect; clearRect.x1 = (int)(matrix._41) - 2; clearRect.y1 = (int)(matrix._42) - 2; clearRect.x2 = (int)(matrix._41 + ( bwidth * matrix._11 )) + 2; @@ -124,7 +124,7 @@ HRESULT CXuiCtrlEnchantmentButtonText::OnRender(XUIMessageRender *pRenderData, B glColor4f(1, 1, 1, 1); if (cost != 0) { - wstring line = _toString<int>(cost); + wstring line = std::to_wstring(cost); Font *font = pMinecraft->altFont; //int col = 0x685E4A; unsigned int col = m_textColour; diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSkinPreview.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSkinPreview.cpp index 80750deb..0acd250f 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSkinPreview.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_MinecraftSkinPreview.cpp @@ -145,7 +145,7 @@ void CXuiCtrlMinecraftSkinPreview::CycleNextAnimation() void CXuiCtrlMinecraftSkinPreview::CyclePreviousAnimation() { - m_currentAnimation = (ESkinPreviewAnimations)(m_currentAnimation - 1); + m_currentAnimation = (ESkinPreviewAnimations)(m_currentAnimation - 1); if(m_currentAnimation < e_SkinPreviewAnimation_Walking) m_currentAnimation = (ESkinPreviewAnimations)(e_SkinPreviewAnimation_Count - 1); m_swingTime = 0.0f; @@ -253,13 +253,11 @@ HRESULT CXuiCtrlMinecraftSkinPreview::OnRender(XUIMessageRender *pRenderData, BO { // 4J-PB - any additional parts to turn on for this player (skin dependent) //vector<ModelPart *> *pAdditionalModelParts=mob->GetAdditionalModelParts(); - + if(m_pvAdditionalModelParts && m_pvAdditionalModelParts->size()!=0) - { - for(AUTO_VAR(it, m_pvAdditionalModelParts->begin()); it != m_pvAdditionalModelParts->end(); ++it) + { + for(auto& pModelPart : *m_pvAdditionalModelParts) { - ModelPart *pModelPart=*it; - pModelPart->visible=true; } } @@ -269,11 +267,9 @@ HRESULT CXuiCtrlMinecraftSkinPreview::OnRender(XUIMessageRender *pRenderData, BO // hide the additional parts if(m_pvAdditionalModelParts && m_pvAdditionalModelParts->size()!=0) - { - for(AUTO_VAR(it, m_pvAdditionalModelParts->begin()); it != m_pvAdditionalModelParts->end(); ++it) + { + for(auto& pModelPart : *m_pvAdditionalModelParts) { - ModelPart *pModelPart=*it; - pModelPart->visible=false; } } @@ -344,7 +340,7 @@ void CXuiCtrlMinecraftSkinPreview::render(EntityRenderer *renderer, double x, do float bodyRot = m_yRot; //(mob->yBodyRotO + (mob->yBodyRot - mob->yBodyRotO) * a); float headRot = m_yRot; //(mob->yRotO + (mob->yRot - mob->yRotO) * a); float headRotx = 0; //(mob->xRotO + (mob->xRot - mob->xRotO) * a); - + //setupPosition(mob, x, y, z); // is equivalent to glTranslatef((float) x, (float) y, (float) z); @@ -515,7 +511,7 @@ bool CXuiCtrlMinecraftSkinPreview::bindTexture(const wstring& urlTexture, int ba Textures *t = Minecraft::GetInstance()->textures; // 4J-PB - no http textures on the xbox, mem textures instead - + //int id = t->loadHttpTexture(urlTexture, backupTexture); int id = t->loadMemTexture(urlTexture, backupTexture); @@ -535,7 +531,7 @@ bool CXuiCtrlMinecraftSkinPreview::bindTexture(const wstring& urlTexture, const Textures *t = Minecraft::GetInstance()->textures; // 4J-PB - no http textures on the xbox, mem textures instead - + //int id = t->loadHttpTexture(urlTexture, backupTexture); int id = t->loadMemTexture(urlTexture, backupTexture); diff --git a/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.cpp b/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.cpp index 87abbcd3..f8ceeb69 100644 --- a/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Ctrl_SlotItemCtrlBase.cpp @@ -64,7 +64,7 @@ HRESULT CXuiCtrlSlotItemCtrlBase::OnCustomMessage_GetSlotItem(HXUIOBJ hObj, Cust // 11 bits - auxval // 6 bits - count // 6 bits - scale - pData->iDataBitField = MAKE_SLOTDISPLAY_DATA_BITMASK(pUserDataContainer->m_iPad, (int)(31*pUserDataContainer->m_fAlpha),true,item->GetCount(),7,item->popTime); + pData->iDataBitField = MAKE_SLOTDISPLAY_DATA_BITMASK(pUserDataContainer->m_iPad, (int)(31*pUserDataContainer->m_fAlpha),true,item->GetCount(),7,item->popTime); } else { @@ -93,7 +93,7 @@ void CXuiCtrlSlotItemCtrlBase::SetUserIndex( HXUIOBJ hObj, int iPad ) XuiElementGetUserData( hObj, &pvUserData ); SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; - + pUserDataContainer->m_iPad = iPad; } @@ -103,7 +103,7 @@ void CXuiCtrlSlotItemCtrlBase::SetAlpha( HXUIOBJ hObj, float fAlpha ) XuiElementGetUserData( hObj, &pvUserData ); SlotControlUserDataContainer* pUserDataContainer = (SlotControlUserDataContainer*)pvUserData; - + pUserDataContainer->m_fAlpha = fAlpha; } @@ -137,16 +137,15 @@ wstring CXuiCtrlSlotItemCtrlBase::GetItemDescription( HXUIOBJ hObj, vector<wstri wstring desc = L""; vector<wstring> *strings = pUserDataContainer->slot->getItem()->getHoverText(Minecraft::GetInstance()->localplayers[pUserDataContainer->m_iPad], false, unformattedStrings); bool firstLine = true; - for(AUTO_VAR(it, strings->begin()); it != strings->end(); ++it) - { - wstring thisString = *it; + for ( wstring& thisString : *strings ) + { if(!firstLine) { desc.append( L"<br />" ); } else { - firstLine = false; + firstLine = false; wchar_t formatted[256]; eMinecraftColour rarityColour = pUserDataContainer->slot->getItem()->getRarity()->color; int colour = app.GetHTMLColour(rarityColour); @@ -156,7 +155,7 @@ wstring CXuiCtrlSlotItemCtrlBase::GetItemDescription( HXUIOBJ hObj, vector<wstri colour = app.GetHTMLColour(eTextColor_RenamedItemTitle); } - swprintf(formatted, 256, L"<font color=\"#%08x\">%s</font>",colour,thisString.c_str()); + swprintf(formatted, 256, L"<font color=\"#%08x\">%s</font>",colour,thisString.c_str()); thisString = formatted; } desc.append( thisString ); @@ -221,7 +220,7 @@ HRESULT CXuiCtrlSlotItemCtrlBase::OnKeyDown(HXUIOBJ hObj, XUIMessageInput *pInpu XUIMessage message; XUIMessageInput messageInput; - + XuiMessageInput( &message, &messageInput, XUI_KEYDOWN, pInputData->dwKeyCode, pInputData->wch, pInputData->dwFlags, pInputData->UserIndex ); if (HRESULT_SUCCEEDED(hr)) @@ -358,7 +357,7 @@ bool CXuiCtrlSlotItemCtrlBase::IsSameItemAs( HXUIOBJ hThisObj, HXUIOBJ hOtherObj // 4J WESTY : Pointer Prototype : Added to support prototype only. // Returns number of items that can still be stacked into this slot. -int CXuiCtrlSlotItemCtrlBase::GetEmptyStackSpace( HXUIOBJ hObj ) +int CXuiCtrlSlotItemCtrlBase::GetEmptyStackSpace( HXUIOBJ hObj ) { int iResult = 0; diff --git a/Minecraft.Client/Common/XUI/XUI_DebugItemEditor.cpp b/Minecraft.Client/Common/XUI/XUI_DebugItemEditor.cpp index 56b41267..6b96a4e3 100644 --- a/Minecraft.Client/Common/XUI/XUI_DebugItemEditor.cpp +++ b/Minecraft.Client/Common/XUI/XUI_DebugItemEditor.cpp @@ -9,7 +9,7 @@ #include "..\..\Common\GameRules\ConsoleGameRules.h" #include "XUI_DebugItemEditor.h" -#ifdef _DEBUG_MENUS_ENABLED +#ifdef _DEBUG_MENUS_ENABLED HRESULT CScene_DebugItemEditor::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) { MapChildControls(); @@ -22,13 +22,13 @@ HRESULT CScene_DebugItemEditor::OnInit( XUIMessageInit *pInitData, BOOL &bHandle if(m_item!=NULL) { - m_icon->SetIcon(m_iPad, m_item->id,m_item->getAuxValue(),m_item->count,10,31,false,m_item->isFoil()); + m_icon->SetIcon(m_iPad, m_item->id,m_item->getAuxValue(),m_item->count,10,31,false,m_item->isFoil()); m_itemName.SetText( app.GetString( Item::items[m_item->id]->getDescriptionId(m_item) ) ); - m_itemId .SetText( _toString<int>(m_item->id).c_str() ); - m_itemAuxValue .SetText( _toString<int>(m_item->getAuxValue()).c_str() ); - m_itemCount .SetText( _toString<int>(m_item->count).c_str() ); - m_item4JData .SetText( _toString<int>(m_item->get4JData()).c_str() ); + m_itemId .SetText( std::to_wstring(m_item->id).c_str() ); + m_itemAuxValue .SetText( std::to_wstring(m_item->getAuxValue()).c_str() ); + m_itemCount .SetText( std::to_wstring(m_item->count).c_str() ); + m_item4JData .SetText( std::to_wstring(m_item->get4JData()).c_str() ); } m_itemId .SetKeyboardType(C_4JInput::EKeyboardMode_Numeric); @@ -107,7 +107,7 @@ HRESULT CScene_DebugItemEditor::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINot if(!value.empty()) data = _fromString<int>( value ); m_item->set4JData(data); } - + m_icon->SetIcon(m_iPad, m_item->id,m_item->getAuxValue(),m_item->count,10,31,false,m_item->isFoil()); m_itemName.SetText( app.GetString( Item::items[m_item->id]->getDescriptionId(m_item) ) ); diff --git a/Minecraft.Client/Common/XUI/XUI_DebugOverlay.cpp b/Minecraft.Client/Common/XUI/XUI_DebugOverlay.cpp index a23e97b7..e6db6a80 100644 --- a/Minecraft.Client/Common/XUI/XUI_DebugOverlay.cpp +++ b/Minecraft.Client/Common/XUI/XUI_DebugOverlay.cpp @@ -28,7 +28,7 @@ #include "..\..\..\Minecraft.World\net.minecraft.commands.common.h" #include "..\..\..\Minecraft.World\ConsoleSaveFileOriginal.h" -#ifdef _DEBUG_MENUS_ENABLED +#ifdef _DEBUG_MENUS_ENABLED HRESULT CScene_DebugOverlay::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) { MapChildControls(); @@ -53,7 +53,7 @@ HRESULT CScene_DebugOverlay::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) m_enchantmentIds.push_back(ench->id); m_enchantments.SetText( i, app.GetString( ench->getDescriptionId() ) ); } - + m_mobs.InsertItems( 0, 21 ); m_mobs.SetText( m_mobFactories.size(), L"Chicken" ); @@ -98,7 +98,7 @@ HRESULT CScene_DebugOverlay::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) m_mobFactories.push_back(eTYPE_BLAZE); m_mobs.SetText( m_mobFactories.size(), L"Magma Cube" ); m_mobFactories.push_back(eTYPE_LAVASLIME); - + Minecraft *pMinecraft = Minecraft::GetInstance(); m_setTime.SetValue( pMinecraft->level->getLevelData()->getTime() % 24000 ); @@ -135,7 +135,7 @@ HRESULT CScene_DebugOverlay::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress { nIndex = m_mobs.GetCurSel(); if(nIndex<m_mobFactories.size()) - { + { app.SetXuiServerAction(ProfileManager.GetPrimaryPad(),eXuiServerAction_SpawnMob,(void *)m_mobFactories[nIndex]); } } @@ -171,7 +171,7 @@ HRESULT CScene_DebugOverlay::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress HXUIOBJ hScene; HRESULT hr; //const WCHAR XZP_SEPARATOR = L'#'; - const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string + const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/"); @@ -189,7 +189,7 @@ HRESULT CScene_DebugOverlay::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPress HXUIOBJ hScene; HRESULT hr; //const WCHAR XZP_SEPARATOR = L'#'; - const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string + const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; swprintf(szResourceLocator, LOCATOR_SIZE, L"section://%X,%ls#%ls",c_ModuleHandle,L"media", L"media/"); @@ -256,7 +256,7 @@ HRESULT CScene_DebugOverlay::OnNotifyValueChanged( HXUIOBJ hObjSource, XUINotify if( hObjSource == m_setTime ) { Minecraft *pMinecraft = Minecraft::GetInstance(); - + // Need to set the time on both levels to stop the flickering as the local level // tries to predict the time // Only works if we are on the host machine, but shouldn't break if not @@ -365,11 +365,11 @@ void CScene_DebugOverlay::SaveLimitedFile(int chunkRadius) RegionFile *CScene_DebugOverlay::getRegionFile(unordered_map<File, RegionFile *, FileKeyHash, FileKeyEq> &newFileCache, ConsoleSaveFile *saveFile, const wstring &prefix, int chunkX, int chunkZ) // 4J - TODO was synchronized { - File file( prefix + wstring(L"r.") + _toString(chunkX>>5) + L"." + _toString(chunkZ>>5) + L".mcr" ); + File file( prefix + wstring(L"r.") + std::to_wstring(chunkX>>5) + L"." + std::to_wstring(chunkZ>>5) + L".mcr" ); RegionFile *ref = NULL; - AUTO_VAR(it, newFileCache.find(file)); - if( it != newFileCache.end() ) + auto it = newFileCache.find(file); + if( it != newFileCache.end() ) ref = it->second; // 4J Jev, put back in. diff --git a/Minecraft.Client/Common/XUI/XUI_DebugSetCamera.cpp b/Minecraft.Client/Common/XUI/XUI_DebugSetCamera.cpp index 2227e895..f6335191 100644 --- a/Minecraft.Client/Common/XUI/XUI_DebugSetCamera.cpp +++ b/Minecraft.Client/Common/XUI/XUI_DebugSetCamera.cpp @@ -23,7 +23,7 @@ HRESULT CScene_DebugSetCamera::OnInit( XUIMessageInit *pInitData, BOOL &bHandled currentPosition = new DebugSetCameraPosition(); currentPosition->player = playerNo; - + Minecraft *pMinecraft = Minecraft::GetInstance(); if (pMinecraft != NULL) { @@ -43,13 +43,13 @@ HRESULT CScene_DebugSetCamera::OnInit( XUIMessageInit *pInitData, BOOL &bHandled m_yRot.SetKeyboardType(C_4JInput::EKeyboardMode_Full); m_elevation.SetKeyboardType(C_4JInput::EKeyboardMode_Full); - m_camX.SetText((CONST WCHAR *) _toString<double>(currentPosition->m_camX).c_str()); - m_camY.SetText((CONST WCHAR *) _toString<double>(currentPosition->m_camY + 1.62).c_str()); - m_camZ.SetText((CONST WCHAR *) _toString<double>(currentPosition->m_camZ).c_str()); + m_camX.SetText((CONST WCHAR *) std::to_wstring(currentPosition->m_camX).c_str()); + m_camY.SetText((CONST WCHAR *) std::to_wstring(currentPosition->m_camY + 1.62).c_str()); + m_camZ.SetText((CONST WCHAR *) std::to_wstring(currentPosition->m_camZ).c_str()); + + m_yRot.SetText((CONST WCHAR *) std::to_wstring(currentPosition->m_yRot).c_str()); + m_elevation.SetText((CONST WCHAR *) std::to_wstring(currentPosition->m_elev).c_str()); - m_yRot.SetText((CONST WCHAR *) _toString<double>(currentPosition->m_yRot).c_str()); - m_elevation.SetText((CONST WCHAR *) _toString<double>(currentPosition->m_elev).c_str()); - //fpp = new FreezePlayerParam(); //fpp->player = playerNo; //fpp->freeze = true; @@ -69,7 +69,7 @@ HRESULT CScene_DebugSetCamera::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotifyPre if (hObjPressed == m_teleport) { app.SetXuiServerAction( ProfileManager.GetPrimaryPad(), - eXuiServerAction_SetCameraLocation, + eXuiServerAction_SetCameraLocation, (void *)currentPosition); rfHandled = TRUE; } diff --git a/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp b/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp index 73f25da5..c5e2fe9a 100644 --- a/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp +++ b/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp @@ -42,13 +42,13 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand m_iTexturePacksNotInstalled=0; m_iConfigA=NULL; - + XuiControlSetText(m_LabelNoGames,app.GetString(IDS_NO_GAMES_FOUND)); XuiControlSetText(m_GamesList,app.GetString(IDS_JOIN_GAME)); XuiControlSetText(m_SavesList,app.GetString(IDS_START_GAME)); - const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string + const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); @@ -64,17 +64,17 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand m_bRetrievingSaveInfo=false; m_bSaveTransferInProgress=false; - + // check for a default custom cloak in the global storage // 4J-PB - changed to a config file // if(ProfileManager.IsSignedInLive( m_iPad )) -// { +// { // app.InstallDefaultCape(); // } m_initData= new JoinMenuInitData(); m_bMultiplayerAllowed = ProfileManager.IsSignedInLive( m_iPad ) && ProfileManager.AllowedToPlayMultiplayer(m_iPad); - + XPARTY_USER_LIST partyList; if((XPartyGetUserList( &partyList ) != XPARTY_E_NOT_IN_PARTY ) && (partyList.dwUserCount>1)) @@ -90,7 +90,7 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand if(m_bInParty) iLB = IDS_TOOLTIPS_PARTY_GAMES; XuiSetTimer(m_hObj,JOIN_LOAD_ONLINE_TIMER_ID,JOIN_LOAD_ONLINE_TIMER_TIME); - + m_iSaveInfoC=0; VOID *pObj; @@ -110,7 +110,7 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand { // if we're waiting for DLC to mount, don't fill the save list. The custom message on end of dlc mounting will do that m_bIgnoreInput=false; - + m_iChangingSaveGameInfoIndex = 0; @@ -135,7 +135,7 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand // saving is disabled, but we should still be able to load from a selected save device ui.SetTooltips( DEFAULT_XUI_MENU_USER, IDS_TOOLTIPS_SELECT,IDS_TOOLTIPS_BACK,IDS_TOOLTIPS_CHANGEDEVICE,-1,-1,-1,iLB,IDS_TOOLTIPS_DELETESAVE); - + GetSaveInfo(); } else @@ -153,7 +153,7 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand // 4J-PB - we need to check that there is enough space left to create a copy of the save (for a rename) bool bCanRename = StorageManager.EnoughSpaceForAMinSaveGame(); ui.SetTooltips( DEFAULT_XUI_MENU_USER, IDS_TOOLTIPS_SELECT,IDS_TOOLTIPS_BACK,IDS_TOOLTIPS_CHANGEDEVICE,-1,-1,-1,-1,bCanRename?IDS_TOOLTIPS_SAVEOPTIONS:IDS_TOOLTIPS_DELETESAVE); - + GetSaveInfo(); } } @@ -165,7 +165,7 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand // 4J Stu - Fix for #12530 -TCR 001 BAS Game Stability: Title will crash if the player disconnects while starting a new world and then opts to play the tutorial once they have been returned to the Main Menu. MinecraftServer::resetFlags(); - + // If we're not ignoring input, then we aren't still waiting for the DLC to mount, and can now check for corrupt dlc. Otherwise this will happen when the dlc has finished mounting. if( !m_bIgnoreInput) { @@ -191,7 +191,7 @@ HRESULT CScene_MultiGameJoinLoad::OnInit( XUIMessageInit* pInitData, BOOL& bHand bool bTexturePackAlreadyListed; bool bNeedToGetTPD=false; Minecraft *pMinecraft = Minecraft::GetInstance(); - int texturePacksCount = pMinecraft->skins->getTexturePackCount(); + int texturePacksCount = pMinecraft->skins->getTexturePackCount(); //CXuiCtrl4JList::LIST_ITEM_INFO ListInfo; //HRESULT hr; @@ -267,9 +267,8 @@ void CScene_MultiGameJoinLoad::AddDefaultButtons() int iGeneratorIndex = 0; m_iMashUpButtonsC=0; - for(AUTO_VAR(it, m_generators->begin()); it != m_generators->end(); ++it) - { - LevelGenerationOptions *levelGen = *it; + for (LevelGenerationOptions *levelGen : *m_generators ) + { ListInfo.pwszText = levelGen->getWorldName(); ListInfo.fEnabled = TRUE; ListInfo.iData = iGeneratorIndex++; // used to index into the list of generators @@ -295,7 +294,7 @@ void CScene_MultiGameJoinLoad::AddDefaultButtons() // increment the count of the mash-up pack worlds in the save list m_iMashUpButtonsC++; TexturePack *tp = Minecraft::GetInstance()->skins->getTexturePackById(levelGen->getRequiredTexturePackId()); - DWORD dwImageBytes; + DWORD dwImageBytes; PBYTE pbImageData = tp->getPackIcon(dwImageBytes); HXUIBRUSH hXuiBrush; @@ -353,8 +352,8 @@ HRESULT CScene_MultiGameJoinLoad::GetSaveInfo( ) ListInfo.fEnabled=TRUE; ListInfo.iData = -1; m_pSavesList->AddData(ListInfo); - } - m_pSavesList->SetCurSelVisible(0); + } + m_pSavesList->SetCurSelVisible(0); } else { @@ -387,9 +386,9 @@ HRESULT CScene_MultiGameJoinLoad::OnDestroy() { g_NetworkManager.SetSessionsUpdatedCallback( NULL, NULL ); - for(AUTO_VAR(it, currentSessions.begin()); it < currentSessions.end(); ++it) - { - delete (*it); + for (auto& it : currentSessions ) + { + delete it; } if(m_bSaveTransferInProgress) @@ -419,7 +418,7 @@ int CScene_MultiGameJoinLoad::DeviceRemovedDialogReturned(void *pParam,int iPad, CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; // results switched for this dialog - if(result==C4JStorage::EMessage_ResultDecline) + if(result==C4JStorage::EMessage_ResultDecline) { StorageManager.SetSaveDisabled(true); StorageManager.SetSaveDeviceSelected(ProfileManager.GetPrimaryPad(),false); @@ -462,7 +461,7 @@ HRESULT CScene_MultiGameJoinLoad::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotify //CScene_MultiGameInfo::JoinMenuInitData *initData = new CScene_MultiGameInfo::JoinMenuInitData(); m_initData->iPad = m_iPad; m_initData->selectedSession = currentSessions.at( nIndex ); - + // check that we have the texture pack available // If it's not the default texture pack if(m_initData->selectedSession->data.texturePackParentId!=0) @@ -513,7 +512,7 @@ HRESULT CScene_MultiGameJoinLoad::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotify return S_OK; } } - + m_NetGamesListTimer.SetShow( FALSE ); // Reset the background downloading, in case we changed it by attempting to download a texture pack @@ -536,7 +535,7 @@ HRESULT CScene_MultiGameJoinLoad::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotify CXuiCtrl4JList::LIST_ITEM_INFO info = m_pSavesList->GetData(iIndex); if(iIndex == JOIN_LOAD_CREATE_BUTTON_INDEX) - { + { app.SetTutorialMode( false ); m_NetGamesListTimer.SetShow( FALSE ); @@ -571,7 +570,7 @@ HRESULT CScene_MultiGameJoinLoad::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotify } } else - { + { // check if this is a damaged save if(m_pSavesList->GetData(iIndex).bIsDamaged) { @@ -582,7 +581,7 @@ HRESULT CScene_MultiGameJoinLoad::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotify StorageManager.RequestMessageBox(IDS_CORRUPT_OR_DAMAGED_SAVE_TITLE, IDS_CORRUPT_OR_DAMAGED_SAVE_TEXT, uiIDA, 2, pNotifyPressData->UserIndex,&CScene_MultiGameJoinLoad::DeleteSaveDialogReturned,this, app.GetStringTable()); } else - { + { app.SetTutorialMode( false ); if(app.DebugSettingsOn() && app.GetLoadSavesFromFolderEnabled()) { @@ -605,7 +604,7 @@ HRESULT CScene_MultiGameJoinLoad::OnNotifyPressEx(HXUIOBJ hObjPressed, XUINotify } } } - + return S_OK; } @@ -632,11 +631,11 @@ HRESULT CScene_MultiGameJoinLoad::OnKeyDown(XUIMessageInput* pInputData, BOOL& r app.NavigateBack(XUSER_INDEX_ANY); rfHandled = TRUE; - break; + break; case VK_PAD_X: // Change device - // Fix for #12531 - TCR 001: BAS Game Stability: When a player selects to change a storage + // Fix for #12531 - TCR 001: BAS Game Stability: When a player selects to change a storage // device, and repeatedly backs out of the SD screen, disconnects from LIVE, and then selects a SD, the title crashes. m_bIgnoreInput=true; StorageManager.SetSaveDevice(&CScene_MultiGameJoinLoad::DeviceSelectReturned,this,true); @@ -657,7 +656,7 @@ HRESULT CScene_MultiGameJoinLoad::OnKeyDown(XUIMessageInput* pInputData, BOOL& r { // save transfer - make sure they want to overwrite a save that is up there if(ProfileManager.IsSignedInLive( m_iPad )) - { + { // 4J-PB - required for a delete of the save if it's found to be a corrupted save DWORD nIndex = m_pSavesList->GetCurSel(); m_iChangingSaveGameInfoIndex=m_pSavesList->GetData(nIndex).iIndex; @@ -668,13 +667,13 @@ HRESULT CScene_MultiGameJoinLoad::OnKeyDown(XUIMessageInput* pInputData, BOOL& r ui.RequestMessageBox(IDS_SAVE_TRANSFER_TITLE, IDS_SAVE_TRANSFER_TEXT, uiIDA, 2, pInputData->UserIndex,&CScene_MultiGameJoinLoad::SaveTransferDialogReturned,this, app.GetStringTable()); } - } + } break; case VK_PAD_RSHOULDER: if(DoesSavesListHaveFocus()) { m_bIgnoreInput = true; - + int iIndex=m_SavesList.GetCurSel(); m_iChangingSaveGameInfoIndex=m_pSavesList->GetData(iIndex).iIndex; @@ -755,19 +754,19 @@ HRESULT CScene_MultiGameJoinLoad::OnKeyDown(XUIMessageInput* pInputData, BOOL& r } break; } - + return hr; } HRESULT CScene_MultiGameJoinLoad::OnNavReturn(HXUIOBJ hSceneFrom,BOOL& rfHandled) { - + CXuiSceneBase::ShowLogo( DEFAULT_XUI_MENU_USER, TRUE ); // start the texture pack timer again XuiSetTimer(m_hObj,CHECKFORAVAILABLETEXTUREPACKS_TIMER_ID,CHECKFORAVAILABLETEXTUREPACKS_TIMER_TIME); - m_bMultiplayerAllowed = ProfileManager.IsSignedInLive( m_iPad ) && ProfileManager.AllowedToPlayMultiplayer(m_iPad); - + m_bMultiplayerAllowed = ProfileManager.IsSignedInLive( m_iPad ) && ProfileManager.AllowedToPlayMultiplayer(m_iPad); + // re-enable button presses m_bIgnoreInput=false; @@ -812,7 +811,7 @@ HRESULT CScene_MultiGameJoinLoad::OnNavReturn(HXUIOBJ hSceneFrom,BOOL& rfHandled iY = IDS_TOOLTIPS_VIEW_GAMERCARD; } else if(DoesSavesListHaveFocus()) - { + { if(ProfileManager.IsSignedInLive( m_iPad )) { iY=IDS_TOOLTIPS_UPLOAD_SAVE_FOR_XBOXONE; @@ -901,7 +900,7 @@ HRESULT CScene_MultiGameJoinLoad::OnTransitionStart( XUIMessageTransition *pTran if(pTransition->dwTransType == XUI_TRANSITION_BACKTO) { // Can't call this here because if you back out of the load info screen and then go back in and load a game, it will attempt to use the dlc as it's running a mount of the dlc - + // block input if we're waiting for DLC to install, and wipe the saves list. The end of dlc mounting custom message will fill the list again if(app.StartInstallDLCProcess(m_iPad)==false) { @@ -925,14 +924,14 @@ HRESULT CScene_MultiGameJoinLoad::OnFontRendererChange() // update the tooltips // if the saves list has focus, then we should show the Delete Save tooltip // if the games list has focus, then we should the the View Gamercard tooltip - int iRB=-1; + int iRB=-1; int iY = -1; if( DoesGamesListHaveFocus() ) { iY = IDS_TOOLTIPS_VIEW_GAMERCARD; - } + } else if(DoesSavesListHaveFocus()) - { + { if(ProfileManager.IsSignedInLive( m_iPad )) { iY=IDS_TOOLTIPS_UPLOAD_SAVE_FOR_XBOXONE; @@ -986,12 +985,12 @@ HRESULT CScene_MultiGameJoinLoad::OnNotifySetFocus(HXUIOBJ hObjSource, XUINotify // update the tooltips // if the saves list has focus, then we should show the Delete Save tooltip // if the games list has focus, then we should the the View Gamercard tooltip - int iRB=-1; + int iRB=-1; int iY = -1; if( DoesGamesListHaveFocus() ) { iY = IDS_TOOLTIPS_VIEW_GAMERCARD; - } + } else if(DoesSavesListHaveFocus()) { if(ProfileManager.IsSignedInLive( m_iPad )) @@ -1118,7 +1117,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesListCallback(LPVOID lpParam) // check this there's no save transfer in progress if(!pClass->m_bSaveTransferInProgress) { - pClass->UpdateGamesList(); + pClass->UpdateGamesList(); } } } @@ -1145,17 +1144,17 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() if( pSelectedSession != NULL )selectedSessionId = pSelectedSession->sessionId; pSelectedSession = NULL; - for(AUTO_VAR(it, currentSessions.begin()); it < currentSessions.end(); ++it) - { - delete (*it); + for (auto& it : currentSessions ) + { + delete it; } currentSessions.clear(); - + m_NetGamesListTimer.SetShow( FALSE ); - + // if the saves list has focus, then we should show the Delete Save tooltip // if the games list has focus, then we should show the View Gamercard tooltip - int iRB=-1; + int iRB=-1; int iY = -1; if( DoesGamesListHaveFocus() ) @@ -1163,7 +1162,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() iY = IDS_TOOLTIPS_VIEW_GAMERCARD; } else if(DoesSavesListHaveFocus()) - { + { if(ProfileManager.IsSignedInLive( m_iPad )) { iY=IDS_TOOLTIPS_UPLOAD_SAVE_FOR_XBOXONE; @@ -1248,9 +1247,8 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() unsigned int sessionIndex = 0; m_pGamesList->SetCurSel(0); - for( AUTO_VAR(it, currentSessions.begin()); it < currentSessions.end(); ++it) - { - FriendSessionInfo *sessionInfo = *it; + for ( FriendSessionInfo *sessionInfo : currentSessions ) + { HXUIBRUSH hXuiBrush; CXuiCtrl4JList::LIST_ITEM_INFO ListInfo; @@ -1282,7 +1280,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() // is it in the tpd data ? app.GetFileFromTPD(eTPDFileType_Icon,pbData,dwBytes,&pbImageData,&dwImageBytes ); if(dwImageBytes > 0 && pbImageData) - { + { hr=XuiCreateTextureBrushFromMemory(pbImageData,dwImageBytes,&hXuiBrush); m_pGamesList->UpdateGraphic(sessionIndex,hXuiBrush); } @@ -1291,7 +1289,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() { pbImageData = tp->getPackIcon(dwImageBytes); if(dwImageBytes > 0 && pbImageData) - { + { hr=XuiCreateTextureBrushFromMemory(pbImageData,dwImageBytes,&hXuiBrush); m_pGamesList->UpdateGraphic(sessionIndex,hXuiBrush); } @@ -1303,7 +1301,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() XuiCreateTextureBrushFromMemory(m_DefaultMinecraftIconData,m_DefaultMinecraftIconSize,&hXuiBrush); m_pGamesList->UpdateGraphic(sessionIndex,hXuiBrush); } - + if(memcmp( &selectedSessionId, &sessionInfo->sessionId, sizeof(SessionID) ) == 0) { @@ -1324,14 +1322,14 @@ void CScene_MultiGameJoinLoad::UpdateGamesList(DWORD dwNumResults, IQNetGameSear if(m_searches>0) --m_searches; - + if(m_searches==0) { m_NetGamesListTimer.SetShow( FALSE ); - + // if the saves list has focus, then we should show the Delete Save tooltip // if the games list has focus, then we should show the View Gamercard tooltip - int iRB=-1; + int iRB=-1; int iY = -1; if( DoesGamesListHaveFocus() ) @@ -1374,7 +1372,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList(DWORD dwNumResults, IQNetGameSear } unsigned int startOffset = m_GamesList.GetItemCount(); - //m_GamesList.InsertItems(startOffset,dwNumResults); + //m_GamesList.InsertItems(startOffset,dwNumResults); //m_GamesList.SetEnable(TRUE); //XuiElementSetDisableFocusRecursion( m_GamesList.m_hObj, FALSE); @@ -1390,7 +1388,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList(DWORD dwNumResults, IQNetGameSear FriendSessionInfo *sessionInfo = NULL; bool foundSession = false; - for(AUTO_VAR(it, friendsSessions.begin()); it < friendsSessions.end(); ++it) + for( auto it = friendsSessions.begin(); it != friendsSessions.end(); ++it) { sessionInfo = *it; if(memcmp( &pSearchResult->info.sessionID, &sessionInfo->sessionId, sizeof(SessionID) ) == 0) @@ -1449,7 +1447,7 @@ void CScene_MultiGameJoinLoad::UpdateGamesList(DWORD dwNumResults, IQNetGameSear #endif } } - + if( m_GamesList.GetItemCount() == 0) { m_LabelNoGames.SetShow( TRUE ); @@ -1537,14 +1535,14 @@ int CScene_MultiGameJoinLoad::DeviceSelectReturned(void *pParam,bool bContinue) { // if the saves list has focus, then we should show the Delete Save tooltip // if the games list has focus, then we should show the View Gamercard tooltip - int iRB=-1; + int iRB=-1; int iY = -1; if( pClass->DoesGamesListHaveFocus() ) { iY = IDS_TOOLTIPS_VIEW_GAMERCARD; } else if(pClass->DoesSavesListHaveFocus()) - { + { if(ProfileManager.IsSignedInLive( pClass->m_iPad )) { iY=IDS_TOOLTIPS_UPLOAD_SAVE_FOR_XBOXONE; @@ -1593,7 +1591,7 @@ int CScene_MultiGameJoinLoad::DeviceSelectReturned(void *pParam,bool bContinue) pClass->GetSaveInfo(); } else - { + { ui.SetTooltips( DEFAULT_XUI_MENU_USER, IDS_TOOLTIPS_SELECT,IDS_TOOLTIPS_BACK,IDS_TOOLTIPS_SELECTDEVICE,iY,-1,-1,iLB,iRB); // clear the saves list pClass->m_pSavesList->RemoveAllData(); @@ -1623,11 +1621,11 @@ int CScene_MultiGameJoinLoad::DeviceSelectReturned(void *pParam,bool bContinue) HRESULT CScene_MultiGameJoinLoad::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandled ) { - // 4J-PB - TODO - Don't think we can do this - if a 2nd player signs in here with an offline profile, the signed in LIVE player gets re-logged in, and bMultiplayerAllowed is false briefly + // 4J-PB - TODO - Don't think we can do this - if a 2nd player signs in here with an offline profile, the signed in LIVE player gets re-logged in, and bMultiplayerAllowed is false briefly switch(pTimer->nId) { - + case JOIN_LOAD_ONLINE_TIMER_ID: { XPARTY_USER_LIST partyList; @@ -1673,7 +1671,7 @@ HRESULT CScene_MultiGameJoinLoad::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandl { } else if(DoesSavesListHaveFocus()) - { + { if(ProfileManager.IsSignedInLive( m_iPad )) { iY=IDS_TOOLTIPS_UPLOAD_SAVE_FOR_XBOXONE; @@ -1737,7 +1735,7 @@ HRESULT CScene_MultiGameJoinLoad::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandl //CXuiCtrl4JList::LIST_ITEM_INFO ListInfo; // for each iConfig, check if the data is available, and add it to the List, then remove it from the viConfig - + for(int i=0;i<m_iTexturePacksNotInstalled;i++) { if(m_iConfigA[i]!=-1) @@ -1760,7 +1758,7 @@ HRESULT CScene_MultiGameJoinLoad::OnTimer( XUIMessageTimer *pTimer, BOOL& bHandl bool bAllDone=true; for(int i=0;i<m_iTexturePacksNotInstalled;i++) { - if(m_iConfigA[i]!=-1) + if(m_iConfigA[i]!=-1) { bAllDone = false; } @@ -1878,25 +1876,25 @@ int CScene_MultiGameJoinLoad::DeleteSaveDataReturned(void *pParam,bool bSuccess) pClass->m_iSaveInfoC=0; pClass->GetSaveInfo(); } - + pClass->m_bIgnoreInput=false; return 0; } void CScene_MultiGameJoinLoad::LoadLevelGen(LevelGenerationOptions *levelGen) -{ +{ // Load data from disc //File saveFile( L"Tutorial\\Tutorial" ); //LoadSaveFromDisk(&saveFile); // clear out the app's terrain features list app.ClearTerrainFeaturePosition(); - + StorageManager.ResetSaveData(); // Make our next save default to the name of the level StorageManager.SetSaveTitle(levelGen->getDefaultSaveName().c_str()); - + bool isClientSide = false; bool isPrivate = false; int maxPlayers = MINECRAFT_NET_MAX_PLAYERS; @@ -1918,7 +1916,7 @@ void CScene_MultiGameJoinLoad::LoadLevelGen(LevelGenerationOptions *levelGen) if(levelGen->requiresTexturePack()) { param->texturePackId = levelGen->getRequiredTexturePackId(); - + Minecraft *pMinecraft = Minecraft::GetInstance(); pMinecraft->skins->selectTexturePackById(param->texturePackId); //pMinecraft->skins->updateUI(); @@ -1939,7 +1937,7 @@ void CScene_MultiGameJoinLoad::LoadLevelGen(LevelGenerationOptions *levelGen) } void CScene_MultiGameJoinLoad::LoadSaveFromDisk(File *saveFile) -{ +{ // we'll only be coming in here when the tutorial is loaded now StorageManager.ResetSaveData(); @@ -1952,7 +1950,7 @@ void CScene_MultiGameJoinLoad::LoadSaveFromDisk(File *saveFile) byteArray ba(fileSize); fis.read(ba); fis.close(); - + bool isClientSide = false; bool isPrivate = false; int maxPlayers = MINECRAFT_NET_MAX_PLAYERS; @@ -1962,7 +1960,7 @@ void CScene_MultiGameJoinLoad::LoadSaveFromDisk(File *saveFile) isClientSide = false; maxPlayers = 4; } - + app.SetGameHostOption(eGameHostOption_GameType,GameType::CREATIVE->getId()); g_NetworkManager.HostGame(0,isClientSide,isPrivate,maxPlayers,0); @@ -1992,7 +1990,7 @@ int CScene_MultiGameJoinLoad::DeleteSaveDialogReturned(void *pParam,int iPad,C4J { CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; // results switched for this dialog - if(result==C4JStorage::EMessage_ResultDecline) + if(result==C4JStorage::EMessage_ResultDecline) { if(app.DebugSettingsOn() && app.GetLoadSavesFromFolderEnabled()) { @@ -2017,7 +2015,7 @@ int CScene_MultiGameJoinLoad::SaveTransferDialogReturned(void *pParam,int iPad,C { CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad*)pParam; // results switched for this dialog - if(result==C4JStorage::EMessage_ResultAccept) + if(result==C4JStorage::EMessage_ResultAccept) { // upload the save @@ -2042,7 +2040,7 @@ int CScene_MultiGameJoinLoad::SaveTransferDialogReturned(void *pParam,int iPad,C int CScene_MultiGameJoinLoad::UploadSaveForXboxOneThreadProc( LPVOID lpParameter ) { CScene_MultiGameJoinLoad* pClass = (CScene_MultiGameJoinLoad *) lpParameter; - Minecraft *pMinecraft = Minecraft::GetInstance(); + Minecraft *pMinecraft = Minecraft::GetInstance(); pMinecraft->progressRenderer->progressStart(IDS_SAVE_TRANSFER_TITLE); pMinecraft->progressRenderer->progressStage( IDS_SAVE_TRANSFER_UPLOADING ); @@ -2092,7 +2090,7 @@ int CScene_MultiGameJoinLoad::UploadSaveForXboxOneThreadProc( LPVOID lpParameter StorageManager.GetSaveCacheFileInfo(iIndex,XContentData); StorageManager.GetSaveCacheFileInfo(iIndex,&pbImageData,&dwImageBytes); - // if there is no thumbnail, retrieve the default one from the file. + // if there is no thumbnail, retrieve the default one from the file. // Don't delete the image data after creating the xuibrush, since we'll use it in the rename of the save if(pbImageData==NULL) { @@ -2143,7 +2141,7 @@ int CScene_MultiGameJoinLoad::UploadSaveForXboxOneThreadProc( LPVOID lpParameter return 0; } - // change text for completion confirmation + // change text for completion confirmation pMinecraft->progressRenderer->progressStage( IDS_SAVE_TRANSFER_UPLOADCOMPLETE ); // done @@ -2180,7 +2178,7 @@ void CScene_MultiGameJoinLoad::UploadFile(CScene_MultiGameJoinLoad *pClass, char C4JStorage::TMS_FILETYPE_BINARY, C4JStorage::TMS_UGCTYPE_NONE, filename, - (CHAR *)data, + (CHAR *)data, size, &CScene_MultiGameJoinLoad::TransferComplete,pClass, 0, &CScene_MultiGameJoinLoad::Progress,pClass); @@ -2219,7 +2217,7 @@ bool CScene_MultiGameJoinLoad::WaitForTransferComplete( CScene_MultiGameJoinLoad // cancelled return false; } - Sleep(50); + Sleep(50); // update the progress pMinecraft->progressRenderer->progressStagePercentage((unsigned int)(pClass->m_fProgress*100.0f)); } @@ -2235,7 +2233,7 @@ int CScene_MultiGameJoinLoad::SaveOptionsDialogReturned(void *pParam,int iPad,C4 // results switched for this dialog // EMessage_ResultAccept means cancel - if(result==C4JStorage::EMessage_ResultDecline || result==C4JStorage::EMessage_ResultThirdOption) + if(result==C4JStorage::EMessage_ResultDecline || result==C4JStorage::EMessage_ResultThirdOption) { if(result==C4JStorage::EMessage_ResultDecline) // rename { @@ -2302,9 +2300,9 @@ int CScene_MultiGameJoinLoad::LoadSaveDataReturned(void *pParam,bool bContinue) UINT uiIDA[2]; uiIDA[0]=IDS_CONFIRM_CANCEL; uiIDA[1]=IDS_CONFIRM_OK; - StorageManager.RequestMessageBox(IDS_CORRUPT_OR_DAMAGED_SAVE_TITLE, IDS_CORRUPT_OR_DAMAGED_SAVE_TEXT, uiIDA, 2, + StorageManager.RequestMessageBox(IDS_CORRUPT_OR_DAMAGED_SAVE_TITLE, IDS_CORRUPT_OR_DAMAGED_SAVE_TEXT, uiIDA, 2, pClass->m_iPad,&CScene_MultiGameJoinLoad::DeleteSaveDialogReturned,pClass, app.GetStringTable()); - + } return 0; @@ -2366,7 +2364,7 @@ int CScene_MultiGameJoinLoad::KeyboardReturned(void *pParam,bool bSet) if(eLoadStatus==C4JStorage::ELoadGame_DeviceRemoved) { - // disable saving + // disable saving StorageManager.SetSaveDisabled(true); StorageManager.SetSaveDeviceSelected(ProfileManager.GetPrimaryPad(),false); UINT uiIDA[1]; @@ -2375,11 +2373,11 @@ int CScene_MultiGameJoinLoad::KeyboardReturned(void *pParam,bool bSet) } #else // rename the save - + #endif } else - { + { pClass->m_bIgnoreInput=false; } @@ -2400,7 +2398,7 @@ int CScene_MultiGameJoinLoad::LoadSaveDataForRenameReturned(void *pParam,bool bC StorageManager.GetSaveCacheFileInfo(pClass->m_iChangingSaveGameInfoIndex-pClass->m_iDefaultButtonsC,XContentData); StorageManager.GetSaveCacheFileInfo(pClass->m_iChangingSaveGameInfoIndex-pClass->m_iDefaultButtonsC,&pbImageData,&dwImageBytes); - // if there is no thumbnail, retrieve the default one from the file. + // if there is no thumbnail, retrieve the default one from the file. // Don't delete the image data after creating the xuibrush, since we'll use it in the rename of the save if(pbImageData==NULL) { @@ -2456,7 +2454,7 @@ int CScene_MultiGameJoinLoad::TexturePackDialogReturned(void *pParam,int iPad,C4 // Exit with or without saving // Decline means install full version of the texture pack in this dialog - if(result==C4JStorage::EMessage_ResultDecline || result==C4JStorage::EMessage_ResultAccept) + if(result==C4JStorage::EMessage_ResultDecline || result==C4JStorage::EMessage_ResultAccept) { // we need to enable background downloading for the DLC XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_ALWAYS_ALLOW); @@ -2480,7 +2478,7 @@ int CScene_MultiGameJoinLoad::TexturePackDialogReturned(void *pParam,int iPad,C4 ullIndexA[0]=pDLCInfo->ullOfferID_Trial; StorageManager.InstallOffer(1,ullIndexA,NULL,NULL); } - } + } } pClass->m_bIgnoreInput=false; return 0; @@ -2489,7 +2487,7 @@ int CScene_MultiGameJoinLoad::TexturePackDialogReturned(void *pParam,int iPad,C4 HRESULT CScene_MultiGameJoinLoad::OnCustomMessage_DLCInstalled() { // mounted DLC may have changed - + if(app.StartInstallDLCProcess(m_iPad)==false) { // not doing a mount, so re-enable input @@ -2508,7 +2506,7 @@ HRESULT CScene_MultiGameJoinLoad::OnCustomMessage_DLCInstalled() } HRESULT CScene_MultiGameJoinLoad::OnCustomMessage_DLCMountingComplete() -{ +{ VOID *pObj; XuiObjectFromHandle( m_SavesList, &pObj ); @@ -2534,7 +2532,7 @@ HRESULT CScene_MultiGameJoinLoad::OnCustomMessage_DLCMountingComplete() int iY=-1; if(DoesSavesListHaveFocus()) - { + { if(ProfileManager.IsSignedInLive( m_iPad )) { iY=IDS_TOOLTIPS_UPLOAD_SAVE_FOR_XBOXONE; @@ -2627,7 +2625,7 @@ void CScene_MultiGameJoinLoad::UpdateTooltips() // 4J-PB - we need to check that there is enough space left to create a copy of the save (for a rename) bool bCanRename = StorageManager.EnoughSpaceForAMinSaveGame(); - if(bCanRename) + if(bCanRename) { iRB=IDS_TOOLTIPS_SAVEOPTIONS; } @@ -2694,11 +2692,11 @@ bool CScene_MultiGameJoinLoad::GetSavesInfoCallback(LPVOID pParam,int iTotalSave pbCurrentImagePtr=pbImageData+InfoA[i].dwImageOffset; hr=XuiCreateTextureBrushFromMemory(pbCurrentImagePtr,InfoA[i].dwImageBytes,&hXuiBrush); pClass->m_pSavesList->UpdateGraphic(i+pClass->m_iDefaultButtonsC,hXuiBrush ); - } + } else { // we could put in a damaged save icon here - const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string + const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); @@ -2724,7 +2722,7 @@ bool CScene_MultiGameJoinLoad::GetSavesInfoCallback(LPVOID pParam,int iTotalSave // It's possible that the games list is updated but we haven't displayed it yet as we were still waiting on saves list to load // This is to fix a bug where joining a game before the saves list has loaded causes a crash when this callback is called // as the scene no longer exists - pClass->UpdateGamesList(); + pClass->UpdateGamesList(); // Fix for #45154 - Frontend: DLC: Content can only be downloaded from the frontend if you have not joined/exited multiplayer XBackgroundDownloadSetMode(XBACKGROUND_DOWNLOAD_MODE_AUTO); diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_AbstractContainer.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_AbstractContainer.cpp index 10369d5e..03e783f4 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_AbstractContainer.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_AbstractContainer.cpp @@ -24,7 +24,7 @@ #include "XUI_Ctrl_SlotItem.h" #include "XUI_Ctrl_SlotItemListItem.h" #include "XUI_Scene_AbstractContainer.h" -#ifdef _DEBUG_MENUS_ENABLED +#ifdef _DEBUG_MENUS_ENABLED #include "XUI_DebugItemEditor.h" #endif @@ -44,14 +44,14 @@ void CXuiSceneAbstractContainer::PlatformInitialize(int iPad, int startIndex) // We may have varying depths of controls here, so base off the pointers parent HXUIOBJ parent; - XuiElementGetBounds( m_pointerControl->m_hObj, &fPointerWidth, &fPointerHeight ); + XuiElementGetBounds( m_pointerControl->m_hObj, &fPointerWidth, &fPointerHeight ); XuiElementGetParent( m_pointerControl->m_hObj, &parent ); m_pointerControl->SetShow(TRUE); - XuiElementGetBounds( parent, &fPanelWidth, &fPanelHeight ); + XuiElementGetBounds( parent, &fPanelWidth, &fPanelHeight ); // Get size of pointer m_fPointerImageOffsetX = floor(fPointerWidth/2.0f); m_fPointerImageOffsetY = floor(fPointerHeight/2.0f); - + m_fPanelMinX = 0.0f; m_fPanelMaxX = fPanelWidth; m_fPanelMinY = 0.0f; @@ -97,13 +97,13 @@ void CXuiSceneAbstractContainer::PlatformInitialize(int iPad, int startIndex) m_pointerPos.x = newPointerPos.x; m_pointerPos.y = newPointerPos.y; -#ifdef USE_POINTER_ACCEL +#ifdef USE_POINTER_ACCEL m_fPointerVelX = 0.0f; m_fPointerVelY = 0.0f; m_fPointerAccelX = 0.0f; m_fPointerAccelY = 0.0f; #endif - + // Add timer to poll controller stick input at 60Hz HRESULT timerResult = SetTimer( POINTER_INPUT_TIMER_ID, ( 1000 / 60 ) ); assert( timerResult == S_OK ); @@ -114,7 +114,7 @@ void CXuiSceneAbstractContainer::PlatformInitialize(int iPad, int startIndex) for ( int iSection = m_eFirstSection; iSection < m_eMaxSection; ++iSection ) { ESceneSection eSection = ( ESceneSection )( iSection ); - + if(!IsSectionSlotList(eSection)) continue; // Get dimensions of this section. @@ -153,7 +153,7 @@ int CXuiSceneAbstractContainer::getSectionRows(ESceneSection eSection) return GetSectionSlotList( eSection )->GetRows(); } -// Adding this so we can turn off the pointer text background, since it flickers on then off at the start of a scene where a tutorial popup is +// Adding this so we can turn off the pointer text background, since it flickers on then off at the start of a scene where a tutorial popup is HRESULT CXuiSceneAbstractContainer::OnTransitionStart( XUIMessageTransition *pTransition, BOOL& bHandled ) { if(pTransition->dwTransAction==XUI_TRANSITION_ACTION_DESTROY ) return S_OK; @@ -327,7 +327,7 @@ HRESULT CXuiSceneAbstractContainer::OnTimer( XUIMessageTimer *pTimer, BOOL& bHan // Update pointer from stick input on timer. if ( pTimer->nId == POINTER_INPUT_TIMER_ID ) { - + onMouseTick(); D3DXVECTOR3 pointerPos; pointerPos.x = m_pointerPos.x; @@ -348,7 +348,7 @@ HRESULT CXuiSceneAbstractContainer::OnTimer( XUIMessageTimer *pTimer, BOOL& bHan hr = handleCustomTimer( pTimer, bHandled ); } return hr; -} +} HRESULT CXuiSceneAbstractContainer::OnCustomMessage_Splitscreenplayer(bool bJoining, BOOL& bHandled) { @@ -388,15 +388,15 @@ void CXuiSceneAbstractContainer::SetPointerText(const wstring &description, vect } bool smallPointer = m_bSplitscreen || (!RenderManager.IsHiDef() && !RenderManager.IsWidescreen()); - wstring desc = L"<font size=\"" + _toString<int>(smallPointer ? 12 :14) + L"\">" + description + L"</font>"; + wstring desc = L"<font size=\"" + std::to_wstring(smallPointer ? 12 :14) + L"\">" + description + L"</font>"; XUIRect tempXuiRect, xuiRect; HRESULT hr; xuiRect.right = 0; - for(AUTO_VAR(it, unformattedStrings.begin()); it != unformattedStrings.end(); ++it) - { - XuiTextPresenterMeasureText(m_hPointerTextMeasurer, parseXMLSpecials((*it)).c_str(), &tempXuiRect); + for (auto& it : unformattedStrings ) + { + XuiTextPresenterMeasureText(m_hPointerTextMeasurer, parseXMLSpecials(it).c_str(), &tempXuiRect); if(tempXuiRect.right > xuiRect.right) xuiRect = tempXuiRect; } @@ -443,7 +443,7 @@ void CXuiSceneAbstractContainer::adjustPointerForSafeZone() D3DXVECTOR2 baseSceneOrigin; float baseWidth, baseHeight; if(CXuiSceneBase::GetBaseSceneSafeZone( m_iPad, baseSceneOrigin, baseWidth, baseHeight)) - { + { D3DXMATRIX pointerBackgroundMatrix; XuiElementGetFullXForm( m_hPointerTextBkg, &pointerBackgroundMatrix); diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Inventory.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Inventory.cpp index 04e77e5e..6024b8d6 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Inventory.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Inventory.cpp @@ -33,7 +33,7 @@ HRESULT CXuiSceneInventory::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) { if(m_bSplitscreen) { - app.AdjustSplitscreenScene(m_hObj,&m_OriginalPosition,m_iPad); + app.AdjustSplitscreenScene(m_hObj,&m_OriginalPosition,m_iPad); } } @@ -57,7 +57,7 @@ HRESULT CXuiSceneInventory::OnInit( XUIMessageInit *pInitData, BOOL &bHandled ) initData->player->awardStat(GenericStats::openInventory(), GenericStats::param_noArgs()); CXuiSceneAbstractContainer::Initialize( initData->iPad, menu, false, InventoryMenu::INV_SLOT_START, eSectionInventoryUsing, eSectionInventoryMax, initData->bNavigateBack ); - + delete initData; float fWidth; @@ -86,7 +86,7 @@ HRESULT CXuiSceneInventory::OnDestroy() } // 4J Stu - Fix for #11302 - TCR 001: Network Connectivity: Host crashed after being killed by the client while accessing a chest during burst packet loss. - // We need to make sure that we call closeContainer() anytime this menu is closed, even if it is forced to close by some other reason (like the player dying) + // We need to make sure that we call closeContainer() anytime this menu is closed, even if it is forced to close by some other reason (like the player dying) if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -176,8 +176,8 @@ void CXuiSceneInventory::updateEffectsDisplay() // Fill out details for display D3DXVECTOR3 position; m_hEffectDisplayA[0]->GetPosition(&position); - AUTO_VAR(it, activeEffects->begin()); - for(unsigned int i = 0; i < MAX_EFFECTS; ++i) + auto it = activeEffects->begin(); + for(unsigned int i = 0; i < MAX_EFFECTS; ++i) { if(it != activeEffects->end()) { @@ -185,7 +185,7 @@ void CXuiSceneInventory::updateEffectsDisplay() if(i > 0) position.y -= fNextEffectYOffset; // Stack from the bottom m_hEffectDisplayA[i]->SetPosition(&position); - + MobEffectInstance *effect = *it; MobEffect *mobEffect = MobEffect::effects[effect->getId()]; diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Trading.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Trading.cpp index fec13460..8738e683 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Trading.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Trading.cpp @@ -19,11 +19,11 @@ HRESULT CXuiSceneTrading::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) { MapChildControls(); - + //XuiControlSetText(m_villagerText,app.GetString(IDS_VILLAGER)); XuiControlSetText(m_inventoryLabel,app.GetString(IDS_INVENTORY)); XuiControlSetText(m_requiredLabel,app.GetString(IDS_REQUIRED_ITEMS_FOR_TRADE)); - + Minecraft *pMinecraft = Minecraft::GetInstance(); @@ -36,7 +36,7 @@ HRESULT CXuiSceneTrading::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) if(m_bSplitscreen) { - app.AdjustSplitscreenScene(m_hObj,&m_OriginalPosition,m_iPad); + app.AdjustSplitscreenScene(m_hObj,&m_OriginalPosition,m_iPad); } if( pMinecraft->localgameModes[m_iPad] != NULL ) @@ -65,7 +65,7 @@ HRESULT CXuiSceneTrading::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) // store the slot 0 highlight position m_tradingSelector.GetPosition(&m_vSelectorInitialPos); - + //app.SetRichPresenceContextValue(m_iPad,CONTEXT_GAME_STATE_FORGING); XuiSetTimer(m_hObj,TRADING_UPDATE_TIMER_ID,TRADING_UPDATE_TIMER_TIME); @@ -86,7 +86,7 @@ HRESULT CXuiSceneTrading::OnDestroy() } // 4J Stu - Fix for #11302 - TCR 001: Network Connectivity: Host crashed after being killed by the client while accessing a chest during burst packet loss. - // We need to make sure that we call closeContainer() anytime this menu is closed, even if it is forced to close by some other reason (like the player dying) + // We need to make sure that we call closeContainer() anytime this menu is closed, even if it is forced to close by some other reason (like the player dying) if(Minecraft::GetInstance()->localplayers[m_iPad] != NULL) Minecraft::GetInstance()->localplayers[m_iPad]->closeContainer(); return S_OK; } @@ -270,15 +270,15 @@ void CXuiSceneTrading::setOfferDescription(const wstring &name, vector<wstring> } bool smallPointer = m_bSplitscreen || (!RenderManager.IsHiDef() && !RenderManager.IsWidescreen()); - wstring desc = L"<font size=\"" + _toString<int>(smallPointer ? 12 :14) + L"\">" + name + L"</font>"; + wstring desc = L"<font size=\"" + std::to_wstring(smallPointer ? 12 :14) + L"\">" + name + L"</font>"; XUIRect tempXuiRect, xuiRect; HRESULT hr; xuiRect.right = 0; - for(AUTO_VAR(it, unformattedStrings.begin()); it != unformattedStrings.end(); ++it) - { - XuiTextPresenterMeasureText(m_hOfferInfoTextMeasurer, (*it).c_str(), &tempXuiRect); + for (auto& it : unformattedStrings ) + { + XuiTextPresenterMeasureText(m_hOfferInfoTextMeasurer, it.c_str(), &tempXuiRect); if(tempXuiRect.right > xuiRect.right) xuiRect = tempXuiRect; } @@ -299,7 +299,7 @@ void CXuiSceneTrading::setOfferDescription(const wstring &name, vector<wstring> XuiElementSetBounds(m_hOfferInfoText,xuiRect.right+4.0f+4.0f,xuiRect.bottom+4.0f+4.0f); // edge graphics are 8 pixels, text is centred m_offerInfoControl.SetShow(TRUE); - + D3DXVECTOR3 highlightPos, offerInfoPos; float highlightWidth, highlightHeight; m_tradingSelector.GetPosition(&highlightPos); diff --git a/Minecraft.Client/Common/XUI/XUI_Scene_Win.cpp b/Minecraft.Client/Common/XUI/XUI_Scene_Win.cpp index 0f0c678b..19e6b016 100644 --- a/Minecraft.Client/Common/XUI/XUI_Scene_Win.cpp +++ b/Minecraft.Client/Common/XUI/XUI_Scene_Win.cpp @@ -20,7 +20,7 @@ const float CScene_Win::PLAYER_SCROLL_SPEED = 3.0f; // Performs initialization tasks - retrieves controls. //---------------------------------------------------------------------------------- HRESULT CScene_Win::OnInit( XUIMessageInit* pInitData, BOOL& bHandled ) -{ +{ m_iPad = *(int *)pInitData->pvInitData; m_bIgnoreInput = false; @@ -194,8 +194,8 @@ void CScene_Win::updateNoise() { Minecraft *pMinecraft = Minecraft::GetInstance(); noiseString = noNoiseString; - - int length = 0; + + size_t length = 0; wchar_t replacements[64]; wstring replaceString = L""; wchar_t randomChar = L'a'; @@ -205,18 +205,18 @@ void CScene_Win::updateNoise() wstring tag = L"{*NOISE*}"; - AUTO_VAR(it, m_noiseLengths.begin()); - int found=(int)noiseString.find_first_of(L"{"); + auto it = m_noiseLengths.begin(); + size_t found = noiseString.find_first_of(L"{"); while (found!=string::npos && it != m_noiseLengths.end() ) { length = *it; ++it; replaceString = L""; - for(int i = 0; i < length; ++i) + for(size_t i = 0; i < length; ++i) { - randomChar = SharedConstants::acceptableLetters[random->nextInt((int)SharedConstants::acceptableLetters.length())]; - + randomChar = SharedConstants::acceptableLetters[random->nextInt(SharedConstants::acceptableLetters.length())]; + wstring randomCharStr = L""; randomCharStr.push_back(randomChar); if(randomChar == L'<') @@ -262,7 +262,7 @@ void CScene_Win::updateNoise() //ib.put(listPos + 256 + random->nextInt(2) + 8 + (darken ? 16 : 0)); //ib.put(listPos + pos + 32); - found=(int)noiseString.find_first_of(L"{",found+1); + found = noiseString.find_first_of(L"{",found+1); } } diff --git a/Minecraft.Client/Common/XUI/XUI_TextEntry.cpp b/Minecraft.Client/Common/XUI/XUI_TextEntry.cpp index 8934350d..0369928b 100644 --- a/Minecraft.Client/Common/XUI/XUI_TextEntry.cpp +++ b/Minecraft.Client/Common/XUI/XUI_TextEntry.cpp @@ -53,7 +53,7 @@ HRESULT CScene_TextEntry::OnNotifyValueChanged (HXUIOBJ hObjSource, XUINotifyVal if(pValueChangedData->nValue==10) { LPCWSTR pText = m_EditText.GetText(); - + if(pText) { wstring wText = pText; @@ -61,7 +61,7 @@ HRESULT CScene_TextEntry::OnNotifyValueChanged (HXUIOBJ hObjSource, XUINotifyVal } app.NavigateBack(m_iPad); - rfHandled = TRUE; + rfHandled = TRUE; } return S_OK; @@ -86,7 +86,7 @@ HRESULT CScene_TextEntry::OnKeyDown(XUIMessageInput* pInputData, BOOL& rfHandled app.NavigateBack(m_iPad); rfHandled = TRUE; - } + } break; case VK_PAD_B: @@ -113,8 +113,8 @@ HRESULT CScene_TextEntry::InterpretString(wstring &wsText) swscanf_s(wsText.c_str(), L"%s", wchCommand,40); #endif - AUTO_VAR(it, m_CommandSet.find(wchCommand)); - if(it != m_CommandSet.end()) + auto it = m_CommandSet.find(wchCommand); + if(it != m_CommandSet.end()) { // found it @@ -125,7 +125,7 @@ HRESULT CScene_TextEntry::InterpretString(wstring &wsText) case eCommand_Teleport: { int x,z; - + #ifdef __PS3__ // 4J Stu - The Xbox version uses swscanf_s which isn't available in GCC. swscanf(wsText.c_str(), L"%40s%c%d%c%d", wchCommand,wchSep,&x,wchSep,&z); @@ -146,9 +146,9 @@ HRESULT CScene_TextEntry::InterpretString(wstring &wsText) } break; case eCommand_Give: - { + { int iItem,iCount; - + #ifdef __PS3__ // 4J Stu - The Xbox version uses swscanf_s which isn't available in GCC. swscanf(wsText.c_str(), L"%40s%c%d%c%d", wchCommand,wchSep,&iItem,wchSep,&iCount); diff --git a/Minecraft.Client/DeathScreen.cpp b/Minecraft.Client/DeathScreen.cpp index a06606ec..e7ab1328 100644 --- a/Minecraft.Client/DeathScreen.cpp +++ b/Minecraft.Client/DeathScreen.cpp @@ -48,7 +48,7 @@ void DeathScreen::render(int xm, int ym, float a) glScalef(2, 2, 2); drawCenteredString(font, L"Game over!", width / 2 / 2, 60 / 2, 0xffffff); glPopMatrix(); - drawCenteredString(font, L"Score: &e" + _toString( minecraft->player->getScore() ), width / 2, 100, 0xffffff); + drawCenteredString(font, L"Score: &e" + std::to_wstring( minecraft->player->getScore() ), width / 2, 100, 0xffffff); Screen::render(xm, ym, a); diff --git a/Minecraft.Client/DemoMode.cpp b/Minecraft.Client/DemoMode.cpp index 3b24af7a..c52580c3 100644 --- a/Minecraft.Client/DemoMode.cpp +++ b/Minecraft.Client/DemoMode.cpp @@ -26,7 +26,7 @@ void DemoMode::tick() { if (day <= (DEMO_DAYS + 1)) { - minecraft->gui->displayClientMessage(L"demo.day." + _toString<__int64>(day)); + minecraft->gui->displayClientMessage(L"demo.day." + std::to_wstring(day)); } } else if (day == 1) diff --git a/Minecraft.Client/Durango/Durango_App.cpp b/Minecraft.Client/Durango/Durango_App.cpp index 2ec81a29..59ac8ba0 100644 --- a/Minecraft.Client/Durango/Durango_App.cpp +++ b/Minecraft.Client/Durango/Durango_App.cpp @@ -171,7 +171,7 @@ int CConsoleMinecraftApp::LoadLocalDLCImages() { unordered_map<wstring,DLC_INFO * > *pDLCInfoA=app.GetDLCInfo(); // 4J-PB - Any local graphic files for the Minecraft Store? - for( AUTO_VAR(it, pDLCInfoA->begin()); it != pDLCInfoA->end(); it++ ) + for (auto it = pDLCInfoA->begin(); it != pDLCInfoA->end(); it++) { DLC_INFO * pDLCInfo=(*it).second; @@ -185,7 +185,7 @@ void CConsoleMinecraftApp::FreeLocalDLCImages() // 4J-PB - Any local graphic files for the Minecraft Store? unordered_map<wstring,DLC_INFO * > *pDLCInfoA=app.GetDLCInfo(); - for( AUTO_VAR(it, pDLCInfoA->begin()); it != pDLCInfoA->end(); it++ ) + for (auto it = pDLCInfoA->begin(); it != pDLCInfoA->end(); it++) { DLC_INFO * pDLCInfo=(*it).second; @@ -567,8 +567,8 @@ int CConsoleMinecraftApp::Callback_TMSPPRetrieveFileList(void *pParam,int iPad, // dump out the file list app.DebugPrintf("TMSPP filecount - %d\nFiles - \n",pvTmsFileDetails->size()); int iCount=0; - AUTO_VAR(itEnd, pvTmsFileDetails->end()); - for( AUTO_VAR(it, pvTmsFileDetails->begin()); it != itEnd; it++ ) + auto itEnd = pvTmsFileDetails->end(); + for (auto it = pvTmsFileDetails->begin(); it != itEnd; it++) { C4JStorage::PTMSPP_FILE_DETAILS fd = *it; app.DebugPrintf("%2d. %ls (size - %d)\n",iCount++,fd->wchFilename,fd->ulFileSize); diff --git a/Minecraft.Client/Durango/Durango_Minecraft.cpp b/Minecraft.Client/Durango/Durango_Minecraft.cpp index 48d5c319..a563c9f3 100644 --- a/Minecraft.Client/Durango/Durango_Minecraft.cpp +++ b/Minecraft.Client/Durango/Durango_Minecraft.cpp @@ -1102,12 +1102,12 @@ SIZE_T WINAPI XMemSize( void DumpMem() { int totalLeak = 0; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) + for( auto& it : allocCounts ) { - if(it->second > 0 ) + if(it.second > 0 ) { - app.DebugPrintf("%d %d %d %d\n",( it->first >> 26 ) & 0x3f,it->first & 0x03ffffff, it->second, (it->first & 0x03ffffff) * it->second); - totalLeak += ( it->first & 0x03ffffff ) * it->second; + app.DebugPrintf("%d %d %d %d\n",( it.first >> 26 ) & 0x3f,it.first & 0x03ffffff, it.second, (it.first & 0x03ffffff) * it.second); + totalLeak += ( it.first & 0x03ffffff ) * it.second; } } app.DebugPrintf("Total %d\n",totalLeak); @@ -1150,13 +1150,13 @@ void MemPixStuff() int totals[MAX_SECT] = {0}; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) + for ( auto& it : allocCounts ) { - if(it->second > 0 ) + if ( it.second > 0 ) { - int sect = ( it->first >> 26 ) & 0x3f; - int bytes = it->first & 0x03ffffff; - totals[sect] += bytes * it->second; + int sect = ( it.first >> 26 ) & 0x3f; + int bytes = it.first & 0x03ffffff; + totals[sect] += bytes * it.second; } } diff --git a/Minecraft.Client/Durango/Leaderboards/DurangoLeaderboardManager.cpp b/Minecraft.Client/Durango/Leaderboards/DurangoLeaderboardManager.cpp index cbedb033..46b04606 100644 --- a/Minecraft.Client/Durango/Leaderboards/DurangoLeaderboardManager.cpp +++ b/Minecraft.Client/Durango/Leaderboards/DurangoLeaderboardManager.cpp @@ -21,52 +21,52 @@ DurangoLeaderboardManager::DurangoLeaderboardManager() m_difficulty = 0; m_type = eStatsType_UNDEFINED; - m_statNames = ref new PC::Vector<P::String^>(); + m_statNames = ref new PC::Vector<P::String^>(); m_xboxUserIds = ref new PC::Vector<P::String^>(); m_leaderboardAsyncOp = nullptr; m_statsAsyncOp = nullptr; for(unsigned int difficulty = 0; difficulty < 4; ++difficulty) { - m_leaderboardNames[difficulty][eStatsType_Travelling] = L"LeaderboardTravelling" + _toString(difficulty); - m_leaderboardNames[difficulty][eStatsType_Mining] = L"LeaderboardMining" + _toString(difficulty); - m_leaderboardNames[difficulty][eStatsType_Farming] = L"LeaderboardFarming" + _toString(difficulty); - m_leaderboardNames[difficulty][eStatsType_Kills] = L"LeaderboardKills" + _toString(difficulty); - - m_socialLeaderboardNames[difficulty][eStatsType_Travelling] = L"Leaderboard.LeaderboardId.0.DifficultyLevelId." + _toString(difficulty); - m_socialLeaderboardNames[difficulty][eStatsType_Mining] = L"Leaderboard.LeaderboardId.1.DifficultyLevelId." + _toString(difficulty); - m_socialLeaderboardNames[difficulty][eStatsType_Farming] = L"Leaderboard.LeaderboardId.2.DifficultyLevelId." + _toString(difficulty); - m_socialLeaderboardNames[difficulty][eStatsType_Kills] = L"Leaderboard.LeaderboardId.3.DifficultyLevelId." + _toString(difficulty); - - m_leaderboardStatNames[difficulty][eStatsType_Travelling].push_back( L"DistanceTravelled.DifficultyLevelId." + _toString(difficulty) + L".TravelMethodId.0"); // Walked - m_leaderboardStatNames[difficulty][eStatsType_Travelling].push_back( L"DistanceTravelled.DifficultyLevelId." + _toString(difficulty) + L".TravelMethodId.2"); // Fallen - m_leaderboardStatNames[difficulty][eStatsType_Travelling].push_back( L"DistanceTravelled.DifficultyLevelId." + _toString(difficulty) + L".TravelMethodId.4"); // Minecart - m_leaderboardStatNames[difficulty][eStatsType_Travelling].push_back( L"DistanceTravelled.DifficultyLevelId." + _toString(difficulty) + L".TravelMethodId.5"); // Boat - - m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + _toString(difficulty) + L".BlockId.3"); // Dirt - m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + _toString(difficulty) + L".BlockId.4"); // Cobblestone - m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + _toString(difficulty) + L".BlockId.12"); // Sand - m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + _toString(difficulty) + L".BlockId.1"); // Stone - m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + _toString(difficulty) + L".BlockId.13"); // Gravel - m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + _toString(difficulty) + L".BlockId.82"); // Clay - m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + _toString(difficulty) + L".BlockId.49"); // Obsidian - - m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"McItemAcquired.DifficultyLevelId." + _toString(difficulty) + L".AcquisitionMethodId.1.ItemId.344"); // Eggs - m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"BlockBroken.DifficultyLevelId." + _toString(difficulty) + L".BlockId.59"); // Wheat - m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"BlockBroken.DifficultyLevelId." + _toString(difficulty) + L".BlockId.39"); // Mushroom - m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"BlockBroken.DifficultyLevelId." + _toString(difficulty) + L".BlockId.83"); // Sugarcane - m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"McItemAcquired.DifficultyLevelId." + _toString(difficulty) + L".AcquisitionMethodId.2.ItemId.335"); // Milk - m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"McItemAcquired.DifficultyLevelId." + _toString(difficulty) + L".AcquisitionMethodId.1.ItemId.86"); // Pumpkin - - m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + _toString(difficulty) + L".EnemyRoleId.54"); // Zombie - m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + _toString(difficulty) + L".EnemyRoleId.51"); // Skeleton - m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + _toString(difficulty) + L".EnemyRoleId.50"); // Creeper - m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + _toString(difficulty) + L".EnemyRoleId.52"); // Spider - m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + _toString(difficulty) + L".EnemyRoleId.49"); // Spider Jockey - m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + _toString(difficulty) + L".EnemyRoleId.57"); // Zombie Pigman - m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + _toString(difficulty) + L".EnemyRoleId.55"); // Slime + m_leaderboardNames[difficulty][eStatsType_Travelling] = L"LeaderboardTravelling" + std::to_wstring(difficulty); + m_leaderboardNames[difficulty][eStatsType_Mining] = L"LeaderboardMining" + std::to_wstring(difficulty); + m_leaderboardNames[difficulty][eStatsType_Farming] = L"LeaderboardFarming" + std::to_wstring(difficulty); + m_leaderboardNames[difficulty][eStatsType_Kills] = L"LeaderboardKills" + std::to_wstring(difficulty); + + m_socialLeaderboardNames[difficulty][eStatsType_Travelling] = L"Leaderboard.LeaderboardId.0.DifficultyLevelId." + std::to_wstring(difficulty); + m_socialLeaderboardNames[difficulty][eStatsType_Mining] = L"Leaderboard.LeaderboardId.1.DifficultyLevelId." + std::to_wstring(difficulty); + m_socialLeaderboardNames[difficulty][eStatsType_Farming] = L"Leaderboard.LeaderboardId.2.DifficultyLevelId." + std::to_wstring(difficulty); + m_socialLeaderboardNames[difficulty][eStatsType_Kills] = L"Leaderboard.LeaderboardId.3.DifficultyLevelId." + std::to_wstring(difficulty); + + m_leaderboardStatNames[difficulty][eStatsType_Travelling].push_back( L"DistanceTravelled.DifficultyLevelId." + std::to_wstring(difficulty) + L".TravelMethodId.0"); // Walked + m_leaderboardStatNames[difficulty][eStatsType_Travelling].push_back( L"DistanceTravelled.DifficultyLevelId." + std::to_wstring(difficulty) + L".TravelMethodId.2"); // Fallen + m_leaderboardStatNames[difficulty][eStatsType_Travelling].push_back( L"DistanceTravelled.DifficultyLevelId." + std::to_wstring(difficulty) + L".TravelMethodId.4"); // Minecart + m_leaderboardStatNames[difficulty][eStatsType_Travelling].push_back( L"DistanceTravelled.DifficultyLevelId." + std::to_wstring(difficulty) + L".TravelMethodId.5"); // Boat + + m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + std::to_wstring(difficulty) + L".BlockId.3"); // Dirt + m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + std::to_wstring(difficulty) + L".BlockId.4"); // Cobblestone + m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + std::to_wstring(difficulty) + L".BlockId.12"); // Sand + m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + std::to_wstring(difficulty) + L".BlockId.1"); // Stone + m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + std::to_wstring(difficulty) + L".BlockId.13"); // Gravel + m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + std::to_wstring(difficulty) + L".BlockId.82"); // Clay + m_leaderboardStatNames[difficulty][eStatsType_Mining].push_back( L"BlockBroken.DifficultyLevelId." + std::to_wstring(difficulty) + L".BlockId.49"); // Obsidian + + m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"McItemAcquired.DifficultyLevelId." + std::to_wstring(difficulty) + L".AcquisitionMethodId.1.ItemId.344"); // Eggs + m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"BlockBroken.DifficultyLevelId." + std::to_wstring(difficulty) + L".BlockId.59"); // Wheat + m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"BlockBroken.DifficultyLevelId." + std::to_wstring(difficulty) + L".BlockId.39"); // Mushroom + m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"BlockBroken.DifficultyLevelId." + std::to_wstring(difficulty) + L".BlockId.83"); // Sugarcane + m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"McItemAcquired.DifficultyLevelId." + std::to_wstring(difficulty) + L".AcquisitionMethodId.2.ItemId.335"); // Milk + m_leaderboardStatNames[difficulty][eStatsType_Farming].push_back( L"McItemAcquired.DifficultyLevelId." + std::to_wstring(difficulty) + L".AcquisitionMethodId.1.ItemId.86"); // Pumpkin + + m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + std::to_wstring(difficulty) + L".EnemyRoleId.54"); // Zombie + m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + std::to_wstring(difficulty) + L".EnemyRoleId.51"); // Skeleton + m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + std::to_wstring(difficulty) + L".EnemyRoleId.50"); // Creeper + m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + std::to_wstring(difficulty) + L".EnemyRoleId.52"); // Spider + m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + std::to_wstring(difficulty) + L".EnemyRoleId.49"); // Spider Jockey + m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + std::to_wstring(difficulty) + L".EnemyRoleId.57"); // Zombie Pigman + m_leaderboardStatNames[difficulty][eStatsType_Kills].push_back( L"MobKilledTotal.DifficultyLevelId." + std::to_wstring(difficulty) + L".EnemyRoleId.55"); // Slime } -} +} void DurangoLeaderboardManager::Tick() { @@ -93,7 +93,7 @@ void DurangoLeaderboardManager::Tick() { app.DebugPrintf("[LeaderboardManager] Second continuation\n"); m_statsAsyncOp = nullptr; - + WFC::IVectorView<MXS::UserStatistics::UserStatisticsResult^>^ resultList = resultListTask.get(); if (m_xboxLiveContext == nullptr) throw(ref new P::Exception(-1)); @@ -170,7 +170,7 @@ void DurangoLeaderboardManager::Tick() eStatsReturn ret = view.m_numQueries > 0 ? eStatsReturn_Success : eStatsReturn_NoResults; - if (m_readListener != NULL) + if (m_readListener != NULL) { app.DebugPrintf("[LeaderboardManager] OnStatsReadComplete(%i, %i, _)\n", ret, m_readCount); m_readListener->OnStatsReadComplete(ret, m_maxRank, view); @@ -380,10 +380,10 @@ void DurangoLeaderboardManager::CancelOperation() //if (m_transactionCtx != 0) //{ // int ret = sceNpScoreAbortTransaction(m_transactionCtx); - // + // // if (ret < 0) // { - // app.DebugPrintf("[LeaderboardManager] CancelOperation(): Problem encountered aborting current operation, 0x%X.\n", ret); + // app.DebugPrintf("[LeaderboardManager] CancelOperation(): Problem encountered aborting current operation, 0x%X.\n", ret); // } // else // { @@ -415,20 +415,20 @@ void DurangoLeaderboardManager::runLeaderboardRequest(WF::IAsyncOperation<MXSL:: app.DebugPrintf("[LeaderboardManager] Running request\n"); CC::create_task(asyncOp) - .then( [this, readCount, difficulty, type, filter] (CC::task<MXSL::LeaderboardResult^> resultTask) + .then( [this, readCount, difficulty, type, filter] (CC::task<MXSL::LeaderboardResult^> resultTask) { try { app.DebugPrintf("[LeaderboardManager] First continuation.\n"); m_leaderboardAsyncOp = nullptr; - + MXSL::LeaderboardResult^ lastResult = resultTask.get(); - app.DebugPrintf( - "Name: %ls - Filter: %ls - Rows: Retrieved=%d Total=%d Requested=%d.\n", - lastResult->DisplayName->Data(), - LeaderboardManager::filterNames[ (int) filter ].c_str(), + app.DebugPrintf( + "Name: %ls - Filter: %ls - Rows: Retrieved=%d Total=%d Requested=%d.\n", + lastResult->DisplayName->Data(), + LeaderboardManager::filterNames[ (int) filter ].c_str(), lastResult->Rows->Size, lastResult->TotalRowCount, readCount ); @@ -459,21 +459,21 @@ void DurangoLeaderboardManager::runLeaderboardRequest(WF::IAsyncOperation<MXSL:: m_readCount = lastResult->Rows->Size; if (m_scores != NULL) delete [] m_scores; - m_scores = new ReadScore[m_readCount]; + m_scores = new ReadScore[m_readCount]; ZeroMemory(m_scores, sizeof(ReadScore) * m_readCount); - + m_xboxUserIds->Clear(); app.DebugPrintf("[LeaderboardManager] Retrieved Scores:\n"); for( UINT index = 0; index < lastResult->Rows->Size; index++ ) { MXSL::LeaderboardRow^ row = lastResult->Rows->GetAt(index); - + app.DebugPrintf( - "\tIndex: %d\tRank: %d\tPercentile: %.1f%%\tXboxUserId: %ls\tValue: %ls.\n", + "\tIndex: %d\tRank: %d\tPercentile: %.1f%%\tXboxUserId: %ls\tValue: %ls.\n", index, row->Rank, - row->Percentile * 100, + row->Percentile * 100, row->XboxUserId->Data(), row->Values->GetAt(0)->Data() ); @@ -484,7 +484,7 @@ void DurangoLeaderboardManager::runLeaderboardRequest(WF::IAsyncOperation<MXSL:: // 4J-JEV: Added to help determine if this player's score is hidden due to their privacy settings. m_scores[index].m_totalScore = (unsigned long) _fromString<long long>(row->Values->GetAt(0)->Data()); - + m_xboxUserIds->Append(row->XboxUserId); } @@ -681,12 +681,12 @@ void DurangoLeaderboardManager::setState(EStatsState newState) }; break; }; - + #ifndef _CONTENT_PACKAGE app.DebugPrintf( - "[LeaderboardManager] %s state transition:\t%ls(%d) -> %ls(%d).\n", + "[LeaderboardManager] %s state transition:\t%ls(%d) -> %ls(%d).\n", (validTransition ? "Valid" : "INVALID"), - stateToString(m_eStatsState).c_str(), m_eStatsState, + stateToString(m_eStatsState).c_str(), m_eStatsState, stateToString(newState).c_str(), newState ); #endif diff --git a/Minecraft.Client/Durango/Network/DQRNetworkManager.cpp b/Minecraft.Client/Durango/Network/DQRNetworkManager.cpp index f13cc4aa..8d502d23 100644 --- a/Minecraft.Client/Durango/Network/DQRNetworkManager.cpp +++ b/Minecraft.Client/Durango/Network/DQRNetworkManager.cpp @@ -1460,7 +1460,7 @@ void DQRNetworkManager::UpdateRoomSyncPlayers(RoomSyncData *pNewSyncData) { PlayerSyncData *pNewPlayer = &pNewSyncData->players[i]; bool bAlreadyExisted = false; - for( AUTO_VAR(it, tempPlayers.begin()); it != tempPlayers.end(); it++ ) + for (auto it = tempPlayers.begin(); it != tempPlayers.end(); it++) { if( pNewPlayer->m_smallId == (*it)->GetSmallId() ) { diff --git a/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.cpp b/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.cpp index 3efba5ed..925a37a8 100644 --- a/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.cpp +++ b/Minecraft.Client/Durango/Network/PlatformNetworkManagerDurango.cpp @@ -1,4 +1,4 @@ -#include "stdafx.h" +#include "stdafx.h" #include "..\..\..\Minecraft.World\Socket.h" #include "..\..\..\Minecraft.World\StringHelpers.h" #include "PlatformNetworkManagerDurango.h" @@ -131,9 +131,8 @@ void CPlatformNetworkManagerDurango::HandlePlayerJoined(DQRNetworkPlayer *pDQRPl { // Do we already have a primary player for this system? bool systemHasPrimaryPlayer = false; - for(AUTO_VAR(it, m_machineDQRPrimaryPlayers.begin()); it < m_machineDQRPrimaryPlayers.end(); ++it) - { - DQRNetworkPlayer *pQNetPrimaryPlayer = *it; + for ( DQRNetworkPlayer *pQNetPrimaryPlayer : m_machineDQRPrimaryPlayers ) + { if( pDQRPlayer->IsSameSystem(pQNetPrimaryPlayer) ) { systemHasPrimaryPlayer = true; @@ -145,7 +144,7 @@ void CPlatformNetworkManagerDurango::HandlePlayerJoined(DQRNetworkPlayer *pDQRPl } } g_NetworkManager.PlayerJoining( networkPlayer ); - + if( createFakeSocket == true && !m_bHostChanged ) { g_NetworkManager.CreateSocket( networkPlayer, localPlayer ); @@ -164,7 +163,7 @@ void CPlatformNetworkManagerDurango::HandlePlayerJoined(DQRNetworkPlayer *pDQRPl g_NetworkManager.UpdateAndSetGameSessionData(); SystemFlagAddPlayer( networkPlayer ); } - + for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { if(playerChangedCallback[idx] != NULL) @@ -233,8 +232,8 @@ void CPlatformNetworkManagerDurango::HandlePlayerLeaving(DQRNetworkPlayer *pDQRP break; } } - AUTO_VAR(it, find( m_machineDQRPrimaryPlayers.begin(), m_machineDQRPrimaryPlayers.end(), pDQRPlayer)); - if( it != m_machineDQRPrimaryPlayers.end() ) + auto it = find(m_machineDQRPrimaryPlayers.begin(), m_machineDQRPrimaryPlayers.end(), pDQRPlayer); + if( it != m_machineDQRPrimaryPlayers.end() ) { m_machineDQRPrimaryPlayers.erase( it ); } @@ -249,7 +248,7 @@ void CPlatformNetworkManagerDurango::HandlePlayerLeaving(DQRNetworkPlayer *pDQRP } g_NetworkManager.PlayerLeaving( networkPlayer ); - + for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { if(playerChangedCallback[idx] != NULL) @@ -322,7 +321,7 @@ bool CPlatformNetworkManagerDurango::Initialise(CGameNetworkManager *pGameNetwor { playerChangedCallback[ i ] = NULL; } - + m_bLeavingGame = false; m_bLeaveGameOnTick = false; m_bHostChanged = false; @@ -593,7 +592,7 @@ void CPlatformNetworkManagerDurango::UnRegisterPlayerChangedCallback(int iPad, v void CPlatformNetworkManagerDurango::HandleSignInChange() { - return; + return; } void CPlatformNetworkManagerDurango::HandleAddLocalPlayerFailed(int idx, bool serverFull) @@ -618,10 +617,10 @@ void CPlatformNetworkManagerDurango::UpdateAndSetGameSessionData(INetworkPlayer { if( this->m_bLeavingGame ) return; - + if( GetHostPlayer() == NULL ) return; - + m_hostGameSessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); m_pDQRNet->UpdateCustomSessionData(); @@ -847,8 +846,8 @@ INetworkPlayer *CPlatformNetworkManagerDurango::addNetworkPlayer(DQRNetworkPlaye void CPlatformNetworkManagerDurango::removeNetworkPlayer(DQRNetworkPlayer *pDQRPlayer) { INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pDQRPlayer); - for( AUTO_VAR(it, currentNetworkPlayers.begin()); it != currentNetworkPlayers.end(); it++ ) - { + for (auto it = currentNetworkPlayers.begin(); it != currentNetworkPlayers.end(); ++it) + { if( *it == pNetworkPlayer ) { currentNetworkPlayers.erase(it); @@ -865,7 +864,7 @@ INetworkPlayer *CPlatformNetworkManagerDurango::getNetworkPlayer(DQRNetworkPlaye INetworkPlayer *CPlatformNetworkManagerDurango::GetLocalPlayerByUserIndex(int userIndex ) { - return getNetworkPlayer(m_pDQRNet->GetLocalPlayerByUserIndex(userIndex)); + return getNetworkPlayer(m_pDQRNet->GetLocalPlayerByUserIndex(userIndex)); } INetworkPlayer *CPlatformNetworkManagerDurango::GetPlayerByIndex(int playerIndex) diff --git a/Minecraft.Client/Durango/Sentient/DurangoTelemetry.cpp b/Minecraft.Client/Durango/Sentient/DurangoTelemetry.cpp index d51ce966..2386a348 100644 --- a/Minecraft.Client/Durango/Sentient/DurangoTelemetry.cpp +++ b/Minecraft.Client/Durango/Sentient/DurangoTelemetry.cpp @@ -51,7 +51,7 @@ HRESULT CDurangoTelemetryManager::Flush() bool CDurangoTelemetryManager::RecordPlayerSessionStart(int iPad) { durangoStats()->generatePlayerSession(); - + return true; } @@ -123,7 +123,7 @@ bool CDurangoTelemetryManager::RecordPlayerSessionExit(int iPad, int exitStatus) bool CDurangoTelemetryManager::RecordLevelStart(int iPad, ESen_FriendOrMatch friendsOrMatch, ESen_CompeteOrCoop competeOrCoop, int difficulty, int numberOfLocalPlayers, int numberOfOnlinePlayers) { CTelemetryManager::RecordLevelStart(iPad, friendsOrMatch, competeOrCoop, difficulty, numberOfLocalPlayers, numberOfOnlinePlayers); - + ULONG hr = 0; // Grab player info. @@ -191,10 +191,10 @@ bool CDurangoTelemetryManager::RecordLevelStart(int iPad, ESen_FriendOrMatch fri GetSubLevelId(iPad), GetLevelInstanceID(), &ZERO_GUID, - friendsOrMatch, - competeOrCoop, - difficulty, - numberOfLocalPlayers, + friendsOrMatch, + competeOrCoop, + difficulty, + numberOfLocalPlayers, numberOfOnlinePlayers, &ZERO_GUID ); @@ -219,10 +219,10 @@ bool CDurangoTelemetryManager::RecordLevelStart(int iPad, ESen_FriendOrMatch fri // Durango // /* GUID */ guid2str(DurangoStats::getPlayerSession()).c_str(), /* WSTR */ DurangoStats::getMultiplayerCorrelationId(), - /* int */ friendsOrMatch, - /* int */ competeOrCoop, - /* int */ difficulty, - /* int */ numberOfLocalPlayers, + /* int */ friendsOrMatch, + /* int */ competeOrCoop, + /* int */ difficulty, + /* int */ numberOfLocalPlayers, /* int */ numberOfOnlinePlayers ); @@ -577,7 +577,7 @@ bool CDurangoTelemetryManager::RecordMediaShareUpload(int iPad, ESen_MediaDestin mediaDestination, mediaType ); -#else +#else ULONG hr = -1; #endif @@ -974,11 +974,11 @@ DurangoStats *CDurangoTelemetryManager::durangoStats() wstring CDurangoTelemetryManager::guid2str(LPCGUID guid) { wstring out = L"GUID<"; - out += _toString<unsigned long>(guid->Data1); + out += std::to_wstring(guid->Data1); out += L":"; - out += _toString<unsigned short>(guid->Data2); + out += std::to_wstring(guid->Data2); out += L":"; - out += _toString<unsigned short>(guid->Data3); + out += std::to_wstring(guid->Data3); //out += L":"; //out += convStringToWstring(string((char*)&guid->Data4,8)); out += L">"; diff --git a/Minecraft.Client/EntityRenderDispatcher.cpp b/Minecraft.Client/EntityRenderDispatcher.cpp index f23c713c..5bb98ead 100644 --- a/Minecraft.Client/EntityRenderDispatcher.cpp +++ b/Minecraft.Client/EntityRenderDispatcher.cpp @@ -169,10 +169,9 @@ EntityRenderDispatcher::EntityRenderDispatcher() renderers[eTYPE_LIGHTNINGBOLT] = new LightningBoltRenderer(); glDisable(GL_LIGHTING); - AUTO_VAR(itEnd, renderers.end()); - for( classToRendererMap::iterator it = renderers.begin(); it != itEnd; it++ ) + for( auto& it : renderers ) { - it->second->init(this); + it.second->init(this); } isGuiRender = false; // 4J added @@ -182,7 +181,7 @@ EntityRenderer *EntityRenderDispatcher::getRenderer(eINSTANCEOF e) { if( (e & eTYPE_PLAYER) == eTYPE_PLAYER) e = eTYPE_PLAYER; //EntityRenderer * r = renderers[e]; - AUTO_VAR(it, renderers.find( e )); // 4J Stu - The .at and [] accessors insert elements if they don't exist + auto it = renderers.find(e); // 4J Stu - The .at and [] accessors insert elements if they don't exist if( it == renderers.end() ) { @@ -305,10 +304,9 @@ Font *EntityRenderDispatcher::getFont() void EntityRenderDispatcher::registerTerrainTextures(IconRegister *iconRegister) { - //for (EntityRenderer<? extends Entity> renderer : renderers.values()) - for(AUTO_VAR(it, renderers.begin()); it != renderers.end(); ++it) + for( auto& it : renderers ) { - EntityRenderer *renderer = it->second; + EntityRenderer *renderer = it.second; renderer->registerTerrainTextures(iconRegister); } } diff --git a/Minecraft.Client/EntityTracker.cpp b/Minecraft.Client/EntityTracker.cpp index 0d7d424c..db175542 100644 --- a/Minecraft.Client/EntityTracker.cpp +++ b/Minecraft.Client/EntityTracker.cpp @@ -33,11 +33,11 @@ void EntityTracker::addEntity(shared_ptr<Entity> e) { addEntity(e, 32 * 16, 2); shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(e); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) + for ( auto& it : entities ) { - if( (*it)->e != player ) + if( it && it->e != player ) { - (*it)->updatePlayer(this, player); + it->updatePlayer(this, player); } } } @@ -95,7 +95,7 @@ void EntityTracker::addEntity(shared_ptr<Entity> e, int range, int updateInterva // This is to allow us to now choose to remove the player as a "seenBy" only when the player has actually been removed from the level's own player array void EntityTracker::removeEntity(shared_ptr<Entity> e) { - AUTO_VAR(it, entityMap.find(e->entityId)); + auto it = entityMap.find(e->entityId); if( it != entityMap.end() ) { shared_ptr<TrackedEntity> te = it->second; @@ -110,9 +110,10 @@ void EntityTracker::removePlayer(shared_ptr<Entity> e) if (e->GetType() == eTYPE_SERVERPLAYER) { shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(e); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) + for( auto& it : entities ) { - (*it)->removePlayer(player); + if ( it ) + it->removePlayer(player); } // 4J: Flush now to ensure remove packets are sent before player respawns and add entity packets are sent @@ -123,14 +124,16 @@ void EntityTracker::removePlayer(shared_ptr<Entity> e) void EntityTracker::tick() { vector<shared_ptr<ServerPlayer> > movedPlayers; - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) + for( auto& te : entities ) { - shared_ptr<TrackedEntity> te = *it; - te->tick(this, &level->players); - if (te->moved && te->e->GetType() == eTYPE_SERVERPLAYER) + if ( te ) { - movedPlayers.push_back(dynamic_pointer_cast<ServerPlayer>(te->e)); - } + te->tick(this, &level->players); + if (te->moved && te->e->GetType() == eTYPE_SERVERPLAYER) + { + movedPlayers.push_back(dynamic_pointer_cast<ServerPlayer>(te->e)); + } + } } // 4J Stu - If one player on a system is updated, then make sure they all are as they all have their @@ -168,10 +171,9 @@ void EntityTracker::tick() { shared_ptr<ServerPlayer> player = movedPlayers[i]; if(player->connection == NULL) continue; - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) + for( auto& te : entities ) { - shared_ptr<TrackedEntity> te = *it; - if (te->e != player) + if ( te && te->e != player) { te->updatePlayer(this, player); } @@ -179,10 +181,10 @@ void EntityTracker::tick() } // 4J Stu - We want to do this for dead players as they don't tick normally - for(AUTO_VAR(it, level->players.begin()); it != level->players.end(); ++it) + for (auto& it : level->players ) { - shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(*it); - if(!player->isAlive()) + shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(it); + if( player && !player->isAlive()) { player->flushEntitiesToRemove(); } @@ -191,7 +193,7 @@ void EntityTracker::tick() void EntityTracker::broadcast(shared_ptr<Entity> e, shared_ptr<Packet> packet) { - AUTO_VAR(it, entityMap.find( e->entityId )); + auto it = entityMap.find(e->entityId); if( it != entityMap.end() ) { shared_ptr<TrackedEntity> te = it->second; @@ -201,7 +203,7 @@ void EntityTracker::broadcast(shared_ptr<Entity> e, shared_ptr<Packet> packet) void EntityTracker::broadcastAndSend(shared_ptr<Entity> e, shared_ptr<Packet> packet) { - AUTO_VAR(it, entityMap.find( e->entityId )); + auto it = entityMap.find(e->entityId); if( it != entityMap.end() ) { shared_ptr<TrackedEntity> te = it->second; @@ -211,18 +213,17 @@ void EntityTracker::broadcastAndSend(shared_ptr<Entity> e, shared_ptr<Packet> pa void EntityTracker::clear(shared_ptr<ServerPlayer> serverPlayer) { - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) + for ( auto& te : entities ) { - shared_ptr<TrackedEntity> te = *it; - te->clear(serverPlayer); + if ( te ) + te->clear(serverPlayer); } } void EntityTracker::playerLoadedChunk(shared_ptr<ServerPlayer> player, LevelChunk *chunk) { - for (AUTO_VAR(it,entities.begin()); it != entities.end(); ++it) + for ( auto& te : entities ) { - shared_ptr<TrackedEntity> te = *it; if (te->e != player && te->e->xChunk == chunk->x && te->e->zChunk == chunk->z) { te->updatePlayer(this, player); @@ -239,7 +240,7 @@ void EntityTracker::updateMaxRange() shared_ptr<TrackedEntity> EntityTracker::getTracker(shared_ptr<Entity> e) { - AUTO_VAR(it, entityMap.find(e->entityId)); + auto it = entityMap.find(e->entityId); if( it != entityMap.end() ) { return it->second; diff --git a/Minecraft.Client/Font.cpp b/Minecraft.Client/Font.cpp index 7a37dd7b..8a90711b 100644 --- a/Minecraft.Client/Font.cpp +++ b/Minecraft.Client/Font.cpp @@ -60,7 +60,7 @@ Font::Font(Options *options, const wstring& name, Textures* textures, bool enfor { int xt = i % m_cols; int yt = i / m_cols; - + int x = 7; for (; x >= 0; x--) { @@ -70,7 +70,7 @@ Font::Font(Options *options, const wstring& name, Textures* textures, bool enfor { int yPixel = (yt * 8 + y) * w; bool emptyPixel = (rawPixels[xPixel + yPixel] >> 24) == 0; // Check the alpha value - if (!emptyPixel) emptyColumn = false; + if (!emptyPixel) emptyColumn = false; } if (!emptyColumn) { @@ -127,13 +127,13 @@ Font::~Font() #endif void Font::renderCharacter(wchar_t c) -{ +{ float xOff = c % m_cols * m_charWidth; float yOff = c / m_cols * m_charWidth; float width = charWidths[c] - .01f; float height = m_charHeight - .01f; - + float fontWidth = m_cols * m_charWidth; float fontHeight = m_rows * m_charHeight; @@ -235,7 +235,7 @@ void Font::draw(const wstring &str, bool dropShadow) i += 1; continue; } - + // "noise" for crazy splash screen message if (noise) { @@ -245,7 +245,7 @@ void Font::draw(const wstring &str, bool dropShadow) newc = random->nextInt(SharedConstants::acceptableLetters.length()); } while (charWidths[c + 32] != charWidths[newc + 32]); c = newc; - } + } renderCharacter(c); } @@ -366,13 +366,12 @@ void Font::drawWordWrapInternal(const wstring& string, int x, int y, int w, int vector<wstring>lines = stringSplit(string,L'\n'); if (lines.size() > 1) { - AUTO_VAR(itEnd, lines.end()); - for (AUTO_VAR(it, lines.begin()); it != itEnd; it++) - { + for ( auto& it : lines ) + { // 4J Stu - Don't draw text that will be partially cutoff/overlap something it shouldn't - if( (y + this->wordWrapHeight(*it, w)) > h) break; - drawWordWrapInternal(*it, x, y, w, col, h); - y += this->wordWrapHeight(*it, w); + if( (y + this->wordWrapHeight(it, w)) > h) break; + drawWordWrapInternal(it, x, y, w, col, h); + y += this->wordWrapHeight(it, w); } return; } @@ -418,10 +417,9 @@ int Font::wordWrapHeight(const wstring& string, int w) if (lines.size() > 1) { int h = 0; - AUTO_VAR(itEnd, lines.end()); - for (AUTO_VAR(it, lines.begin()); it != itEnd; it++) - { - h += this->wordWrapHeight(*it, w); + for ( auto& it : lines ) + { + h += this->wordWrapHeight(it, w); } return h; } @@ -483,7 +481,7 @@ bool Font::AllCharactersValid(const wstring &str) int index = SharedConstants::acceptableLetters.find(c); if ((c != ' ') && !(index > 0 && !enforceUnicodeSheet)) - { + { return false; } } @@ -598,7 +596,7 @@ void Font::renderUnicodeCharacter(wchar_t c) float xOff = c % 16 * 16 + left; float yOff = (c & 0xFF) / 16 * 16; float width = right - left - .02f; - + Tesselator *t = Tesselator::getInstance(); t->begin(GL_TRIANGLE_STRIP); t->tex(xOff / 256.0F, yOff / 256.0F); diff --git a/Minecraft.Client/GameRenderer.cpp b/Minecraft.Client/GameRenderer.cpp index d3c5e8d3..5a936c82 100644 --- a/Minecraft.Client/GameRenderer.cpp +++ b/Minecraft.Client/GameRenderer.cpp @@ -186,7 +186,7 @@ GameRenderer::~GameRenderer() } void GameRenderer::tick(bool first) // 4J - add bFirst -{ +{ tickFov(); tickLightTexture(); // 4J - change brought forward from 1.8.2 fogBrO = fogBr; @@ -308,11 +308,9 @@ void GameRenderer::pick(float a) vector<shared_ptr<Entity> > *objects = mc->level->getEntities(mc->cameraTargetPlayer, mc->cameraTargetPlayer->bb->expand(b->x * (range), b->y * (range), b->z * (range))->grow(overlap, overlap, overlap)); double nearest = dist; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) - { - shared_ptr<Entity> e = *it; //objects->at(i); - if (!e->isPickable()) continue; + for (auto& e : *objects ) + { + if ( e == nullptr || !e->isPickable() ) continue; float rr = e->getPickRadius(); AABB *bb = e->bb->grow(rr, rr, rr); @@ -325,7 +323,7 @@ void GameRenderer::pick(float a) nearest = 0; } } - else if (p != NULL) + else if (p != nullptr) { double dd = from->distanceTo(p->pos); if (e == mc->cameraTargetPlayer->riding != NULL) @@ -335,7 +333,7 @@ void GameRenderer::pick(float a) hovered = e; } } - else + else { hovered = e; nearest = dd; @@ -595,7 +593,7 @@ void GameRenderer::unZoomRegion() void GameRenderer::getFovAndAspect(float& fov, float& aspect, float a, bool applyEffects) { // 4J - split out aspect ratio and fov here so we can adjust for viewports - we might need to revisit these as - // they are maybe be too generous for performance. + // they are maybe be too generous for performance. aspect = mc->width / (float) mc->height; fov = getFov(a, applyEffects); @@ -735,14 +733,14 @@ void GameRenderer::renderItemInHand(float a, int eye) bool bNoLegAnim =(localplayer->getAnimOverrideBitmask()&( (1<<HumanoidModel::eAnim_NoLegAnim) | (1<<HumanoidModel::eAnim_NoBobbing) ))!=0; if(app.GetGameSettings(localplayer->GetXboxPad(),eGameSetting_ViewBob) && !localplayer->abilities.flying && !bNoLegAnim) bobView(a); - // 4J: Skip hand rendering if render hand is off + // 4J: Skip hand rendering if render hand is off if (renderHand) { // 4J-PB - changing this to be per player //if (!mc->options->thirdPersonView && !mc->cameraTargetPlayer->isSleeping()) if (!localplayer->ThirdPersonView() && !mc->cameraTargetPlayer->isSleeping()) { - if (!mc->options->hideGui && !mc->gameMode->isCutScene()) + if (!mc->options->hideGui && !mc->gameMode->isCutScene()) { turnOnLightLayer(a); PIXBeginNamedEvent(0,"Item in hand render"); @@ -770,7 +768,7 @@ void GameRenderer::renderItemInHand(float a, int eye) // 4J - change brought forward from 1.8.2 void GameRenderer::turnOffLightLayer(double alpha) { // 4J - TODO -#if 0 +#if 0 if (SharedConstants::TEXTURE_LIGHTING) { glClientActiveTexture(GL_TEXTURE1); @@ -1111,7 +1109,7 @@ int GameRenderer::runUpdate(LPVOID lpParam) Vec3::CreateNewThreadStorage(); AABB::CreateNewThreadStorage(); IntCache::CreateNewThreadStorage(); - Tesselator::CreateNewThreadStorage(1024*1024); + Tesselator::CreateNewThreadStorage(1024*1024); Compression::UseDefaultThreadStorage(); RenderManager.InitialiseContext(); #ifdef _LARGE_WORLDS @@ -1185,7 +1183,7 @@ int GameRenderer::runUpdate(LPVOID lpParam) AABB::resetPool(); Vec3::resetPool(); - IntCache::Reset(); + IntCache::Reset(); m_updateEvents->Set(eUpdateEventIsFinished); } @@ -1217,7 +1215,7 @@ void GameRenderer::DisableUpdateThread() if( !updateRunning) return; app.DebugPrintf("------------------DisableUpdateThread--------------------\n"); updateRunning = false; - m_updateEvents->Clear(eUpdateCanRun); + m_updateEvents->Clear(eUpdateCanRun); m_updateEvents->WaitForSingle(eUpdateEventIsFinished,INFINITE); #endif } @@ -1588,7 +1586,7 @@ void GameRenderer::renderSnowAndRain(float a) turnOnLightLayer(a); - if (rainXa == NULL) + if (rainXa == NULL) { rainXa = new float[32 * 32]; rainZa = new float[32 * 32]; @@ -1709,9 +1707,9 @@ void GameRenderer::renderSnowAndRain(float a) float Alpha = ((1 - dd * dd) * 0.5f + 0.5f) * rainLevel; int tex2 = (level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4; t->tileRainQuad(x - xa + 0.5, yy0, z - za + 0.5, 0 * s, yy0 * s / 4.0f + ra * s, - x + xa + 0.5, yy0, z + za + 0.5, 1 * s, yy0 * s / 4.0f + ra * s, - x + xa + 0.5, yy1, z + za + 0.5, 1 * s, yy1 * s / 4.0f + ra * s, - x - xa + 0.5, yy1, z - za + 0.5, 0 * s, yy1 * s / 4.0f + ra * s, + x + xa + 0.5, yy0, z + za + 0.5, 1 * s, yy0 * s / 4.0f + ra * s, + x + xa + 0.5, yy1, z + za + 0.5, 1 * s, yy1 * s / 4.0f + ra * s, + x - xa + 0.5, yy1, z - za + 0.5, 0 * s, yy1 * s / 4.0f + ra * s, br, br, br, Alpha, br, br, br, 0, tex2); #else t->tex2(level->getLightColor(x, yl, z, 0)); @@ -1747,9 +1745,9 @@ void GameRenderer::renderSnowAndRain(float a) float Alpha = ((1 - dd * dd) * 0.3f + 0.5f) * rainLevel; int tex2 = (level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4; t->tileRainQuad(x - xa + 0.5, yy0, z - za + 0.5, 0 * s + uo, yy0 * s / 4.0f + ra * s + vo, - x + xa + 0.5, yy0, z + za + 0.5, 1 * s + uo, yy0 * s / 4.0f + ra * s + vo, - x + xa + 0.5, yy1, z + za + 0.5, 1 * s + uo, yy1 * s / 4.0f + ra * s + vo, - x - xa + 0.5, yy1, z - za + 0.5, 0 * s + uo, yy1 * s / 4.0f + ra * s + vo, + x + xa + 0.5, yy0, z + za + 0.5, 1 * s + uo, yy0 * s / 4.0f + ra * s + vo, + x + xa + 0.5, yy1, z + za + 0.5, 1 * s + uo, yy1 * s / 4.0f + ra * s + vo, + x - xa + 0.5, yy1, z - za + 0.5, 0 * s + uo, yy1 * s / 4.0f + ra * s + vo, br, br, br, Alpha, br, br, br, Alpha, tex2); #else t->tex2((level->getLightColor(x, yl, z, 0) * 3 + 0xf000f0) / 4); diff --git a/Minecraft.Client/Gui.cpp b/Minecraft.Client/Gui.cpp index 2db0c83c..1199c138 100644 --- a/Minecraft.Client/Gui.cpp +++ b/Minecraft.Client/Gui.cpp @@ -61,7 +61,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) { // 4J Stu - I have copied this code for XUI_BaseScene. If/when it gets changed it should be broken out // 4J - altered to force full screen mode to 3X scaling, and any split screen modes to 2X scaling. This is so that the further scaling by 0.5 that - // happens in split screen modes results in a final scaling of 1 rather than 1.5. + // happens in split screen modes results in a final scaling of 1 rather than 1.5. int splitYOffset;// = 20; // This offset is applied when doing the 2X scaling above to move the gui out of the way of the tool tips int guiScale;// = ( minecraft->player->m_iScreenSection == C4JRender::VIEWPORT_TYPE_FULLSCREEN ? 3 : 2 ); int iPad=minecraft->player->GetXboxPad(); @@ -100,7 +100,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) default: // 2 splitYOffset = 10; break; - } + } // Check which screen section this player is in switch(minecraft->player->m_iScreenSection) @@ -143,7 +143,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) currentGuiScaleFactor *= 0.5f; break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - iSafezoneXHalf = 0; + iSafezoneXHalf = 0; iSafezoneYHalf = splitYOffset + screenHeight/10;// 5% (need to treat the whole screen is 2x this screen) iSafezoneTopYHalf = splitYOffset + screenHeight/10; fScaleFactorHeight=0.5f; @@ -160,7 +160,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) currentGuiScaleFactor *= 0.5f; break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: - iSafezoneXHalf = 0; + iSafezoneXHalf = 0; iSafezoneYHalf = splitYOffset; // 5% iSafezoneTopYHalf = screenHeight/10; iTooltipsYOffset=44; @@ -174,28 +174,28 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) currentGuiScaleFactor *= 0.5f; break; case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: - iSafezoneXHalf = 0; + iSafezoneXHalf = 0; iSafezoneYHalf = splitYOffset + screenHeight/10; // 5% (the whole screen is 2x this screen) iSafezoneTopYHalf = 0; iTooltipsYOffset=44; currentGuiScaleFactor *= 0.5f; break; - + } // 4J-PB - turn off the slot display if a xui menu is up, or if we're autosaving bool bDisplayGui=!ui.GetMenuDisplayed(iPad) && !(app.GetXuiAction(iPad)==eAppAction_AutosaveSaveGameCapturedThumbnail); // if tooltips are off, set the y offset to zero - if(app.GetGameSettings(iPad,eGameSetting_Tooltips)==0 && bDisplayGui) + if(app.GetGameSettings(iPad,eGameSetting_Tooltips)==0 && bDisplayGui) { switch(minecraft->player->m_iScreenSection) { case C4JRender::VIEWPORT_TYPE_FULLSCREEN: - iTooltipsYOffset=screenHeight/10; + iTooltipsYOffset=screenHeight/10; break; default: - //iTooltipsYOffset=screenHeight/10; + //iTooltipsYOffset=screenHeight/10; switch(guiScale) { case 3: @@ -207,11 +207,11 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) default: // 2 iTooltipsYOffset=14;//screenHeight/10; break; - } + } break; } } - + // 4J-PB - Turn off interface if eGameSetting_DisplayHUD is off - for screen shots/videos. if ( app.GetGameSettings(iPad,eGameSetting_DisplayHUD)==0 ) { @@ -222,13 +222,13 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) minecraft->gameRenderer->setupGuiScreen(guiScale); - + glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // 4J - added - this did actually get set in renderVignette but that code is currently commented out - if (Minecraft::useFancyGraphics()) + if (Minecraft::useFancyGraphics()) { renderVignette(minecraft->player->getBrightness(a), screenWidth, screenHeight); } @@ -256,7 +256,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) if(bDisplayGui && bTwoPlayerSplitscreen) { // need to apply scale factors depending on the mode - glPushMatrix(); + glPushMatrix(); glScalef(fScaleFactorWidth, fScaleFactorHeight, fScaleFactorWidth); } #if RENDER_HUD @@ -320,9 +320,9 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) // need to apply scale factors depending on the mode // 4J Stu - Moved this push and scale further up as we still need to do it for the few HUD components not replaced by xui - //glPushMatrix(); + //glPushMatrix(); //glScalef(fScaleFactorWidth, fScaleFactorHeight, fScaleFactorWidth); - + // 4J-PB - move into the safe zone, and account for 2 player splitscreen blit(iWidthOffset + (screenWidth - quickSelectWidth)/2, iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset , 0, 0, 182, 22); blit(iWidthOffset + (screenWidth - quickSelectWidth)/2 - 1 + inventory->selected * 20, iHeightOffset + screenHeight - iSafezoneYHalf - iTooltipsYOffset - 1, 0, 22, 24, 22); @@ -370,13 +370,13 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) int food = foodData->getFoodLevel(); int oldFood = foodData->getLastFoodLevel(); -// if (false) //(true) +// if (false) //(true) // { // renderBossHealth(); // } ///////////////////////////////////////////////////////////////////////////////////// - // Display the experience, food, armour, health and the air bubbles + // Display the experience, food, armour, health and the air bubbles ///////////////////////////////////////////////////////////////////////////////////// if(bDisplayGui) { @@ -625,12 +625,12 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) glEnable(GL_RESCALE_NORMAL); Lighting::turnOnGui(); - + int x,y; for (int i = 0; i < 9; i++) - { + { if(bTwoPlayerSplitscreen) { x = iWidthOffset + screenWidth / 2 - 9 * 10 + i * 20 + 2; @@ -667,11 +667,11 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) else if( minecraft->player->isSprinting() ) { characterDisplayTimer[iPad] = 30; - } + } else if( minecraft->player->abilities.flying) { characterDisplayTimer[iPad] = 5; // quickly get rid of the player display if they stop flying - } + } else if( characterDisplayTimer[iPad] > 0 ) { --characterDisplayTimer[iPad]; @@ -733,7 +733,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) minecraft->player->onFire = 0; minecraft->player->setSharedFlag(Entity::FLAG_ONFIRE, false); - + // 4J - TomK don't offset the player. it's easier to align it with the safe zones that way! //glTranslatef(0, minecraft->player->heightOffset, 0); glTranslatef(0, 0, 0); @@ -777,7 +777,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) { y-=13; } - + if(bTwoPlayerSplitscreen) { y+=iHeightOffset; @@ -849,7 +849,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) glPushMatrix(); if (Minecraft::warezTime > 0) glTranslatef(0, 32, 0); font->drawShadow(ClientConstants::VERSION_STRING + L" (" + minecraft->fpsString + L")", iSafezoneXHalf+2, 20, 0xffffff); - font->drawShadow(L"Seed: " + _toString<__int64>(minecraft->level->getLevelData()->getSeed() ), iSafezoneXHalf+2, 32 + 00, 0xffffff); + font->drawShadow(L"Seed: " + std::to_wstring(minecraft->level->getLevelData()->getSeed() ), iSafezoneXHalf+2, 32 + 00, 0xffffff); font->drawShadow(minecraft->gatherStats1(), iSafezoneXHalf+2, 32 + 10, 0xffffff); font->drawShadow(minecraft->gatherStats2(), iSafezoneXHalf+2, 32 + 20, 0xffffff); font->drawShadow(minecraft->gatherStats3(), iSafezoneXHalf+2, 32 + 30, 0xffffff); @@ -871,7 +871,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) { FEATURE_DATA *pFeatureData=app.m_vTerrainFeatures[i]; - wstring itemInfo = L"[" + _toString<int>( pFeatureData->x*16 ) + L", " + _toString<int>( pFeatureData->z*16 ) + L"] "; + wstring itemInfo = L"[" + std::to_wstring( pFeatureData->x*16 ) + L", " + std::to_wstring( pFeatureData->z*16 ) + L"] "; wfeature[pFeatureData->eTerrainFeature] += itemInfo; } @@ -899,10 +899,10 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) double xBlockPos = floor(minecraft->player->x); double yBlockPos = floor(minecraft->player->y); double zBlockPos = floor(minecraft->player->z); - drawString(font, L"x: " + _toString<double>(minecraft->player->x) + L"/ Head: " + _toString<double>(xBlockPos) + L"/ Chunk: " + _toString<double>(minecraft->player->xChunk), iSafezoneXHalf+2, iYPos + 8 * 0, 0xe0e0e0); - drawString(font, L"y: " + _toString<double>(minecraft->player->y) + L"/ Head: " + _toString<double>(yBlockPos), iSafezoneXHalf+2, iYPos + 8 * 1, 0xe0e0e0); - drawString(font, L"z: " + _toString<double>(minecraft->player->z) + L"/ Head: " + _toString<double>(zBlockPos) + L"/ Chunk: " + _toString<double>(minecraft->player->zChunk), iSafezoneXHalf+2, iYPos + 8 * 2, 0xe0e0e0); - drawString(font, L"f: " + _toString<double>(Mth::floor(minecraft->player->yRot * 4.0f / 360.0f + 0.5) & 0x3) + L"/ yRot: " + _toString<double>(minecraft->player->yRot), iSafezoneXHalf+2, iYPos + 8 * 3, 0xe0e0e0); + drawString(font, L"x: " + std::to_wstring(minecraft->player->x) + L"/ Head: " + std::to_wstring(static_cast<int>(xBlockPos)) + L"/ Chunk: " + std::to_wstring(minecraft->player->xChunk), iSafezoneXHalf+2, iYPos + 8 * 0, 0xe0e0e0); + drawString(font, L"y: " + std::to_wstring(minecraft->player->y) + L"/ Head: " + std::to_wstring(static_cast<int>(yBlockPos)), iSafezoneXHalf+2, iYPos + 8 * 1, 0xe0e0e0); + drawString(font, L"z: " + std::to_wstring(minecraft->player->z) + L"/ Head: " + std::to_wstring(static_cast<int>(zBlockPos)) + L"/ Chunk: " + std::to_wstring(minecraft->player->zChunk), iSafezoneXHalf+2, iYPos + 8 * 2, 0xe0e0e0); + drawString(font, L"f: " + std::to_wstring(Mth::floor(minecraft->player->yRot * 4.0f / 360.0f + 0.5) & 0x3) + L"/ yRot: " + std::to_wstring(minecraft->player->yRot), iSafezoneXHalf+2, iYPos + 8 * 3, 0xe0e0e0); iYPos += 8*4; int px = Mth::floor(minecraft->player->x); @@ -914,7 +914,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) Biome *biome = chunkAt->getBiome(px & 15, pz & 15, minecraft->level->getBiomeSource()); drawString( font, - L"b: " + biome->m_name + L" (" + _toString<int>(biome->id) + L")", iSafezoneXHalf+2, iYPos, 0xe0e0e0); + L"b: " + biome->m_name + L" (" + std::to_wstring(biome->id) + L")", iSafezoneXHalf+2, iYPos, 0xe0e0e0); } glPopMatrix(); @@ -931,7 +931,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) float t = overlayMessageTime - a; int alpha = (int) (t * 256 / 20); if (alpha > 255) alpha = 255; - if (alpha > 0) + if (alpha > 0) { glPushMatrix(); @@ -958,7 +958,7 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) } } #endif - + unsigned int max = 10; bool isChatting = false; if (dynamic_cast<ChatScreen *>(minecraft->screen) != NULL) @@ -1091,35 +1091,35 @@ void Gui::render(float a, bool mouseFree, int xMouse, int yMouse) // void Gui::renderBossHealth(void) // { // if (EnderDragonRenderer::bossInstance == NULL) return; -// +// // shared_ptr<EnderDragon> boss = EnderDragonRenderer::bossInstance; // EnderDragonRenderer::bossInstance = NULL; -// +// // Minecraft *pMinecraft=Minecraft::GetInstance(); -// +// // Font *font = pMinecraft->font; -// +// // ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); // int screenWidth = ssc.getWidth(); -// +// // int w = 182; // int xLeft = screenWidth / 2 - w / 2; -// +// // int progress = (int) (boss->getSynchedHealth() / (float) boss->getMaxHealth() * (float) (w + 1)); -// +// // int yo = 12; // blit(xLeft, yo, 0, 74, w, 5); // blit(xLeft, yo, 0, 74, w, 5); -// if (progress > 0) +// if (progress > 0) // { // blit(xLeft, yo, 0, 79, progress, 5); // } -// +// // wstring msg = L"Boss health - NON LOCALISED"; // font->drawShadow(msg, screenWidth / 2 - font->width(msg) / 2, yo - 10, 0xff00ff); // glColor4f(1, 1, 1, 1); // glBindTexture(GL_TEXTURE_2D, pMinecraft->textures->loadTexture(TN_GUI_ICONS) );//"/gui/icons.png")); -// +// // } void Gui::renderPumpkin(int w, int h) @@ -1146,7 +1146,7 @@ void Gui::renderPumpkin(int w, int h) glColor4f(1, 1, 1, 1); } - + void Gui::renderVignette(float br, int w, int h) { br = 1 - br; @@ -1191,7 +1191,7 @@ void Gui::renderTp(float br, int w, int h) MemSect(31); minecraft->textures->bindTexture(&TextureAtlas::LOCATION_BLOCKS); MemSect(0); - + Icon *slot = Tile::portalTile->getTexture(Facing::UP); float u0 = slot->getU0(); float v0 = slot->getV0(); @@ -1243,15 +1243,14 @@ void Gui::tick() tickCount++; for(int iPad=0;iPad<XUSER_MAX_COUNT;iPad++) - { + { // 4J Stu - Fix for #10929 - MP LAB: Network Disconnects: Host does not receive an error message stating the client left the game when viewing the Pause Menu. // We don't show the guiMessages when a menu is up, so don't fade them out if(!ui.GetMenuDisplayed(iPad)) { - AUTO_VAR(itEnd, guiMessages[iPad].end()); - for (AUTO_VAR(it, guiMessages[iPad].begin()); it != itEnd; it++) - { - (*it).ticks++; + for (auto& it : guiMessages[iPad]) + { + it.ticks++; } } } @@ -1267,7 +1266,7 @@ void Gui::clearMessages(int iPad) { guiMessages[i].clear(); } - } + } } else { @@ -1500,7 +1499,7 @@ void Gui::renderGraph(int dataLength, int dataPos, __int64 *dataA, float dataASc t->vertex((float)(xScale*i + 0.5f), (float)( height - aVal + 0.5f), (float)( 0)); t->vertex((float)(xScale*i + 0.5f), (float)( height + 0.5f), (float)( 0)); } - + if( dataB != NULL ) { if (dataB[i]>dataBWarning) diff --git a/Minecraft.Client/GuiParticles.cpp b/Minecraft.Client/GuiParticles.cpp index 6716de7a..79240288 100644 --- a/Minecraft.Client/GuiParticles.cpp +++ b/Minecraft.Client/GuiParticles.cpp @@ -37,10 +37,8 @@ void GuiParticles::render(float a) #if 0 mc->textures->bindTexture(L"/gui/particles.png"); - AUTO_VAR(itEnd, particles.end()); - for (AUTO_VAR(it, particles.begin()); it != itEnd; it++) + for ( GuiParticle *gp : particles ) { - GuiParticle *gp = *it; //particles[i]; int xx = (int) (gp->xo + (gp->x - gp->xo) * a - 4); int yy = (int) (gp->yo + (gp->y - gp->yo) * a - 4); diff --git a/Minecraft.Client/HorseRenderer.cpp b/Minecraft.Client/HorseRenderer.cpp index 006f9e20..e01542d5 100644 --- a/Minecraft.Client/HorseRenderer.cpp +++ b/Minecraft.Client/HorseRenderer.cpp @@ -83,9 +83,9 @@ ResourceLocation *HorseRenderer::getOrCreateLayeredTextureLocation(shared_ptr<En { wstring textureName = horse->getLayeredTextureHashName(); - AUTO_VAR(it, LAYERED_LOCATION_CACHE.find(textureName)); + auto it = LAYERED_LOCATION_CACHE.find(textureName); - ResourceLocation *location; + ResourceLocation *location; if (it != LAYERED_LOCATION_CACHE.end()) { location = it->second; @@ -93,7 +93,7 @@ ResourceLocation *HorseRenderer::getOrCreateLayeredTextureLocation(shared_ptr<En else { LAYERED_LOCATION_CACHE[textureName] = new ResourceLocation(horse->getLayeredTextureLayers()); - + it = LAYERED_LOCATION_CACHE.find(textureName); location = it->second; } diff --git a/Minecraft.Client/HumanoidMobRenderer.cpp b/Minecraft.Client/HumanoidMobRenderer.cpp index a9ff25c4..5329f2d9 100644 --- a/Minecraft.Client/HumanoidMobRenderer.cpp +++ b/Minecraft.Client/HumanoidMobRenderer.cpp @@ -53,7 +53,7 @@ ResourceLocation *HumanoidMobRenderer::getArmorLocation(ArmorItem *armorItem, in case 4: break; }; - wstring path = wstring(L"armor/" + MATERIAL_NAMES[armorItem->modelIndex]).append(L"_").append(_toString<int>(layer == 2 ? 2 : 1)).append((overlay ? L"_b" :L"")).append(L".png"); + wstring path = wstring(L"armor/" + MATERIAL_NAMES[armorItem->modelIndex]).append(L"_").append(std::to_wstring(layer == 2 ? 2 : 1)).append((overlay ? L"_b" :L"")).append(L".png"); std::map<wstring, ResourceLocation>::iterator it = ARMOR_LOCATION_CACHE.find(path); @@ -74,7 +74,7 @@ ResourceLocation *HumanoidMobRenderer::getArmorLocation(ArmorItem *armorItem, in } void HumanoidMobRenderer::prepareSecondPassArmor(shared_ptr<LivingEntity> mob, int layer, float a) -{ +{ shared_ptr<ItemInstance> itemInstance = mob->getArmor(3 - layer); if (itemInstance != NULL) { Item *item = itemInstance->getItem(); @@ -193,7 +193,7 @@ void HumanoidMobRenderer::additionalRendering(shared_ptr<LivingEntity> mob, floa // 4J-PB - need to disable rendering armour/skulls/pumpkins for some special skins (Daleks) if((mob->getAnimOverrideBitmask()&(1<<HumanoidModel::eAnim_DontRenderArmour))==0) - { + { glPushMatrix(); humanoidModel->head->translateTo(1 / 16.0f); diff --git a/Minecraft.Client/ItemRenderer.cpp b/Minecraft.Client/ItemRenderer.cpp index 49e25060..6fb7e633 100644 --- a/Minecraft.Client/ItemRenderer.cpp +++ b/Minecraft.Client/ItemRenderer.cpp @@ -86,7 +86,7 @@ void ItemRenderer::render(shared_ptr<Entity> _itemEntity, double x, double y, do { glRotatef(spin, 0, 1, 0); - if (m_bItemFrame) + if (m_bItemFrame) { glScalef(1.25f, 1.25f, 1.25f); glTranslatef(0, 0.05f, 0); @@ -104,7 +104,7 @@ void ItemRenderer::render(shared_ptr<Entity> _itemEntity, double x, double y, do for (int i = 0; i < count; i++) { glPushMatrix(); - if (i > 0) + if (i > 0) { float xo = (random->nextFloat() * 2 - 1) * 0.2f / s; float yo = (random->nextFloat() * 2 - 1) * 0.2f / s; @@ -119,13 +119,13 @@ void ItemRenderer::render(shared_ptr<Entity> _itemEntity, double x, double y, do } else if (item->getIconType() == Icon::TYPE_ITEM && item->getItem()->hasMultipleSpriteLayers()) { - if (m_bItemFrame) + if (m_bItemFrame) { glScalef(1 / 1.95f, 1 / 1.95f, 1 / 1.95f); glTranslatef(0, -0.05f, 0); glDisable(GL_LIGHTING); - } - else + } + else { glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); } @@ -155,17 +155,17 @@ void ItemRenderer::render(shared_ptr<Entity> _itemEntity, double x, double y, do } else { - if (m_bItemFrame) + if (m_bItemFrame) { glScalef(1 / 1.95f, 1 / 1.95f, 1 / 1.95f); glTranslatef(0, -0.05f, 0); glDisable(GL_LIGHTING); - } - else + } + else { glScalef(1 / 2.0f, 1 / 2.0f, 1 / 2.0f); } - + // 4J Stu - For rendering the static compass, we give it a non-zero aux value if(item->id == Item::compass_Id) item->setAuxValue(255); if(item->id == Item::compass_Id) item->setAuxValue(0); @@ -212,7 +212,7 @@ void ItemRenderer::renderItemBillboard(shared_ptr<ItemEntity> entity, Icon *icon if (entityRenderDispatcher->options->fancyGraphics) { - // Consider forcing the mipmap LOD level to use, if this is to be rendered from a larger than standard source texture. + // Consider forcing the mipmap LOD level to use, if this is to be rendered from a larger than standard source texture. int iconWidth = icon->getWidth(); int LOD = -1; // Default to not doing anything special with LOD forcing if( iconWidth == 32 ) @@ -262,7 +262,7 @@ void ItemRenderer::renderItemBillboard(shared_ptr<ItemEntity> entity, Icon *icon for (int i = 0; i < count; i++) { glTranslatef(0, 0, width + margin); - + bool bIsTerrain = false; if (item->getIconType() == Icon::TYPE_TERRAIN && Tile::tiles[item->id] != NULL) { @@ -270,7 +270,7 @@ void ItemRenderer::renderItemBillboard(shared_ptr<ItemEntity> entity, Icon *icon bindTexture(&TextureAtlas::LOCATION_BLOCKS); // TODO: Do this sanely by Icon } else - { + { bindTexture(&TextureAtlas::LOCATION_ITEMS); // TODO: Do this sanely by Icon } @@ -395,7 +395,7 @@ void ItemRenderer::renderGuiItem(Font *font, Textures *textures, shared_ptr<Item PIXBeginNamedEvent(0,"Potion gui item render %d\n",itemIcon); // special double-layered glDisable(GL_LIGHTING); - + ResourceLocation *location = getTextureLocation(item->getIconType()); textures->bindTexture(location); @@ -487,7 +487,7 @@ void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const s // 4J - added isConstantBlended and blendFactor parameters. This is true if the gui item is being rendered from a context where it already has blending enabled to do general interface fading // (ie from the gui rather than xui). In this case we dno't want to enable/disable blending, and do need to restore the blend state when we are done. -void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const shared_ptr<ItemInstance> item, float x, float y,float fScaleX, float fScaleY,float fAlpha, bool isFoil, bool isConstantBlended, bool useCompiled) +void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const shared_ptr<ItemInstance> item, float x, float y,float fScaleX, float fScaleY,float fAlpha, bool isFoil, bool isConstantBlended, bool useCompiled) { if (item == NULL) { @@ -495,7 +495,7 @@ void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const s } renderGuiItem(font, textures, item, x, y,fScaleX,fScaleY,fAlpha, useCompiled); - + if (isFoil || item->isFoil()) { glDepthFunc(GL_GREATER); @@ -504,7 +504,7 @@ void ItemRenderer::renderAndDecorateItem(Font *font, Textures *textures, const s textures->bindTexture(&ItemInHandRenderer::ENCHANT_GLINT_LOCATION); // 4J was "%blur%/misc/glint.png" blitOffset -= 50; if( !isConstantBlended ) glEnable(GL_BLEND); - + glBlendFunc(GL_DST_COLOR, GL_ONE); // 4J - changed blend equation from GL_DST_COLOR, GL_DST_COLOR so we can fade this out float blendFactor = isConstantBlended ? Gui::currentGuiBlendFactor : 1.0f; @@ -597,7 +597,7 @@ void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, shar { return; } - + if (item->count > 1 || !countText.empty() || item->GetForceNumberDisplay()) { MemSect(31); @@ -607,11 +607,11 @@ void ItemRenderer::renderGuiItemDecorations(Font *font, Textures *textures, shar int count = item->count; if(count > 64) { - amount = _toString<int>(64) + L"+"; + amount = L"64+"; } else { - amount = _toString<int>(item->count); + amount = std::to_wstring(item->count); } } MemSect(0); diff --git a/Minecraft.Client/LevelRenderer.cpp b/Minecraft.Client/LevelRenderer.cpp index 222a5c18..051ad892 100644 --- a/Minecraft.Client/LevelRenderer.cpp +++ b/Minecraft.Client/LevelRenderer.cpp @@ -464,7 +464,7 @@ void LevelRenderer::allChanged(int playerIndex) zMaxChunk = zChunks; // 4J removed - we now only fully clear this on exiting the game (setting level to NULL). Apart from that, the chunk rebuilding is responsible for maintaining this - // renderableTileEntities.clear(); + // renderableTileEntities.clear(); for (int x = 0; x < xChunks; x++) { @@ -533,19 +533,14 @@ void LevelRenderer::renderEntities(Vec3 *cam, Culler *culler, float a) vector<shared_ptr<Entity> > entities = level[playerIndex]->getAllEntities(); totalEntities = (int)entities.size(); - AUTO_VAR(itEndGE, level[playerIndex]->globalEntities.end()); - for (AUTO_VAR(it, level[playerIndex]->globalEntities.begin()); it != itEndGE; it++) + for (auto& entity : level[playerIndex]->globalEntities) { - shared_ptr<Entity> entity = *it; //level->globalEntities[i]; renderedEntities++; if (entity->shouldRender(cam)) EntityRenderDispatcher::instance->render(entity, a); } - AUTO_VAR(itEndEnts, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEndEnts; it++) + for (auto& entity : entities) { - shared_ptr<Entity> entity = *it; //entities[i]; - bool shouldRender = (entity->shouldRender(cam) && (entity->noCulling || culler->isVisible(entity->bb))); // Render the mob if the mob's leash holder is within the culler @@ -580,25 +575,25 @@ void LevelRenderer::renderEntities(Vec3 *cam, Culler *culler, float a) // 4J - have restructed this so that the tile entities are stored within a hashmap by chunk/dimension index. The index // is calculated in the same way as the global flags. EnterCriticalSection(&m_csRenderableTileEntities); - for (AUTO_VAR(it, renderableTileEntities.begin()); it != renderableTileEntities.end(); it++) - { - int idx = it->first; + for (auto & it : renderableTileEntities) + { + int idx = it.first; // Don't render if it isn't in the same dimension as this player if( !isGlobalIndexInSameDimension(idx, level[playerIndex]) ) continue; - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); it2++) + for( auto& it2 : it.second) { - TileEntityRenderDispatcher::instance->render(*it2, a); + TileEntityRenderDispatcher::instance->render(it2, a); } } // Now consider if any of these renderable tile entities have been flagged for removal, and if so, remove - for (AUTO_VAR(it, renderableTileEntities.begin()); it != renderableTileEntities.end();) - { + for (auto it = renderableTileEntities.begin(); it != renderableTileEntities.end();) + { int idx = it->first; - for( AUTO_VAR(it2, it->second.begin()); it2 != it->second.end(); ) - { + for (auto it2 = it->second.begin(); it2 != it->second.end();) + { // If it has been flagged for removal, remove if((*it2)->shouldRemoveForRender()) { @@ -628,12 +623,12 @@ void LevelRenderer::renderEntities(Vec3 *cam, Culler *culler, float a) wstring LevelRenderer::gatherStats1() { - return L"C: " + _toString<int>(renderedChunks) + L"/" + _toString<int>(totalChunks) + L". F: " + _toString<int>(offscreenChunks) + L", O: " + _toString<int>(occludedChunks) + L", E: " + _toString<int>(emptyChunks); + return L"C: " + std::to_wstring(renderedChunks) + L"/" + std::to_wstring(totalChunks) + L". F: " + std::to_wstring(offscreenChunks) + L", O: " + std::to_wstring(occludedChunks) + L", E: " + std::to_wstring(emptyChunks); } wstring LevelRenderer::gatherStats2() { - return L"E: " + _toString<int>(renderedEntities) + L"/" + _toString<int>(totalEntities) + L". B: " + _toString<int>(culledEntities) + L", I: " + _toString<int>((totalEntities - culledEntities) - renderedEntities); + return L"E: " + std::to_wstring(renderedEntities) + L"/" + std::to_wstring(totalEntities) + L". B: " + std::to_wstring(culledEntities) + L", I: " + std::to_wstring((totalEntities - culledEntities) - renderedEntities); } void LevelRenderer::resortChunks(int xc, int yc, int zc) @@ -888,11 +883,8 @@ int LevelRenderer::renderChunks(int from, int to, int layer, double alpha) renderLists[l].clear(); } - AUTO_VAR(itEnd, _renderChunks.end()); - for (AUTO_VAR(it, _renderChunks.begin()); it != itEnd; it++) + for ( Chunk *chunk : _renderChunks ) { - Chunk *chunk = *it; //_renderChunks[i]; - int list = -1; for (int l = 0; l < lists; l++) { @@ -918,7 +910,7 @@ int LevelRenderer::renderChunks(int from, int to, int layer, double alpha) } -void LevelRenderer::renderSameAsLast(int layer, double alpha) +void LevelRenderer::renderSameAsLast(int layer, double alpha) { for (int i = 0; i < RENDERLISTS_LENGTH; i++) { @@ -932,8 +924,8 @@ void LevelRenderer::tick() if ((ticks % SharedConstants::TICKS_PER_SECOND) == 0) { - AUTO_VAR(it , destroyingBlocks.begin()); - while (it != destroyingBlocks.end()) + auto it = destroyingBlocks.begin(); + while (it != destroyingBlocks.end()) { BlockDestructionProgress *block = it->second; @@ -1150,7 +1142,7 @@ void LevelRenderer::renderSky(float alpha) glPopMatrix(); // 4J - can't work out what this big black box is for. Taking it out until someone misses it... it causes a big black box to visible appear in 3rd person mode whilst under the ground. -#if 0 +#if 0 float ss = 1; float yo = -(float) (yy + 65); float y0 = -ss; @@ -1223,7 +1215,7 @@ void LevelRenderer::renderHaloRing(float alpha) // Rough lumninance calculation float Y = (sr+sr+sb+sg+sg+sg)/6; - float br = 0.6f + (Y*0.4f); + float br = 0.6f + (Y*0.4f); //app.DebugPrintf("Luminance = %f, brightness = %f\n", Y, br); glColor3f(br,br,br); @@ -1392,7 +1384,7 @@ void LevelRenderer::createCloudMesh() t->vertexUV(x0, y0, z0, u, v ); t->vertexUV(x1, y0, z0, u, v ); t->vertexUV(x1, y0, z1, u, v ); - t->vertexUV(x0, y0, z1, u, v ); + t->vertexUV(x0, y0, z1, u, v ); } } t->end(); @@ -1492,7 +1484,7 @@ void LevelRenderer::createCloudMesh() t->vertexUV(x0, y1, z0, u, v ); t->vertexUV(x1, y1, z0, u, v ); t->vertexUV(x1, y0, z0, u, v ); - t->vertexUV(x0, y0, z0, u, v ); + t->vertexUV(x0, y0, z0, u, v ); } } t->end(); @@ -1514,10 +1506,10 @@ void LevelRenderer::createCloudMesh() float z1 = z0 + 1.0f; t->color(0.8f, 0.8f, 0.8f, 0.8f); t->normal(1, 0, 0); - t->vertexUV(x0, y0, z1, u, v ); + t->vertexUV(x0, y0, z1, u, v ); t->vertexUV(x1, y0, z1, u, v ); t->vertexUV(x1, y1, z1, u, v ); - t->vertexUV(x0, y1, z1, u, v ); + t->vertexUV(x0, y1, z1, u, v ); } } t->end(); @@ -1796,7 +1788,7 @@ void LevelRenderer::renderAdvancedClouds(float alpha) t->end(); #endif } - } + } } glColor4f(1, 1, 1, 1.0f); @@ -1933,14 +1925,14 @@ bool LevelRenderer::updateDirtyChunks() { // It's possible that the localplayers member can be set to NULL on the main thread when a player chooses to exit the game // So take a reference to the player object now. As it is a shared_ptr it should live as long as we need it - shared_ptr<LocalPlayer> player = mc->localplayers[p]; + shared_ptr<LocalPlayer> player = mc->localplayers[p]; if( player == NULL ) continue; if( chunks[p].data == NULL ) continue; if( level[p] == NULL ) continue; if( chunks[p].length != xChunks * zChunks * CHUNK_Y_COUNT ) continue; int px = (int)player->x; int py = (int)player->y; - int pz = (int)player->z; + int pz = (int)player->z; // app.DebugPrintf("!! %d %d %d, %d %d %d {%d,%d} ",px,py,pz,stackChunkDirty,nonStackChunkDirty,onlyRebuild, xChunks, zChunks); @@ -1955,7 +1947,7 @@ bool LevelRenderer::updateDirtyChunks() ClipChunk *pClipChunk = &chunks[p][(z * yChunks + y) * xChunks + x]; // Get distance to this chunk - deliberately not calling the chunk's method of doing this to avoid overheads (passing entitie, type conversion etc.) that this involves int xd = pClipChunk->xm - px; - int yd = pClipChunk->ym - py; + int yd = pClipChunk->ym - py; int zd = pClipChunk->zm - pz; int distSq = xd * xd + yd * yd + zd * zd; int distSqWeighted = xd * xd + yd * yd * 4 + zd * zd; // Weighting against y to prioritise things in same x/z plane as player first @@ -1970,8 +1962,8 @@ bool LevelRenderer::updateDirtyChunks() // Is this chunk nearer than our nearest? #ifdef _LARGE_WORLDS bool isNearer = nearestClipChunks.empty(); - AUTO_VAR(itNearest, nearestClipChunks.begin()); - for(; itNearest != nearestClipChunks.end(); ++itNearest) + auto itNearest = nearestClipChunks.begin(); + for(; itNearest != nearestClipChunks.end(); ++itNearest) { isNearer = distSqWeighted < itNearest->second; if(isNearer) break; @@ -1997,12 +1989,12 @@ bool LevelRenderer::updateDirtyChunks() // emptiness without actually testing as many data items as uncompressed data would. Chunk *chunk = pClipChunk->chunk; LevelChunk *lc = level[p]->getChunkAt(chunk->x,chunk->z); - if( !lc->isRenderChunkEmpty(y * 16) ) + if( !lc->isRenderChunkEmpty(y * 16) ) { nearChunk = pClipChunk; minDistSq = distSqWeighted; #ifdef _LARGE_WORLDS - nearestClipChunks.insert(itNearest, std::pair<ClipChunk *, int>(nearChunk, minDistSq) ); + nearestClipChunks.insert(itNearest, std::make_pair(nearChunk, minDistSq) ); if(nearestClipChunks.size() > maxNearestChunks) { nearestClipChunks.pop_back(); @@ -2044,9 +2036,9 @@ bool LevelRenderer::updateDirtyChunks() if(!nearestClipChunks.empty()) { int index = 0; - for(AUTO_VAR(it, nearestClipChunks.begin()); it != nearestClipChunks.end(); ++it) + for(auto & it : nearestClipChunks) { - chunk = it->first->chunk; + chunk = it.first->chunk; // If this chunk is very near, then move the renderer into a deferred mode. This won't commit any command buffers // for rendering until we call CBuffDeferredModeEnd(), allowing us to group any near changes into an atomic unit. This // is essential so we don't temporarily create any holes in the environment whilst updating one chunk and not the neighbours. @@ -2081,7 +2073,7 @@ bool LevelRenderer::updateDirtyChunks() if((veryNearCount > 0)) bAtomic = true; //MGH - if veryNearCount, then we're trying to rebuild atomically, so do it all on the main thread - if( bAtomic || (index == 0) ) + if( bAtomic || (index == 0) ) { //PIXBeginNamedEvent(0,"Rebuilding near chunk %d %d %d",chunk->x, chunk->y, chunk->z); // static __int64 totalTime = 0; @@ -2090,9 +2082,9 @@ bool LevelRenderer::updateDirtyChunks() //app.DebugPrintf("Rebuilding permaChunk %d\n", index); - permaChunk[index].rebuild(); + permaChunk[index].rebuild(); - if(index !=0) + if(index !=0) s_rebuildCompleteEvents->Set(index-1); // MGH - this rebuild happening on the main thread instead, mark the thread it should have been running on as complete // __int64 endTime = System::currentTimeMillis(); @@ -2233,8 +2225,8 @@ void LevelRenderer::renderDestroyAnimation(Tesselator *t, shared_ptr<Player> pla #endif t->noColor(); - AUTO_VAR(it, destroyingBlocks.begin()); - while (it != destroyingBlocks.end()) + auto it = destroyingBlocks.begin(); + while (it != destroyingBlocks.end()) { BlockDestructionProgress *block = it->second; double xd = block->getX() - xo; @@ -2337,7 +2329,7 @@ void LevelRenderer::setDirty(int x0, int y0, int z0, int x1, int y1, int z1, Lev { // 4J - level is passed if this is coming from setTilesDirty, which could come from when connection is being ticked outside of normal level tick, and player won't // be set up - if( level == NULL ) level = this->level[mc->player->GetXboxPad()]; + if( level == NULL ) level = this->level[mc->player->GetXboxPad()]; // EnterCriticalSection(&m_csDirtyChunks); int _x0 = Mth::intFloorDiv(x0, CHUNK_XZSIZE); int _y0 = Mth::intFloorDiv(y0, CHUNK_SIZE); @@ -2368,10 +2360,10 @@ void LevelRenderer::setDirty(int x0, int y0, int z0, int x1, int y1, int z1, Lev // AP - by the time we reach this function the area passed in has a 1 block border added to it to make sure geometry and lighting is updated correctly. // Some of those blocks will only need lighting updated so it is acceptable to not have those blocks grouped in the deferral system as the mismatch - // will hardly be noticable. The blocks that need geometry updated will be adjacent to the original, non-bordered area. + // will hardly be noticable. The blocks that need geometry updated will be adjacent to the original, non-bordered area. // This bit of code will mark a chunk as 'non-critical' if all of the blocks inside it are NOT adjacent to the original area. This has the greatest effect // when digging a single block. Only 6 of the blocks out of the possible 26 are actually adjacent to the original block. The other 20 only need lighting updated. - // Note I have noticed a new side effect of this system where it's possible to see into the sides of water but this is acceptable compared to seeing through + // Note I have noticed a new side effect of this system where it's possible to see into the sides of water but this is acceptable compared to seeing through // the entire landscape. // is the left or right most block just inside this chunk if( ((x0 & 15) == 15 && x == _x0) || ((x1 & 15) == 0 && x == _x1) ) @@ -2398,7 +2390,7 @@ void LevelRenderer::setDirty(int x0, int y0, int z0, int x1, int y1, int z1, Lev dirtyChunksLockFreeStack.Push((int *)(index)); #else - dirtyChunksLockFreeStack.Push((int *)(index + 2)); + dirtyChunksLockFreeStack.Push((int *)(index + 2)); #endif #ifdef _XBOX @@ -2511,7 +2503,7 @@ void LevelRenderer::cull_SPU(int playerIndex, Culler *culler, float a) m_jobPort_CullSPU->submitSync(); // static int doSort = false; // if(doSort) - { + { m_jobPort_CullSPU->submitJob(&sortJob); } // doSort ^= 1; @@ -2624,7 +2616,7 @@ void LevelRenderer::playSoundExceptPlayer(shared_ptr<Player> player, int iSound, } // 4J-PB - original function. I've changed to an enum instead of string compares -// 4J removed - +// 4J removed - /* void LevelRenderer::addParticle(const wstring& name, double x, double y, double z, double xa, double ya, double za) { @@ -2788,7 +2780,7 @@ shared_ptr<Particle> LevelRenderer::addParticleInternal(ePARTICLE_TYPE eParticle float fStart=((float)(cStart&0xFF)); float fDiff=(float)((cEnd-cStart)&0xFF); - float fCol = (fStart + (Math::random() * fDiff))/255.0f; + float fCol = (fStart + (Math::random() * fDiff))/255.0f; particle->setColor( fCol, fCol, fCol ); } } @@ -2933,11 +2925,11 @@ void LevelRenderer::entityAdded(shared_ptr<Entity> entity) player->prepareCustomTextures(); // 4J-PB - adding these from global title storage - if (player->customTextureUrl != L"") + if (player->customTextureUrl != L"") { textures->addMemTexture(player->customTextureUrl, new MobSkinMemTextureProcessor()); } - if (player->customTextureUrl2 != L"") + if (player->customTextureUrl2 != L"") { textures->addMemTexture(player->customTextureUrl2, new MobSkinMemTextureProcessor()); } @@ -2949,11 +2941,11 @@ void LevelRenderer::entityRemoved(shared_ptr<Entity> entity) if(entity->instanceof(eTYPE_PLAYER)) { shared_ptr<Player> player = dynamic_pointer_cast<Player>(entity); - if (player->customTextureUrl != L"") + if (player->customTextureUrl != L"") { textures->removeMemTexture(player->customTextureUrl); } - if (player->customTextureUrl2 != L"") + if (player->customTextureUrl2 != L"") { textures->removeMemTexture(player->customTextureUrl2); } @@ -3032,7 +3024,7 @@ void LevelRenderer::levelEvent(shared_ptr<Player> source, int type, int x, int y { //case LevelEvent::SOUND_WITHER_BOSS_SPAWN: case LevelEvent::SOUND_DRAGON_DEATH: - if (mc->cameraTargetPlayer != NULL) + if (mc->cameraTargetPlayer != NULL) { // play the sound at an offset from the player double dx = x - mc->cameraTargetPlayer->x; @@ -3044,7 +3036,7 @@ void LevelRenderer::levelEvent(shared_ptr<Player> source, int type, int x, int y double sy = mc->cameraTargetPlayer->y; double sz = mc->cameraTargetPlayer->z; - if (len > 0) + if (len > 0) { sx += (dx / len) * 2; sy += (dy / len) * 2; @@ -3284,8 +3276,8 @@ void LevelRenderer::destroyTileProgress(int id, int x, int y, int z, int progres { if (progress < 0 || progress >= 10) { - AUTO_VAR(it, destroyingBlocks.find(id)); - if(it != destroyingBlocks.end()) + auto it = destroyingBlocks.find(id); + if(it != destroyingBlocks.end()) { delete it->second; destroyingBlocks.erase(it); @@ -3296,8 +3288,8 @@ void LevelRenderer::destroyTileProgress(int id, int x, int y, int z, int progres { BlockDestructionProgress *entry = NULL; - AUTO_VAR(it, destroyingBlocks.find(id)); - if(it != destroyingBlocks.end()) entry = it->second; + auto it = destroyingBlocks.find(id); + if(it != destroyingBlocks.end()) entry = it->second; if (entry == NULL || entry->getX() != x || entry->getY() != y || entry->getZ() != z) { @@ -3316,7 +3308,7 @@ void LevelRenderer::registerTextures(IconRegister *iconRegister) for (int i = 0; i < 10; i++) { - breakingTextures[i] = iconRegister->registerIcon(L"destroy_" + _toString(i) ); + breakingTextures[i] = iconRegister->registerIcon(L"destroy_" + std::to_wstring(i) ); } } @@ -3473,7 +3465,7 @@ unsigned char LevelRenderer::incGlobalChunkRefCount(int x, int y, int z, Level * unsigned char refCount = (flags >> CHUNK_FLAG_REF_SHIFT ) & CHUNK_FLAG_REF_MASK; refCount++; flags &= ~(CHUNK_FLAG_REF_MASK<<CHUNK_FLAG_REF_SHIFT); - flags |= refCount << CHUNK_FLAG_REF_SHIFT; + flags |= refCount << CHUNK_FLAG_REF_SHIFT; globalChunkFlags[ index ] = flags; return refCount; @@ -3509,13 +3501,11 @@ unsigned char LevelRenderer::decGlobalChunkRefCount(int x, int y, int z, Level * void LevelRenderer::fullyFlagRenderableTileEntitiesToBeRemoved() { EnterCriticalSection(&m_csRenderableTileEntities); - AUTO_VAR(itChunkEnd, renderableTileEntities.end()); - for (AUTO_VAR(it, renderableTileEntities.begin()); it != itChunkEnd; it++) - { - AUTO_VAR(itTEEnd, it->second.end()); - for( AUTO_VAR(it2, it->second.begin()); it2 != itTEEnd; it2++ ) + for (auto& it : renderableTileEntities) + { + for(auto& it2 : it.second) { - (*it2)->upgradeRenderRemoveStage(); + it2->upgradeRenderRemoveStage(); } } LeaveCriticalSection(&m_csRenderableTileEntities); @@ -3529,9 +3519,9 @@ LevelRenderer::DestroyedTileManager::RecentTile::RecentTile(int x, int y, int z, LevelRenderer::DestroyedTileManager::RecentTile::~RecentTile() { - for( AUTO_VAR(it, boxes.begin()); it!= boxes.end(); it++ ) + for(auto& it : boxes) { - delete *it; + delete it; } } @@ -3645,7 +3635,7 @@ void LevelRenderer::DestroyedTileManager::addAABBs( Level *level, AABB *box, AAB // without worrying about the lifespan of the copy we've passed out if( m_destroyedTiles[i]->boxes[j]->intersects( box ) ) { - boxes->push_back(AABB::newTemp( m_destroyedTiles[i]->boxes[j]->x0, + boxes->push_back(AABB::newTemp( m_destroyedTiles[i]->boxes[j]->x0, m_destroyedTiles[i]->boxes[j]->y0, m_destroyedTiles[i]->boxes[j]->z0, m_destroyedTiles[i]->boxes[j]->x1, diff --git a/Minecraft.Client/MemoryTracker.cpp b/Minecraft.Client/MemoryTracker.cpp index c1652d3b..9d0b29de 100644 --- a/Minecraft.Client/MemoryTracker.cpp +++ b/Minecraft.Client/MemoryTracker.cpp @@ -23,8 +23,8 @@ int MemoryTracker::genTextures() void MemoryTracker::releaseLists(int id) { - AUTO_VAR(it, GL_LIST_IDS.find(id)); - if( it != GL_LIST_IDS.end() ) + auto it = GL_LIST_IDS.find(id); + if( it != GL_LIST_IDS.end() ) { glDeleteLists(id, it->second); GL_LIST_IDS.erase(it); @@ -43,9 +43,9 @@ void MemoryTracker::releaseTextures() void MemoryTracker::release() { //for (Map.Entry<Integer, Integer> entry : GL_LIST_IDS.entrySet()) - for(AUTO_VAR(it, GL_LIST_IDS.begin()); it != GL_LIST_IDS.end(); ++it) + for(auto& it : GL_LIST_IDS) { - glDeleteLists(it->first, it->second); + glDeleteLists(it.first, it.second); } GL_LIST_IDS.clear(); diff --git a/Minecraft.Client/Minecraft.Client.vcxproj b/Minecraft.Client/Minecraft.Client.vcxproj index d7c49acf..6a4a3e1b 100644 --- a/Minecraft.Client/Minecraft.Client.vcxproj +++ b/Minecraft.Client/Minecraft.Client.vcxproj @@ -747,6 +747,9 @@ <LinkIncremental>true</LinkIncremental> <ImageXexOutput>$(OutDir)$(ProjectName)_D.xex</ImageXexOutput> <IncludePath>$(ProjectDir)\..\Minecraft.World\x64headers;$(ProjectDir)\Xbox\Sentient\Include;$(IncludePath)</IncludePath> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64EC'"> <LinkIncremental>true</LinkIncremental> @@ -778,6 +781,9 @@ <LinkIncremental>false</LinkIncremental> <ImageXexOutput>$(OutDir)$(ProjectName)_D.xex</ImageXexOutput> <IncludePath>$(ProjectDir)\..\Minecraft.World\x64headers;$(ProjectDir)\Xbox\Sentient\Include;$(IncludePath)</IncludePath> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64EC'"> <LinkIncremental>true</LinkIncremental> @@ -793,6 +799,9 @@ <LinkIncremental>true</LinkIncremental> <ImageXexOutput>$(OutDir)$(ProjectName)_D.xex</ImageXexOutput> <IncludePath>$(ProjectDir)\..\Minecraft.World\x64headers;$(ProjectDir)\Xbox\Sentient\Include;$(IncludePath)</IncludePath> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ContentPackage_Vita|ARM64EC'"> <LinkIncremental>true</LinkIncremental> @@ -909,6 +918,9 @@ <OutputFile>$(OutDir)default$(TargetExt)</OutputFile> <ImageXexOutput>$(OutDir)default.xex</ImageXexOutput> <IncludePath>$(ProjectDir)\Xbox\Sentient\Include;$(IncludePath)</IncludePath> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ContentPackage|ARM64EC'"> <LinkIncremental>false</LinkIncremental> @@ -927,6 +939,9 @@ <OutputFile>$(OutDir)default$(TargetExt)</OutputFile> <ImageXexOutput>$(OutDir)default.xex</ImageXexOutput> <IncludePath>$(ProjectDir)\Xbox\Sentient\Include;$(IncludePath)</IncludePath> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='CONTENTPACKAGE_SYMBOLS|ARM64EC'"> <LinkIncremental>false</LinkIncremental> @@ -945,6 +960,9 @@ <OutputFile>$(OutDir)default$(TargetExt)</OutputFile> <ImageXexOutput>$(OutDir)default.xex</ImageXexOutput> <IncludePath>$(ProjectDir)\Xbox\Sentient\Include;$(IncludePath)</IncludePath> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseForArt|ARM64EC'"> <LinkIncremental>false</LinkIncremental> @@ -963,6 +981,9 @@ <OutputFile>$(OutDir)default$(TargetExt)</OutputFile> <ImageXexOutput>$(OutDir)default.xex</ImageXexOutput> <IncludePath>$(ProjectDir)\Xbox\Sentient\Include;$(IncludePath)</IncludePath> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ContentPackage_NO_TU|ARM64EC'"> <LinkIncremental>false</LinkIncremental> @@ -48678,4 +48699,4 @@ xcopy /q /y /i /s /e $(ProjectDir)Durango\CU $(LayoutDir)Image\Loose\CU</Comman <ImportGroup Label="ExtensionTargets"> <Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" /> </ImportGroup> -</Project> +</Project>
\ No newline at end of file diff --git a/Minecraft.Client/Minecraft.cpp b/Minecraft.Client/Minecraft.cpp index 3cc9ac59..b197638c 100644 --- a/Minecraft.Client/Minecraft.cpp +++ b/Minecraft.Client/Minecraft.cpp @@ -79,7 +79,7 @@ //#define DEBUG_RENDER_SHOWS_PACKETS 1 //#define SPLITSCREEN_TEST -// If not disabled, this creates an event queue on a seperate thread so that the Level::tick calls can be offloaded +// If not disabled, this creates an event queue on a seperate thread so that the Level::tick calls can be offloaded // from the main thread, and have longer to run, since it's called at 20Hz instead of 60 #define DISABLE_LEVELTICK_THREAD @@ -96,7 +96,7 @@ TOUCHSCREENRECT QuickSelectRect[3]= { { 560, 890, 1360, 980 }, { 450, 840, 1449, 960 }, - { 320, 840, 1600, 970 }, + { 320, 840, 1600, 970 }, }; int QuickSelectBoxWidth[3]= @@ -741,7 +741,7 @@ void Minecraft::run() while (System::currentTimeMillis() >= lastTime + 1000) { - fpsString = _toString<int>(frames) + L" fps, " + _toString<int>(Chunk::updates) + L" chunk updates"; + fpsString = std::to_wstring(frames) + L" fps, " + std::to_wstring(Chunk::updates) + L" chunk updates"; Chunk::updates = 0; lastTime += 1000; frames = 0; @@ -1286,7 +1286,7 @@ void Minecraft::run_middle() if( pDLCPack ) { if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) - { + { bTrialTexturepack=true; } } @@ -1408,7 +1408,7 @@ void Minecraft::run_middle() { delete m_pPsPlusUpsell; m_pPsPlusUpsell = NULL; - + if ( ProfileManager.HasPlayStationPlus(i) ) { app.DebugPrintf("<Minecraft.cpp> Player_%i is now authorised for PsPlus.\n", i); @@ -2034,7 +2034,7 @@ void Minecraft::run_middle() while (System::nanoTime() >= lastTime + 1000000000) { MemSect(31); - fpsString = _toString<int>(frames) + L" fps, " + _toString<int>(Chunk::updates) + L" chunk updates"; + fpsString = std::to_wstring(frames) + L" fps, " + std::to_wstring(Chunk::updates) + L" chunk updates"; MemSect(0); Chunk::updates = 0; lastTime += 1000000000; @@ -2231,7 +2231,7 @@ void Minecraft::levelTickThreadInitFunc() { AABB::CreateNewThreadStorage(); Vec3::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); Compression::UseDefaultThreadStorage(); } @@ -2861,10 +2861,10 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) shared_ptr<ItemInstance> heldItem = nullptr; if (player->inventory->IsHeldItem()) { - heldItem = player->inventory->getSelected(); + heldItem = player->inventory->getSelected(); } int heldItemId = heldItem != NULL ? heldItem->getItem()->id : -1; - + switch(entityType) { case eTYPE_CHICKEN: @@ -2906,7 +2906,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) case eTYPE_COW: { if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - + shared_ptr<Animal> animal = dynamic_pointer_cast<Animal>(hitResult->entity); if (animal->isLeashed() && animal->getLeashHolder() == player) @@ -2970,7 +2970,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) *piUse=IDS_TOOLTIPS_MILK; break; case Item::shears_Id: - { + { if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; if(!animal->isBaby()) *piUse=IDS_TOOLTIPS_SHEAR; } @@ -2998,10 +2998,10 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) *piAction = IDS_TOOLTIPS_MINE; *piUse = IDS_TOOLTIPS_RIDE; // are we in the minecart already? - 4J-JEV: Doesn't matter anymore. break; - + case eTYPE_MINECART_FURNACE: *piAction = IDS_TOOLTIPS_MINE; - + // if you have coal, it'll go. Is there an object in hand? if (heldItemId == Item::coal_Id) *piUse=IDS_TOOLTIPS_USE; break; @@ -3082,7 +3082,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; shared_ptr<Pig> pig = dynamic_pointer_cast<Pig>(hitResult->entity); - + if (pig->isLeashed() && pig->getLeashHolder() == player) { *piUse=IDS_TOOLTIPS_UNLEASH; @@ -3225,7 +3225,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) shared_ptr<Ocelot> ocelot = dynamic_pointer_cast<Ocelot>(hitResult->entity); if(player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; - + if (ocelot->isLeashed() && ocelot->getLeashHolder() == player) { *piUse = IDS_TOOLTIPS_UNLEASH; @@ -3254,7 +3254,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } else { - *piUse=IDS_TOOLTIPS_FEED; + *piUse=IDS_TOOLTIPS_FEED; } } @@ -3277,7 +3277,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } } break; - + case eTYPE_PLAYER: { // Fix for #58576 - TU6: Content: Gameplay: Hit button prompt is available when attacking a host who has "Invisible" option turned on @@ -3343,9 +3343,9 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) case eTYPE_HORSE: { shared_ptr<EntityHorse> horse = dynamic_pointer_cast<EntityHorse>(hitResult->entity); - + bool heldItemIsFood = false, heldItemIsLove = false, heldItemIsArmour = false; - + switch( heldItemId ) { case Item::wheat_Id: @@ -3400,7 +3400,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) *piUse = IDS_TOOLTIPS_FEED; } } - else if ( player->isSneaking() + else if ( player->isSneaking() || (heldItemId == Item::saddle_Id) || (horse->canWearArmor() && heldItemIsArmour) ) @@ -3409,7 +3409,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) if (*piUse == -1) *piUse = IDS_TOOLTIPS_OPEN; } else if ( horse->canWearBags() - && !horse->isChestedHorse() + && !horse->isChestedHorse() && (heldItemId == Tile::chest_Id) ) { // 4j - Attach saddle-bags (chest) to donkey or mule. @@ -3431,7 +3431,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) // 4j - Ride tamed horse. *piUse = IDS_TOOLTIPS_MOUNT; } - + if (player->isAllowedToAttackAnimals()) *piAction=IDS_TOOLTIPS_HIT; } break; @@ -3471,7 +3471,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } } *piAction=IDS_TOOLTIPS_HIT; - break; + break; } break; } @@ -3666,7 +3666,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) player->abilities.debugflying = !player->abilities.debugflying; player->abilities.flying = !player->abilities.flying; } -#endif // PSVITA +#endif // PSVITA } #endif @@ -3743,7 +3743,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } __uint64 ullButtonsPressed=player->ullButtonsPressed; - + bool selected = false; #ifdef __PSVITA__ // 4J-PB - use the touchscreen for quickselect @@ -3768,7 +3768,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) shared_ptr<ItemInstance> selectedItem = player->getSelectedItem(); // Dropping items happens over network, so if we only have one then assume that we dropped it and should hide the item int iCount=0; - + if(selectedItem != NULL) iCount=selectedItem->GetCount(); if(selectedItem != NULL && !( (player->ullButtonsPressed&(1LL<<MINECRAFT_ACTION_DROP)) && selectedItem->GetCount() == 1)) { @@ -4077,7 +4077,7 @@ void Minecraft::tick(bool bFirst, bool bUpdateTextures) } #ifdef __PS3__ -// while(!g_tickLevelQueue.empty()) +// while(!g_tickLevelQueue.empty()) // { // Level* pLevel = g_tickLevelQueue.front(); // g_tickLevelQueue.pop(); @@ -4305,7 +4305,7 @@ void Minecraft::setLevel(MultiPlayerLevel *level, int message /*=-1*/, shared_pt player->resetPos(); gameMode->initPlayer(player); - + player->SetXboxPad(iPrimaryPlayer); for(int i=0;i<XUSER_MAX_COUNT;i++) @@ -4432,7 +4432,7 @@ void Minecraft::prepareLevel(int title) wstring Minecraft::gatherStats1() { //return levelRenderer->gatherStats1(); - return L"Time to autosave: " + _toString<unsigned int>( app.SecondsToAutosave() ) + L"s"; + return L"Time to autosave: " + std::to_wstring( app.SecondsToAutosave() ) + L"s"; } wstring Minecraft::gatherStats2() @@ -4610,7 +4610,7 @@ void Minecraft::startAndConnectTo(const wstring& name, const wstring& sid, const } else { - minecraft->user = new User(L"Player" + _toString<int>(System::currentTimeMillis() % 1000), L""); + minecraft->user = new User(L"Player" + std::to_wstring(System::currentTimeMillis() % 1000), L""); } } //else @@ -4691,7 +4691,7 @@ void Minecraft::main() } app.DebugPrintf("\n\n\n\n\n"); - + for(unsigned int i = 0; i < 256; ++i) { if(Tile::tiles[i] != NULL) @@ -4705,7 +4705,7 @@ void Minecraft::main() // 4J-PB - Can't call this for the first 5 seconds of a game - MS rule //if (ProfileManager.IsFullVersion()) { - name = L"Player" + _toString<__int64>(System::currentTimeMillis() % 1000); + name = L"Player" + std::to_wstring(System::currentTimeMillis() % 1000); sessionId = L"-"; /* 4J - TODO - get a session ID from somewhere? if (args.length > 0) name = args[0]; @@ -5106,8 +5106,8 @@ void Minecraft::tickAllConnections() bool Minecraft::addPendingClientTextureRequest(const wstring &textureName) { - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it == m_pendingTextureRequests.end() ) + auto it = find(m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName); + if( it == m_pendingTextureRequests.end() ) { m_pendingTextureRequests.push_back(textureName); return true; @@ -5117,8 +5117,8 @@ bool Minecraft::addPendingClientTextureRequest(const wstring &textureName) void Minecraft::handleClientTextureReceived(const wstring &textureName) { - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it != m_pendingTextureRequests.end() ) + auto it = find(m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName); + if( it != m_pendingTextureRequests.end() ) { m_pendingTextureRequests.erase(it); } @@ -5148,8 +5148,8 @@ int Minecraft::MustSignInReturnedPSN(void *pParam, int iPad, C4JStorage::EMessag { Minecraft* pMinecraft = (Minecraft *)pParam; - if(result == C4JStorage::EMessage_ResultAccept) - { + if(result == C4JStorage::EMessage_ResultAccept) + { SQRNetworkManager_Orbis::AttemptPSNSignIn(&Minecraft::InGame_SignInReturned, pMinecraft, false, iPad); } diff --git a/Minecraft.Client/MinecraftServer.cpp b/Minecraft.Client/MinecraftServer.cpp index af9e226b..699ffa8c 100644 --- a/Minecraft.Client/MinecraftServer.cpp +++ b/Minecraft.Client/MinecraftServer.cpp @@ -211,7 +211,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom { wstring playerNames = (playerList != NULL) ? playerList->getPlayerNames() : L""; if (playerNames.empty()) playerNames = L"(none)"; - server->info(L"Players (" + _toString((playerList != NULL) ? playerList->getPlayerCount() : 0) + L"): " + playerNames); + server->info(L"Players (" + std::to_wstring((playerList != NULL) ? playerList->getPlayerCount() : 0) + L"): " + playerNames); return true; } @@ -273,7 +273,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom } } - server->info(L"Added " + _toString(delta) + L" ticks."); + server->info(L"Added " + std::to_wstring(delta) + L" ticks."); return true; } @@ -304,7 +304,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom } SetAllLevelTimes(server, targetTime); - server->info(L"Time set to " + _toString(targetTime) + L"."); + server->info(L"Time set to " + std::to_wstring(targetTime) + L"."); return true; } @@ -427,7 +427,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom } if (itemId <= 0 || Item::items[itemId] == NULL) { - server->warn(L"Unknown item id: " + _toString(itemId)); + server->warn(L"Unknown item id: " + std::to_wstring(itemId)); return false; } if (amount <= 0) @@ -442,7 +442,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom { drop->throwTime = 0; } - server->info(L"Gave item " + _toString(itemId) + L" x" + _toString(amount) + L" to " + player->getName() + L"."); + server->info(L"Gave item " + std::to_wstring(itemId) + L" x" + std::to_wstring(amount) + L" to " + player->getName() + L"."); return true; } @@ -484,7 +484,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom Enchantment *enchantment = Enchantment::enchantments[enchantmentId]; if (enchantment == NULL) { - server->warn(L"Unknown enchantment id: " + _toString(enchantmentId)); + server->warn(L"Unknown enchantment id: " + std::to_wstring(enchantmentId)); return false; } if (!enchantment->canEnchant(selectedItem)) @@ -514,7 +514,7 @@ static bool ExecuteConsoleCommand(MinecraftServer *server, const wstring &rawCom } selectedItem->enchant(enchantment, enchantmentLevel); - server->info(L"Enchanted " + player->getName() + L"'s held item with " + _toString(enchantmentId) + L" " + _toString(enchantmentLevel) + L"."); + server->info(L"Enchanted " + player->getName() + L"'s held item with " + std::to_wstring(enchantmentId) + L" " + std::to_wstring(enchantmentLevel) + L"."); return true; } @@ -712,7 +712,7 @@ bool MinecraftServer::initServer(__int64 seed, NetworkGameInitData *initData, DW } LevelType *pLevelType = LevelType::getLevelType(levelTypeString); - if (pLevelType == NULL) + if (pLevelType == NULL) { pLevelType = LevelType::lvl_normal; } @@ -771,7 +771,7 @@ int MinecraftServer::runPostUpdate(void* lpParam) Entity::useSmallIds(); // This thread can end up spawning entities as resources IntCache::CreateNewThreadStorage(); AABB::CreateNewThreadStorage(); - Vec3::CreateNewThreadStorage(); + Vec3::CreateNewThreadStorage(); Compression::UseDefaultThreadStorage(); Level::enableLightingCache(); Tile::CreateNewThreadStorage(); @@ -892,7 +892,7 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring { // We are loading a file from disk with the data passed in -#ifdef SPLIT_SAVES +#ifdef SPLIT_SAVES ConsoleSaveFileOriginal oldFormatSave( initData->saveData->saveName, initData->saveData->data, initData->saveData->fileSize, false, initData->savePlatform ); ConsoleSaveFile* pSave = new ConsoleSaveFileSplit( &oldFormatSave ); @@ -936,7 +936,7 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring } // McRegionLevelStorage *storage = new McRegionLevelStorage(new ConsoleSaveFile( L"" ), L"", L"", 0); // original - // McRegionLevelStorage *storage = new McRegionLevelStorage(File(L"."), name, true); // TODO + // McRegionLevelStorage *storage = new McRegionLevelStorage(File(L"."), name, true); // TODO for (unsigned int i = 0; i < levels.length; i++) { if( s_bServerHalted || !g_NetworkManager.IsInSession() ) @@ -1022,7 +1022,7 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring #ifdef __PSVITA__ int r = 48; #else - int r = 196; + int r = 196; #endif // 4J JEV: load gameRules. @@ -1173,7 +1173,7 @@ bool MinecraftServer::loadLevel(LevelStorageSource *storageSource, const wstring if(!levels[0]->getLevelData()->getHasStronghold()) { - int x,z; + int x,z; if(app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold,&x,&z)) { levels[0]->getLevelData()->setXStronghold(x); @@ -1401,7 +1401,7 @@ void MinecraftServer::Suspend() // Save the start time QueryPerformanceCounter( &qwTime ); if(m_bLoaded && ProfileManager.IsFullVersion() && (!StorageManager.GetSaveDisabled())) - { + { if (players != NULL) { players->saveAll(NULL); @@ -1476,7 +1476,7 @@ void MinecraftServer::stopServer(bool didInit) #endif // if trial version or saving is disabled, then don't save anything. Also don't save anything if we didn't actually get through the server initialisation. if(m_saveOnExit && ProfileManager.IsFullVersion() && (!StorageManager.GetSaveDisabled()) && didInit) - { + { if (players != NULL) { players->saveAll(Minecraft::GetInstance()->progressRenderer, true); @@ -1715,7 +1715,7 @@ void MinecraftServer::run(__int64 seed, void *lpParameter) if(pLevelData && pLevelData->getHasStronghold()==false) { - int x,z; + int x,z; if(app.GetTerrainFeaturePosition(eTerrainFeature_Stronghold,&x,&z)) { pLevelData->setXStronghold(x); @@ -1815,7 +1815,7 @@ void MinecraftServer::run(__int64 seed, void *lpParameter) } } - // Process delayed actions + // Process delayed actions eXuiServerAction eAction; LPVOID param; for(int i=0;i<XUSER_MAX_COUNT;i++) @@ -1898,7 +1898,7 @@ void MinecraftServer::run(__int64 seed, void *lpParameter) { saveGameRules(); - levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, (eAction==eXuiServerAction_AutoSaveGame)); + levels[0]->saveToDisc(Minecraft::GetInstance()->progressRenderer, (eAction==eXuiServerAction_AutoSaveGame)); } app.LeaveSaveNotificationSection(); break; @@ -1923,19 +1923,19 @@ void MinecraftServer::run(__int64 seed, void *lpParameter) case eXuiServerAction_PauseServer: m_isServerPaused = ( (size_t) param == TRUE ); if( m_isServerPaused ) - { + { m_serverPausedEvent->Set(); } break; case eXuiServerAction_ToggleRain: - { + { bool isRaining = levels[0]->getLevelData()->isRaining(); levels[0]->getLevelData()->setRaining(!isRaining); levels[0]->getLevelData()->setRainTime(levels[0]->random->nextInt(Level::TICKS_PER_DAY * 7) + Level::TICKS_PER_DAY / 2); } break; case eXuiServerAction_ToggleThunder: - { + { bool isThundering = levels[0]->getLevelData()->isThundering(); levels[0]->getLevelData()->setThundering(!isThundering); levels[0]->getLevelData()->setThunderTime(levels[0]->random->nextInt(Level::TICKS_PER_DAY * 7) + Level::TICKS_PER_DAY / 2); @@ -1973,7 +1973,7 @@ void MinecraftServer::run(__int64 seed, void *lpParameter) File dataFile = File( targetFileDir, wstring(filename) ); if(dataFile.exists()) dataFile._delete(); FileOutputStream fos = FileOutputStream(dataFile); - DataOutputStream dos = DataOutputStream(&fos); + DataOutputStream dos = DataOutputStream(&fos); ConsoleSchematicFile::generateSchematicFile(&dos, levels[0], initData->startX, initData->startY, initData->startZ, initData->endX, initData->endY, initData->endZ, initData->bSaveMobs, initData->compressionType); dos.close(); @@ -1990,7 +1990,7 @@ void MinecraftServer::run(__int64 seed, void *lpParameter) app.DebugPrintf( "DEBUG: Player=%i\n", pos->player ); app.DebugPrintf( "DEBUG: Teleporting to pos=(%f.2, %f.2, %f.2), looking at=(%f.2,%f.2)\n", pos->m_camX, pos->m_camY, pos->m_camZ, - pos->m_yRot, pos->m_elev + pos->m_yRot, pos->m_elev ); shared_ptr<ServerPlayer> player = players->players.at(pos->player); @@ -2064,21 +2064,21 @@ void MinecraftServer::broadcastStopSavingPacket() void MinecraftServer::tick() { vector<wstring> toRemove; - for (AUTO_VAR(it, ironTimers.begin()); it != ironTimers.end(); it++ ) - { - int t = it->second; + for ( auto& it : ironTimers ) + { + int t = it.second; if (t > 0) { - ironTimers[it->first] = t - 1; + ironTimers[it.first] = t - 1; } else { - toRemove.push_back(it->first); + toRemove.push_back(it.first); } } - for (unsigned int i = 0; i < toRemove.size(); i++) + for (const auto& i : toRemove) { - ironTimers.erase(toRemove[i]); + ironTimers.erase(i); } AABB::resetPool(); @@ -2316,8 +2316,8 @@ void MinecraftServer::chunkPacketManagement_PreTick() do { int longestTime = 0; - AUTO_VAR(playerConnectionBest,playersOrig.begin()); - for( AUTO_VAR(it, playersOrig.begin()); it != playersOrig.end(); it++) + auto playerConnectionBest = playersOrig.begin(); + for( auto it = playersOrig.begin(); it != playersOrig.end(); it++) { int thisTime = 0; INetworkPlayer *np = (*it)->getNetworkPlayer(); @@ -2326,7 +2326,7 @@ void MinecraftServer::chunkPacketManagement_PreTick() thisTime = np->GetTimeSinceLastChunkPacket_ms(); } - if( thisTime > longestTime ) + if( thisTime > longestTime ) { playerConnectionBest = it; longestTime = thisTime; diff --git a/Minecraft.Client/Minimap.cpp b/Minecraft.Client/Minimap.cpp index c18cd267..65c6d5f2 100644 --- a/Minecraft.Client/Minimap.cpp +++ b/Minecraft.Client/Minimap.cpp @@ -85,7 +85,7 @@ void Minimap::reloadColours() LUT[i] = 255 << 24 | r << 16 | g << 8 | b; #elif defined __ORBIS__ r >>= 3; g >>= 3; b >>= 3; - LUT[i] = 1 << 15 | ( r << 10 ) | ( g << 5 ) | b; + LUT[i] = 1 << 15 | ( r << 10 ) | ( g << 5 ) | b; #else LUT[i] = r << 24 | g << 16 | b << 8 | 255; #endif @@ -144,18 +144,14 @@ void Minimap::render(shared_ptr<Player> player, Textures *textures, shared_ptr<M textures->bind(textures->loadTexture(TN_MISC_MAPICONS));//L"/misc/mapicons.png")); - AUTO_VAR(itEnd, data->decorations.end()); - #ifdef _LARGE_WORLDS vector<MapItemSavedData::MapDecoration *> m_edgeIcons; #endif // 4J-PB - stack the map icons float fIconZ=-0.04f;// 4J - moved to -0.04 (was -0.02) to stop z fighting - for( vector<MapItemSavedData::MapDecoration *>::iterator it = data->decorations.begin(); it != itEnd; it++ ) + for( MapItemSavedData::MapDecoration *dec : data->decorations ) { - MapItemSavedData::MapDecoration *dec = *it; - if(!dec->visible) continue; char imgIndex = dec->img; @@ -200,10 +196,8 @@ void Minimap::render(shared_ptr<Player> player, Textures *textures, shared_ptr<M textures->bind(textures->loadTexture(TN_MISC_ADDITIONALMAPICONS)); fIconZ=-0.04f;// 4J - moved to -0.04 (was -0.02) to stop z fighting - for( AUTO_VAR(it,m_edgeIcons.begin()); it != m_edgeIcons.end(); it++ ) + for( MapItemSavedData::MapDecoration *dec : m_edgeIcons ) { - MapItemSavedData::MapDecoration *dec = *it; - char imgIndex = dec->img; imgIndex -= 16; @@ -253,7 +247,7 @@ void Minimap::render(shared_ptr<Player> player, Textures *textures, shared_ptr<M int posy = floor(player->y); int posz = floor(player->z); swprintf(playerPosText, 32, L"X: %d, Y: %d, Z: %d", posx, posy, posz); - + font->draw(playerPosText, x, y, Minecraft::GetInstance()->getColourTable()->getColour(eMinecraftColour_Map_Text)); } //#endif diff --git a/Minecraft.Client/ModelPart.cpp b/Minecraft.Client/ModelPart.cpp index 615ff8bd..c59a821c 100644 --- a/Minecraft.Client/ModelPart.cpp +++ b/Minecraft.Client/ModelPart.cpp @@ -24,23 +24,23 @@ ModelPart::ModelPart() _init(); } -ModelPart::ModelPart(Model *model, const wstring& id) +ModelPart::ModelPart(Model *model, const wstring& id) { construct(model, id); } -ModelPart::ModelPart(Model *model) +ModelPart::ModelPart(Model *model) { construct(model); } -ModelPart::ModelPart(Model *model, int xTexOffs, int yTexOffs) +ModelPart::ModelPart(Model *model, int xTexOffs, int yTexOffs) { construct(model, xTexOffs, yTexOffs); } -void ModelPart::construct(Model *model, const wstring& id) +void ModelPart::construct(Model *model, const wstring& id) { _init(); this->model = model; @@ -49,13 +49,13 @@ void ModelPart::construct(Model *model, const wstring& id) setTexSize(model->texWidth, model->texHeight); } -void ModelPart::construct(Model *model) +void ModelPart::construct(Model *model) { _init(); construct(model, L""); } -void ModelPart::construct(Model *model, int xTexOffs, int yTexOffs) +void ModelPart::construct(Model *model, int xTexOffs, int yTexOffs) { _init(); construct(model); @@ -63,22 +63,18 @@ void ModelPart::construct(Model *model, int xTexOffs, int yTexOffs) } -void ModelPart::addChild(ModelPart *child) +void ModelPart::addChild(ModelPart *child) { //if (children == NULL) children = new ModelPartArray; children.push_back(child); } -ModelPart * ModelPart::retrieveChild(SKIN_BOX *pBox) +ModelPart * ModelPart::retrieveChild(SKIN_BOX *pBox) { - for(AUTO_VAR(it, children.begin()); it != children.end(); ++it) + for( ModelPart *child : children ) { - ModelPart *child=*it; - - for(AUTO_VAR(itcube, child->cubes.begin()); itcube != child->cubes.end(); ++itcube) - { - Cube *pCube=*itcube; - + for ( const Cube *pCube : child->cubes ) + { if((pCube->x0==pBox->fX) && (pCube->y0==pBox->fY) && (pCube->z0==pBox->fZ) && @@ -96,20 +92,20 @@ ModelPart * ModelPart::retrieveChild(SKIN_BOX *pBox) return NULL; } -ModelPart *ModelPart::mirror() +ModelPart *ModelPart::mirror() { bMirror = !bMirror; return this; } -ModelPart *ModelPart::texOffs(int xTexOffs, int yTexOffs) +ModelPart *ModelPart::texOffs(int xTexOffs, int yTexOffs) { this->xTexOffs = xTexOffs; this->yTexOffs = yTexOffs; return this; } -ModelPart *ModelPart::addBox(wstring id, float x0, float y0, float z0, int w, int h, int d) +ModelPart *ModelPart::addBox(wstring id, float x0, float y0, float z0, int w, int h, int d) { id = this->id + L"." + id; TexOffs *offs = model->getMapTex(id); @@ -118,42 +114,42 @@ ModelPart *ModelPart::addBox(wstring id, float x0, float y0, float z0, int w, in return this; } -ModelPart *ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d) +ModelPart *ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d) { cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0)); return this; } -void ModelPart::addHumanoidBox(float x0, float y0, float z0, int w, int h, int d, float g) +void ModelPart::addHumanoidBox(float x0, float y0, float z0, int w, int h, int d, float g) { cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, g, 63, true)); } -ModelPart *ModelPart::addBoxWithMask(float x0, float y0, float z0, int w, int h, int d, int faceMask) +ModelPart *ModelPart::addBoxWithMask(float x0, float y0, float z0, int w, int h, int d, int faceMask) { cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, 0, faceMask)); return this; } -void ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d, float g) +void ModelPart::addBox(float x0, float y0, float z0, int w, int h, int d, float g) { cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, g)); } -void ModelPart::addTexBox(float x0, float y0, float z0, int w, int h, int d, int tex) +void ModelPart::addTexBox(float x0, float y0, float z0, int w, int h, int d, int tex) { cubes.push_back(new Cube(this, xTexOffs, yTexOffs, x0, y0, z0, w, h, d, (float)tex)); } -void ModelPart::setPos(float x, float y, float z) +void ModelPart::setPos(float x, float y, float z) { this->x = x; this->y = y; this->z = z; } -void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) +void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) { if (neverRender) return; if (!visible) return; @@ -161,7 +157,7 @@ void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) glTranslatef(translateX, translateY, translateZ); - if (xRot != 0 || yRot != 0 || zRot != 0) + if (xRot != 0 || yRot != 0 || zRot != 0) { glPushMatrix(); glTranslatef(x * scale, y * scale, z * scale); @@ -170,7 +166,7 @@ void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); if(!bHideParentBodyPart) - { + { if( usecompiled ) { glCallList(list); @@ -178,53 +174,53 @@ void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) else { Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < cubes.size(); i++) + for (unsigned int i = 0; i < cubes.size(); i++) { cubes[i]->render(t, scale); } } - } - //if (children != NULL) + } + //if (children != NULL) { - for (unsigned int i = 0; i < children.size(); i++) + for (unsigned int i = 0; i < children.size(); i++) { children.at(i)->render(scale,usecompiled); } } glPopMatrix(); - } - else if (x != 0 || y != 0 || z != 0) + } + else if (x != 0 || y != 0 || z != 0) { glTranslatef(x * scale, y * scale, z * scale); if(!bHideParentBodyPart) - { + { if( usecompiled ) { glCallList(list); } else { - Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < cubes.size(); i++) + Tesselator *t = Tesselator::getInstance(); + for (unsigned int i = 0; i < cubes.size(); i++) { cubes[i]->render(t, scale); } } } - //if (children != NULL) + //if (children != NULL) { - for (unsigned int i = 0; i < children.size(); i++) + for (unsigned int i = 0; i < children.size(); i++) { children.at(i)->render(scale,usecompiled); } } glTranslatef(-x * scale, -y * scale, -z * scale); - } - else + } + else { if(!bHideParentBodyPart) - { + { if( usecompiled ) { glCallList(list); @@ -232,15 +228,15 @@ void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) else { Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < cubes.size(); i++) + for (unsigned int i = 0; i < cubes.size(); i++) { cubes[i]->render(t, scale); } } } - //if (children != NULL) + //if (children != NULL) { - for (unsigned int i = 0; i < children.size(); i++) + for (unsigned int i = 0; i < children.size(); i++) { children.at(i)->render(scale,usecompiled); } @@ -250,7 +246,7 @@ void ModelPart::render(float scale, bool usecompiled, bool bHideParentBodyPart) glTranslatef(-translateX, -translateY, -translateZ); } -void ModelPart::renderRollable(float scale, bool usecompiled) +void ModelPart::renderRollable(float scale, bool usecompiled) { if (neverRender) return; if (!visible) return; @@ -266,29 +262,29 @@ void ModelPart::renderRollable(float scale, bool usecompiled) } -void ModelPart::translateTo(float scale) +void ModelPart::translateTo(float scale) { if (neverRender) return; if (!visible) return; if (!compiled) compile(scale); - if (xRot != 0 || yRot != 0 || zRot != 0) + if (xRot != 0 || yRot != 0 || zRot != 0) { glTranslatef(x * scale, y * scale, z * scale); if (zRot != 0) glRotatef(zRot * RAD, 0, 0, 1); if (yRot != 0) glRotatef(yRot * RAD, 0, 1, 0); if (xRot != 0) glRotatef(xRot * RAD, 1, 0, 0); - } - else if (x != 0 || y != 0 || z != 0) + } + else if (x != 0 || y != 0 || z != 0) { glTranslatef(x * scale, y * scale, z * scale); - } - else + } + else { } } -void ModelPart::compile(float scale) +void ModelPart::compile(float scale) { list = MemoryTracker::genLists(1); @@ -299,24 +295,24 @@ void ModelPart::compile(float scale) glDepthMask(true); Tesselator *t = Tesselator::getInstance(); - for (unsigned int i = 0; i < cubes.size(); i++) + for (unsigned int i = 0; i < cubes.size(); i++) { cubes.at(i)->render(t, scale); } - + glEndList(); compiled = true; } -ModelPart *ModelPart::setTexSize(int xs, int ys) +ModelPart *ModelPart::setTexSize(int xs, int ys) { this->xTexSize = (float)xs; this->yTexSize = (float)ys; return this; } -void ModelPart::mimic(ModelPart *o) +void ModelPart::mimic(ModelPart *o) { x = o->x; y = o->y; diff --git a/Minecraft.Client/MultiPlayerChunkCache.cpp b/Minecraft.Client/MultiPlayerChunkCache.cpp index b5e1dd25..a4c200be 100644 --- a/Minecraft.Client/MultiPlayerChunkCache.cpp +++ b/Minecraft.Client/MultiPlayerChunkCache.cpp @@ -105,11 +105,13 @@ MultiPlayerChunkCache::~MultiPlayerChunkCache() delete cache; delete hasData; - AUTO_VAR(itEnd, loadedChunkList.end()); - for (AUTO_VAR(it, loadedChunkList.begin()); it != itEnd; it++) - delete *it; + for (auto& it : loadedChunkList) + { + if ( it ) + delete it; + } - DeleteCriticalSection(&m_csLoadCreate); + DeleteCriticalSection(&m_csLoadCreate); } @@ -146,7 +148,7 @@ void MultiPlayerChunkCache::drop(int x, int z) { // Added parameter here specifies that we don't want to delete tile entities, as they won't get recreated unless they've got update packets // The tile entities are in general only created on the client by virtue of the chunk rebuild - chunk->unload(false); + chunk->unload(false); // 4J - We just want to clear out the entities in the chunk, but everything else should be valid chunk->loaded = true; @@ -174,7 +176,7 @@ LevelChunk *MultiPlayerChunkCache::create(int x, int z) // 4J-JEV: We are about to use shared data, abort if the server is stopped and the data is deleted. if (MinecraftServer::getInstance()->serverHalted()) return NULL; - // If we're the host, then don't create the chunk, share data from the server's copy + // If we're the host, then don't create the chunk, share data from the server's copy #ifdef _LARGE_WORLDS LevelChunk *serverChunk = MinecraftServer::getInstance()->getLevel(level->dimension->id)->cache->getChunkLoadedOrUnloaded(x,z); #else @@ -193,7 +195,7 @@ LevelChunk *MultiPlayerChunkCache::create(int x, int z) chunk = new LevelChunk(level, bytes, x, z); // 4J - changed to use new methods for lighting - chunk->setSkyLightDataAllBright(); + chunk->setSkyLightDataAllBright(); // Arrays::fill(chunk->skyLight->data, (byte) 255); } @@ -294,7 +296,7 @@ wstring MultiPlayerChunkCache::gatherStats() EnterCriticalSection(&m_csLoadCreate); int size = (int)loadedChunkList.size(); LeaveCriticalSection(&m_csLoadCreate); - return L"MultiplayerChunkCache: " + _toString<int>(size); + return L"MultiplayerChunkCache: " + std::to_wstring(size); } diff --git a/Minecraft.Client/MultiPlayerLevel.cpp b/Minecraft.Client/MultiPlayerLevel.cpp index 5c27e450..86b2914f 100644 --- a/Minecraft.Client/MultiPlayerLevel.cpp +++ b/Minecraft.Client/MultiPlayerLevel.cpp @@ -97,7 +97,7 @@ void MultiPlayerLevel::tick() if (getGameRules()->getBoolean(GameRules::RULE_DAYLIGHT)) { // 4J: Debug setting added to keep it at day time -#ifndef _FINAL_BUILD +#ifndef _FINAL_BUILD bool freezeTime = app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<<eDebugSetting_FreezeTime); if (!freezeTime) #endif @@ -131,9 +131,10 @@ void MultiPlayerLevel::tick() PIXBeginNamedEvent(0,"Connection ticking"); // 4J HEG - Copy the connections vector to prevent crash when moving to Nether vector<ClientConnection *> connectionsTemp = connections; - for(AUTO_VAR(connection, connectionsTemp.begin()); connection < connectionsTemp.end(); ++connection ) - { - (*connection)->tick(); + for (auto connection : connectionsTemp ) + { + if ( connection ) + connection->tick(); } PIXEndNamedEvent(); @@ -383,10 +384,8 @@ void MultiPlayerLevel::tickTiles() { ChunkPos cp = chunksToPoll.get(i); #else - AUTO_VAR(itEndCtp, chunksToPoll.end()); - for (AUTO_VAR(it, chunksToPoll.begin()); it != itEndCtp; it++) + for (ChunkPos cp : chunksToPoll) { - ChunkPos cp = *it; #endif int xo = cp.x * 16; int zo = cp.z * 16; @@ -433,8 +432,8 @@ void MultiPlayerLevel::removeEntity(shared_ptr<Entity> e) { // 4J Stu - Add this remove from the reEntries collection to stop us continually removing and re-adding things, // in particular the MultiPlayerLocalPlayer when they die - AUTO_VAR(it, reEntries.find(e)); - if (it!=reEntries.end()) + auto it = reEntries.find(e); + if (it!=reEntries.end()) { reEntries.erase(it); } @@ -446,8 +445,8 @@ void MultiPlayerLevel::removeEntity(shared_ptr<Entity> e) void MultiPlayerLevel::entityAdded(shared_ptr<Entity> e) { Level::entityAdded(e); - AUTO_VAR(it, reEntries.find(e)); - if (it!=reEntries.end()) + auto it = reEntries.find(e); + if (it!=reEntries.end()) { reEntries.erase(it); } @@ -456,8 +455,8 @@ void MultiPlayerLevel::entityAdded(shared_ptr<Entity> e) void MultiPlayerLevel::entityRemoved(shared_ptr<Entity> e) { Level::entityRemoved(e); - AUTO_VAR(it, forced.find(e)); - if (it!=forced.end()) + auto it = forced.find(e); + if (it!=forced.end()) { reEntries.insert(e); } @@ -482,16 +481,16 @@ void MultiPlayerLevel::putEntity(int id, shared_ptr<Entity> e) shared_ptr<Entity> MultiPlayerLevel::getEntity(int id) { - AUTO_VAR(it, entitiesById.find(id)); - if( it == entitiesById.end() ) return nullptr; + auto it = entitiesById.find(id); + if( it == entitiesById.end() ) return nullptr; return it->second; } shared_ptr<Entity> MultiPlayerLevel::removeEntity(int id) { shared_ptr<Entity> e; - AUTO_VAR(it, entitiesById.find(id)); - if( it != entitiesById.end() ) + auto it = entitiesById.find(id); + if( it != entitiesById.end() ) { e = it->second; entitiesById.erase(it); @@ -508,19 +507,20 @@ shared_ptr<Entity> MultiPlayerLevel::removeEntity(int id) // This gets called when a chunk is unloaded, but we only do half an unload to remove entities slightly differently void MultiPlayerLevel::removeEntities(vector<shared_ptr<Entity> > *list) { - for(AUTO_VAR(it, list->begin()); it < list->end(); ++it) + if ( list ) { - shared_ptr<Entity> e = *it; - - AUTO_VAR(reIt, reEntries.find(e)); - if (reIt!=reEntries.end()) + for (auto& e : *list ) { - reEntries.erase(reIt); - } + auto reIt = reEntries.find(e); + if (reIt!=reEntries.end()) + { + reEntries.erase(reIt); + } - forced.erase(e); + forced.erase(e); + } + Level::removeEntities(list); } - Level::removeEntities(list); } bool MultiPlayerLevel::setData(int x, int y, int z, int data, int updateFlags, bool forceUpdate/*=false*/) // 4J added forceUpdate) @@ -590,7 +590,7 @@ bool MultiPlayerLevel::doSetTileAndData(int x, int y, int z, int tile, int data) // and so the thing being notified of any update through tileUpdated is the renderer int prevTile = getTile(x, y, z); bool visuallyImportant = (!( ( ( prevTile == Tile::water_Id ) && ( tile == Tile::calmWater_Id ) ) || - ( ( prevTile == Tile::calmWater_Id ) && ( tile == Tile::water_Id ) ) || + ( ( prevTile == Tile::calmWater_Id ) && ( tile == Tile::water_Id ) ) || ( ( prevTile == Tile::lava_Id ) && ( tile == Tile::calmLava_Id ) ) || ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::calmLava_Id ) ) || ( ( prevTile == Tile::calmLava_Id ) && ( tile == Tile::lava_Id ) ) ) ); @@ -615,16 +615,18 @@ void MultiPlayerLevel::disconnect(bool sendDisconnect /*= true*/) { if( sendDisconnect ) { - for(AUTO_VAR(it, connections.begin()); it < connections.end(); ++it ) - { - (*it)->sendAndDisconnect( shared_ptr<DisconnectPacket>( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) ); + for (auto& it : connections ) + { + if ( it ) + it->sendAndDisconnect( shared_ptr<DisconnectPacket>( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) ); } } else { - for(AUTO_VAR(it, connections.begin()); it < connections.end(); ++it ) + for (auto& it : connections ) { - (*it)->close(); + if ( it ) + it->close(); } } } @@ -707,9 +709,8 @@ void MultiPlayerLevel::animateTickDoWork() for( int i = 0; i < ticksPerChunk; i++ ) { - for( AUTO_VAR(it, chunksToAnimate.begin()); it != chunksToAnimate.end(); it++ ) + for(int packed : chunksToAnimate) { - int packed = *it; int cx = ( packed << 8 ) >> 24; int cy = ( packed << 16 ) >> 24; int cz = ( packed << 24 ) >> 24; @@ -809,12 +810,12 @@ void MultiPlayerLevel::removeAllPendingEntityRemovals() //entities.removeAll(entitiesToRemove); EnterCriticalSection(&m_entitiesCS); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); ) - { + for (auto it = entities.begin(); it != entities.end();) + { bool found = false; - for( AUTO_VAR(it2, entitiesToRemove.begin()); it2 != entitiesToRemove.end(); it2++ ) + for(auto & it2 : entitiesToRemove) { - if( (*it) == (*it2) ) + if( (*it) == it2 ) { found = true; break; @@ -831,29 +832,30 @@ void MultiPlayerLevel::removeAllPendingEntityRemovals() } LeaveCriticalSection(&m_entitiesCS); - AUTO_VAR(endIt, entitiesToRemove.end()); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != endIt; it++) + for (auto& e : entitiesToRemove) { - shared_ptr<Entity> e = *it; - int xc = e->xChunk; - int zc = e->zChunk; - if (e->inChunk && hasChunk(xc, zc)) + if ( e ) { - getChunk(xc, zc)->removeEntity(e); + int xc = e->xChunk; + int zc = e->zChunk; + if (e->inChunk && hasChunk(xc, zc)) + { + getChunk(xc, zc)->removeEntity(e); + } } } // 4J Stu - Is there a reason do this in a separate loop? Thats what the Java does... - endIt = entitiesToRemove.end(); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != endIt; it++) + for (auto& it : entitiesToRemove) { - entityRemoved(*it); + if ( it ) + entityRemoved(it); } entitiesToRemove.clear(); //for (int i = 0; i < entities.size(); i++) EnterCriticalSection(&m_entitiesCS); - vector<shared_ptr<Entity> >::iterator it = entities.begin(); + auto it = entities.begin(); while( it != entities.end() ) { shared_ptr<Entity> e = *it;//entities.at(i); @@ -865,7 +867,7 @@ void MultiPlayerLevel::removeAllPendingEntityRemovals() e->riding->rider = weak_ptr<Entity>(); e->riding = nullptr; } - else + else { ++it; continue; @@ -900,8 +902,8 @@ void MultiPlayerLevel::removeClientConnection(ClientConnection *c, bool sendDisc c->sendAndDisconnect( shared_ptr<DisconnectPacket>( new DisconnectPacket(DisconnectPacket::eDisconnect_Quitting) ) ); } - AUTO_VAR(it, find( connections.begin(), connections.end(), c )); - if( it != connections.end() ) + auto it = find(connections.begin(), connections.end(), c); + if( it != connections.end() ) { connections.erase( it ); } @@ -910,9 +912,10 @@ void MultiPlayerLevel::removeClientConnection(ClientConnection *c, bool sendDisc void MultiPlayerLevel::tickAllConnections() { PIXBeginNamedEvent(0,"Connection ticking"); - for(AUTO_VAR(it, connections.begin()); it < connections.end(); ++it ) - { - (*it)->tick(); + for (auto& it : connections ) + { + if ( it ) + it->tick(); } PIXEndNamedEvent(); } diff --git a/Minecraft.Client/Options.cpp b/Minecraft.Client/Options.cpp index c18c136b..fac7fe13 100644 --- a/Minecraft.Client/Options.cpp +++ b/Minecraft.Client/Options.cpp @@ -328,7 +328,7 @@ wstring Options::getMessage(const Options::Option *item) { return caption + language->getElement(L"options.sensitivity.max"); } - return caption + _toString<int>((int) (progressValue * 200)) + L"%"; + return caption + std::to_wstring(static_cast<int>(progressValue * 200)) + L"%"; } else if (item == Option::FOV) { if (progressValue == 0) @@ -339,7 +339,7 @@ wstring Options::getMessage(const Options::Option *item) { return caption + language->getElement(L"options.fov.max"); } - return caption + _toString<int>((int) (70 + progressValue * 40)); + return caption + std::to_wstring(static_cast<int>(70.0f + progressValue * 40.0f)); } else if (item == Option::GAMMA) { if (progressValue == 0) @@ -350,7 +350,7 @@ wstring Options::getMessage(const Options::Option *item) { return caption + language->getElement(L"options.gamma.max"); } - return caption + L"+" + _toString<int>((int) (progressValue * 100)) + L"%"; + return caption + L"+" + std::to_wstring( static_cast<int>(progressValue * 100.0f)) + L"%"; } else { @@ -358,7 +358,7 @@ wstring Options::getMessage(const Options::Option *item) { return caption + language->getElement(L"options.off"); } - return caption + _toString<int>((int) (progressValue * 100)) + L"%"; + return caption + std::to_wstring(static_cast<int>(progressValue * 100.0f)) + L"%"; } } else if (item->isBoolean()) { @@ -410,7 +410,7 @@ void Options::load() if (!optionsFile.exists()) return; // 4J - was new BufferedReader(new FileReader(optionsFile)); BufferedReader *br = new BufferedReader(new InputStreamReader( new FileInputStream( optionsFile ) ) ); - + wstring line = L""; while ((line = br->readLine()) != L"") // 4J - was check against NULL - do we need to distinguish between empty lines and a fail here? { @@ -486,29 +486,29 @@ void Options::save() DataOutputStream dos = DataOutputStream(&fos); // PrintWriter pw = new PrintWriter(new FileWriter(optionsFile)); - dos.writeChars(L"music:" + _toString<float>(music) + L"\n"); - dos.writeChars(L"sound:" + _toString<float>(sound) + L"\n"); + dos.writeChars(L"music:" + std::to_wstring(music) + L"\n"); + dos.writeChars(L"sound:" + std::to_wstring(sound) + L"\n"); dos.writeChars(L"invertYMouse:" + wstring(invertYMouse ? L"true" : L"false") + L"\n"); - dos.writeChars(L"mouseSensitivity:" + _toString<float>(sensitivity)); - dos.writeChars(L"fov:" + _toString<float>(fov)); - dos.writeChars(L"gamma:" + _toString<float>(gamma)); - dos.writeChars(L"viewDistance:" + _toString<int>(viewDistance)); - dos.writeChars(L"guiScale:" + _toString<int>(guiScale)); - dos.writeChars(L"particles:" + _toString<int>(particles)); + dos.writeChars(L"mouseSensitivity:" + std::to_wstring(sensitivity)); + dos.writeChars(L"fov:" + std::to_wstring(fov)); + dos.writeChars(L"gamma:" + std::to_wstring(gamma)); + dos.writeChars(L"viewDistance:" + std::to_wstring(viewDistance)); + dos.writeChars(L"guiScale:" + std::to_wstring(guiScale)); + dos.writeChars(L"particles:" + std::to_wstring(particles)); dos.writeChars(L"bobView:" + wstring(bobView ? L"true" : L"false")); dos.writeChars(L"anaglyph3d:" + wstring(anaglyph3d ? L"true" : L"false")); dos.writeChars(L"advancedOpengl:" + wstring(advancedOpengl ? L"true" : L"false")); - dos.writeChars(L"fpsLimit:" + _toString<int>(framerateLimit)); - dos.writeChars(L"difficulty:" + _toString<int>(difficulty)); + dos.writeChars(L"fpsLimit:" + std::to_wstring(framerateLimit)); + dos.writeChars(L"difficulty:" + std::to_wstring(difficulty)); dos.writeChars(L"fancyGraphics:" + wstring(fancyGraphics ? L"true" : L"false")); - dos.writeChars(L"ao:" + wstring(ambientOcclusion ? L"true" : L"false")); - dos.writeChars(L"clouds:" + _toString<bool>(renderClouds)); + dos.writeChars(ambientOcclusion ? L"ao:true" : L"ao:false"); + dos.writeChars(renderClouds ? L"clouds:true" : L"clouds:false"); dos.writeChars(L"skin:" + skin); dos.writeChars(L"lastServer:" + lastMpIp); for (int i = 0; i < keyMappings_length; i++) { - dos.writeChars(L"key_" + keyMappings[i]->name + L":" + _toString<int>(keyMappings[i]->key)); + dos.writeChars(L"key_" + keyMappings[i]->name + L":" + std::to_wstring(keyMappings[i]->key)); } dos.close(); diff --git a/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.cpp b/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.cpp index 5c02cb08..650683b0 100644 --- a/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.cpp +++ b/Minecraft.Client/Orbis/Network/SQRNetworkManager_Orbis.cpp @@ -51,7 +51,7 @@ int g_numRUDPContextsBound = 0; //unsigned int SQRNetworkManager_Orbis::RoomSyncData::playerCount = 0; // This maps internal to extern states, and needs to match element-by-element the eSQRNetworkManagerInternalState enumerated type -const SQRNetworkManager_Orbis::eSQRNetworkManagerState SQRNetworkManager_Orbis::m_INTtoEXTStateMappings[SQRNetworkManager_Orbis::SNM_INT_STATE_COUNT] = +const SQRNetworkManager_Orbis::eSQRNetworkManagerState SQRNetworkManager_Orbis::m_INTtoEXTStateMappings[SQRNetworkManager_Orbis::SNM_INT_STATE_COUNT] = { SNM_STATE_INITIALISING, // SNM_INT_STATE_UNINITIALISED SNM_STATE_INITIALISING, // SNM_INT_STATE_SIGNING_IN @@ -143,7 +143,7 @@ void SQRNetworkManager_Orbis::Initialise() assert( m_state == SNM_INT_STATE_UNINITIALISED ); - + //Initialize libnetctl ret = sceNetCtlInit(); if( ( ret < 0 /*&& ret != CELL_NET_CTL_ERROR_NOT_TERMINATED*/ ) || ForceErrorPoint( SNM_FORCE_ERROR_NET_CTL_INIT ) ) @@ -172,14 +172,14 @@ void SQRNetworkManager_Orbis::Initialise() SonyHttp::init(); ret = sceNpSetNpTitleId(GetSceNpTitleId(), GetSceNpTitleSecret()); - if (ret < 0) + if (ret < 0) { app.DebugPrintf("sceNpSetNpTitleId failed, ret=%x\n", ret); assert(0); } ret = sceRudpEnableInternalIOThread(RUDP_THREAD_STACK_SIZE, RUDP_THREAD_PRIORITY); - if(ret < 0) + if(ret < 0) { app.DebugPrintf("sceRudpEnableInternalIOThread failed with error code 0x%08x\n", ret); assert(0); @@ -192,7 +192,7 @@ void SQRNetworkManager_Orbis::Initialise() else { // On Orbis, PSN sign in is only handled by the XMB - SetState(SNM_INT_STATE_IDLE); + SetState(SNM_INT_STATE_IDLE); } SonyVoiceChat_Orbis::init(); @@ -299,7 +299,7 @@ void SQRNetworkManager_Orbis::InitialiseAfterOnline() ret = sceNpMatching2CreateContext(¶m, &m_matchingContext); - + if( ( ret < 0 ) || ForceErrorPoint( SNM_FORCE_ERROR_CREATE_MATCHING_CONTEXT ) ) { app.DebugPrintf("SQRNetworkManager_Orbis::InitialiseAfterOnline - sceNpMatching2CreateContext failed with error 0x%08x\n", ret); @@ -398,7 +398,7 @@ void SQRNetworkManager_Orbis::Tick() { // make sure we've removed all the remote players and killed the udp connections before we bail out if(m_RudpCtxToPlayerMap.size() == 0) - ResetToIdle(); + ResetToIdle(); } EnterCriticalSection(&m_csStateChangeQueue); @@ -451,7 +451,7 @@ void SQRNetworkManager_Orbis::tickErrorDialog() if(s_errorDialogRunning) { SceErrorDialogStatus s = sceErrorDialogUpdateStatus(); - switch (s) + switch (s) { case SCE_ERROR_DIALOG_STATUS_NONE: assert(0); @@ -465,9 +465,9 @@ void SQRNetworkManager_Orbis::tickErrorDialog() case SCE_ERROR_DIALOG_STATUS_FINISHED: sceErrorDialogTerminate(); s_errorDialogRunning = false; - + // Start callback timer - s_SignInCompleteCallbackPending = true; + s_SignInCompleteCallbackPending = true; s_errorDialogClosed = System::currentTimeMillis(); break; } @@ -490,9 +490,9 @@ void SQRNetworkManager_Orbis::tickErrorDialog() SceSystemServiceStatus status = SceSystemServiceStatus(); sceSystemServiceGetStatus(&status); bool systemUiDisplayed = status.isInBackgroundExecution || status.isSystemUiOverlaid; - + if (systemUiDisplayed) - { + { // Wait till the system goes away } else @@ -583,7 +583,7 @@ void SQRNetworkManager_Orbis::ErrorHandlingTick() DeleteServerContext(); break; } - + } // Start hosting a game, by creating a room & joining it. We explicity create a server context here (via GetServerContext) as Sony suggest that @@ -643,7 +643,7 @@ void SQRNetworkManager_Orbis::UpdateExternalRoomData() { if( m_offlineGame ) return; if( m_isHosting ) - { + { SceNpMatching2SetRoomDataExternalRequest reqParam; memset( &reqParam, 0, sizeof(reqParam) ); reqParam.roomId = m_room; @@ -774,13 +774,13 @@ int SQRNetworkManager_Orbis::BasicEventThreadProc( void *lpParameter ) do { ret = sceKernelWaitEqueue(manager->m_basicEventQueue, &event, 1, &outEv, NULL); - + // If the sys_event_t we've sent here from the handler has a non-zero data1 element, this is to signify that we should terminate the thread if( event.udata == 0 ) { // int iEvent; // SceNpUserInfo from; -// uint8_t buffer[SCE_NP_BASIC_MAX_MESSAGE_SIZE]; +// uint8_t buffer[SCE_NP_BASIC_MAX_MESSAGE_SIZE]; // size_t bufferSize = SCE_NP_BASIC_MAX_MESSAGE_SIZE; // int ret = sceNpBasicGetEvent(&iEvent, &from, &buffer, &bufferSize); // if( ret == 0 ) @@ -788,7 +788,7 @@ int SQRNetworkManager_Orbis::BasicEventThreadProc( void *lpParameter ) // if( iEvent == SCE_NP_BASIC_EVENT_INCOMING_BOOTABLE_INVITATION ) // { // // 4J Stu - Don't do this here as it can be very disruptive to gameplay. Players can bring this up from LoadOrJoinMenu, PauseMenu and InGameInfoMenu -// //sceNpBasicRecvMessageCustom(SCE_NP_BASIC_MESSAGE_MAIN_TYPE_INVITE, SCE_NP_BASIC_RECV_MESSAGE_OPTIONS_INCLUDE_BOOTABLE, SYS_MEMORY_CONTAINER_ID_INVALID); +// //sceNpBasicRecvMessageCustom(SCE_NP_BASIC_MESSAGE_MAIN_TYPE_INVITE, SCE_NP_BASIC_RECV_MESSAGE_OPTIONS_INCLUDE_BOOTABLE, SYS_MEMORY_CONTAINER_ID_INVALID); // } // if( iEvent == SCE_NP_BASIC_EVENT_RECV_INVITATION_RESULT ) // { @@ -835,12 +835,12 @@ int SQRNetworkManager_Orbis::GetFriendsThreadProc( void* lpParameter ) return 0; } - if (friendList.hasResult()) + if (friendList.hasResult()) { - sce::Toolkit::NP::FriendsList::const_iterator iter ; + sce::Toolkit::NP::FriendsList::const_iterator iter ; int i = 1 ; bool noFriends = true; - for (iter = friendList.get()->begin(); iter != friendList.get()->end() ; ++iter,i++) + for (iter = friendList.get()->begin(); iter != friendList.get()->end() ; ++iter,i++) { manager->m_friendCount++; noFriends = false; @@ -848,7 +848,7 @@ int SQRNetworkManager_Orbis::GetFriendsThreadProc( void* lpParameter ) app.DebugPrintf("Online Name: %s\n",iter->npid.handle.data); app.DebugPrintf("------------------------\n"); - + sce::Toolkit::NP::PresenceRequest presenceRequest; sce::Toolkit::NP::Utilities::Future<sce::Toolkit::NP::PresenceInfo> presenceInfo; memset(&presenceRequest,0,sizeof(presenceRequest)); @@ -858,11 +858,11 @@ int SQRNetworkManager_Orbis::GetFriendsThreadProc( void* lpParameter ) ret = sce::Toolkit::NP::Presence::Interface::getPresence(&presenceRequest,&presenceInfo,false); - if( ret < 0 ) + if( ret < 0 ) { app.DebugPrintf("getPresence() error. ret = 0x%x\n", ret); } - else + else { app.DebugPrintf("\nPresence Data Retrieved:\n"); app.DebugPrintf("Platform Type: %s\n", presenceInfo.get()->platformType.c_str()); @@ -897,13 +897,13 @@ int SQRNetworkManager_Orbis::GetFriendsThreadProc( void* lpParameter ) } } } - else if (friendList.hasError()) + else if (friendList.hasError()) { app.DebugPrintf( "Error occurred while retrieving FriendsList, ret = 0x%x\n", friendList.getError()); app.DebugPrintf("Check sign-in status\n"); } - + return 0; } @@ -944,7 +944,7 @@ bool SQRNetworkManager_Orbis::IsReadyToPlayOrIdle() // Consider as "in session" from the moment that a game is created or joined, until the point where the game itself has been told via state change that we are now idle. The -// game code requires IsInSession to return true as soon as it has asked to do one of these things (even if the state system hasn't really caught up with this request yet), and +// game code requires IsInSession to return true as soon as it has asked to do one of these things (even if the state system hasn't really caught up with this request yet), and // it also requires that it is informed of the state changes leading up to not being in the session, before this should report false. bool SQRNetworkManager_Orbis::IsInSession() { @@ -1119,7 +1119,7 @@ bool SQRNetworkManager_Orbis::JoinRoom(SceNpMatching2RoomId roomId, SceNpMatchin m_localPlayerJoinMask = localPlayerMask; m_localPlayerCount = 0; m_localPlayerJoined = 0; - + for( int i = 0; i < MAX_LOCAL_PLAYER_COUNT; i++ ) { if( localPlayerMask & ( 1 << i ) ) m_localPlayerCount++; @@ -1240,7 +1240,7 @@ bool SQRNetworkManager_Orbis::AddLocalPlayerByUserIndex(int idx) // Sync this back out to our networked clients... SyncRoomData(); - + UpdateRemotePlay(); // no connections being made because we're all on the host, so add this player to the existing connections @@ -1264,7 +1264,7 @@ bool SQRNetworkManager_Orbis::AddLocalPlayerByUserIndex(int idx) memset(&reqParam, 0, sizeof(reqParam)); memset(&binAttr, 0, sizeof(binAttr)); - + binAttr.id = SCE_NP_MATCHING2_ROOMMEMBER_BIN_ATTR_INTERNAL_1_ID; binAttr.ptr = &m_localPlayerJoinMask; binAttr.size = sizeof(m_localPlayerJoinMask); @@ -1357,7 +1357,7 @@ bool SQRNetworkManager_Orbis::RemoveLocalPlayerByUserIndex(int idx) memset(&reqParam, 0, sizeof(reqParam)); memset(&binAttr, 0, sizeof(binAttr)); - + binAttr.id = SCE_NP_MATCHING2_ROOMMEMBER_BIN_ATTR_INTERNAL_1_ID; binAttr.ptr = &m_localPlayerJoinMask; binAttr.size = sizeof(m_localPlayerJoinMask); @@ -1395,7 +1395,7 @@ void SQRNetworkManager_Orbis::UpdateRemotePlay() extern uint8_t *mallocAndCreateUTF8ArrayFromString(int iID); -// Bring up a Gui to send an invite so a player that the user can select. This invite will contain the room Id so that +// Bring up a Gui to send an invite so a player that the user can select. This invite will contain the room Id so that void SQRNetworkManager_Orbis::SendInviteGUI() { if(s_bInviteDialogRunning) @@ -1403,7 +1403,7 @@ void SQRNetworkManager_Orbis::SendInviteGUI() app.DebugPrintf("SendInviteGUI - Invite dialog is already running so ignoring request\n"); return; } - + s_bInviteDialogRunning = true; //Set invitation information - this is now exactly the same as the presence information that we synchronise out. @@ -1428,7 +1428,7 @@ void SQRNetworkManager_Orbis::SendInviteGUI() messData.dialogFlag = SCE_TOOLKIT_NP_DIALOG_TYPE_USER_EDITABLE; messData.npIdsCount = 2; // TODO: Set this to the number of available slots messData.npIds = NULL; - messData.userInfo.userId = userId; + messData.userInfo.userId = userId; // Set expire to maximum messData.expireMinutes = 0; @@ -1451,9 +1451,9 @@ void SQRNetworkManager_Orbis::SendInviteGUI() // int ret = sce::Toolkit::NP::Messaging::Interface::sendMessage(&messData, SCE_TOOLKIT_NP_MESSAGE_TYPE_INVITE); free(subject); - free(body); + free(body); - if(ret < SCE_TOOLKIT_NP_SUCCESS ) + if(ret < SCE_TOOLKIT_NP_SUCCESS ) { s_bInviteDialogRunning = false; app.DebugPrintf("Send Message failed 0x%x ...\n",ret); @@ -1513,7 +1513,7 @@ void SQRNetworkManager_Orbis::TickInviteGUI() int32_t ret = sceGameCustomDataDialogGetResult( &dialogResult ); if( SCE_OK != ret ) - { + { app.DebugPrintf( "***** sceGameCustomDataDialogGetResult error:0x%x\n", ret); } sceGameCustomDataDialogClose(); @@ -1536,7 +1536,7 @@ void SQRNetworkManager_Orbis::GetInviteDataAndProcess(sce::Toolkit::NP::MessageA } // InvitationInfoRequest requestInfo; // sce::Toolkit::NP::Utilities::Future< NpSessionInvitationInfo > inviteInfo; -// +// // requestInfo.invitationId = pInvite->invitationId; // requestInfo.userInfo.npId = pInvite->onlineId; // int err = sce::Toolkit::NP::Sessions::Interface::getInvitationInfo(&requestInfo, &inviteInfo, false); @@ -1555,21 +1555,21 @@ void SQRNetworkManager_Orbis::GetInviteDataAndProcess(sce::Toolkit::NP::MessageA // { // app.DebugPrintf("getInvitationInfo error 0x%08x", err); // } -// -// -// +// +// +// // INVITE_INFO *invite = &m_inviteReceived[m_inviteIndex]; // m_inviteIndex = ( m_inviteIndex + 1 ) % MAX_SIMULTANEOUS_INVITES; // size_t dataSize = sizeof(INVITE_INFO); // int ret = sceNpBasicRecvMessageAttachmentLoad(id, invite, &dataSize); -// +// // // If we fail ( which we might do if we aren't online at this point) then zero the invite information and we'll try and get it later after (possibly) signing in // if( ret != 0 ) // { // memset(invite, 0, sizeof( INVITE_INFO ) ); // s_lastInviteIdToRetry = id; // } -// +// // m_gameBootInvite = invite; } @@ -1588,8 +1588,8 @@ void SQRNetworkManager_Orbis::GetInviteDataAndProcess(sce::Toolkit::NP::MessageA // and there's a period when starting up the host game where it doesn't accurately know the memberId for its own local players void SQRNetworkManager_Orbis::FindOrCreateNonNetworkPlayer(int slot, int playerType, SceNpMatching2RoomMemberId memberId, int localPlayerIdx, int smallId) { - for(AUTO_VAR(it, m_vecTempPlayers.begin()); it != m_vecTempPlayers.end(); it++ ) - { + for (auto it = m_vecTempPlayers.begin(); it != m_vecTempPlayers.end(); it++) + { if( ((*it)->m_type == playerType ) && ( (*it)->m_localPlayerIdx == localPlayerIdx ) ) { if( ( playerType != SQRNetworkPlayer::SNP_TYPE_REMOTE ) || ( (*it)->m_roomMemberId == memberId ) ) @@ -1647,7 +1647,7 @@ void SQRNetworkManager_Orbis::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) { EnterCriticalSection(&m_csRoomSyncData); - // If we pass an explicit roomSlotPlayerCount, it is because we are removing a player, and this is the count of slots that there were *before* the removal. + // If we pass an explicit roomSlotPlayerCount, it is because we are removing a player, and this is the count of slots that there were *before* the removal. bool zeroLastSlot = false; if( roomSlotPlayerCount == -1 ) { @@ -1751,7 +1751,7 @@ void SQRNetworkManager_Orbis::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) } else { - FindOrCreateNonNetworkPlayer( i, SQRNetworkPlayer::SNP_TYPE_REMOTE, m_roomSyncData.players[i].m_roomMemberId, m_roomSyncData.players[i].m_localIdx, m_roomSyncData.players[i].m_smallId); + FindOrCreateNonNetworkPlayer( i, SQRNetworkPlayer::SNP_TYPE_REMOTE, m_roomSyncData.players[i].m_roomMemberId, m_roomSyncData.players[i].m_localIdx, m_roomSyncData.players[i].m_smallId); m_aRoomSlotPlayers[i]->SetUID(m_roomSyncData.players[i].m_UID); // On client, UIDs flow from m_roomSyncData->player data } } @@ -1759,8 +1759,8 @@ void SQRNetworkManager_Orbis::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) } // Clear up any non-network players that are no longer required - this would be a good point to notify of players leaving when we support that // FindOrCreateNonNetworkPlayer will have pulled any players that we Do need out of m_vecTempPlayers, so the ones that are remaining are no longer in the game - for(AUTO_VAR(it, m_vecTempPlayers.begin()); it != m_vecTempPlayers.end(); it++ ) - { + for (auto it = m_vecTempPlayers.begin(); it != m_vecTempPlayers.end(); it++) + { if( m_listener ) { m_listener->HandlePlayerLeaving(*it); @@ -1844,7 +1844,7 @@ bool SQRNetworkManager_Orbis::AddRemotePlayersAndSync( SceNpMatching2RoomMemberI } // We want to keep all players from a particular machine together, so search through the room sync data to see if we can find - // any pre-existing players from this machine. + // any pre-existing players from this machine. int firstIdx = -1; for( int i = 0; i < m_roomSyncData.getPlayerCount(); i++ ) { @@ -1950,7 +1950,7 @@ void SQRNetworkManager_Orbis::RemoveRemotePlayersAndSync( SceNpMatching2RoomMemb // Update mapping from the room slot players to SQRNetworkPlayer instances MapRoomSlotPlayers(); - + // And then synchronise this out to all other machines SyncRoomData(); @@ -1964,8 +1964,8 @@ void SQRNetworkManager_Orbis::RemoveNetworkPlayers( int mask ) { assert( !m_isHosting ); - for(AUTO_VAR(it, m_RudpCtxToPlayerMap.begin()); it != m_RudpCtxToPlayerMap.end(); ) - { + for (auto it = m_RudpCtxToPlayerMap.begin(); it != m_RudpCtxToPlayerMap.end();) + { SQRNetworkPlayer *player = it->second; if( (player->m_roomMemberId == m_localMemberId ) && ( ( 1 << player->m_localPlayerIdx ) & mask ) ) { @@ -1993,7 +1993,7 @@ void SQRNetworkManager_Orbis::RemoveNetworkPlayers( int mask ) removePlayerFromVoiceChat(player); // Delete the player itself and the mapping from context to player map as this context is no longer valid - delete player; + delete player; } else { @@ -2107,7 +2107,7 @@ bool SQRNetworkManager_Orbis::GetMatchingContext(eSQRNetworkManagerInternalState // Starts the process of obtaining a server context. This is an asynchronous operation, at the end of which (if successful), we'll be creating // a room. General procedure followed here is as suggested by Sony - we get a list of servers, then pick a random one, and see if it is available. -// If not we just cycle round trying other random ones until we either find an available one or fail. +// If not we just cycle round trying other random ones until we either find an available one or fail. bool SQRNetworkManager_Orbis::GetServerContext() { assert(m_state == SNM_INT_STATE_IDLE); @@ -2165,7 +2165,7 @@ bool SQRNetworkManager_Orbis::GetServerContext(SceNpMatching2ServerId serverId) // ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED ) ) // Also checking for this as a means of simulating the previous error // { // sceNpMatching2DestroyContext(m_matchingContext); -// m_matchingContextValid = false; +// m_matchingContextValid = false; // if( !GetMatchingContext(SNM_INT_STATE_JOINING_STARTING_MATCHING_CONTEXT) ) return false; // } // } @@ -2298,7 +2298,7 @@ void SQRNetworkManager_Orbis::NetworkPlayerConnectionComplete(SQRNetworkPlayer * if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2327,7 +2327,7 @@ void SQRNetworkManager_Orbis::NetworkPlayerSmallIdAllocated(SQRNetworkPlayer *pl if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2345,7 +2345,7 @@ void SQRNetworkManager_Orbis::NetworkPlayerInitialDataReceived(SQRNetworkPlayer if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2361,7 +2361,7 @@ void SQRNetworkManager_Orbis::HandlePlayerJoined(SQRNetworkPlayer *player) { if( m_listener ) { - m_listener->HandlePlayerJoined( player ); + m_listener->HandlePlayerJoined( player ); } app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> HandlePlayerJoined\n"); @@ -2425,7 +2425,7 @@ std::string getIPAddressString(SceNetInAddr add) { char str[32]; unsigned char *vals = (unsigned char*)&add.s_addr; - sprintf(str, "%d.%d.%d.%d", (int)vals[0], (int)vals[1], (int)vals[2], (int)vals[3]); + sprintf(str, "%d.%d.%d.%d", (int)vals[0], (int)vals[1], (int)vals[2], (int)vals[3]); return std::string(str); } @@ -2495,7 +2495,7 @@ bool SQRNetworkManager_Orbis::CreateVoiceRudpConnections(SceNpMatching2RoomId ro SQRVoiceConnection* pConnection = SonyVoiceChat_Orbis::getVoiceConnectionFromRoomMemberID(peerMemberId); if(pConnection == NULL) { - + // Create an Rudp context for the voice connection, this will happen regardless of whether the peer is client or host int rudpCtx; ret = sceRudpCreateContext( RudpContextCallback, this, &rudpCtx ); @@ -2510,7 +2510,7 @@ bool SQRNetworkManager_Orbis::CreateVoiceRudpConnections(SceNpMatching2RoomId ro g_numRUDPContextsBound++; app.DebugPrintf(sc_verbose, "-----------------::::::::::::: sceRudpBind\n" ); - ret = sceRudpInitiate( rudpCtx, (SceNetSockaddr*)&sinp2pPeer, sizeof(sinp2pPeer), 0); + ret = sceRudpInitiate( rudpCtx, (SceNetSockaddr*)&sinp2pPeer, sizeof(sinp2pPeer), 0); if(ret < 0){ app.DebugPrintf("sceRudpInitiate %s failed : 0x%08x\n", getIPAddressString(sinp2pPeer.sin_addr).c_str(), ret); assert(0); } if ( ( ret < 0 ) || ForceErrorPoint(SNM_FORCE_ERROR_RUDP_INIT2) ) return false; app.DebugPrintf(sc_verbose, "-----------------::::::::::::: sceRudpInitiate\n" ); @@ -2521,7 +2521,7 @@ bool SQRNetworkManager_Orbis::CreateVoiceRudpConnections(SceNpMatching2RoomId ro pConnection = SonyVoiceChat_Orbis::addRemoteConnection(rudpCtx, peerMemberId); } - + for( int i = 0; i < MAX_LOCAL_PLAYER_COUNT; i++ ) { bool bMaskVal = ( playerMask & ( 1 << i ) ); @@ -2544,11 +2544,11 @@ bool SQRNetworkManager_Orbis::CreateRudpConnections(SceNpMatching2RoomId roomId, memset(&sinp2pPeer, 0, sizeof(sinp2pPeer)); sinp2pPeer.sin_len = sizeof(sinp2pPeer); sinp2pPeer.sin_family = AF_INET; - + int ret = sceNpMatching2SignalingGetConnectionStatus(m_matchingContext, roomId, peerMemberId, &connStatus, &sinp2pPeer.sin_addr, &sinp2pPeer.sin_port); app.DebugPrintf(CMinecraftApp::USER_RR,"sceNpMatching2SignalingGetConnectionStatus returned 0x%x, connStatus %d peer add:%s peer port:0x%x\n",ret, connStatus,getIPAddressString(sinp2pPeer.sin_addr).c_str(),sinp2pPeer.sin_port); - // Set vport + // Set vport sinp2pPeer.sin_vport = sceNetHtons(1); // Create socket & bind, if we don't already have one @@ -2606,8 +2606,8 @@ bool SQRNetworkManager_Orbis::CreateRudpConnections(SceNpMatching2RoomId roomId, SQRNetworkPlayer *SQRNetworkManager_Orbis::GetPlayerFromRudpCtx(int rudpCtx) { - AUTO_VAR(it,m_RudpCtxToPlayerMap.find(rudpCtx)); - if( it != m_RudpCtxToPlayerMap.end() ) + auto it = m_RudpCtxToPlayerMap.find(rudpCtx); + if( it != m_RudpCtxToPlayerMap.end() ) { return it->second; } @@ -2618,8 +2618,8 @@ SQRNetworkPlayer *SQRNetworkManager_Orbis::GetPlayerFromRudpCtx(int rudpCtx) SQRNetworkPlayer *SQRNetworkManager_Orbis::GetPlayerFromRoomMemberAndLocalIdx(int roomMember, int localIdx) { - for(AUTO_VAR(it, m_RudpCtxToPlayerMap.begin()); it != m_RudpCtxToPlayerMap.end(); it++ ) - { + for (auto it = m_RudpCtxToPlayerMap.begin(); it != m_RudpCtxToPlayerMap.end(); it++) + { if( (it->second->m_roomMemberId == roomMember ) && ( it->second->m_localPlayerIdx == localIdx ) ) { return it->second; @@ -2706,7 +2706,7 @@ void SQRNetworkManager_Orbis::ContextCallback(SceNpMatching2ContextId id, SceNp manager->m_state == SNM_INT_STATE_HOSTING_STARTING_MATCHING_CONTEXT || manager->m_state == SNM_INT_STATE_JOINING_STARTING_MATCHING_CONTEXT) { - // matching context failed to start (this can happen when you block the IP addresses of the matching servers on your router + // matching context failed to start (this can happen when you block the IP addresses of the matching servers on your router // agent-0101.ww.sp-int.matching.playstation.net (198.107.157.191) // static-resource.sp-int.community.playstation.net (203.105.77.140) app.DebugPrintf("SQRNetworkManager_Orbis::ContextCallback - Error\n"); @@ -2771,7 +2771,7 @@ void SQRNetworkManager_Orbis::ContextCallback(SceNpMatching2ContextId id, SceNp // unsigned int type, attributes; // CellGameContentSize gameSize;` // char dirName[CELL_GAME_DIRNAME_SIZE]; -// +// // if( g_bBootedFromInvite ) // { // manager->GetInviteDataAndProcess(SCE_NP_BASIC_SELECTED_INVITATION_DATA); @@ -2789,7 +2789,7 @@ void SQRNetworkManager_Orbis::ContextCallback(SceNpMatching2ContextId id, SceNp assert(false); break; case SCE_NP_MATCHING2_CONTEXT_EVENT_START_OVER: - + app.DebugPrintf("SCE_NP_MATCHING2_CONTEXT_EVENT_START_OVER\n"); app.DebugPrintf("eventCause=%u, errorCode=0x%08x\n", eventCause, errorCode); @@ -2950,7 +2950,7 @@ void SQRNetworkManager_Orbis::DefaultRequestCallback(SceNpMatching2ContextId id, if( success1 ) { success2 = manager->CreateRudpConnections(manager->m_room, pRoomMemberData->roomMemberDataInternal->memberId, playerMask, pRoomMemberData->roomMemberDataInternal->memberId); - if( success2 ) + if( success2 ) { bool ret = manager->CreateVoiceRudpConnections( manager->m_room, pRoomMemberData->roomMemberDataInternal->memberId, 0); assert(ret == true); @@ -3055,7 +3055,7 @@ void SQRNetworkManager_Orbis::DefaultRequestCallback(SceNpMatching2ContextId id, void SQRNetworkManager_Orbis::RoomEventCallback(SceNpMatching2ContextId id, SceNpMatching2RoomId roomId, SceNpMatching2Event event, const void *data, void *arg) { SQRNetworkManager_Orbis *manager = (SQRNetworkManager_Orbis *)arg; - + bool gotEventData = false; switch( event ) { @@ -3186,7 +3186,7 @@ void SQRNetworkManager_Orbis::RoomEventCallback(SceNpMatching2ContextId id, SceN int oldMask = manager->GetOldMask( pRoomMemberData->newRoomMemberDataInternal->memberId ); int addedMask = manager->GetAddedMask(playerMask, oldMask ); int removedMask = manager->GetRemovedMask(playerMask, oldMask ); - + if( addedMask != 0 ) { bool success = manager->AddRemotePlayersAndSync( pRoomMemberData->newRoomMemberDataInternal->memberId, addedMask ); @@ -3203,7 +3203,7 @@ void SQRNetworkManager_Orbis::RoomEventCallback(SceNpMatching2ContextId id, SceN memset(&reqParam, 0, sizeof(reqParam)); memset(&binAttr, 0, sizeof(binAttr)); - + binAttr.id = SCE_NP_MATCHING2_ROOMMEMBER_BIN_ATTR_INTERNAL_1_ID; binAttr.ptr = &oldMask; binAttr.size = sizeof(oldMask); @@ -3265,7 +3265,7 @@ void SQRNetworkManager_Orbis::RoomEventCallback(SceNpMatching2ContextId id, SceN } } } - + } } break; @@ -3426,7 +3426,7 @@ void SQRNetworkManager_Orbis::SysUtilCallback(uint64_t status, uint64_t param, v // } // return; // } -// +// // if( netstart_result.result != 0 ) // { // // Failed, or user may have decided not to sign in - maybe need to differentiate here @@ -3440,7 +3440,7 @@ void SQRNetworkManager_Orbis::SysUtilCallback(uint64_t status, uint64_t param, v // s_SignInCompleteCallbackFn = NULL; // } // } -// +// // break; // case CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED: // break; @@ -3608,7 +3608,7 @@ void SQRNetworkManager_Orbis::NetCtlCallback(int eventType, void *arg) if( eventType == SCE_NET_CTL_EVENT_TYPE_DISCONNECTED)// CELL_NET_CTL_EVENT_LINK_DISCONNECTED ) { manager->m_bLinkDisconnected = true; - manager->m_listener->HandleDisconnect(false); + manager->m_listener->HandleDisconnect(false); } else //if( event == CELL_NET_CTL_EVENT_ESTABLISH ) { @@ -3762,7 +3762,7 @@ void SQRNetworkManager_Orbis::GetExtDataForRoom( SceNpMatching2RoomId roomId, vo if( ret == SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED ) // Also checking for this as a means of simulating the previous error { sceNpMatching2DestroyContext(m_matchingContext); - m_matchingContextValid = false; + m_matchingContextValid = false; if( !GetMatchingContext(SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT) ) { // No matching context, and failed to try and make one. We're really broken here. @@ -3789,7 +3789,7 @@ bool SQRNetworkManager_Orbis::ForceErrorPoint(eSQRForceError error) return false; } #else -bool SQRNetworkManager_Orbis::aForceError[SNM_FORCE_ERROR_COUNT] = +bool SQRNetworkManager_Orbis::aForceError[SNM_FORCE_ERROR_COUNT] = { false, // SNM_FORCE_ERROR_NP2_INIT false, // SNM_FORCE_ERROR_NET_INITIALIZE_NETWORK @@ -3919,7 +3919,7 @@ void SQRNetworkManager_Orbis::AttemptPSNSignIn(int (*SignInCompleteCallbackFn)(v ui.RequestMessageBox( IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA,1,iPad,ErrorPSNDisconnectedDialogReturned,pParam, app.GetStringTable()); } -} +} int SQRNetworkManager_Orbis::SetRichPresence(const void *data) { @@ -3971,13 +3971,13 @@ void SQRNetworkManager_Orbis::SendLastPresenceInfo() // On PS4 we can't set the status and the data at the same time unsigned int options = 0; - if( s_presenceDataDirty ) + if( s_presenceDataDirty ) { // Prioritise data over status as it is critical to discovering the network game s_lastPresenceInfo.presenceType = SCE_TOOLKIT_NP_PRESENCE_DATA; } - else if( s_presenceStatusDirty ) - { + else if( s_presenceStatusDirty ) + { s_lastPresenceInfo.presenceType = SCE_TOOLKIT_NP_PRESENCE_STATUS; } else @@ -4065,7 +4065,7 @@ void SQRNetworkManager_Orbis::removePlayerFromVoiceChat( SQRNetworkPlayer* pPlay { if(pPlayer->IsLocal()) { - + SonyVoiceChat_Orbis::disconnectLocalPlayer(pPlayer->GetLocalPlayerIndex()); } else @@ -4097,7 +4097,7 @@ void SQRNetworkManager_Orbis::removePlayerFromVoiceChat( SQRNetworkPlayer* pPlay void SQRNetworkManager_Orbis::TickNotify() { if (g_NetworkManager.IsInSession() && !g_NetworkManager.IsLocalGame()) - { + { long long currentTime = System::currentTimeMillis(); // Note: interval at which to notify Sony of realtime play, according to docs an interval greater than 1 sec is bad @@ -4109,7 +4109,7 @@ void SQRNetworkManager_Orbis::TickNotify() m_lastNotifyTime = currentTime; for(int i = 0; i < XUSER_MAX_COUNT; i++) { - if (ProfileManager.IsSignedInLive(i)) + if (ProfileManager.IsSignedInLive(i)) { NotifyRealtimePlusFeature(i); } @@ -4143,8 +4143,8 @@ void SQRNetworkManager_Orbis::NotifyRealtimePlusFeature(int iQuadrant) // { // app.DebugPrintf("============ Calling CallSignInCompleteCallback and s_SignInCompleteCallbackFn is OK\n"); // bool isSignedIn = ProfileManager.IsSignedInLive(s_SignInCompleteCallbackPad); -// -// s_SignInCompleteCallbackFn(s_SignInCompleteParam, isSignedIn, s_SignInCompleteCallbackPad); +// +// s_SignInCompleteCallbackFn(s_SignInCompleteParam, isSignedIn, s_SignInCompleteCallbackPad); // s_SignInCompleteCallbackFn = NULL; // s_SignInCompleteCallbackPad = -1; // } diff --git a/Minecraft.Client/Orbis/OrbisExtras/OrbisTypes.h b/Minecraft.Client/Orbis/OrbisExtras/OrbisTypes.h index 006a0060..b91f3714 100644 --- a/Minecraft.Client/Orbis/OrbisExtras/OrbisTypes.h +++ b/Minecraft.Client/Orbis/OrbisExtras/OrbisTypes.h @@ -170,7 +170,3 @@ typedef LPVOID LPSECURITY_ATTRIBUTES; #define __in_ecount(a) #define __in_bcount(a) - -#ifndef AUTO_VAR -#define AUTO_VAR(_var, _val) auto _var = _val -#endif
\ No newline at end of file diff --git a/Minecraft.Client/Orbis/Orbis_App.cpp b/Minecraft.Client/Orbis/Orbis_App.cpp index 9af5ee12..cd1ee215 100644 --- a/Minecraft.Client/Orbis/Orbis_App.cpp +++ b/Minecraft.Client/Orbis/Orbis_App.cpp @@ -35,7 +35,7 @@ CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() m_bVoiceChatAndUGCRestricted=false; m_bDisplayFullVersionPurchase=false; - // #ifdef _DEBUG_MENUS_ENABLED + // #ifdef _DEBUG_MENUS_ENABLED // debugOverlayCreated = false; // #endif @@ -101,8 +101,8 @@ SONYDLC *CConsoleMinecraftApp::GetSONYDLCInfo(char *pchTitle) { wstring wstrTemp=convStringToWstring(pchTitle); - AUTO_VAR(it, m_SONYDLCMap.find(wstrTemp)); - if(it == m_SONYDLCMap.end()) + auto it = m_SONYDLCMap.find(wstrTemp); + if(it == m_SONYDLCMap.end()) { app.DebugPrintf("Couldn't find DLC info for %s\n", pchTitle); assert(0); @@ -114,9 +114,9 @@ SONYDLC *CConsoleMinecraftApp::GetSONYDLCInfo(char *pchTitle) SONYDLC *CConsoleMinecraftApp::GetSONYDLCInfoFromKeyname(char *pchKeyName) { - for(AUTO_VAR(it, m_SONYDLCMap.begin()); it != m_SONYDLCMap.end(); ++it) - { - SONYDLC *pDLCInfo=(*it).second; + for ( auto& it : m_SONYDLCMap ) + { + SONYDLC *pDLCInfo=it.second; if(strcmp(pDLCInfo->chDLCKeyname,pchKeyName)==0) { @@ -289,9 +289,9 @@ int CConsoleMinecraftApp::LoadLocalDLCImages() { // 4J-PB - Any local graphic files for the Minecraft Store? unordered_map<wstring, SONYDLC *>*pDLCInfoA=app.GetSonyDLCMap(); - for( AUTO_VAR(it, pDLCInfoA->begin()); it != pDLCInfoA->end(); it++ ) - { - SONYDLC * pDLCInfo=(*it).second; + for (auto& it : *pDLCInfoA ) + { + SONYDLC * pDLCInfo = it.second; LoadLocalDLCImage(pDLCInfo); } @@ -302,9 +302,9 @@ void CConsoleMinecraftApp::FreeLocalDLCImages() { // 4J-PB - Any local graphic files for the Minecraft Store? unordered_map<wstring, SONYDLC *>*pDLCInfoA=app.GetSonyDLCMap(); - for( AUTO_VAR(it, pDLCInfoA->begin()); it != pDLCInfoA->end(); it++ ) + for( auto& it : *pDLCInfoA ) { - SONYDLC * pDLCInfo=(*it).second; + SONYDLC * pDLCInfo = it.second; if(pDLCInfo->dwImageBytes!=0) { @@ -333,7 +333,7 @@ int CConsoleMinecraftApp::LoadLocalDLCImage(SONYDLC *pDLCInfo) DWORD dwHigh=0; pDLCInfo->dwImageBytes = GetFileSize(hFile,&dwHigh); - + if(pDLCInfo->dwImageBytes!=0) { DWORD dwBytesRead; @@ -485,7 +485,7 @@ void CConsoleMinecraftApp::CommerceTick() break; case eCommerce_State_GetProductList: - { + { m_eCommerce_State=eCommerce_State_GetProductList_Pending; SonyCommerce::CategoryInfo *pCategories=app.GetCategoryInfo(); std::list<SonyCommerce::CategoryInfoSub>::iterator iter = pCategories->subCategories.begin(); @@ -501,7 +501,7 @@ void CConsoleMinecraftApp::CommerceTick() break; case eCommerce_State_AddProductInfoDetailed: - { + { m_eCommerce_State=eCommerce_State_AddProductInfoDetailed_Pending; // for each of the products in the categories, get the detailed info. We really only need the long description and price info. @@ -538,7 +538,7 @@ void CConsoleMinecraftApp::CommerceTick() break; case eCommerce_State_RegisterDLC: - { + { m_eCommerce_State=eCommerce_State_Online; // register the DLC info SonyCommerce::CategoryInfo *pCategories=app.GetCategoryInfo(); @@ -625,20 +625,20 @@ SonyCommerce::CategoryInfo *CConsoleMinecraftApp::GetCategoryInfo() return &m_CategoryInfo; } -#endif +#endif void CConsoleMinecraftApp::ClearCommerceDetails() { #ifdef ORBIS_COMMERCE_ENABLED for(int i=0;i<m_ProductListCategoriesC;i++) { - std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; + std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; pProductList->clear(); } if(m_ProductListA!=NULL) { - delete [] m_ProductListA; + delete [] m_ProductListA; m_ProductListA=NULL; } @@ -668,17 +668,14 @@ void CConsoleMinecraftApp::GetDLCSkuIDFromProductList(char * pchDLCProductID, ch for(int j=0;j<m_ProductListA[i].size();j++) { std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; - AUTO_VAR(itEnd, pProductList->end()); - - for (AUTO_VAR(it, pProductList->begin()); it != itEnd; it++) + for ( SonyCommerce::ProductInfo& : *pProductList ) { - SonyCommerce::ProductInfo Info=*it; if(strcmp(pchDLCProductID,Info.productId)==0) - { + { memcpy(pchSkuID,Info.skuId,SCE_NP_COMMERCE2_SKU_ID_LEN); return; } - } + } } } return; @@ -689,7 +686,7 @@ void CConsoleMinecraftApp::GetDLCSkuIDFromProductList(char * pchDLCProductID, ch void CConsoleMinecraftApp::Checkout(char *pchSkuID) { if(m_eCommerce_State==eCommerce_State_Online) - { + { strcpy(m_pchSkuID,pchSkuID); m_eCommerce_State=eCommerce_State_Checkout; } @@ -698,7 +695,7 @@ void CConsoleMinecraftApp::Checkout(char *pchSkuID) void CConsoleMinecraftApp::DownloadAlreadyPurchased(char *pchSkuID) { if(m_eCommerce_State==eCommerce_State_Online) - { + { strcpy(m_pchSkuID,pchSkuID); m_eCommerce_State=eCommerce_State_DownloadAlreadyPurchased; } @@ -707,7 +704,7 @@ void CConsoleMinecraftApp::DownloadAlreadyPurchased(char *pchSkuID) bool CConsoleMinecraftApp::UpgradeTrial() { if(m_eCommerce_State==eCommerce_State_Online) - { + { m_eCommerce_State=eCommerce_State_UpgradeTrial; return true; } @@ -742,33 +739,6 @@ bool CConsoleMinecraftApp::DLCAlreadyPurchased(char *pchTitle) #ifdef ORBIS_COMMERCE_ENABLED // purchasability flag is not return on PS4 return false; - // find the DLC -// for(int i=0;i<m_ProductListCategoriesC;i++) -// { -// for(int j=0;j<m_ProductListA[i].size();j++) -// { -// std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; -// AUTO_VAR(itEnd, pProductList->end()); -// -// for (AUTO_VAR(it, pProductList->begin()); it != itEnd; it++) -// { -// SonyCommerce::ProductInfo Info=*it; -// if(strcmp(pchTitle,Info.skuId)==0) -// { -// ORBIS_STUBBED; -// SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_OFF -// // if(Info.purchasabilityFlag==SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_OFF) -// // { -// // return true; -// // } -// // else -// // { -// // return false; -// // } -// } -// } -// } -// } #endif // #ifdef ORBIS_COMMERCE_ENABLED return false; @@ -804,7 +774,7 @@ void CConsoleMinecraftApp::CommerceGetCategoriesCallback(LPVOID lpParam,int err) if(err==0) { pClass->m_ProductListCategoriesC=pClass->m_CategoryInfo.countOfSubCategories; - // allocate the memory for the product info for each categories + // allocate the memory for the product info for each categories if(pClass->m_CategoryInfo.countOfSubCategories>0) { pClass->m_ProductListA = (std::vector<SonyCommerce::ProductInfo> *) new std::vector<SonyCommerce::ProductInfo> [pClass->m_CategoryInfo.countOfSubCategories]; @@ -838,7 +808,7 @@ void CConsoleMinecraftApp::CommerceGetProductListCallback(LPVOID lpParam,int err { // we're done, so now retrieve the additional product details for each product pClass->m_eCommerce_State=eCommerce_State_AddProductInfoDetailed; - pClass->m_bCommerceProductListRetrieved=true; + pClass->m_bCommerceProductListRetrieved=true; } else { @@ -848,21 +818,21 @@ void CConsoleMinecraftApp::CommerceGetProductListCallback(LPVOID lpParam,int err else { pClass->m_eCommerce_State=eCommerce_State_Error; - pClass->m_bCommerceProductListRetrieved=true; + pClass->m_bCommerceProductListRetrieved=true; } } // void CConsoleMinecraftApp::CommerceGetDetailedProductInfoCallback(LPVOID lpParam,int err) // { // CConsoleMinecraftApp *pScene=(CConsoleMinecraftApp *)lpParam; -// +// // if(err==0) // { // pScene->m_eCommerce_State=eCommerce_State_Idle; -// //pScene->m_bCommerceProductListRetrieved=true; +// //pScene->m_bCommerceProductListRetrieved=true; // } // //printf("Callback hit, error 0x%08x\n", err); -// +// // } void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam,int err) @@ -882,7 +852,7 @@ void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam { // MGH - change this to a while loop so we can skip empty categories. do - { + { pClass->m_iCurrentCategory++; }while(pClass->m_ProductListA[pClass->m_iCurrentCategory].size() == 0 && pClass->m_iCurrentCategory<pClass->m_ProductListCategoriesC); @@ -891,12 +861,12 @@ void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam { // there are no more categories, so we're done pClass->m_eCommerce_State=eCommerce_State_RegisterDLC; - pClass->m_bProductListAdditionalDetailsRetrieved=true; + pClass->m_bProductListAdditionalDetailsRetrieved=true; } else { // continue with the next category - pClass->m_eCommerce_State=eCommerce_State_AddProductInfoDetailed; + pClass->m_eCommerce_State=eCommerce_State_AddProductInfoDetailed; } } else @@ -908,7 +878,7 @@ void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam else { pClass->m_eCommerce_State=eCommerce_State_Error; - pClass->m_bProductListAdditionalDetailsRetrieved=true; + pClass->m_bProductListAdditionalDetailsRetrieved=true; pClass->m_iCurrentProduct=0; pClass->m_iCurrentCategory=0; } @@ -1062,9 +1032,9 @@ void CConsoleMinecraftApp::SystemServiceTick() for (int i = 0; i < status.eventNum; i++) { ret = sceSystemServiceReceiveEvent(&event); - if (ret == SCE_OK) + if (ret == SCE_OK) { - switch(event.eventType) + switch(event.eventType) { case SCE_SYSTEM_SERVICE_EVENT_GAME_CUSTOM_DATA: { @@ -1072,7 +1042,7 @@ void CConsoleMinecraftApp::SystemServiceTick() // Processing after invitation //SceNpSessionInvitationEventParam* pInvite = (SceNpSessionInvitationEventParam*)event.data.param; //SQRNetworkManager_Orbis::GetInviteDataAndProcess(pInvite); - break; + break; } case SCE_SYSTEM_SERVICE_EVENT_ON_RESUME: // Resume means that the user signed out (but came back), sensible thing to do is exit to main menu @@ -1217,7 +1187,7 @@ bool CConsoleMinecraftApp::CheckForEmptyStore(int iPad) bool bEmptyStore=true; if(pCategories!=NULL) - { + { if(pCategories->countOfProducts>0) { bEmptyStore=false; @@ -1247,7 +1217,7 @@ bool CConsoleMinecraftApp::CheckForEmptyStore(int iPad) void CConsoleMinecraftApp::ShowPatchAvailableError() { int32_t ret=sceErrorDialogInitialize(); - if ( ret==SCE_OK ) + if ( ret==SCE_OK ) { m_bPatchAvailableDialogRunning = true; @@ -1256,7 +1226,7 @@ void CConsoleMinecraftApp::ShowPatchAvailableError() // 4J-PB - We want to display the option to get the patch now param.errorCode = SCE_NP_ERROR_LATEST_PATCH_PKG_DOWNLOADED; ret = sceUserServiceGetInitialUser( ¶m.userId ); - if ( ret == SCE_OK ) + if ( ret == SCE_OK ) { ret=sceErrorDialogOpen( ¶m ); } @@ -1266,9 +1236,9 @@ void CConsoleMinecraftApp::ShowPatchAvailableError() void CConsoleMinecraftApp::PatchAvailableDialogTick() { if(m_bPatchAvailableDialogRunning) - { + { SceErrorDialogStatus stat = sceErrorDialogUpdateStatus(); - if( stat == SCE_ERROR_DIALOG_STATUS_FINISHED ) + if( stat == SCE_ERROR_DIALOG_STATUS_FINISHED ) { sceErrorDialogTerminate(); diff --git a/Minecraft.Client/Orbis/Orbis_Minecraft.cpp b/Minecraft.Client/Orbis/Orbis_Minecraft.cpp index 947b9df8..64616565 100644 --- a/Minecraft.Client/Orbis/Orbis_Minecraft.cpp +++ b/Minecraft.Client/Orbis/Orbis_Minecraft.cpp @@ -67,7 +67,7 @@ DWORD dwProfileSettingsA[NUM_PROFILE_VALUES]= }; //------------------------------------------------------------------------------------- -// Time Since fAppTime is a float, we need to keep the quadword app time +// Time Since fAppTime is a float, we need to keep the quadword app time // as a LARGE_INTEGER so that we don't lose precision after running // for a long time. //------------------------------------------------------------------------------------- @@ -84,7 +84,7 @@ void DefineActions(void) // The app needs to define the actions required, and the possible mappings for these // Split into Menu actions, and in-game actions - + if(InputManager.IsCircleCrossSwapped()) { InputManager.SetGameJoypadMaps(MAP_STYLE_0,ACTION_MENU_A, _PS4_JOY_BUTTON_O); @@ -140,7 +140,7 @@ void DefineActions(void) InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_LEFT, _PS4_JOY_BUTTON_DPAD_LEFT); InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_RIGHT, _PS4_JOY_BUTTON_DPAD_RIGHT); InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_UP, _PS4_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_DOWN, _PS4_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_DOWN, _PS4_JOY_BUTTON_DPAD_DOWN); if(InputManager.IsCircleCrossSwapped()) { @@ -198,7 +198,7 @@ void DefineActions(void) InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_LEFT, _PS4_JOY_BUTTON_DPAD_LEFT); InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_RIGHT, _PS4_JOY_BUTTON_DPAD_RIGHT); InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_UP, _PS4_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_DOWN, _PS4_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_DOWN, _PS4_JOY_BUTTON_DPAD_DOWN); if(InputManager.IsCircleCrossSwapped()) { @@ -255,7 +255,7 @@ void DefineActions(void) InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_LEFT, _PS4_JOY_BUTTON_DPAD_LEFT); InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_RIGHT, _PS4_JOY_BUTTON_DPAD_RIGHT); InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_UP, _PS4_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_DOWN, _PS4_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_DOWN, _PS4_JOY_BUTTON_DPAD_DOWN); // Vita remote play map if(InputManager.IsCircleCrossSwapped()) @@ -278,7 +278,7 @@ void DefineActions(void) InputManager.SetGameJoypadMaps(MAP_STYLE_3,ACTION_MENU_DOWN, _PS4_JOY_BUTTON_DPAD_DOWN | _PS4_JOY_BUTTON_LSTICK_DOWN); InputManager.SetGameJoypadMaps(MAP_STYLE_3,ACTION_MENU_LEFT, _PS4_JOY_BUTTON_DPAD_LEFT | _PS4_JOY_BUTTON_LSTICK_LEFT); InputManager.SetGameJoypadMaps(MAP_STYLE_3,ACTION_MENU_RIGHT, _PS4_JOY_BUTTON_DPAD_RIGHT | _PS4_JOY_BUTTON_LSTICK_RIGHT); - InputManager.SetGameJoypadMaps(MAP_STYLE_3,ACTION_MENU_PAUSEMENU, _PS4_JOY_BUTTON_OPTIONS); + InputManager.SetGameJoypadMaps(MAP_STYLE_3,ACTION_MENU_PAUSEMENU, _PS4_JOY_BUTTON_OPTIONS); InputManager.SetGameJoypadMaps(MAP_STYLE_3,ACTION_MENU_OTHER_STICK_UP, _PS4_JOY_BUTTON_RSTICK_UP); InputManager.SetGameJoypadMaps(MAP_STYLE_3,ACTION_MENU_OTHER_STICK_DOWN, _PS4_JOY_BUTTON_RSTICK_DOWN); InputManager.SetGameJoypadMaps(MAP_STYLE_3,ACTION_MENU_OTHER_STICK_LEFT, _PS4_JOY_BUTTON_RSTICK_LEFT); @@ -300,11 +300,11 @@ void DefineActions(void) InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_LOOK_RIGHT, _PS4_JOY_BUTTON_RSTICK_RIGHT); InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_LOOK_UP, _PS4_JOY_BUTTON_RSTICK_UP); InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_LOOK_DOWN, _PS4_JOY_BUTTON_RSTICK_DOWN); - + InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_INVENTORY, _PS4_JOY_BUTTON_TRIANGLE); InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_PAUSEMENU, _PS4_JOY_BUTTON_OPTIONS); - InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_DROP, _PS4_JOY_BUTTON_O); - InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_CRAFTING, _PS4_JOY_BUTTON_SQUARE); + InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_DROP, _PS4_JOY_BUTTON_O); + InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_CRAFTING, _PS4_JOY_BUTTON_SQUARE); InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_GAME_INFO, _PS4_JOY_BUTTON_TOUCHPAD); InputManager.SetGameJoypadMaps(MAP_STYLE_3,MINECRAFT_ACTION_USE, _PS4_JOY_BUTTON_L1); @@ -326,7 +326,7 @@ void DefineActions(void) } #if 0 -HRESULT InitD3D( IDirect3DDevice9 **ppDevice, +HRESULT InitD3D( IDirect3DDevice9 **ppDevice, D3DPRESENT_PARAMETERS *pd3dPP ) { IDirect3D9 *pD3D; @@ -353,14 +353,14 @@ HRESULT InitD3D( IDirect3DDevice9 **ppDevice, //pd3dPP->Flags = D3DPRESENTFLAG_NO_LETTERBOX; //ERR[D3D]: Can't set D3DPRESENTFLAG_NO_LETTERBOX when wide-screen is enabled // in the launcher/dashboard. - if(g_bWidescreen) + if(g_bWidescreen) pd3dPP->Flags=0; - else + else pd3dPP->Flags = D3DPRESENTFLAG_NO_LETTERBOX; // Create the device. return pD3D->CreateDevice( - 0, + 0, D3DDEVTYPE_HAL, NULL, D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_BUFFER_2_FRAMES, @@ -559,7 +559,7 @@ HRESULT InitDevice() // Create a depth stencil buffer D3D11_TEXTURE2D_DESC descDepth; - + descDepth.Width = width; descDepth.Height = height; descDepth.MipLevels = 1; @@ -571,7 +571,7 @@ HRESULT InitDevice() descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; - hr = g_pd3dDevice->CreateTexture2D(&descDepth, NULL, &g_pDepthStencilBuffer); + hr = g_pd3dDevice->CreateTexture2D(&descDepth, NULL, &g_pDepthStencilBuffer); D3D11_DEPTH_STENCIL_VIEW_DESC descDSView; descDSView.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; @@ -808,14 +808,14 @@ int main(int argc, const char *argv[] ) } // Initialize the application, assuming sharing of the d3d interface. - hr = app.InitShared( pDevice, &d3dpp, + hr = app.InitShared( pDevice, &d3dpp, XuiPNGTextureLoader ); if ( FAILED(hr) ) { app.DebugPrintf ( "Failed initializing application.\n" ); - + return -1; } @@ -992,9 +992,9 @@ int main(int argc, const char *argv[] ) StorageManager.SetOptionsFolderTitle((WCHAR *)app.GetString(IDS_OPTIONSFILE)); StorageManager.SetCorruptSaveName((WCHAR *)app.GetString(IDS_CORRUPTSAVE_TITLE)); #if (defined _FINAL_BUILD) || (defined _ART_BUILD) - StorageManager.SetGameSaveFolderPrefix(app.GetSaveFolderPrefix()); + StorageManager.SetGameSaveFolderPrefix(app.GetSaveFolderPrefix()); #else - // Use debug directory to prevent debug saves being loaded/edited in package build (since debug can't edit package save games this causes various problems) + // Use debug directory to prevent debug saves being loaded/edited in package build (since debug can't edit package save games this causes various problems) StorageManager.SetGameSaveFolderPrefix("DEBUG01899"); #endif StorageManager.SetMaxSaves(99); @@ -1030,7 +1030,7 @@ int main(int argc, const char *argv[] ) // set a function to be called when the ethernet is disconnected, so we can back out if required ProfileManager.SetNotificationsCallback(&CConsoleMinecraftApp::NotificationsCallback,(LPVOID)&app); - + #endif // set a function to be called when there's a sign in change, so we can exit a level if the primary player signs out ProfileManager.SetSignInChangeCallback(&CConsoleMinecraftApp::SignInChangeCallback,(LPVOID)&app); @@ -1064,13 +1064,13 @@ int main(int argc, const char *argv[] ) if(XNuiGetHardwareStatus()!=0) { - // If the Kinect Sensor is not physically connected, this function returns 0. - NuiInitialize(NUI_INITIALIZE_FLAG_USES_HIGH_QUALITY_COLOR | NUI_INITIALIZE_FLAG_USES_DEPTH | + // If the Kinect Sensor is not physically connected, this function returns 0. + NuiInitialize(NUI_INITIALIZE_FLAG_USES_HIGH_QUALITY_COLOR | NUI_INITIALIZE_FLAG_USES_DEPTH | NUI_INITIALIZE_FLAG_EXTRAPOLATE_FLOOR_PLANE | NUI_INITIALIZE_FLAG_USES_FITNESS | NUI_INITIALIZE_FLAG_NUI_GUIDE_DISABLED | NUI_INITIALIZE_FLAG_SUPPRESS_AUTOMATIC_UI,NUI_INITIALIZE_DEFAULT_HARDWARE_THREAD ); } // Sentient ! - hr = TelemetryManager->Init(); + hr = TelemetryManager->Init(); #endif @@ -1080,7 +1080,7 @@ int main(int argc, const char *argv[] ) AABB::CreateNewThreadStorage(); Vec3::CreateNewThreadStorage(); IntCache::CreateNewThreadStorage(); - Compression::CreateNewThreadStorage(); + Compression::CreateNewThreadStorage(); OldChunkStorage::CreateNewThreadStorage(); Level::enableLightingCache(); Tile::CreateNewThreadStorage(); @@ -1090,7 +1090,7 @@ int main(int argc, const char *argv[] ) // Minecraft::main () used to call Minecraft::Start, but this takes ~2.5 seconds, so now running this in another thread // so we can do some basic renderer calls whilst it is happening. This is at attempt to stop getting TRC failure on SubmitDone taking > 5 seconds on boot C4JThread *minecraftThread = new C4JThread(&StartMinecraftThreadProc, NULL, "Running minecraft start"); - minecraftThread->Run(); + minecraftThread->Run(); do { RenderManager.StartFrame(); @@ -1121,7 +1121,7 @@ int main(int argc, const char *argv[] ) #endif // set the default profile values for(int i=0;i<XUSER_MAX_COUNT;i++) - { + { app.SetDefaultOptions(StorageManager.GetDashboardProfileSettings(i),i); } #if 0 @@ -1227,7 +1227,7 @@ int main(int argc, const char *argv[] ) PIXBeginNamedEvent(0,"Social network manager tick"); // CSocialManager::Instance()->Tick(); PIXEndNamedEvent(); - + // Tick sentient. PIXBeginNamedEvent(0,"Sentient tick"); MemSect(37); @@ -1241,7 +1241,7 @@ int main(int argc, const char *argv[] ) LeaderboardManager::Instance()->Tick(); // Render game graphics. - if(app.GetGameStarted()) + if(app.GetGameStarted()) { pMinecraft->run_middle(); app.SetAppPaused( g_NetworkManager.IsLocalGame() && g_NetworkManager.GetPlayerCount() == 1 && ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()) ); @@ -1324,7 +1324,7 @@ int main(int argc, const char *argv[] ) for(int i=0;i<8;i++) { - if(RenderStateA2[i]!=RenderStateA[i]) + if(RenderStateA2[i]!=RenderStateA[i]) { //printf("Reseting RenderStateA[%d] after a XUI render\n",i); pDevice->SetRenderState(RenderStateModes[i],RenderStateA[i]); @@ -1332,7 +1332,7 @@ int main(int argc, const char *argv[] ) } for(int i=0;i<5;i++) { - if(SamplerStateA2[i]!=SamplerStateA[i]) + if(SamplerStateA2[i]!=SamplerStateA[i]) { //printf("Reseting SamplerStateA[%d] after a XUI render\n",i); pDevice->SetSamplerState(0,SamplerStateModes[i],SamplerStateA[i]); @@ -1364,7 +1364,7 @@ int main(int argc, const char *argv[] ) #ifdef _DEBUG_MENUS_ENABLED if(app.DebugSettingsOn()) { - app.ActionDebugMask(i); + app.ActionDebugMask(i); } else { @@ -1390,7 +1390,7 @@ int main(int argc, const char *argv[] ) for(int i=0;i<XUSER_MAX_COUNT;i++) { if(bOptionsNoSpace==false) - { + { if(app.GetOptionsCallbackStatus(i)==C4JStorage::eOptions_Callback_Write_Fail_NoSpace) { // get the game to bring up the save space handling @@ -1422,7 +1422,7 @@ int main(int argc, const char *argv[] ) if(!ProfileManager.IsFullVersion()) { // display the trial timer - if(app.GetGameStarted()) + if(app.GetGameStarted()) { // 4J-PB - if the game is paused, add the elapsed time to the trial timer count so it doesn't tick down if(app.IsAppPaused()) @@ -1522,7 +1522,7 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) { if( !trackStarted ) { - void *p = XMemAllocDefault(dwSize,dwAllocAttributes); + void *p = XMemAllocDefault(dwSize,dwAllocAttributes); size_t realSize = XMemSizeDefault(p, dwAllocAttributes); totalAllocGen += realSize; return p; @@ -1530,7 +1530,7 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) EnterCriticalSection(&memCS); - void *p=XMemAllocDefault(dwSize + 16,dwAllocAttributes); + void *p=XMemAllocDefault(dwSize + 16,dwAllocAttributes); size_t realSize = XMemSizeDefault(p,dwAllocAttributes) - 16; if( trackEnable ) @@ -1556,7 +1556,7 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) trackEnable = true; } } - + LeaveCriticalSection(&memCS); return p; @@ -1591,7 +1591,7 @@ void WINAPI XMemFree(PVOID pAddress, DWORD dwAllocAttributes) if( pAddress ) { size_t realSize = XMemSizeDefault(pAddress, dwAllocAttributes) - 16; - + if(trackEnable) { int sect = *(((unsigned char *)pAddress)+realSize); @@ -1627,7 +1627,7 @@ SIZE_T WINAPI XMemSize( void DumpMem() { int totalLeak = 0; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) + for( auto it = allocCounts.begin(); it != allocCounts.end(); it++ ) { if(it->second > 0 ) { @@ -1675,7 +1675,7 @@ void MemPixStuff() int totals[MAX_SECT] = {0}; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) + for( auto it = allocCounts.begin(); it != allocCounts.end(); it++ ) { if(it->second > 0 ) { diff --git a/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.cpp b/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.cpp index 46b1916d..8ab30beb 100644 --- a/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.cpp +++ b/Minecraft.Client/PS3/Network/SQRNetworkManager_PS3.cpp @@ -36,7 +36,7 @@ bool SQRNetworkManager_PS3::m_bCallPSNSignInCallback=false; //unsigned int SQRNetworkManager_PS3::RoomSyncData::playerCount = 0; // This maps internal to extern states, and needs to match element-by-element the eSQRNetworkManagerInternalState enumerated type -const SQRNetworkManager_PS3::eSQRNetworkManagerState SQRNetworkManager_PS3::m_INTtoEXTStateMappings[SQRNetworkManager_PS3::SNM_INT_STATE_COUNT] = +const SQRNetworkManager_PS3::eSQRNetworkManagerState SQRNetworkManager_PS3::m_INTtoEXTStateMappings[SQRNetworkManager_PS3::SNM_INT_STATE_COUNT] = { SNM_STATE_INITIALISING, // SNM_INT_STATE_UNINITIALISED SNM_STATE_INITIALISING, // SNM_INT_STATE_SIGNING_IN @@ -104,7 +104,7 @@ SQRNetworkManager_PS3::SQRNetworkManager_PS3(ISQRNetworkManagerListener *listene InitializeCriticalSection(&m_csRoomSyncData); InitializeCriticalSection(&m_csPlayerState); InitializeCriticalSection(&m_csStateChangeQueue); - + sys_event_port_create(&m_basicEventPort, SYS_EVENT_PORT_LOCAL, SYS_EVENT_PORT_NO_NAME); sys_event_queue_attribute_t queue_attr = {SYS_SYNC_PRIORITY, SYS_PPU_QUEUE}; @@ -134,7 +134,7 @@ void SQRNetworkManager_PS3::Initialise() SetState(SNM_INT_STATE_INITIALISE_FAILED); return; } - + //Initialize libnetctl ret = cellNetCtlInit(); #else @@ -175,7 +175,7 @@ void SQRNetworkManager_PS3::Initialise() memset(&netstart_param, 0, sizeof(netstart_param)); netstart_param.size = sizeof(netstart_param); - netstart_param.type = CELL_NET_CTL_NETSTART_TYPE_NP; + netstart_param.type = CELL_NET_CTL_NETSTART_TYPE_NP; SetState(SNM_INT_STATE_SIGNING_IN); ret = cellNetCtlNetStartDialogLoadAsync(&netstart_param); @@ -305,7 +305,7 @@ void SQRNetworkManager_PS3::InitialiseAfterOnline() } app.DebugPrintf("SQRNetworkManager::InitialiseAfterOnline - matching context is now valid\n"); m_matchingContextValid = true; - + bool bRet = RegisterCallbacks(); if( ( !bRet ) || ForceErrorPoint( SNM_FORCE_ERROR_REGISTER_CALLBACKS ) ) { @@ -459,7 +459,7 @@ void SQRNetworkManager_PS3::ErrorHandlingTick() DeleteServerContext(); break; } - + } // Start hosting a game, by creating a room & joining it. We explicity create a server context here (via GetServerContext) as Sony suggest that @@ -519,7 +519,7 @@ void SQRNetworkManager_PS3::UpdateExternalRoomData() { if( m_offlineGame ) return; if( m_isHosting ) - { + { SceNpMatching2SetRoomDataExternalRequest reqParam; memset( &reqParam, 0, sizeof(reqParam) ); reqParam.roomId = m_room; @@ -655,13 +655,13 @@ int SQRNetworkManager_PS3::BasicEventThreadProc( void *lpParameter ) do { sys_event_queue_receive(manager->m_basicEventQueue, &event, 0); - + // If the sys_event_t we've sent here from the handler has a non-zero data1 element, this is to signify that we should terminate the thread if( event.data1 == 0 ) { int iEvent; SceNpUserInfo from; - uint8_t buffer[SCE_NP_BASIC_MAX_MESSAGE_SIZE]; + uint8_t buffer[SCE_NP_BASIC_MAX_MESSAGE_SIZE]; size_t bufferSize = SCE_NP_BASIC_MAX_MESSAGE_SIZE; int ret = sceNpBasicGetEvent(&iEvent, &from, &buffer, &bufferSize); if( ret == 0 ) @@ -669,7 +669,7 @@ int SQRNetworkManager_PS3::BasicEventThreadProc( void *lpParameter ) if( iEvent == SCE_NP_BASIC_EVENT_INCOMING_BOOTABLE_INVITATION ) { // 4J Stu - Don't do this here as it can be very disruptive to gameplay. Players can bring this up from LoadOrJoinMenu, PauseMenu and InGameInfoMenu - //sceNpBasicRecvMessageCustom(SCE_NP_BASIC_MESSAGE_MAIN_TYPE_INVITE, SCE_NP_BASIC_RECV_MESSAGE_OPTIONS_INCLUDE_BOOTABLE, SYS_MEMORY_CONTAINER_ID_INVALID); + //sceNpBasicRecvMessageCustom(SCE_NP_BASIC_MESSAGE_MAIN_TYPE_INVITE, SCE_NP_BASIC_RECV_MESSAGE_OPTIONS_INCLUDE_BOOTABLE, SYS_MEMORY_CONTAINER_ID_INVALID); } if( iEvent == SCE_NP_BASIC_EVENT_RECV_INVITATION_RESULT ) { @@ -697,7 +697,7 @@ int SQRNetworkManager_PS3::GetFriendsThreadProc( void* lpParameter ) // This is likely when friend list hasn't been received from the server yet - will be returning SCE_NP_BASIC_ERROR_BUSY in this case manager->m_friendCount = 0; } - + // There shouldn't ever be more than 100 friends returned but limit here just in case if( manager->m_friendCount > 100 ) manager->m_friendCount = 100; @@ -711,8 +711,8 @@ int SQRNetworkManager_PS3::GetFriendsThreadProc( void* lpParameter ) memset(&userInfo, 0x00, sizeof(userInfo)); memset(&presenceDetails, 0x00, sizeof(presenceDetails)); presenceDetails.struct_size = sizeof(presenceDetails); - - int ret = sceNpBasicGetFriendPresenceByIndex2( i, &userInfo, &presenceDetails, 0 ); + + int ret = sceNpBasicGetFriendPresenceByIndex2( i, &userInfo, &presenceDetails, 0 ); if( ( ret == 0 ) && ( !manager->ForceErrorPoint( SNM_FORCE_ERROR_GET_FRIEND_LIST_ENTRY ) ) ) { @@ -778,7 +778,7 @@ bool SQRNetworkManager_PS3::IsReadyToPlayOrIdle() // Consider as "in session" from the moment that a game is created or joined, until the point where the game itself has been told via state change that we are now idle. The -// game code requires IsInSession to return true as soon as it has asked to do one of these things (even if the state system hasn't really caught up with this request yet), and +// game code requires IsInSession to return true as soon as it has asked to do one of these things (even if the state system hasn't really caught up with this request yet), and // it also requires that it is informed of the state changes leading up to not being in the session, before this should report false. bool SQRNetworkManager_PS3::IsInSession() { @@ -950,7 +950,7 @@ bool SQRNetworkManager_PS3::JoinRoom(SceNpMatching2RoomId roomId, SceNpMatching2 m_localPlayerJoinMask = localPlayerMask; m_localPlayerCount = 0; m_localPlayerJoined = 0; - + for( int i = 0; i < MAX_LOCAL_PLAYER_COUNT; i++ ) { if( localPlayerMask & ( 1 << i ) ) m_localPlayerCount++; @@ -1090,7 +1090,7 @@ bool SQRNetworkManager_PS3::AddLocalPlayerByUserIndex(int idx) memset(&reqParam, 0, sizeof(reqParam)); memset(&binAttr, 0, sizeof(binAttr)); - + binAttr.id = SCE_NP_MATCHING2_ROOMMEMBER_BIN_ATTR_INTERNAL_1_ID; binAttr.ptr = &m_localPlayerJoinMask; binAttr.size = sizeof(m_localPlayerJoinMask); @@ -1174,7 +1174,7 @@ bool SQRNetworkManager_PS3::RemoveLocalPlayerByUserIndex(int idx) memset(&reqParam, 0, sizeof(reqParam)); memset(&binAttr, 0, sizeof(binAttr)); - + binAttr.id = SCE_NP_MATCHING2_ROOMMEMBER_BIN_ATTR_INTERNAL_1_ID; binAttr.ptr = &m_localPlayerJoinMask; binAttr.size = sizeof(m_localPlayerJoinMask); @@ -1197,7 +1197,7 @@ bool SQRNetworkManager_PS3::RemoveLocalPlayerByUserIndex(int idx) } } -// Bring up a Gui to send an invite so a player that the user can select. This invite will contain the room Id so that +// Bring up a Gui to send an invite so a player that the user can select. This invite will contain the room Id so that void SQRNetworkManager_PS3::SendInviteGUI() { SceNpBasicMessageDetails msg; @@ -1270,8 +1270,8 @@ bool SQRNetworkManager_PS3::UpdateInviteData(SQRNetworkManager_PS3::PresenceSync // and there's a period when starting up the host game where it doesn't accurately know the memberId for its own local players void SQRNetworkManager_PS3::FindOrCreateNonNetworkPlayer(int slot, int playerType, SceNpMatching2RoomMemberId memberId, int localPlayerIdx, int smallId) { - for(AUTO_VAR(it, m_vecTempPlayers.begin()); it != m_vecTempPlayers.end(); it++ ) - { + for (auto it = m_vecTempPlayers.begin(); it != m_vecTempPlayers.end(); it++) + { if( ((*it)->m_type == playerType ) && ( (*it)->m_localPlayerIdx == localPlayerIdx ) ) { if( ( playerType != SQRNetworkPlayer::SNP_TYPE_REMOTE ) || ( (*it)->m_roomMemberId == memberId ) ) @@ -1329,7 +1329,7 @@ void SQRNetworkManager_PS3::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) { EnterCriticalSection(&m_csRoomSyncData); - // If we pass an explicit roomSlotPlayerCount, it is because we are removing a player, and this is the count of slots that there were *before* the removal. + // If we pass an explicit roomSlotPlayerCount, it is because we are removing a player, and this is the count of slots that there were *before* the removal. bool zeroLastSlot = false; if( roomSlotPlayerCount == -1 ) { @@ -1433,7 +1433,7 @@ void SQRNetworkManager_PS3::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) } else { - FindOrCreateNonNetworkPlayer( i, SQRNetworkPlayer::SNP_TYPE_REMOTE, m_roomSyncData.players[i].m_roomMemberId, m_roomSyncData.players[i].m_localIdx, m_roomSyncData.players[i].m_smallId); + FindOrCreateNonNetworkPlayer( i, SQRNetworkPlayer::SNP_TYPE_REMOTE, m_roomSyncData.players[i].m_roomMemberId, m_roomSyncData.players[i].m_localIdx, m_roomSyncData.players[i].m_smallId); m_aRoomSlotPlayers[i]->SetUID(m_roomSyncData.players[i].m_UID); // On client, UIDs flow from m_roomSyncData->player data } } @@ -1441,8 +1441,8 @@ void SQRNetworkManager_PS3::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) } // Clear up any non-network players that are no longer required - this would be a good point to notify of players leaving when we support that // FindOrCreateNonNetworkPlayer will have pulled any players that we Do need out of m_vecTempPlayers, so the ones that are remaining are no longer in the game - for(AUTO_VAR(it, m_vecTempPlayers.begin()); it != m_vecTempPlayers.end(); it++ ) - { + for (auto it = m_vecTempPlayers.begin(); it != m_vecTempPlayers.end(); it++) + { if( m_listener ) { m_listener->HandlePlayerLeaving(*it); @@ -1526,7 +1526,7 @@ bool SQRNetworkManager_PS3::AddRemotePlayersAndSync( SceNpMatching2RoomMemberId } // We want to keep all players from a particular machine together, so search through the room sync data to see if we can find - // any pre-existing players from this machine. + // any pre-existing players from this machine. int firstIdx = -1; for( int i = 0; i < m_roomSyncData.getPlayerCount(); i++ ) { @@ -1629,7 +1629,7 @@ void SQRNetworkManager_PS3::RemoveRemotePlayersAndSync( SceNpMatching2RoomMember // Update mapping from the room slot players to SQRNetworkPlayer instances MapRoomSlotPlayers(); - + // And then synchronise this out to all other machines SyncRoomData(); @@ -1643,8 +1643,8 @@ void SQRNetworkManager_PS3::RemoveNetworkPlayers( int mask ) { assert( !m_isHosting ); - for(AUTO_VAR(it, m_RudpCtxToPlayerMap.begin()); it != m_RudpCtxToPlayerMap.end(); ) - { + for (auto it = m_RudpCtxToPlayerMap.begin(); it != m_RudpCtxToPlayerMap.end();) + { SQRNetworkPlayer *player = it->second; if( (player->m_roomMemberId == m_localMemberId ) && ( ( 1 << player->m_localPlayerIdx ) & mask ) ) { @@ -1667,7 +1667,7 @@ void SQRNetworkManager_PS3::RemoveNetworkPlayers( int mask ) it = m_RudpCtxToPlayerMap.erase(it); // Delete the player itself and the mapping from context to player map as this context is no longer valid - delete player; + delete player; } else { @@ -1770,7 +1770,7 @@ bool SQRNetworkManager_PS3::GetMatchingContext(eSQRNetworkManagerInternalState a app.DebugPrintf("SQRNetworkManager::GetMatchingContext - sceNpMatching2ContextStartAsync failed with code 0x%08x\n", ret); return false; } - + app.DebugPrintf("SQRNetworkManager::GetMatchingContext - matching context is now valid\n"); m_matchingContextValid = true; return true; @@ -1778,7 +1778,7 @@ bool SQRNetworkManager_PS3::GetMatchingContext(eSQRNetworkManagerInternalState a // Starts the process of obtaining a server context. This is an asynchronous operation, at the end of which (if successful), we'll be creating // a room. General procedure followed here is as suggested by Sony - we get a list of servers, then pick a random one, and see if it is available. -// If not we just cycle round trying other random ones until we either find an available one or fail. +// If not we just cycle round trying other random ones until we either find an available one or fail. bool SQRNetworkManager_PS3::GetServerContext() { assert(m_state == SNM_INT_STATE_IDLE); @@ -1803,7 +1803,7 @@ bool SQRNetworkManager_PS3::GetServerContext2() ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED ) ) // Also checking for this as a means of simulating the previous error { sceNpMatching2DestroyContext(m_matchingContext); - m_matchingContextValid = false; + m_matchingContextValid = false; if( !GetMatchingContext(SNM_INT_STATE_HOSTING_STARTING_MATCHING_CONTEXT) ) return false; // If this caused an async thing to be started up, then we've done as much as we can here - the rest of the code will happen when the async matching 2 context starting completes // ( event SCE_NP_MATCHING2_CONTEXT_EVENT_Start is received ) @@ -1860,7 +1860,7 @@ bool SQRNetworkManager_PS3::GetServerContext(SceNpMatching2ServerId serverId) app.DebugPrintf("SQRNetworkManager::GetServerContext - sceNpMatching2GetServerIdListLocal failed with error 0x%08x\n", serverCount); int ret = sceNpMatching2DestroyContext(m_matchingContext); app.DebugPrintf("SQRNetworkManager::GetServerContext - sceNpMatching2DestroyContext returned 0x%08x\n", ret); - m_matchingContextValid = false; + m_matchingContextValid = false; if( !GetMatchingContext(SNM_INT_STATE_JOINING_STARTING_MATCHING_CONTEXT) ) { app.DebugPrintf("SQRNetworkManager::GetServerContext - Failed due to no matching context after recreating\n"); @@ -2003,7 +2003,7 @@ void SQRNetworkManager_PS3::NetworkPlayerConnectionComplete(SQRNetworkPlayer *pl if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2029,7 +2029,7 @@ void SQRNetworkManager_PS3::NetworkPlayerSmallIdAllocated(SQRNetworkPlayer *play if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2047,7 +2047,7 @@ void SQRNetworkManager_PS3::NetworkPlayerInitialDataReceived(SQRNetworkPlayer *p if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2063,7 +2063,7 @@ void SQRNetworkManager_PS3::HandlePlayerJoined(SQRNetworkPlayer *player) { if( m_listener ) { - m_listener->HandlePlayerJoined( player ); + m_listener->HandlePlayerJoined( player ); } // On client, keep a count of how many local players we have told the game about. We can only transition to telling the game that we are playing once the room is set up And all the local players are valid to use. if( !m_isHosting ) @@ -2160,11 +2160,11 @@ bool SQRNetworkManager_PS3::CreateRudpConnections(SceNpMatching2RoomId roomId, S sinp2pLocal.sin_family = AF_INET; sinp2pLocal.sin_port = htons(SCE_NP_PORT); // sinp2pLocal.sin_addr = netInfo.localAddr; - + // ... and then the peer memset(&sinp2pPeer, 0, sizeof(sinp2pPeer)); sinp2pPeer.sin_family = AF_INET; - + ret = sceNpMatching2SignalingGetConnectionStatus(m_matchingContext, roomId, peerMemberId, &connStatus, &sinp2pPeer.sin_addr, &sinp2pPeer.sin_port); app.DebugPrintf(CMinecraftApp::USER_RR,"sceNpMatching2SignalingGetConnectionStatus returned 0x%x, connStatus %d peer add:0x%x peer port:0x%x\n",ret, connStatus,sinp2pPeer.sin_addr,sinp2pPeer.sin_port); @@ -2232,8 +2232,8 @@ bool SQRNetworkManager_PS3::CreateRudpConnections(SceNpMatching2RoomId roomId, S SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerFromRudpCtx(int rudpCtx) { - AUTO_VAR(it,m_RudpCtxToPlayerMap.find(rudpCtx)); - if( it != m_RudpCtxToPlayerMap.end() ) + auto it = m_RudpCtxToPlayerMap.find(rudpCtx); + if( it != m_RudpCtxToPlayerMap.end() ) { return it->second; } @@ -2242,8 +2242,8 @@ SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerFromRudpCtx(int rudpCtx) SQRNetworkPlayer *SQRNetworkManager_PS3::GetPlayerFromRoomMemberAndLocalIdx(int roomMember, int localIdx) { - for(AUTO_VAR(it, m_RudpCtxToPlayerMap.begin()); it != m_RudpCtxToPlayerMap.end(); it++ ) - { + for (auto it = m_RudpCtxToPlayerMap.begin(); it != m_RudpCtxToPlayerMap.end(); it++) + { if( (it->second->m_roomMemberId == roomMember ) && ( it->second->m_localPlayerIdx == localIdx ) ) { return it->second; @@ -2329,7 +2329,7 @@ void SQRNetworkManager_PS3::ContextCallback(SceNpMatching2ContextId id, SceNpMa manager->m_state == SNM_INT_STATE_JOINING_STARTING_MATCHING_CONTEXT) { - // matching context failed to start (this can happen when you block the IP addresses of the matching servers on your router + // matching context failed to start (this can happen when you block the IP addresses of the matching servers on your router // agent-0101.ww.sp-int.matching.playstation.net (198.107.157.191) // static-resource.sp-int.community.playstation.net (203.105.77.140) manager->SetState(SNM_INT_STATE_INITIALISE_FAILED); @@ -2773,7 +2773,7 @@ void SQRNetworkManager_PS3::RoomEventCallback(SceNpMatching2ContextId id, SceNpM #endif { SQRNetworkManager_PS3 *manager = (SQRNetworkManager_PS3 *)arg; - + bool gotEventData = false; switch( event ) { @@ -2910,7 +2910,7 @@ void SQRNetworkManager_PS3::RoomEventCallback(SceNpMatching2ContextId id, SceNpM int oldMask = manager->GetOldMask( pRoomMemberData->newRoomMemberDataInternal->memberId ); int addedMask = manager->GetAddedMask(playerMask, oldMask ); int removedMask = manager->GetRemovedMask(playerMask, oldMask ); - + if( addedMask != 0 ) { bool success = manager->AddRemotePlayersAndSync( pRoomMemberData->newRoomMemberDataInternal->memberId, addedMask ); @@ -2927,7 +2927,7 @@ void SQRNetworkManager_PS3::RoomEventCallback(SceNpMatching2ContextId id, SceNpM memset(&reqParam, 0, sizeof(reqParam)); memset(&binAttr, 0, sizeof(binAttr)); - + binAttr.id = SCE_NP_MATCHING2_ROOMMEMBER_BIN_ATTR_INTERNAL_1_ID; binAttr.ptr = &oldMask; binAttr.size = sizeof(oldMask); @@ -2983,7 +2983,7 @@ void SQRNetworkManager_PS3::RoomEventCallback(SceNpMatching2ContextId id, SceNpM } } } - + } } break; @@ -3079,7 +3079,7 @@ void SQRNetworkManager_PS3::ManagerCallback(int event, int result, void *arg) manager->InitialiseAfterOnline(); break; case SCE_NP_MANAGER_EVENT_GOT_TICKET: - { + { // Let the profile Manager deal with any tickets SonyRemoteStorage_PS3* pRemote = (SonyRemoteStorage_PS3*)app.getRemoteStorage(); if(pRemote->isWaitingForTicket()) @@ -3427,7 +3427,7 @@ void SQRNetworkManager_PS3::GetExtDataForRoom( SceNpMatching2RoomId roomId, void ( ret == SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED ) ) // Also checking for this as a means of simulating the previous error { sceNpMatching2DestroyContext(m_matchingContext); - m_matchingContextValid = false; + m_matchingContextValid = false; if( !GetMatchingContext(SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT) ) { // No matching context, and failed to try and make one. We're really broken here. @@ -3454,7 +3454,7 @@ bool SQRNetworkManager_PS3::ForceErrorPoint(eSQRForceError error) return false; } #else -bool SQRNetworkManager_PS3::aForceError[SNM_FORCE_ERROR_COUNT] = +bool SQRNetworkManager_PS3::aForceError[SNM_FORCE_ERROR_COUNT] = { false, // SNM_FORCE_ERROR_NP2_INIT false, // SNM_FORCE_ERROR_NET_INITIALIZE_NETWORK diff --git a/Minecraft.Client/PS3/Network/SonyVoiceChat.cpp b/Minecraft.Client/PS3/Network/SonyVoiceChat.cpp index 721ddf26..41c52bed 100644 --- a/Minecraft.Client/PS3/Network/SonyVoiceChat.cpp +++ b/Minecraft.Client/PS3/Network/SonyVoiceChat.cpp @@ -74,7 +74,7 @@ void SonyVoiceChat::setEnabled( bool bEnabled ) { if(bEnabled) startStream(); - else + else stopStream(); } sm_bEnabled = bEnabled; @@ -185,18 +185,18 @@ int SonyVoiceChat::eventcb_voiceDetected(CellSysutilAvc2EventId event_id, CellSy UNUSED_VARIABLE( userdata ); // To the upper 32 bits, the room member ID of the player is passed. -// In the lower 32 bits, a value of 0 (mute) or a value between 1 (low volume) -// and 10 (high volume) is passed as the audio signal value when the notification -// method is the level method, or a value of 1 (start of speaking) or 0 (end of speaking) +// In the lower 32 bits, a value of 0 (mute) or a value between 1 (low volume) +// and 10 (high volume) is passed as the audio signal value when the notification +// method is the level method, or a value of 1 (start of speaking) or 0 (end of speaking) // is stored when the notification method is the trigger method. SceNpMatching2RoomMemberId roomMemberID = (SceNpMatching2RoomMemberId)(event_param >> 32); uint32_t volume = (uint32_t)(event_param & 0xffffffff); -// The precision of voice detection is not very high. Since the audio signal values may -// always be relatively high depending on the audio input device and the noise level in the -// room, you should set a large reference value for determining whether or not a player is -// speaking. Relatively good results can be obtained when an audio signal value of at +// The precision of voice detection is not very high. Since the audio signal values may +// always be relatively high depending on the audio input device and the noise level in the +// room, you should set a large reference value for determining whether or not a player is +// speaking. Relatively good results can be obtained when an audio signal value of at // least 9 is used to determine if a player is speaking. bool bTalking = false; if(volume >= 9) @@ -514,7 +514,7 @@ void SonyVoiceChat::do_state_transition( state_transition_table *tbl, int tbl_si } if(bCalledFunc == false) { - assert( (sm_event == AVC_EVENT_NON) || + assert( (sm_event == AVC_EVENT_NON) || (sm_state == AVC_STATE_IDLE && sm_event == AVC_EVENT_EPSILON) ); } } @@ -547,7 +547,7 @@ void SonyVoiceChat::mute( bool bMute ) { if(sm_bLoaded && !sm_bUnloading) { - int err = cellSysutilAvc2SetVoiceMuting(bMute); + int err = cellSysutilAvc2SetVoiceMuting(bMute); assert(err == CELL_OK); } } @@ -576,14 +576,14 @@ bool SonyVoiceChat::isMuted() if(sm_bLoaded && !sm_bUnloading) { uint8_t bMute; - int err = cellSysutilAvc2GetVoiceMuting(&bMute); + int err = cellSysutilAvc2GetVoiceMuting(&bMute); assert(err == CELL_OK); return bMute; } return false; } -bool SonyVoiceChat::isMutedPlayer( const SceNpMatching2RoomMemberId member_id) +bool SonyVoiceChat::isMutedPlayer( const SceNpMatching2RoomMemberId member_id) { if(sm_bLoaded && !sm_bUnloading) { @@ -595,7 +595,7 @@ bool SonyVoiceChat::isMutedPlayer( const SceNpMatching2RoomMemberId member_id) return false; } -bool SonyVoiceChat::isMutedLocalPlayer() +bool SonyVoiceChat::isMutedLocalPlayer() { if(sm_bLoaded && !sm_bUnloading) { @@ -611,10 +611,10 @@ void SonyVoiceChat::setVolume( float vol ) { if(sm_bLoaded && !sm_bUnloading) { - // The volume level can be set to a value in the range 0.0 to 40.0. - // Volume levels are linear values such that if 1.0 is specified, the - // volume level will be 1 times the reference power (0dB), and if 0.5 - // is specified, the volume level will be 0.5 times the reference power + // The volume level can be set to a value in the range 0.0 to 40.0. + // Volume levels are linear values such that if 1.0 is specified, the + // volume level will be 1 times the reference power (0dB), and if 0.5 + // is specified, the volume level will be 0.5 times the reference power // (-6dB). If 0.0 is specified, chat audio will no longer be audible. int err =cellSysutilAvc2SetSpeakerVolumeLevel(vol * 40.0f); @@ -636,8 +636,8 @@ float SonyVoiceChat::getVolume() bool SonyVoiceChat::isTalking( SceNpMatching2RoomMemberId* players_id ) { - AUTO_VAR(it, sm_bTalkingMap.find(*players_id)); - if (it != sm_bTalkingMap.end() ) + auto it = sm_bTalkingMap.find(*players_id); + if (it != sm_bTalkingMap.end() ) return it->second; return false; } @@ -648,11 +648,11 @@ void SonyVoiceChat::setBitRate() return; int numPlayers = sm_pNetworkManager->GetPlayerCount(); -// This internal attribute represents the maximum voice bit rate. attr_param -// is an integer value. The units are bps, and the specifiable values are +// This internal attribute represents the maximum voice bit rate. attr_param +// is an integer value. The units are bps, and the specifiable values are // 4000, 8000, 16000, 20000, 24000, and 28000. The initial value is 28000. - static int bitRates[8] = { 28000, 28000, + static int bitRates[8] = { 28000, 28000, 28000, 28000, 24000, 20000, 16000, 16000}; @@ -686,14 +686,14 @@ const char* getStateString(EAVCState state) { CASE_STR_VALUE(AVC_STATE_IDLE); - CASE_STR_VALUE(AVC_STATE_CHAT_INIT) - CASE_STR_VALUE(AVC_STATE_CHAT_LOAD); + CASE_STR_VALUE(AVC_STATE_CHAT_INIT) + CASE_STR_VALUE(AVC_STATE_CHAT_LOAD); CASE_STR_VALUE(AVC_STATE_CHAT_JOIN); CASE_STR_VALUE(AVC_STATE_CHAT_SESSION_PROCESSING); CASE_STR_VALUE(AVC_STATE_CHAT_LEAVE); CASE_STR_VALUE(AVC_STATE_CHAT_RESET); - CASE_STR_VALUE(AVC_STATE_CHAT_UNLOAD); - CASE_STR_VALUE(AVC_STATE_EXIT); + CASE_STR_VALUE(AVC_STATE_CHAT_UNLOAD); + CASE_STR_VALUE(AVC_STATE_EXIT); default: return "unknown state"; } diff --git a/Minecraft.Client/PS3/PS3Extras/Ps3Stubs.cpp b/Minecraft.Client/PS3/PS3Extras/Ps3Stubs.cpp index 47cd7106..2177739a 100644 --- a/Minecraft.Client/PS3/PS3Extras/Ps3Stubs.cpp +++ b/Minecraft.Client/PS3/PS3Extras/Ps3Stubs.cpp @@ -5,7 +5,7 @@ #include <libsn.h> #include <cell/cell_fs.h> #include <sys/vm.h> -#include <sys/memory.h> +#include <sys/memory.h> #undef __in #undef __out #include <cell/atomic.h> @@ -31,49 +31,49 @@ vector<int> vOpenFileHandles; namespace boost { void assertion_failed(char const * expr, - char const * function, char const * file, long line) - { + char const * function, char const * file, long line) + { #ifndef _CONTENT_PACKAGE - printf("Assert failed!!!\n"); - printf(expr); - printf("\n"); - printf("----------------------\n %s failed. File %s at line %d \n----------------------\n", function, file, line); + printf("Assert failed!!!\n"); + printf(expr); + printf("\n"); + printf("----------------------\n %s failed. File %s at line %d \n----------------------\n", function, file, line); snPause(); #endif } // user defined } // namespace boost - char* getConsoleHomePath() - { - return contentInfoPath; + char* getConsoleHomePath() + { + return contentInfoPath; } -char* getUsrDirPath() -{ - return usrdirPath; +char* getUsrDirPath() +{ + return usrdirPath; } -char* getConsoleHomePathBDPatch() -{ - return contentInfoPathBDPatch; +char* getConsoleHomePathBDPatch() +{ + return contentInfoPathBDPatch; } -char* getUsrDirPathBDPatch() -{ - return usrdirPathBDPatch; +char* getUsrDirPathBDPatch() +{ + return usrdirPathBDPatch; } -char* getDirName() -{ - return dirName; +char* getDirName() +{ + return dirName; } int _wcsicmp( const wchar_t * dst, const wchar_t * src ) { wchar_t f,l; - // validation section + // validation section // _VALIDATE_RETURN(dst != NULL, EINVAL, _NLSCMPERROR); // _VALIDATE_RETURN(src != NULL, EINVAL, _NLSCMPERROR); @@ -101,7 +101,7 @@ size_t wcsnlen(const wchar_t *wcs, size_t maxsize) Cnullptr nullptr; -VOID GetSystemTime( LPSYSTEMTIME lpSystemTime) +VOID GetSystemTime( LPSYSTEMTIME lpSystemTime) { CellRtcDateTime dateTime; int err = cellRtcGetCurrentClock(&dateTime, 0); @@ -118,8 +118,8 @@ VOID GetSystemTime( LPSYSTEMTIME lpSystemTime) } BOOL FileTimeToSystemTime(CONST FILETIME *lpFileTime, LPSYSTEMTIME lpSystemTime) { PS3_STUBBED; return false; } BOOL SystemTimeToFileTime(CONST SYSTEMTIME *lpSystemTime, LPFILETIME lpFileTime) { PS3_STUBBED; return false; } -VOID GetLocalTime(LPSYSTEMTIME lpSystemTime) -{ +VOID GetLocalTime(LPSYSTEMTIME lpSystemTime) +{ CellRtcDateTime dateTime; int err = cellRtcGetCurrentClockLocalTime(&dateTime); assert(err == CELL_OK); @@ -135,26 +135,26 @@ VOID GetLocalTime(LPSYSTEMTIME lpSystemTime) } HANDLE CreateEvent(void* lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName) { PS3_STUBBED; return NULL; } -VOID Sleep(DWORD dwMilliseconds) -{ +VOID Sleep(DWORD dwMilliseconds) +{ C4JThread::Sleep(dwMilliseconds); } BOOL SetThreadPriority(HANDLE hThread, int nPriority) { PS3_STUBBED; return FALSE; } DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) { PS3_STUBBED; return false; } -LONG InterlockedCompareExchangeRelease(LONG volatile *Destination, LONG Exchange,LONG Comperand ) -{ +LONG InterlockedCompareExchangeRelease(LONG volatile *Destination, LONG Exchange,LONG Comperand ) +{ return cellAtomicCompareAndSwap32((uint32_t*)Destination, (uint32_t)Comperand, (uint32_t)Exchange); } -LONG64 InterlockedCompareExchangeRelease64(LONG64 volatile *Destination, LONG64 Exchange, LONG64 Comperand) -{ +LONG64 InterlockedCompareExchangeRelease64(LONG64 volatile *Destination, LONG64 Exchange, LONG64 Comperand) +{ return cellAtomicCompareAndSwap64((uint64_t*)Destination, (uint64_t)Comperand, (uint64_t)Exchange); } -VOID InitializeCriticalSection(PCRITICAL_SECTION CriticalSection) +VOID InitializeCriticalSection(PCRITICAL_SECTION CriticalSection) { sys_lwmutex_attribute_t attr; // from the defaults in sys_lwmutex_attribute_initialize @@ -167,7 +167,7 @@ VOID InitializeCriticalSection(PCRITICAL_SECTION CriticalSection) } -VOID InitializeCriticalSectionAndSpinCount(PCRITICAL_SECTION CriticalSection, ULONG SpinCount) +VOID InitializeCriticalSectionAndSpinCount(PCRITICAL_SECTION CriticalSection, ULONG SpinCount) { // no spin count on PS3 InitializeCriticalSection(CriticalSection); @@ -179,9 +179,9 @@ VOID DeleteCriticalSection(PCRITICAL_SECTION CriticalSection) PS3_ASSERT_CELL_ERROR(err); } -extern CRITICAL_SECTION g_singleThreadCS; +extern CRITICAL_SECTION g_singleThreadCS; -VOID EnterCriticalSection(PCRITICAL_SECTION CriticalSection) +VOID EnterCriticalSection(PCRITICAL_SECTION CriticalSection) { // if(CriticalSection != &g_singleThreadCS &&(C4JThread::isMainThread() == false) ) // LeaveCriticalSection(&g_singleThreadCS); @@ -192,7 +192,7 @@ VOID EnterCriticalSection(PCRITICAL_SECTION CriticalSection) } -VOID LeaveCriticalSection(PCRITICAL_SECTION CriticalSection) +VOID LeaveCriticalSection(PCRITICAL_SECTION CriticalSection) { int err = sys_lwmutex_unlock(CriticalSection); PS3_ASSERT_CELL_ERROR(err); @@ -200,7 +200,7 @@ VOID LeaveCriticalSection(PCRITICAL_SECTION CriticalSection) ULONG TryEnterCriticalSection(PCRITICAL_SECTION CriticalSection) { - int err = sys_lwmutex_trylock(CriticalSection); + int err = sys_lwmutex_trylock(CriticalSection); if(err == CELL_OK) return true; return false; @@ -209,8 +209,8 @@ DWORD WaitForMultipleObjects(DWORD nCount, CONST HANDLE *lpHandles,BOOL bWaitAll -BOOL CloseHandle(HANDLE hObject) -{ +BOOL CloseHandle(HANDLE hObject) +{ if(hObject==INVALID_HANDLE_VALUE) { //printf("\n\nTRYING TO CLOSE AN INVALID FILE HANDLE\n\n"); @@ -219,13 +219,13 @@ BOOL CloseHandle(HANDLE hObject) else { CellFsErrno err; - err=cellFsClose(int(hObject)); + err=cellFsClose(int(hObject)); if(err==CELL_FS_SUCCEEDED) { iFilesOpen--; - AUTO_VAR(itEnd, vOpenFileHandles.end()); - for (AUTO_VAR(it, vOpenFileHandles.begin()); it != itEnd; it++) + auto itEnd = vOpenFileHandles.end(); + for ( auto it = vOpenFileHandles.begin(); it != itEnd; it++) { int iFH=(int)*it; if(iFH==(int)hObject) @@ -235,7 +235,7 @@ BOOL CloseHandle(HANDLE hObject) } } //printf("\n\nFiles Open - %d\n\n",iFilesOpen); - return true; + return true; } else { @@ -249,8 +249,8 @@ BOOL SetEvent(HANDLE hEvent) { PS3_STUBBED; return false; } HMODULE GetModuleHandle(LPCSTR lpModuleName) { PS3_STUBBED; return 0; } -sys_ppu_thread_t GetCurrentThreadId(VOID) -{ +sys_ppu_thread_t GetCurrentThreadId(VOID) +{ sys_ppu_thread_t id; int err = sys_ppu_thread_get_id(&id); PS3_ASSERT_CELL_ERROR(err); @@ -264,8 +264,8 @@ BOOL TlsFree(DWORD dwTlsIndex) { return TLSStoragePS3::Instance()->Free(dwTlsInd LPVOID TlsGetValue(DWORD dwTlsIndex) { return TLSStoragePS3::Instance()->GetValue(dwTlsIndex); } BOOL TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue) { return TLSStoragePS3::Instance()->SetValue(dwTlsIndex, lpTlsValue); } -LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) -{ +LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) +{ int err; sys_addr_t newAddress = NULL; if(lpAddress == NULL) @@ -299,7 +299,7 @@ LPVOID VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWO return (LPVOID)newAddress; } -BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) +BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) { if(dwFreeType == MEM_DECOMMIT) { @@ -307,12 +307,12 @@ BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) sys_vm_statistics_t stat; err = sys_vm_get_statistics((sys_addr_t)lpAddress, &stat); PS3_ASSERT(err == CELL_OK); - + // 4J Stu - We can only return what we have actually committed on PS3 // From PS3 Docs: // The maximum amount of memory that can be returned is the difference of the total amount of physical memory used by the virtual memory area minus 1MB. When an amount exceeding this value is specified, EBUSY will return. SIZE_T memToFree = stat.pmem_total - (1024 * 1024); - if(dwSize < memToFree) + if(dwSize < memToFree) memToFree = dwSize; app.DebugPrintf("VirtualFree: Requested size - %d, Actual size - %d\n", dwSize, memToFree); @@ -349,10 +349,10 @@ BOOL WriteFile( HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPD uint64_t bytesWritten; CellFsErrno err = cellFsWrite(fd, lpBuffer, nNumberOfBytesToWrite, &bytesWritten); *lpNumberOfBytesWritten = (DWORD)bytesWritten; - return (err == CELL_FS_OK); + return (err == CELL_FS_OK); } -BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped ) +BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped ) { int fd = (int)hFile; uint64_t bytesRead; @@ -374,7 +374,7 @@ BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD break; } - return (err==CELL_FS_SUCCEEDED); + return (err==CELL_FS_SUCCEEDED); } BOOL SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, DWORD dwMoveMethod) @@ -407,7 +407,7 @@ void replaceBackslashes(char* szFilename) } } -HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) +HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { char filePath[256]; std::string mountedPath; @@ -445,7 +445,7 @@ HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, int fd = 0; int flags = 0; switch(dwDesiredAccess) - { + { case GENERIC_READ: flags = CELL_FS_O_RDONLY; break; case GENERIC_WRITE: @@ -508,7 +508,7 @@ HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, switch(err) { case CELL_FS_SUCCEEDED: - { + { app.DebugPrintf("CELL_FS_SUCCEEDED\n"); DWORD dwFileSize = (DWORD)statData.st_size; @@ -522,7 +522,7 @@ HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, // fd is invalid or the file system on a removable media has been unmounted // When cellFsFstat() returns CELL_FS_EBADF, it can be deduced that the above error occurred because a disc was ejected. - // Explicitly call cellFsClose() and close the applicable file. When using stream supporting APIs, call cellFsStReadFinish() before calling cellFsClose(). + // Explicitly call cellFsClose() and close the applicable file. When using stream supporting APIs, call cellFsStReadFinish() before calling cellFsClose(). app.DebugPrintf("CELL_FS_EBADF\n"); CloseHandle((HANDLE)fd); @@ -531,7 +531,7 @@ HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, //ShutdownManager::StartShutdown(); return INVALID_HANDLE_VALUE; - + case CELL_FS_EIO: app.DebugPrintf("CELL_FS_EIO\n"); break; @@ -550,8 +550,8 @@ HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, return (void*)fd; } -BOOL CreateDirectoryA(LPCSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes) -{ +BOOL CreateDirectoryA(LPCSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes) +{ char filePath[256]; sprintf(filePath,"%s/%s",usrdirPath, lpPathName ); CellFsErrno err = cellFsMkdir(filePath, CELL_FS_DEFAULT_CREATE_MODE_1); @@ -563,12 +563,12 @@ BOOL CreateDirectoryA(LPCSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttribu BOOL DeleteFileA(LPCSTR lpFileName) { PS3_STUBBED; return false; } -// BOOL XCloseHandle(HANDLE a) -// { -// cellFsClose(int(a)); +// BOOL XCloseHandle(HANDLE a) +// { +// cellFsClose(int(a)); // } -DWORD GetFileAttributesA(LPCSTR lpFileName) +DWORD GetFileAttributesA(LPCSTR lpFileName) { char filePath[256]; std::string mountedPath = StorageManager.GetMountedPath(lpFileName); @@ -582,7 +582,7 @@ DWORD GetFileAttributesA(LPCSTR lpFileName) sprintf(filePath,"%s/%s",usrdirPath, lpFileName ); // set to load from host //strcat(filePath,".edat"); - + //printf("GetFileAttributesA - %s\n",filePath); // check if the file exists first @@ -606,7 +606,7 @@ VOID DebugBreak(VOID) { snPause(); } DWORD GetLastError(VOID) { PS3_STUBBED; return 0; } -VOID GlobalMemoryStatus(LPMEMORYSTATUS lpBuffer) +VOID GlobalMemoryStatus(LPMEMORYSTATUS lpBuffer) { malloc_managed_size stat; int err = malloc_stats(&stat); @@ -620,20 +620,20 @@ VOID GlobalMemoryStatus(LPMEMORYSTATUS lpBuffer) lpBuffer->dwAvailVirtual = stat.max_system_size - stat.current_inuse_size; } -DWORD GetTickCount() +DWORD GetTickCount() { - // This function returns the current system time at this function is called. + // This function returns the current system time at this function is called. // The system time is represented the time elapsed since the system starts up in microseconds. system_time_t sysTime = sys_time_get_system_time(); - return sysTime / 1000; + return sysTime / 1000; } // we should really use libperf for this kind of thing, but this will do for now. -BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency) -{ +BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency) +{ // microseconds - lpFrequency->QuadPart = (1000 * 1000); - return false; + lpFrequency->QuadPart = (1000 * 1000); + return false; } BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount) { @@ -646,24 +646,24 @@ BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount) } #ifndef _FINAL_BUILD -VOID OutputDebugStringW(LPCWSTR lpOutputString) -{ - wprintf(lpOutputString); +VOID OutputDebugStringW(LPCWSTR lpOutputString) +{ + wprintf(lpOutputString); } -VOID OutputDebugString(LPCSTR lpOutputString) -{ - printf(lpOutputString); +VOID OutputDebugString(LPCSTR lpOutputString) +{ + printf(lpOutputString); } -VOID OutputDebugStringA(LPCSTR lpOutputString) -{ - printf(lpOutputString); +VOID OutputDebugStringA(LPCSTR lpOutputString) +{ + printf(lpOutputString); } #endif // _CONTENT_PACKAGE BOOL GetFileAttributesExA(LPCSTR lpFileName,GET_FILEEX_INFO_LEVELS fInfoLevelId,LPVOID lpFileInformation) -{ +{ PS3_STUBBED; return false; } @@ -680,13 +680,13 @@ int _wtoi(const wchar_t *_Str) -DWORD XGetLanguage() -{ +DWORD XGetLanguage() +{ unsigned char ucLang = app.GetMinecraftLanguage(0); int iLang; // check if we should override the system language or not - if(ucLang==MINECRAFT_LANGUAGE_DEFAULT) + if(ucLang==MINECRAFT_LANGUAGE_DEFAULT) { cellSysutilGetSystemParamInt(CELL_SYSUTIL_SYSTEMPARAM_ID_LANG,&iLang); } @@ -701,7 +701,7 @@ DWORD XGetLanguage() case CELL_SYSUTIL_LANG_ENGLISH_US : return XC_LANGUAGE_ENGLISH; case CELL_SYSUTIL_LANG_FRENCH : return XC_LANGUAGE_FRENCH; - case CELL_SYSUTIL_LANG_SPANISH : + case CELL_SYSUTIL_LANG_SPANISH : if(app.IsAmericanSKU()) { return XC_LANGUAGE_LATINAMERICANSPANISH; @@ -714,7 +714,7 @@ DWORD XGetLanguage() case CELL_SYSUTIL_LANG_GERMAN : return XC_LANGUAGE_GERMAN; case CELL_SYSUTIL_LANG_ITALIAN : return XC_LANGUAGE_ITALIAN; case CELL_SYSUTIL_LANG_PORTUGUESE_PT : return XC_LANGUAGE_PORTUGUESE; - + case CELL_SYSUTIL_LANG_RUSSIAN : return XC_LANGUAGE_RUSSIAN; case CELL_SYSUTIL_LANG_KOREAN : return XC_LANGUAGE_KOREAN; case CELL_SYSUTIL_LANG_CHINESE_T : return XC_LANGUAGE_TCHINESE; @@ -735,8 +735,8 @@ DWORD XGetLanguage() } } -DWORD XGetLocale() -{ +DWORD XGetLocale() +{ int iLang; cellSysutilGetSystemParamInt(CELL_SYSUTIL_SYSTEMPARAM_ID_LANG,&iLang); switch(iLang) @@ -745,7 +745,7 @@ DWORD XGetLocale() case CELL_SYSUTIL_LANG_ENGLISH_US : return XC_LOCALE_UNITED_STATES; case CELL_SYSUTIL_LANG_FRENCH : return XC_LOCALE_FRANCE; - case CELL_SYSUTIL_LANG_SPANISH : + case CELL_SYSUTIL_LANG_SPANISH : if(app.IsAmericanSKU()) { return XC_LOCALE_LATIN_AMERICA; @@ -753,7 +753,7 @@ DWORD XGetLocale() else { return XC_LOCALE_SPAIN; - } + } return XC_LOCALE_SPAIN; case CELL_SYSUTIL_LANG_GERMAN : return XC_LOCALE_GERMANY; @@ -777,11 +777,11 @@ DWORD XGetLocale() case CELL_SYSUTIL_LANG_CHINESE_S : return XC_LOCALE_CHINA; default : return XC_LOCALE_UNITED_STATES; - } + } } -DWORD XEnableGuestSignin(BOOL fEnable) -{ - return 0; +DWORD XEnableGuestSignin(BOOL fEnable) +{ + return 0; } #endif // __PS3__ diff --git a/Minecraft.Client/PS3/PS3Extras/Ps3Types.h b/Minecraft.Client/PS3/PS3Extras/Ps3Types.h index b6cf351d..d3d8cc6a 100644 --- a/Minecraft.Client/PS3/PS3Extras/Ps3Types.h +++ b/Minecraft.Client/PS3/PS3Extras/Ps3Types.h @@ -35,29 +35,28 @@ using boost::hash; // user the pool_allocator for all unordered_set and unordered_map instances -// template < class T, class H = hash<T>, class P = std::equal_to<T>, class A = boost::pool_allocator<T> > -// class unordered_set : public std::tr1::unordered_set<T, H, P, A > +// template < class T, class H = hash<T>, class P = std::equal_to<T>, class A = boost::pool_allocator<T> > +// class unordered_set : public std::tr1::unordered_set<T, H, P, A > // {}; -// -// template <class K, class T, class H = hash<K>, class P = std::equal_to<K>, class A = boost::pool_allocator<std::pair<const K,T> > > -// class unordered_map : public std::tr1::unordered_map<K, T, H, P, A > +// +// template <class K, class T, class H = hash<K>, class P = std::equal_to<K>, class A = boost::pool_allocator<std::pair<const K,T> > > +// class unordered_map : public std::tr1::unordered_map<K, T, H, P, A > // {}; -// template < class T, class H = hash<T>, class P = std::equal_to<T>, class A = C4JPoolAllocator<T> > -// class unordered_set : public std::tr1::unordered_set<T, H, P, A > +// template < class T, class H = hash<T>, class P = std::equal_to<T>, class A = C4JPoolAllocator<T> > +// class unordered_set : public std::tr1::unordered_set<T, H, P, A > // {}; -// -// template <class K, class T, class H = hash<K>, class P = std::equal_to<K>, class A = C4JPoolAllocator<std::pair<const K,T> > > -// class unordered_map : public std::tr1::unordered_map<K, T, H, P, A > +// +// template <class K, class T, class H = hash<K>, class P = std::equal_to<K>, class A = C4JPoolAllocator<std::pair<const K,T> > > +// class unordered_map : public std::tr1::unordered_map<K, T, H, P, A > // {}; // using boost::ublas::vector; #define static_assert(a,b) BOOST_STATIC_ASSERT(a) -#define AUTO_VAR BOOST_AUTO class Cnullptr{ public: diff --git a/Minecraft.Client/PS3/PS3_App.cpp b/Minecraft.Client/PS3/PS3_App.cpp index d2ab7150..e5e23933 100644 --- a/Minecraft.Client/PS3/PS3_App.cpp +++ b/Minecraft.Client/PS3/PS3_App.cpp @@ -31,7 +31,7 @@ CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() m_bVoiceChatAndUGCRestricted=false; m_bDisplayFullVersionPurchase=false; -// #ifdef _DEBUG_MENUS_ENABLED +// #ifdef _DEBUG_MENUS_ENABLED // debugOverlayCreated = false; // #endif @@ -173,7 +173,7 @@ BOOL CConsoleMinecraftApp::ReadProductCodes() WRAPPED_READFILE(file,&pDLCInfo->iConfig,sizeof(int),&bytesRead,NULL); // push this into a vector - + wstring wstrTemp=convStringToWstring(chDLCTitle); m_SONYDLCMap[wstrTemp]=pDLCInfo; } @@ -266,7 +266,7 @@ void CConsoleMinecraftApp::FatalLoadError() aStrings[1] = L"Ðе удалоÑÑŒ загрузить игру \"Minecraft: PlayStation®3 Edition\". Продолжить загрузку невозможно."; aStrings[2] = L"Выйти из игры"; break; - case XC_LANGUAGE_TCHINESE: + case XC_LANGUAGE_TCHINESE: aStrings[0] = L"載入錯誤"; aStrings[1] = L"無法載入「Minecraft: PlayStation®3 Editionã€ï¼Œå› æ¤ç„¡æ³•繼續。"; aStrings[2] = L"é›¢é–‹éŠæˆ²"; @@ -360,7 +360,7 @@ void CConsoleMinecraftApp::FatalLoadError() } app.DebugPrintf("Requesting Message Box for Fatal Error again due to BUSY\n"); eResult=InputManager.RequestMessageBox(EMSgBoxType_None,0,NULL,this,(char *)u8Message,0); - } + } while(1) { @@ -467,7 +467,7 @@ void CConsoleMinecraftApp::FreeLocalTMSFiles(eTMSFileType eType) } LoadSaveDataThreadParam* LoadSaveFromDisk(const wstring& pathName) -{ +{ File saveFile(pathName); __int64 fileSize = saveFile.length(); FileInputStream fis(saveFile); @@ -595,7 +595,7 @@ void CConsoleMinecraftApp::CommerceTick() break; case eCommerce_State_GetProductList: - { + { m_eCommerce_State=eCommerce_State_GetProductList_Pending; SonyCommerce::CategoryInfo *pCategories=app.GetCategoryInfo(); std::list<SonyCommerce::CategoryInfoSub>::iterator iter = pCategories->subCategories.begin(); @@ -611,7 +611,7 @@ void CConsoleMinecraftApp::CommerceTick() break; case eCommerce_State_AddProductInfoDetailed: - { + { m_eCommerce_State=eCommerce_State_AddProductInfoDetailed_Pending; // for each of the products in the categories, get the detailed info. We really only need the long description and price info. @@ -648,7 +648,7 @@ void CConsoleMinecraftApp::CommerceTick() break; case eCommerce_State_RegisterDLC: - { + { m_eCommerce_State=eCommerce_State_Online; // register the DLC info SonyCommerce::CategoryInfo *pCategories=app.GetCategoryInfo(); @@ -738,16 +738,16 @@ void CConsoleMinecraftApp::ClearCommerceDetails() { for(int i=0;i<m_ProductListCategoriesC;i++) { - std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; + std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; pProductList->clear(); } if(m_ProductListA!=NULL) { - delete [] m_ProductListA; + delete [] m_ProductListA; m_ProductListA=NULL; } - + m_ProductListRetrievedC=0; m_ProductListAdditionalDetailsC=0; m_ProductListCategoriesC=0; @@ -772,17 +772,17 @@ void CConsoleMinecraftApp::GetDLCSkuIDFromProductList(char * pchDLCProductID, ch for(int j=0;j<m_ProductListA[i].size();j++) { std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; - AUTO_VAR(itEnd, pProductList->end()); + auto itEnd = pProductList->end(); - for (AUTO_VAR(it, pProductList->begin()); it != itEnd; it++) - { + for (auto it = pProductList->begin(); it != itEnd; it++) + { SonyCommerce::ProductInfo Info=*it; if(strcmp(pchDLCProductID,Info.productId)==0) - { + { memcpy(pchSkuID,Info.skuId,SCE_NP_COMMERCE2_SKU_ID_LEN); return; } - } + } } } return; @@ -791,7 +791,7 @@ void CConsoleMinecraftApp::GetDLCSkuIDFromProductList(char * pchDLCProductID, ch void CConsoleMinecraftApp::Checkout(char *pchSkuID) { if(m_eCommerce_State==eCommerce_State_Online) - { + { strcpy(m_pchSkuID,pchSkuID); m_eCommerce_State=eCommerce_State_Checkout; } @@ -800,7 +800,7 @@ void CConsoleMinecraftApp::Checkout(char *pchSkuID) void CConsoleMinecraftApp::DownloadAlreadyPurchased(char *pchSkuID) { if(m_eCommerce_State==eCommerce_State_Online) - { + { strcpy(m_pchSkuID,pchSkuID); m_eCommerce_State=eCommerce_State_DownloadAlreadyPurchased; } @@ -809,7 +809,7 @@ void CConsoleMinecraftApp::DownloadAlreadyPurchased(char *pchSkuID) bool CConsoleMinecraftApp::UpgradeTrial() { if(m_eCommerce_State==eCommerce_State_Online) - { + { m_eCommerce_State=eCommerce_State_UpgradeTrial; return true; } @@ -845,13 +845,13 @@ bool CConsoleMinecraftApp::DLCAlreadyPurchased(char *pchTitle) for(int j=0;j<m_ProductListA[i].size();j++) { std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; - AUTO_VAR(itEnd, pProductList->end()); - - for (AUTO_VAR(it, pProductList->begin()); it != itEnd; it++) - { + auto itEnd = pProductList->end(); + + for (auto it = pProductList->begin(); it != itEnd; it++) + { SonyCommerce::ProductInfo Info=*it; if(strcmp(pchTitle,Info.skuId)==0) - { + { if(Info.purchasabilityFlag==SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_OFF) { return true; @@ -861,7 +861,7 @@ bool CConsoleMinecraftApp::DLCAlreadyPurchased(char *pchTitle) return false; } } - } + } } } return false; @@ -896,7 +896,7 @@ void CConsoleMinecraftApp::CommerceGetCategoriesCallback(LPVOID lpParam,int err) if(err==0) { pClass->m_ProductListCategoriesC=pClass->m_CategoryInfo.countOfSubCategories; - // allocate the memory for the product info for each categories + // allocate the memory for the product info for each categories if(pClass->m_CategoryInfo.countOfSubCategories>0) { pClass->m_ProductListA = (std::vector<SonyCommerce::ProductInfo> *) new std::vector<SonyCommerce::ProductInfo> [pClass->m_CategoryInfo.countOfSubCategories]; @@ -928,7 +928,7 @@ void CConsoleMinecraftApp::CommerceGetProductListCallback(LPVOID lpParam,int err { // we're done, so now retrieve the additional product details for each product pClass->m_eCommerce_State=eCommerce_State_AddProductInfoDetailed; - pClass->m_bCommerceProductListRetrieved=true; + pClass->m_bCommerceProductListRetrieved=true; } else { @@ -938,21 +938,21 @@ void CConsoleMinecraftApp::CommerceGetProductListCallback(LPVOID lpParam,int err else { pClass->m_eCommerce_State=eCommerce_State_Error; - pClass->m_bCommerceProductListRetrieved=true; + pClass->m_bCommerceProductListRetrieved=true; } } // void CConsoleMinecraftApp::CommerceGetDetailedProductInfoCallback(LPVOID lpParam,int err) // { // CConsoleMinecraftApp *pScene=(CConsoleMinecraftApp *)lpParam; -// +// // if(err==0) // { // pScene->m_eCommerce_State=eCommerce_State_Idle; -// //pScene->m_bCommerceProductListRetrieved=true; +// //pScene->m_bCommerceProductListRetrieved=true; // } // //printf("Callback hit, error 0x%08x\n", err); -// +// // } void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam,int err) @@ -971,7 +971,7 @@ void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam { // MGH - change this to a while loop so we can skip empty categories. do - { + { pClass->m_iCurrentCategory++; }while(pClass->m_ProductListA[pClass->m_iCurrentCategory].size() == 0 && pClass->m_iCurrentCategory<pClass->m_ProductListCategoriesC); @@ -980,12 +980,12 @@ void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam { // there are no more categories, so we're done pClass->m_eCommerce_State=eCommerce_State_RegisterDLC; - pClass->m_bProductListAdditionalDetailsRetrieved=true; + pClass->m_bProductListAdditionalDetailsRetrieved=true; } else { // continue with the next category - pClass->m_eCommerce_State=eCommerce_State_AddProductInfoDetailed; + pClass->m_eCommerce_State=eCommerce_State_AddProductInfoDetailed; } } else @@ -997,7 +997,7 @@ void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam else { pClass->m_eCommerce_State=eCommerce_State_Error; - pClass->m_bProductListAdditionalDetailsRetrieved=true; + pClass->m_bProductListAdditionalDetailsRetrieved=true; pClass->m_iCurrentProduct=0; pClass->m_iCurrentCategory=0; } @@ -1166,7 +1166,7 @@ char *PatchFilelist[] = // "/TitleUpdate/res/font/Default.png", "/TitleUpdate/res/font/Mojangles_7.png", "/TitleUpdate/res/font/Mojangles_11.png", - + "music/music/creative1.binka", "music/music/creative2.binka", "music/music/creative3.binka", @@ -1227,7 +1227,7 @@ bool CConsoleMinecraftApp::CheckForEmptyStore(int iPad) bool bEmptyStore=true; if(pCategories!=NULL) - { + { if(pCategories->countOfProducts>0) { bEmptyStore=false; diff --git a/Minecraft.Client/PS3/PS3_Minecraft.cpp b/Minecraft.Client/PS3/PS3_Minecraft.cpp index 821a47d9..53b47d2d 100644 --- a/Minecraft.Client/PS3/PS3_Minecraft.cpp +++ b/Minecraft.Client/PS3/PS3_Minecraft.cpp @@ -36,7 +36,7 @@ SYS_PROCESS_PARAM(1001, 0x10000); // thread priority, and stack size #endif /* Encrypted ID for protected data file (*) You must edit these binaries!! */ -char secureFileId[CELL_SAVEDATA_SECUREFILEID_SIZE] = +char secureFileId[CELL_SAVEDATA_SECUREFILEID_SIZE] = { 0xEE, 0xA9, 0x37, 0xCC, 0x5B, 0xD4, 0xD9, 0x0D, @@ -51,7 +51,7 @@ char secureFileId[CELL_SAVEDATA_SECUREFILEID_SIZE] = //#define HEAPINSPECTOR_PS3 1 // when defining HEAPINSPECTOR_PS3, add this line to the linker settings -// --wrap malloc --wrap free --wrap memalign --wrap calloc --wrap realloc --wrap reallocalign --wrap _malloc_init +// --wrap malloc --wrap free --wrap memalign --wrap calloc --wrap realloc --wrap reallocalign --wrap _malloc_init #if HEAPINSPECTOR_PS3 #include "HeapInspector\Server\HeapInspectorServer.h" @@ -149,13 +149,13 @@ extern "C" void* __wrap__malloc_init(size_t a_Boundary, size_t a_Size) #endif // HEAPINSPECTOR_PS3 //------------------------------------------------------------------------------------- -// Time Since fAppTime is a float, we need to keep the quadword app time +// Time Since fAppTime is a float, we need to keep the quadword app time // as a LARGE_INTEGER so that we don't lose precision after running // for a long time. //------------------------------------------------------------------------------------- BOOL g_bWidescreen = TRUE; -//int g_numberOfSpeakersForMiles = 2; // number of speakers to pass to Miles, this is setup from init_audio_hardware +//int g_numberOfSpeakersForMiles = 2; // number of speakers to pass to Miles, this is setup from init_audio_hardware void DefineActions(void) { @@ -216,12 +216,12 @@ void DefineActions(void) InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_CRAFTING, _360_JOY_BUTTON_X); InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_RENDER_THIRD_PERSON, _360_JOY_BUTTON_LTHUMB); InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_GAME_INFO, _360_JOY_BUTTON_BACK); - + InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_LEFT, _360_JOY_BUTTON_DPAD_LEFT); InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT); InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_UP, _360_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); - + InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); + if(InputManager.IsCircleCrossSwapped()) { InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_A, _360_JOY_BUTTON_B); @@ -275,12 +275,12 @@ void DefineActions(void) InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_CRAFTING, _360_JOY_BUTTON_X); InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_RENDER_THIRD_PERSON, _360_JOY_BUTTON_RTHUMB); InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_GAME_INFO, _360_JOY_BUTTON_BACK); - + InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_LEFT, _360_JOY_BUTTON_DPAD_LEFT); InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT); InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_UP, _360_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); - + InputManager.SetGameJoypadMaps(MAP_STYLE_1,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); + if(InputManager.IsCircleCrossSwapped()) { InputManager.SetGameJoypadMaps(MAP_STYLE_2,ACTION_MENU_A, _360_JOY_BUTTON_B); @@ -334,11 +334,11 @@ void DefineActions(void) InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_CRAFTING, _360_JOY_BUTTON_X); InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_RENDER_THIRD_PERSON, _360_JOY_BUTTON_LTHUMB); InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_GAME_INFO, _360_JOY_BUTTON_BACK); - + InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_LEFT, _360_JOY_BUTTON_DPAD_LEFT); InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT); InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_UP, _360_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_2,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); } @@ -438,7 +438,7 @@ void LoadSysModule(uint16_t module, const char* moduleName) #define LOAD_PS3_MODULE(m) LoadSysModule(m, #m) -int simpleMessageBoxCallback( UINT uiTitle, UINT uiText, +int simpleMessageBoxCallback( UINT uiTitle, UINT uiText, UINT *uiOptionA, UINT uiOptionC, DWORD dwPad, int(*Func) (LPVOID,int,const C4JStorage::EMessageResult), LPVOID lpParam ) @@ -580,7 +580,7 @@ int LoadSysModules() LOAD_PS3_MODULE(CELL_SYSMODULE_AVCONF_EXT); LOAD_PS3_MODULE(CELL_SYSMODULE_SYSUTIL_SAVEDATA); - + unsigned int uiType ; unsigned int uiAttributes ; CellGameContentSize size,sizeBD; @@ -598,20 +598,20 @@ int LoadSysModules() if(ret < 0) { DEBUG_PRINTF("cellGameBootCheck() Error: 0x%x\n", ret); - } - else + } + else { DEBUG_PRINTF("cellGameBootCheck() OK\n"); DEBUG_PRINTF(" get_type = [%d] get_attributes = [0x%08x] dirName = [%s]\n", uiType, uiAttributes, dirName); - DEBUG_PRINTF(" hddFreeSizeKB = [%d] sizeKB = [%d] sysSizeKB = [%d]\n", size.hddFreeSizeKB, size.sizeKB, size.sysSizeKB); + DEBUG_PRINTF(" hddFreeSizeKB = [%d] sizeKB = [%d] sysSizeKB = [%d]\n", size.hddFreeSizeKB, size.sizeKB, size.sysSizeKB); } - if (uiAttributes & CELL_GAME_ATTRIBUTE_INVITE_MESSAGE) + if (uiAttributes & CELL_GAME_ATTRIBUTE_INVITE_MESSAGE) { g_bBootedFromInvite = true; DEBUG_PRINTF("Booted from invite\n"); } - if (uiAttributes & CELL_GAME_ATTRIBUTE_CUSTOM_DATA_MESSAGE) + if (uiAttributes & CELL_GAME_ATTRIBUTE_CUSTOM_DATA_MESSAGE) { DEBUG_PRINTF("Booted from custom data\n"); //bootedFromCustomData = true; @@ -623,12 +623,12 @@ int LoadSysModules() bBootedFromBDPatch=true; app.SetBootedFromDiscPatch(); } - // true if booting from disc, false if booting from HDD + // true if booting from disc, false if booting from HDD StorageManager.SetBootTypeDisc(uiType == CELL_GAME_GAMETYPE_DISC); StorageManager.SetMessageBoxCallback(&simpleMessageBoxCallback); - cellGameContentPermit(contentInfoPath,usrdirPath); + cellGameContentPermit(contentInfoPath,usrdirPath); DEBUG_PRINTF("contentInfoPath - %s\n",contentInfoPath); DEBUG_PRINTF("usrdirPath - %s\n",usrdirPath); @@ -636,12 +636,12 @@ int LoadSysModules() if(ret < 0) { DEBUG_PRINTF("cellGamePatchCheck() Error: 0x%x\n", ret); - } - else + } + else { DEBUG_PRINTF("cellGamePatchCheck() OK - we were booted from a disc patch!\n"); - cellGameContentPermit(contentInfoPathBDPatch,usrdirPathBDPatch); + cellGameContentPermit(contentInfoPathBDPatch,usrdirPathBDPatch); DEBUG_PRINTF("contentInfoPath - %s\n",contentInfoPathBDPatch); DEBUG_PRINTF("usrdirPath - %s\n",usrdirPathBDPatch); @@ -686,7 +686,7 @@ int main() // // initialize the ps3 - // + // int ihddFreeSizeKB=LoadSysModules(); ProfileManager.SetHDDFreeKB(ihddFreeSizeKB); @@ -699,7 +699,7 @@ int main() #ifndef DISABLE_MILES_SOUND -#ifdef USE_SPURS +#ifdef USE_SPURS void * spurs_info[ 2 ]; spurs_info[ 0 ] = C4JThread_SPU::getSpurs2(); extern const CellSpursTaskBinInfo _binary_task_mssspurs_elf_taskbininfo; @@ -753,7 +753,7 @@ int main() // // now initialize libAudio // - + cellAudioInit(); #endif // DISABLE_MILES_SOUND @@ -784,7 +784,7 @@ int main() { case e_sku_SCEE: // 4J-PB - need to be online to do this check, so let's stick with the 7+, and move this - + if(StorageManager.GetBootTypeDisc()) { // set Europe age, then hone down specific countries @@ -961,10 +961,10 @@ int main() } else { - StorageManager.SetGameSaveFolderTitle((WCHAR *)app.GetString(IDS_GAMENAME));//"Minecraft: PlayStation®3 Edition");//GAMENAME); + StorageManager.SetGameSaveFolderTitle((WCHAR *)app.GetString(IDS_GAMENAME));//"Minecraft: PlayStation�3 Edition");//GAMENAME); } - StorageManager.SetSaveCacheFolderTitle((WCHAR *)app.GetString(IDS_SAVECACHEFILE));//"Minecraft: PlayStation®3 Edition");//GAMENAME); - StorageManager.SetOptionsFolderTitle((WCHAR *)app.GetString(IDS_OPTIONSFILE));//"Minecraft: PlayStation®3 Edition");//GAMENAME); + StorageManager.SetSaveCacheFolderTitle((WCHAR *)app.GetString(IDS_SAVECACHEFILE));//"Minecraft: PlayStation�3 Edition");//GAMENAME); + StorageManager.SetOptionsFolderTitle((WCHAR *)app.GetString(IDS_OPTIONSFILE));//"Minecraft: PlayStation�3 Edition");//GAMENAME); StorageManager.SetGameSaveFolderPrefix(app.GetSaveFolderPrefix()); StorageManager.SetMaxSaves(99); byteArray baOptionsIcon = app.getArchiveFile(L"DefaultOptionsImage320x176.png"); @@ -1014,7 +1014,7 @@ int main() // Initialise TLS for AABB and Vec3 pools, for this main thread AABB::CreateNewThreadStorage(); Vec3::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); OldChunkStorage::CreateNewThreadStorage(); Level::enableLightingCache(); Tile::CreateNewThreadStorage(); @@ -1029,7 +1029,7 @@ int main() // set the default profile values // 4J-PB - InitGameSettings already does this /*for(int i=0;i<XUSER_MAX_COUNT;i++) - { + { #ifdef __PS3__ app.SetDefaultOptions(StorageManager.GetDashboardProfileSettings(i),i); #else @@ -1081,7 +1081,7 @@ int main() // 4J-PB - we really need to know at this point if we are playing the trial or full game, so sleep until we know while(app.GetCommerce()->LicenseChecked()==false) { - cellSysutilCheckCallback(); + cellSysutilCheckCallback(); Sleep(50); } // wait for the trophy init to complete - nonblocking semaphore @@ -1112,7 +1112,7 @@ int main() // 4J-PB - really want to wait until we've read the options, so we can set the right language if they've chosen one other than the default // bool bOptionsRead=false; -// +// // while((bOptionsRead==false) && ShutdownManager::ShouldRun(ShutdownManager::eMainThread)) // { // switch(app.GetOptionsCallbackStatus(0)) @@ -1125,7 +1125,7 @@ int main() // } // StorageManager.Tick(); // } -// +// // if(ShutdownManager::ShouldRun(ShutdownManager::eMainThread)) // { // app.loadStringTable(); @@ -1163,7 +1163,7 @@ int main() PIXBeginNamedEvent(0,"Social network manager tick"); // CSocialManager::Instance()->Tick(); PIXEndNamedEvent(); - + // Tick sentient. PIXBeginNamedEvent(0,"Sentient tick"); MemSect(37); @@ -1174,22 +1174,22 @@ int main() PIXBeginNamedEvent(0,"Network manager do work #1"); g_NetworkManager.DoWork(); PIXEndNamedEvent(); - // 4J-PB - these get set every tick causing the write profile flag to be true all the time - + // 4J-PB - these get set every tick causing the write profile flag to be true all the time - // app.SetGameSettingsDebugMask(0,eDebugSetting_LoadSavesFromDisk); // app.SetGameSettingsDebugMask(0,eDebugSetting_WriteSavesToDisk); // app.SetLoadSavesFromFolderEnabled(true); // app.SetWriteSavesToFolderEnabled(true); - + LeaderboardManager::Instance()->Tick(); // Render game graphics. - if(app.GetGameStarted()) + if(app.GetGameStarted()) { // if(InputManager.ButtonPressed(0, MINECRAFT_ACTION_SNEAK_TOGGLE)) // { // app.DebugPrintf("saving game...\n"); // debugSaveGameDirect(); -// +// // } pMinecraft->run_middle(); app.SetAppPaused( g_NetworkManager.IsLocalGame() && g_NetworkManager.GetPlayerCount() == 1 && ui.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()) ); @@ -1272,7 +1272,7 @@ int main() #ifdef _DEBUG_MENUS_ENABLED if(app.DebugSettingsOn()) { - app.ActionDebugMask(i); + app.ActionDebugMask(i); } else { @@ -1323,7 +1323,7 @@ int main() if(!ProfileManager.IsFullVersion()) { // display the trial timer - if(app.GetGameStarted()) + if(app.GetGameStarted()) { // 4J-PB - if the game is paused, add the elapsed time to the trial timer count so it doesn't tick down if(app.IsAppPaused()) @@ -1401,7 +1401,7 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) { if( !trackStarted ) { - void *p = XMemAllocDefault(dwSize,dwAllocAttributes); + void *p = XMemAllocDefault(dwSize,dwAllocAttributes); size_t realSize = XMemSizeDefault(p, dwAllocAttributes); totalAllocGen += realSize; return p; @@ -1409,7 +1409,7 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) EnterCriticalSection(&memCS); - void *p=XMemAllocDefault(dwSize + 16,dwAllocAttributes); + void *p=XMemAllocDefault(dwSize + 16,dwAllocAttributes); size_t realSize = XMemSizeDefault(p,dwAllocAttributes) - 16; if( trackEnable ) @@ -1435,7 +1435,7 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) trackEnable = true; } } - + LeaveCriticalSection(&memCS); return p; @@ -1470,7 +1470,7 @@ void WINAPI XMemFree(PVOID pAddress, DWORD dwAllocAttributes) if( pAddress ) { size_t realSize = XMemSizeDefault(pAddress, dwAllocAttributes) - 16; - + if(trackEnable) { int sect = *(((unsigned char *)pAddress)+realSize); @@ -1504,7 +1504,7 @@ SIZE_T WINAPI XMemSize( void DumpMem() { int totalLeak = 0; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) + for( auto it = allocCounts.begin(); it != allocCounts.end(); it++ ) { if(it->second > 0 ) { @@ -1552,7 +1552,7 @@ void MemPixStuff() int totals[MAX_SECT] = {0}; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) + for( auto it = allocCounts.begin(); it != allocCounts.end(); it++ ) { if(it->second > 0 ) { diff --git a/Minecraft.Client/PS3/Xbox_Minecraft.cpp b/Minecraft.Client/PS3/Xbox_Minecraft.cpp index fa9a33c7..b2630072 100644 --- a/Minecraft.Client/PS3/Xbox_Minecraft.cpp +++ b/Minecraft.Client/PS3/Xbox_Minecraft.cpp @@ -63,7 +63,7 @@ DWORD dwProfileSettingsA[NUM_PROFILE_VALUES]= #endif //------------------------------------------------------------------------------------- -// Time Since fAppTime is a float, we need to keep the quadword app time +// Time Since fAppTime is a float, we need to keep the quadword app time // as a LARGE_INTEGER so that we don't lose precision after running // for a long time. //------------------------------------------------------------------------------------- @@ -114,11 +114,11 @@ void DefineActions(void) InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_CRAFTING, _360_JOY_BUTTON_X); InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_RENDER_THIRD_PERSON, _360_JOY_BUTTON_LTHUMB); InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_GAME_INFO, _360_JOY_BUTTON_BACK); - + InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_LEFT, _360_JOY_BUTTON_DPAD_LEFT); InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_RIGHT, _360_JOY_BUTTON_DPAD_RIGHT); InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_UP, _360_JOY_BUTTON_DPAD_UP); - InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); + InputManager.SetGameJoypadMaps(MAP_STYLE_0,MINECRAFT_ACTION_DPAD_DOWN, _360_JOY_BUTTON_DPAD_DOWN); InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_A, _360_JOY_BUTTON_A); InputManager.SetGameJoypadMaps(MAP_STYLE_1,ACTION_MENU_B, _360_JOY_BUTTON_B); @@ -195,7 +195,7 @@ void DefineActions(void) } #if 0 -HRESULT InitD3D( IDirect3DDevice9 **ppDevice, +HRESULT InitD3D( IDirect3DDevice9 **ppDevice, D3DPRESENT_PARAMETERS *pd3dPP ) { IDirect3D9 *pD3D; @@ -222,14 +222,14 @@ HRESULT InitD3D( IDirect3DDevice9 **ppDevice, //pd3dPP->Flags = D3DPRESENTFLAG_NO_LETTERBOX; //ERR[D3D]: Can't set D3DPRESENTFLAG_NO_LETTERBOX when wide-screen is enabled // in the launcher/dashboard. - if(g_bWidescreen) + if(g_bWidescreen) pd3dPP->Flags=0; - else + else pd3dPP->Flags = D3DPRESENTFLAG_NO_LETTERBOX; // Create the device. return pD3D->CreateDevice( - 0, + 0, D3DDEVTYPE_HAL, NULL, D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_BUFFER_2_FRAMES, @@ -535,18 +535,18 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, } // Initialize the application, assuming sharing of the d3d interface. - hr = app.InitShared( pDevice, &d3dpp, + hr = app.InitShared( pDevice, &d3dpp, XuiPNGTextureLoader ); if ( FAILED(hr) ) { app.DebugPrintf ( "Failed initializing application.\n" ); - + return -1; } - - + + #endif RenderManager.Initialise(g_pd3dDevice, g_pSwapChain); @@ -642,7 +642,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, // set a function to be called when the ethernet is disconnected, so we can back out if required ProfileManager.SetNotificationsCallback(&CXboxMinecraftApp::NotificationsCallback,(LPVOID)&app); - + // Set a callback for the default player options to be set - when there is no profile data for the player ProfileManager.SetDefaultOptionsCallback(&CXboxMinecraftApp::DefaultOptionsCallback,(LPVOID)&app); // Set a callback to deal with old profile versions needing updated to new versions @@ -669,13 +669,13 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, if(XNuiGetHardwareStatus()!=0) { - // If the Kinect Sensor is not physically connected, this function returns 0. - NuiInitialize(NUI_INITIALIZE_FLAG_USES_HIGH_QUALITY_COLOR | NUI_INITIALIZE_FLAG_USES_DEPTH | + // If the Kinect Sensor is not physically connected, this function returns 0. + NuiInitialize(NUI_INITIALIZE_FLAG_USES_HIGH_QUALITY_COLOR | NUI_INITIALIZE_FLAG_USES_DEPTH | NUI_INITIALIZE_FLAG_EXTRAPOLATE_FLOOR_PLANE | NUI_INITIALIZE_FLAG_USES_FITNESS | NUI_INITIALIZE_FLAG_NUI_GUIDE_DISABLED | NUI_INITIALIZE_FLAG_SUPPRESS_AUTOMATIC_UI,NUI_INITIALIZE_DEFAULT_HARDWARE_THREAD ); } // Sentient ! - hr = SentientManager.Init(); + hr = SentientManager.Init(); #endif @@ -763,7 +763,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, } #endif - while( TRUE ) + while( TRUE ) { #if 0 if(pMinecraft->soundEngine->isStreamingWavebankReady() && @@ -792,7 +792,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, PIXBeginNamedEvent(0,"Social network manager tick"); // CSocialManager::Instance()->Tick(); PIXEndNamedEvent(); - + // Tick sentient. PIXBeginNamedEvent(0,"Sentient tick"); MemSect(37); @@ -806,7 +806,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, // LeaderboardManager::Instance()->Tick(); // Render game graphics. - if(app.GetGameStarted()) + if(app.GetGameStarted()) { pMinecraft->run_middle(); app.SetAppPaused( g_qNetManager.IsLocalGame() && g_qNetManager.GetPlayerCount() == 1 && app.IsPauseMenuDisplayed(ProfileManager.GetPrimaryPad()) ); @@ -881,7 +881,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, for(int i=0;i<8;i++) { - if(RenderStateA2[i]!=RenderStateA[i]) + if(RenderStateA2[i]!=RenderStateA[i]) { //printf("Reseting RenderStateA[%d] after a XUI render\n",i); pDevice->SetRenderState(RenderStateModes[i],RenderStateA[i]); @@ -889,7 +889,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, } for(int i=0;i<5;i++) { - if(SamplerStateA2[i]!=SamplerStateA[i]) + if(SamplerStateA2[i]!=SamplerStateA[i]) { //printf("Reseting SamplerStateA[%d] after a XUI render\n",i); pDevice->SetSamplerState(0,SamplerStateModes[i],SamplerStateA[i]); @@ -923,7 +923,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, #ifdef _DEBUG_MENUS_ENABLED if(app.DebugSettingsOn()) { - app.ActionDebugMask(i); + app.ActionDebugMask(i); } else { @@ -968,7 +968,7 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, if(!ProfileManager.IsFullVersion()) { // display the trial timer - if(app.GetGameStarted()) + if(app.GetGameStarted()) { // 4J-PB - if the game is paused, add the elapsed time to the trial timer count so it doesn't tick down if(app.IsAppPaused()) @@ -1016,7 +1016,7 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) { if( !trackStarted ) { - void *p = XMemAllocDefault(dwSize,dwAllocAttributes); + void *p = XMemAllocDefault(dwSize,dwAllocAttributes); size_t realSize = XMemSizeDefault(p, dwAllocAttributes); totalAllocGen += realSize; return p; @@ -1024,7 +1024,7 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) EnterCriticalSection(&memCS); - void *p=XMemAllocDefault(dwSize + 16,dwAllocAttributes); + void *p=XMemAllocDefault(dwSize + 16,dwAllocAttributes); size_t realSize = XMemSizeDefault(p,dwAllocAttributes) - 16; if( trackEnable ) @@ -1050,7 +1050,7 @@ LPVOID XMemAlloc(SIZE_T dwSize, DWORD dwAllocAttributes) trackEnable = true; } } - + LeaveCriticalSection(&memCS); return p; @@ -1085,7 +1085,7 @@ void WINAPI XMemFree(PVOID pAddress, DWORD dwAllocAttributes) if( pAddress ) { size_t realSize = XMemSizeDefault(pAddress, dwAllocAttributes) - 16; - + if(trackEnable) { int sect = *(((unsigned char *)pAddress)+realSize); @@ -1121,7 +1121,7 @@ SIZE_T WINAPI XMemSize( void DumpMem() { int totalLeak = 0; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) + for( auto it = allocCounts.begin(); it != allocCounts.end(); it++ ) { if(it->second > 0 ) { @@ -1169,7 +1169,7 @@ void MemPixStuff() int totals[MAX_SECT] = {0}; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) + for( auto it = allocCounts.begin(); it != allocCounts.end(); it++ ) { if(it->second > 0 ) { diff --git a/Minecraft.Client/PSVita/Network/SQRNetworkManager_AdHoc_Vita.cpp b/Minecraft.Client/PSVita/Network/SQRNetworkManager_AdHoc_Vita.cpp index 9a95ee08..dc9ad61e 100644 --- a/Minecraft.Client/PSVita/Network/SQRNetworkManager_AdHoc_Vita.cpp +++ b/Minecraft.Client/PSVita/Network/SQRNetworkManager_AdHoc_Vita.cpp @@ -68,7 +68,7 @@ SQRNetworkManager_AdHoc_Vita* s_pAdhocVitaManager;// have to use a static var f static bool s_attemptSignInAdhoc = true; // false if we're trying to sign in to the PSN while in adhoc mode, so we can ignore the error if it fails // This maps internal to extern states, and needs to match element-by-element the eSQRNetworkManagerInternalState enumerated type -const SQRNetworkManager_AdHoc_Vita::eSQRNetworkManagerState SQRNetworkManager_AdHoc_Vita::m_INTtoEXTStateMappings[SQRNetworkManager_AdHoc_Vita::SNM_INT_STATE_COUNT] = +const SQRNetworkManager_AdHoc_Vita::eSQRNetworkManagerState SQRNetworkManager_AdHoc_Vita::m_INTtoEXTStateMappings[SQRNetworkManager_AdHoc_Vita::SNM_INT_STATE_COUNT] = { SNM_STATE_INITIALISING, // SNM_INT_STATE_UNINITIALISED SNM_STATE_INITIALISING, // SNM_INT_STATE_SIGNING_IN @@ -144,7 +144,7 @@ SQRNetworkManager_AdHoc_Vita::SQRNetworkManager_AdHoc_Vita(ISQRNetworkManagerLis // assert(ret == SCE_OK); // ret = sceKernelAddUserEvent(m_basicEventQueue, sc_UserEventHandle); // assert(ret == SCE_OK); -// +// // m_basicEventThread = new C4JThread(&BasicEventThreadProc,this,"Basic Event Handler"); // m_basicEventThread->Run(); } @@ -153,7 +153,7 @@ static std::string getIPAddressString(SceNetInAddr add) { char str[32]; unsigned char *vals = (unsigned char*)&add.s_addr; - sprintf(str, "%d.%d.%d.%d", (int)vals[0], (int)vals[1], (int)vals[2], (int)vals[3]); + sprintf(str, "%d.%d.%d.%d", (int)vals[0], (int)vals[1], (int)vals[2], (int)vals[3]); return std::string(str); } @@ -204,14 +204,14 @@ void SQRNetworkManager_AdHoc_Vita::Initialise() // npConf.commPassphrase = &s_npCommunicationPassphrase; // npConf.commSignature = &s_npCommunicationSignature; // ret = sceNpInit(&npConf, NULL); -// if (ret < 0 && ret != SCE_NP_ERROR_ALREADY_INITIALIZED) +// if (ret < 0 && ret != SCE_NP_ERROR_ALREADY_INITIALIZED) // { // app.DebugPrintf("sceNpInit failed, ret=%x\n", ret); // assert(0); // } -// +// ret = sceRudpEnableInternalIOThread(RUDP_THREAD_STACK_SIZE, SCE_KERNEL_DEFAULT_PRIORITY); - if(ret < 0) + if(ret < 0) { app.DebugPrintf("sceRudpEnableInternalIOThread failed with error code 0x%08x\n", ret); assert(0); @@ -343,7 +343,7 @@ void SQRNetworkManager_AdHoc_Vita::StopMatchingContext() bool SQRNetworkManager_AdHoc_Vita::CreateMatchingContext(bool bServer /*= false*/) { - int matchingMode; + int matchingMode; if(bServer) { if(m_matchingContextServerValid) @@ -488,7 +488,7 @@ void SQRNetworkManager_AdHoc_Vita::Tick() TickWriteAcks(); OnlineCheck(); int ret; - if((ret = sceNetCtlCheckCallback()) < 0 ) + if((ret = sceNetCtlCheckCallback()) < 0 ) { app.DebugPrintf("sceNetCtlCheckCallback error[%d]",ret); } @@ -553,7 +553,7 @@ void SQRNetworkManager_AdHoc_Vita::Tick() { // make sure we've removed all the remote players and killed the udp connections before we bail out // if(m_RudpCtxToPlayerMap.size() == 0) - ResetToIdle(); + ResetToIdle(); } EnterCriticalSection(&m_csStateChangeQueue); @@ -735,7 +735,7 @@ bool SQRNetworkManager_AdHoc_Vita::FriendRoomManagerSearch2() // m_friendSearchState = SNM_FRIEND_SEARCH_STATE_IDLE; // return false; // } -// +// // if( m_aFriendSearchResults.size() > 0 ) // { // // If we have some results, then we also want to make sure that we don't have any duplicate rooms here if more than one friend is playing in the same room. @@ -747,7 +747,7 @@ bool SQRNetworkManager_AdHoc_Vita::FriendRoomManagerSearch2() // uniqueRooms.insert( m_aFriendSearchResults[i].m_RoomId ); // } // } -// +// // // Tidy the results up further based on this // for( unsigned int i = 0; i < m_aFriendSearchResults.size(); ) // { @@ -790,21 +790,21 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) PSVITA_STUBBED; return 0; // SQRNetworkManager_AdHoc_Vita *manager = (SQRNetworkManager_AdHoc_Vita *)lpParameter; -// +// // int ret = SCE_OK; // SceKernelEvent event; // int outEv; -// +// // do // { // ret = sceKernelWaitEqueue(manager->m_basicEventQueue, &event, 1, &outEv, NULL); -// +// // // If the sys_event_t we've sent here from the handler has a non-zero data1 element, this is to signify that we should terminate the thread // if( event.udata == 0 ) // { // // int iEvent; // // SceNpUserInfo from; -// // uint8_t buffer[SCE_NP_BASIC_MAX_MESSAGE_SIZE]; +// // uint8_t buffer[SCE_NP_BASIC_MAX_MESSAGE_SIZE]; // // size_t bufferSize = SCE_NP_BASIC_MAX_MESSAGE_SIZE; // // int ret = sceNpBasicGetEvent(&iEvent, &from, &buffer, &bufferSize); // // if( ret == 0 ) @@ -812,7 +812,7 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // // if( iEvent == SCE_NP_BASIC_EVENT_INCOMING_BOOTABLE_INVITATION ) // // { // // // 4J Stu - Don't do this here as it can be very disruptive to gameplay. Players can bring this up from LoadOrJoinMenu, PauseMenu and InGameInfoMenu -// // //sceNpBasicRecvMessageCustom(SCE_NP_BASIC_MESSAGE_MAIN_TYPE_INVITE, SCE_NP_BASIC_RECV_MESSAGE_OPTIONS_INCLUDE_BOOTABLE, SYS_MEMORY_CONTAINER_ID_INVALID); +// // //sceNpBasicRecvMessageCustom(SCE_NP_BASIC_MESSAGE_MAIN_TYPE_INVITE, SCE_NP_BASIC_RECV_MESSAGE_OPTIONS_INCLUDE_BOOTABLE, SYS_MEMORY_CONTAINER_ID_INVALID); // // } // // if( iEvent == SCE_NP_BASIC_EVENT_RECV_INVITATION_RESULT ) // // { @@ -825,7 +825,7 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // // app.DebugPrintf("Incoming basic event of type %d\n",iEvent); // // } // } -// +// // } while(event.udata == 0 ); // return 0; } @@ -833,7 +833,7 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // int SQRNetworkManager_AdHoc_Vita::GetFriendsThreadProc( void* lpParameter ) // { // SQRNetworkManager_AdHoc_Vita *manager = (SQRNetworkManager_AdHoc_Vita *)lpParameter; -// +// // int ret = 0; // manager->m_aFriendSearchResults.clear(); // manager->m_friendCount = 0; @@ -842,19 +842,19 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // app.DebugPrintf("getFriendslist failed, not signed into Live! \n"); // return 0; // } -// -// +// +// // ret = sceNpBasicGetFriendListEntryCount(&manager->m_friendCount); // if( ( ret < 0 ) || manager->ForceErrorPoint( SNM_FORCE_ERROR_GET_FRIEND_LIST_ENTRY_COUNT ) ) // { // // This is likely when friend list hasn't been received from the server yet - will be returning SCE_NP_BASIC_ERROR_BUSY in this case // manager->m_friendCount = 0; // } -// -// +// +// // // There shouldn't ever be more than 100 friends returned but limit here just in case // if( manager->m_friendCount > 100 ) manager->m_friendCount = 100; -// +// // SceNpId* friendIDs = NULL; // if(manager->m_friendCount > 0) // { @@ -862,7 +862,7 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // friendIDs = new SceNpId[manager->m_friendCount]; // SceSize numRecieved; // ret = sceNpBasicGetFriendListEntries(0, friendIDs, manager->m_friendCount, &numRecieved); -// if (ret < 0) +// if (ret < 0) // { // app.DebugPrintf("sceNpBasicGetFriendListEntries() failed: ret = 0x%x\n", ret); // manager->m_friendCount = 0; @@ -872,15 +872,15 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // assert(numRecieved == manager->m_friendCount); // } // } -// -// +// +// // // It is possible that the size of the friend list might vary from what we just received, so only add in friends that we successfully get an entry for // for( unsigned int i = 0; i < manager->m_friendCount; i++ ) // { // static SceNpBasicGamePresence presenceDetails; // static SceNpBasicFriendContextState contextState; // int ret = sceNpBasicGetFriendContextState(&friendIDs[i], &contextState); -// if (ret < 0) +// if (ret < 0) // { // app.DebugPrintf("sceNpBasicGetFriendContextState() failed: ret = 0x%x\n", ret); // contextState = SCE_NP_BASIC_FRIEND_CONTEXT_STATE_UNKNOWN; @@ -893,7 +893,7 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // FriendSearchResult result; // memcpy(&result.m_NpId, &friendIDs[i], sizeof(SceNpId)); // result.m_RoomFound = false; -// +// // // Only include the friend's game if its the same network id ( this also filters out generally Zeroed HelloSyncInfo, which we do when we aren't in an active game session) // // if( presenceDetails.size == sizeof(HelloSyncInfo) ) // { @@ -905,7 +905,7 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // result.m_RoomFound = true; // result.m_RoomId = pso->m_RoomId; // result.m_ServerId = pso->m_ServerId; -// +// // CPlatformNetworkManagerSony::MallocAndSetExtDataFromSQRPresenceInfo(&result.m_RoomExtDataReceived, pso); // manager->m_aFriendSearchResults.push_back(result); // } @@ -914,7 +914,7 @@ int SQRNetworkManager_AdHoc_Vita::BasicEventThreadProc( void *lpParameter ) // } // } // } -// +// // if(friendIDs) // delete friendIDs; // return 0; @@ -960,7 +960,7 @@ bool SQRNetworkManager_AdHoc_Vita::IsReadyToPlayOrIdle() // Consider as "in session" from the moment that a game is created or joined, until the point where the game itself has been told via state change that we are now idle. The -// game code requires IsInSession to return true as soon as it has asked to do one of these things (even if the state P hasn't really caught up with this request yet), and +// game code requires IsInSession to return true as soon as it has asked to do one of these things (even if the state P hasn't really caught up with this request yet), and // it also requires that it is informed of the state changes leading up to not being in the session, before this should report false. bool SQRNetworkManager_AdHoc_Vita::IsInSession() { @@ -1079,7 +1079,7 @@ void SQRNetworkManager_AdHoc_Vita::ResetToIdle() RemoveNetworkPlayers((1 << MAX_LOCAL_PLAYER_COUNT)-1); } else - { + { // we don't get signalling back from the matching libs to destroy connections, so we need to kill everything here std::vector<SceNpMatching2RoomMemberId> memberIDs; for(int i = 0; i < m_roomSyncData.getPlayerCount(); i++ ) @@ -1209,7 +1209,7 @@ void SQRNetworkManager_AdHoc_Vita::LeaveRoom(bool bActuallyLeaveRoom) if(!m_isHosting) { int ret = sceNetAdhocMatchingCancelTarget(m_matchingContext, &m_hostIPAddr); - if (ret < 0) + if (ret < 0) { app.DebugPrintf("sceNetAdhocMatchingCancelTarget error :[%d] [%x]\n",ret,ret) ; assert(0); @@ -1270,7 +1270,7 @@ bool SQRNetworkManager_AdHoc_Vita::RemoveLocalPlayerByUserIndex(int idx) extern uint8_t *mallocAndCreateUTF8ArrayFromString(int iID); -// Bring up a Gui to send an invite so a player that the user can select. This invite will contain the room Id so that +// Bring up a Gui to send an invite so a player that the user can select. This invite will contain the room Id so that void SQRNetworkManager_AdHoc_Vita::SendInviteGUI() { PSVITA_STUBBED; @@ -1309,8 +1309,8 @@ bool SQRNetworkManager_AdHoc_Vita::UpdateInviteData(HelloSyncInfo *invite) // and there's a period when starting up the host game where it doesn't accurately know the memberId for its own local players void SQRNetworkManager_AdHoc_Vita::FindOrCreateNonNetworkPlayer(int slot, int playerType, SceNpMatching2RoomMemberId memberId, int localPlayerIdx, int smallId) { - for(AUTO_VAR(it, m_vecTempPlayers.begin()); it != m_vecTempPlayers.end(); it++ ) - { + for (auto it = m_vecTempPlayers.begin(); it != m_vecTempPlayers.end(); it++) + { if( ((*it)->m_type == playerType ) && ( (*it)->m_localPlayerIdx == localPlayerIdx ) ) { if( ( playerType != SQRNetworkPlayer::SNP_TYPE_REMOTE ) || ( (*it)->m_roomMemberId == memberId ) ) @@ -1368,7 +1368,7 @@ void SQRNetworkManager_AdHoc_Vita::MapRoomSlotPlayers(int roomSlotPlayerCount/*= { EnterCriticalSection(&m_csRoomSyncData); - // If we pass an explicit roomSlotPlayerCount, it is because we are removing a player, and this is the count of slots that there were *before* the removal. + // If we pass an explicit roomSlotPlayerCount, it is because we are removing a player, and this is the count of slots that there were *before* the removal. bool zeroLastSlot = false; if( roomSlotPlayerCount == -1 ) { @@ -1472,7 +1472,7 @@ void SQRNetworkManager_AdHoc_Vita::MapRoomSlotPlayers(int roomSlotPlayerCount/*= } else { - FindOrCreateNonNetworkPlayer( i, SQRNetworkPlayer::SNP_TYPE_REMOTE, m_roomSyncData.players[i].m_roomMemberId, m_roomSyncData.players[i].m_localIdx, m_roomSyncData.players[i].m_smallId); + FindOrCreateNonNetworkPlayer( i, SQRNetworkPlayer::SNP_TYPE_REMOTE, m_roomSyncData.players[i].m_roomMemberId, m_roomSyncData.players[i].m_localIdx, m_roomSyncData.players[i].m_smallId); m_aRoomSlotPlayers[i]->SetUID(m_roomSyncData.players[i].m_UID); // On client, UIDs flow from m_roomSyncData->player data } } @@ -1480,8 +1480,8 @@ void SQRNetworkManager_AdHoc_Vita::MapRoomSlotPlayers(int roomSlotPlayerCount/*= } // Clear up any non-network players that are no longer required - this would be a good point to notify of players leaving when we support that // FindOrCreateNonNetworkPlayer will have pulled any players that we Do need out of m_vecTempPlayers, so the ones that are remaining are no longer in the game - for(AUTO_VAR(it, m_vecTempPlayers.begin()); it != m_vecTempPlayers.end(); it++ ) - { + for (auto it = m_vecTempPlayers.begin(); it != m_vecTempPlayers.end(); it++) + { if( m_listener ) { m_listener->HandlePlayerLeaving(*it); @@ -1565,7 +1565,7 @@ bool SQRNetworkManager_AdHoc_Vita::AddRemotePlayersAndSync( SceNpMatching2RoomMe } // We want to keep all players from a particular machine together, so search through the room sync data to see if we can find - // any pre-existing players from this machine. + // any pre-existing players from this machine. int firstIdx = -1; for( int i = 0; i < m_roomSyncData.getPlayerCount(); i++ ) { @@ -1683,8 +1683,8 @@ void SQRNetworkManager_AdHoc_Vita::RemoveNetworkPlayers( int mask ) { assert( !m_isHosting ); - for(AUTO_VAR(it, m_RudpCtxToPlayerMap.begin()); it != m_RudpCtxToPlayerMap.end(); ) - { + for (auto it = m_RudpCtxToPlayerMap.begin(); it != m_RudpCtxToPlayerMap.end();) + { SQRNetworkPlayer *player = it->second; if( (player->m_roomMemberId == m_localMemberId ) && ( ( 1 << player->m_localPlayerIdx ) & mask ) ) { @@ -1710,7 +1710,7 @@ void SQRNetworkManager_AdHoc_Vita::RemoveNetworkPlayers( int mask ) removePlayerFromVoiceChat(player); // Delete the player itself and the mapping from context to player map as this context is no longer valid - delete player; + delete player; } else { @@ -1724,15 +1724,15 @@ void SQRNetworkManager_AdHoc_Vita::RemoveNetworkPlayers( int mask ) void SQRNetworkManager_AdHoc_Vita::SetLocalPlayersAndSync() { assert( m_isHosting ); - + // Update local IP address UpdateLocalIPAddress(); - m_localMemberId = getRoomMemberID(&m_localIPAddr); + m_localMemberId = getRoomMemberID(&m_localIPAddr); if(IsHost()) m_hostMemberId = m_localMemberId; - + for( int i = 0; i < m_localPlayerCount; i++ ) { m_roomSyncData.players[i].m_roomMemberId = m_localMemberId; @@ -1754,8 +1754,8 @@ void SQRNetworkManager_AdHoc_Vita::SyncRoomData() UpdateRoomSyncUIDsFromPlayers(); // send the room data packet out to all the clients - for(AUTO_VAR(iter, m_RudpCtxToPlayerMap.begin()); iter != m_RudpCtxToPlayerMap.end(); ++iter) - { + for (auto iter = m_RudpCtxToPlayerMap.begin(); iter != m_RudpCtxToPlayerMap.end(); ++iter) + { int ctx = iter->first; SQRNetworkPlayer* pPlayer = GetPlayerFromRudpCtx(ctx); assert(pPlayer); @@ -1772,7 +1772,7 @@ void SQRNetworkManager_AdHoc_Vita::MatchingEventHandler(int id, int event, SceNe app.DebugPrintf("MatchingEventHandler_Server : ev : %d, ip addr : %s\n", event, getIPAddressString(*peer).c_str()); int ret; - switch (event) + switch (event) { case SCE_NET_ADHOC_MATCHING_EVENT_HELLO: app.DebugPrintf("P2P SCE_NET_ADHOC_MATCHING_EVENT_HELLO Received!!\n"); @@ -1843,13 +1843,13 @@ void SQRNetworkManager_AdHoc_Vita::MatchingEventHandler(int id, int event, SceNe case SCE_NET_ADHOC_MATCHING_EVENT_REQUEST: // A join request was received app.DebugPrintf("P2P SCE_NET_ADHOC_MATCHING_EVENT_REQUEST Received!!\n"); - if (optlen > 0 && opt != NULL) + if (optlen > 0 && opt != NULL) { ret = SCE_OK;// parentRequestAdd(opt); - if (ret != SCE_OK) + if (ret != SCE_OK) { ret = sceNetAdhocMatchingCancelTarget(manager->m_matchingContext, peer); - if (ret < 0) + if (ret < 0) { app.DebugPrintf("sceNetAdhocMatchingCancelTarget error :[%d] [%x]\n",ret,ret) ; assert(0); @@ -1912,7 +1912,7 @@ void SQRNetworkManager_AdHoc_Vita::MatchingEventHandler(int id, int event, SceNe // // If we've created a player, then we want to try and patch up any connections that we should have to it // manager->MapRoomSlotPlayers(); - // + // // SQRNetworkPlayer *player = manager->GetPlayerFromRudpCtx(peer->s_addr); // if( player ) // { @@ -1931,7 +1931,7 @@ void SQRNetworkManager_AdHoc_Vita::MatchingEventHandler(int id, int event, SceNe case SCE_NET_ADHOC_MATCHING_EVENT_TIMEOUT: // The participation agreement was canceled because of a Keep Alive timeout case SCE_NET_ADHOC_MATCHING_EVENT_DATA_TIMEOUT: if(event == SCE_NET_ADHOC_MATCHING_EVENT_DENY) - app.SetDisconnectReason(DisconnectPacket::eDisconnect_ServerFull); + app.SetDisconnectReason(DisconnectPacket::eDisconnect_ServerFull); else app.SetDisconnectReason(DisconnectPacket::eDisconnect_TimeOut); ret = sceNetAdhocMatchingCancelTarget(manager->m_matchingContext, peer); @@ -1943,10 +1943,10 @@ void SQRNetworkManager_AdHoc_Vita::MatchingEventHandler(int id, int event, SceNe // no break, carry on through to the BYE case -> // -> case SCE_NET_ADHOC_MATCHING_EVENT_BYE: // Target participating player has stopped matching - { + { app.DebugPrintf("P2P SCE_NET_ADHOC_MATCHING_EVENT_BYE Received!!\n"); - if(event == SCE_NET_ADHOC_MATCHING_EVENT_BYE && ! manager->IsInSession()) // + if(event == SCE_NET_ADHOC_MATCHING_EVENT_BYE && ! manager->IsInSession()) // { // the BYE event comes through like the HELLO event, so even even if we're not connected // so make sure we're actually in session @@ -1984,10 +1984,10 @@ void SQRNetworkManager_AdHoc_Vita::MatchingEventHandler(int id, int event, SceNe break; case SCE_NET_ADHOC_MATCHING_EVENT_DATA: - { + { app.DebugPrintf("P2P SCE_NET_ADHOC_MATCHING_EVENT_DATA Received!!\n"); - if (optlen <= 0 || opt == NULL) + if (optlen <= 0 || opt == NULL) { assert(0); break; @@ -2076,7 +2076,7 @@ void SQRNetworkManager_AdHoc_Vita::NetworkPlayerConnectionComplete(SQRNetworkPla if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2102,7 +2102,7 @@ void SQRNetworkManager_AdHoc_Vita::NetworkPlayerSmallIdAllocated(SQRNetworkPlaye if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2120,7 +2120,7 @@ void SQRNetworkManager_AdHoc_Vita::NetworkPlayerInitialDataReceived(SQRNetworkPl if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2136,7 +2136,7 @@ void SQRNetworkManager_AdHoc_Vita::HandlePlayerJoined(SQRNetworkPlayer *player) { if( m_listener ) { - m_listener->HandlePlayerJoined( player ); + m_listener->HandlePlayerJoined( player ); } // On client, keep a count of how many local players we have told the game about. We can only transition to telling the game that we are playing once the room is set up And all the local players are valid to use. if( !m_isHosting ) @@ -2250,7 +2250,7 @@ bool SQRNetworkManager_AdHoc_Vita::CreateRudpConnections(SceNetInAddr peer) sinp2pPeer.sin_addr = peer; sinp2pPeer.sin_port = sceNetHtons(SCE_NP_PORT); - // Set vport + // Set vport sinp2pPeer.sin_vport = sceNetHtons(ADHOC_VPORT); // Create socket & bind, if we don't already have one @@ -2306,8 +2306,8 @@ bool SQRNetworkManager_AdHoc_Vita::CreateRudpConnections(SceNetInAddr peer) SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetPlayerFromRudpCtx(int rudpCtx) { - AUTO_VAR(it,m_RudpCtxToPlayerMap.find(rudpCtx)); - if( it != m_RudpCtxToPlayerMap.end() ) + auto it = m_RudpCtxToPlayerMap.find(rudpCtx); + if( it != m_RudpCtxToPlayerMap.end() ) { return it->second; } @@ -2317,8 +2317,8 @@ SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetPlayerFromRudpCtx(int rudpCtx SceNetInAddr* SQRNetworkManager_AdHoc_Vita::GetIPAddrFromRudpCtx(int rudpCtx) { - AUTO_VAR(it,m_RudpCtxToIPAddrMap.find(rudpCtx)); - if( it != m_RudpCtxToIPAddrMap.end() ) + auto it = m_RudpCtxToIPAddrMap.find(rudpCtx); + if( it != m_RudpCtxToIPAddrMap.end() ) { return &it->second; } @@ -2329,8 +2329,8 @@ SceNetInAddr* SQRNetworkManager_AdHoc_Vita::GetIPAddrFromRudpCtx(int rudpCtx) SQRNetworkPlayer *SQRNetworkManager_AdHoc_Vita::GetPlayerFromRoomMemberAndLocalIdx(int roomMember, int localIdx) { - for(AUTO_VAR(it, m_RudpCtxToPlayerMap.begin()); it != m_RudpCtxToPlayerMap.end(); it++ ) - { + for (auto it = m_RudpCtxToPlayerMap.begin(); it != m_RudpCtxToPlayerMap.end(); it++) + { if( (it->second->m_roomMemberId == roomMember ) && ( it->second->m_localPlayerIdx == localIdx ) ) { return it->second; @@ -2359,30 +2359,30 @@ bool SQRNetworkManager_AdHoc_Vita::RegisterCallbacks() // app.DebugPrintf("SQRNetworkManager::RegisterCallbacks - sceNpMatching2RegisterContextCallback failed with code 0x%08x\n", ret); // return false; // } -// +// // // Register the default request callback & parameters // SceNpMatching2RequestOptParam optParam; -// +// // memset(&optParam, 0, sizeof(optParam)); // optParam.cbFunc = DefaultRequestCallback; // optParam.cbFuncArg = this; // optParam.timeout = (30 * 1000 * 1000); // optParam.appReqId = 0; -// +// // ret = sceNpMatching2SetDefaultRequestOptParam(m_matchingContext, &optParam); // if (ret < 0) // { // app.DebugPrintf("SQRNetworkManager::RegisterCallbacks - sceNpMatching2SetDefaultRequestOptParam failed with code 0x%08x\n", ret); // return false; // } -// +// // // Register signalling callback // ret = sceNpMatching2RegisterSignalingCallback(m_matchingContext, SignallingCallback, this); // if (ret < 0) // { // return false; // } -// +// // // Register room event callback // ret = sceNpMatching2RegisterRoomEventCallback(m_matchingContext, RoomEventCallback, this); // if (ret < 0) @@ -2390,7 +2390,7 @@ bool SQRNetworkManager_AdHoc_Vita::RegisterCallbacks() // app.DebugPrintf("SQRNetworkManager::RegisterCallbacks - sceNpMatching2RegisterRoomEventCallback failed with code 0x%08x\n", ret); // return false; // } -// +// return true; } @@ -2494,7 +2494,7 @@ void SQRNetworkManager_AdHoc_Vita::SysUtilCallback(uint64_t status, uint64_t par // } // return; // } - // + // // if( netstart_result.result != 0 ) // { // // Failed, or user may have decided not to sign in - maybe need to differentiate here @@ -2508,7 +2508,7 @@ void SQRNetworkManager_AdHoc_Vita::SysUtilCallback(uint64_t status, uint64_t par // s_SignInCompleteCallbackFn = NULL; // } // } - // + // // break; // case CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED: // break; @@ -2529,7 +2529,7 @@ void SQRNetworkManager_AdHoc_Vita::updateNetCheckDialog() { //Check for errors SceNetCheckDialogResult netCheckResult; - int ret = sceNetCheckDialogGetResult(&netCheckResult); + int ret = sceNetCheckDialogGetResult(&netCheckResult); app.DebugPrintf("NetCheckDialogResult = 0x%x\n", netCheckResult.result); ret = sceNetCheckDialogTerm(); app.DebugPrintf("NetCheckDialogTerm ret = 0x%x\n", ret); @@ -2873,7 +2873,7 @@ bool SQRNetworkManager_AdHoc_Vita::ForceErrorPoint(eSQRForceError error) return false; } #else -bool SQRNetworkManager_AdHoc_Vita::aForceError[SNM_FORCE_ERROR_COUNT] = +bool SQRNetworkManager_AdHoc_Vita::aForceError[SNM_FORCE_ERROR_COUNT] = { false, // SNM_FORCE_ERROR_NP2_INIT false, // SNM_FORCE_ERROR_NET_INITIALIZE_NETWORK @@ -2997,7 +2997,7 @@ void SQRNetworkManager_AdHoc_Vita::AttemptPSNSignIn(int (*SignInCompleteCallback // MGH - this code is duplicated in the PSN network manager now too, so any changes will have to be made there too // ------------------------------------------------------------- //CD - Only add if EU sku, not SCEA or SCEJ - if( app.GetProductSKU() == e_sku_SCEE ) + if( app.GetProductSKU() == e_sku_SCEE ) { //CD - Added Country age restrictions SceNetCheckDialogAgeRestriction restrictions[5]; @@ -3075,11 +3075,11 @@ void SQRNetworkManager_AdHoc_Vita::UpdateRichPresenceCustomData(void *data, unsi } // C -// +// // assert(dataBytes <= SCE_NP_BASIC_IN_GAME_PRESENCE_DATA_SIZE_MAX ); // memcpy(s_lastPresenceInfo.data, data, dataBytes); // s_lastPresenceInfo.size = dataBytes; -// +// // s_presenceDataDirty = true; // SendLastPresenceInfo(); } @@ -3101,15 +3101,15 @@ void SQRNetworkManager_AdHoc_Vita::SendLastPresenceInfo() // Don't attempt to send if we are already waiting to resend if( s_resendPresenceCountdown ) return; - // MGH - On Vita, change this to use SCE_NP_BASIC_IN_GAME_PRESENCE_TYPE_GAME_JOINING at some point + // MGH - On Vita, change this to use SCE_NP_BASIC_IN_GAME_PRESENCE_TYPE_GAME_JOINING at some point // On PS4 we can't set the status and the data at the same time -// if( s_presenceDataDirty ) +// if( s_presenceDataDirty ) // { // s_presenceDataDirty = false; // s_lastPresenceInfo.presenceType = SCE_TOOLKIT_NP_PRESENCE_DATA; // } -// else if( s_presenceStatusDirty ) +// else if( s_presenceStatusDirty ) // { // s_presenceStatusDirty = false; // s_lastPresenceInfo.presenceType = SCE_TOOLKIT_NP_PRESENCE_STATUS; @@ -3174,7 +3174,7 @@ void SQRNetworkManager_AdHoc_Vita::removePlayerFromVoiceChat( SQRNetworkPlayer* } else { - int numRemotePlayersLeft = 0; + int numRemotePlayersLeft = 0; for( int i = 0; i < MAX_ONLINE_PLAYER_COUNT; i++ ) { if( m_aRoomSlotPlayers[i] ) @@ -3241,7 +3241,7 @@ void SQRNetworkManager_AdHoc_Vita::UpdateLocalIPAddress() { SceNetInAddr localIPAddr; int ret = sceNetCtlAdhocGetInAddr(&localIPAddr); - + // If we got the IP address, update our cached value if (ret == SCE_OK) { diff --git a/Minecraft.Client/PSVita/Network/SQRNetworkManager_Vita.cpp b/Minecraft.Client/PSVita/Network/SQRNetworkManager_Vita.cpp index 8182674a..a1534f54 100644 --- a/Minecraft.Client/PSVita/Network/SQRNetworkManager_Vita.cpp +++ b/Minecraft.Client/PSVita/Network/SQRNetworkManager_Vita.cpp @@ -39,7 +39,7 @@ bool SQRNetworkManager_Vita::m_bSendingInviteMessage; //unsigned int SQRNetworkManager_Vita::RoomSyncData::playerCount = 0; // This maps internal to extern states, and needs to match element-by-element the eSQRNetworkManagerInternalState enumerated type -const SQRNetworkManager_Vita::eSQRNetworkManagerState SQRNetworkManager_Vita::m_INTtoEXTStateMappings[SQRNetworkManager_Vita::SNM_INT_STATE_COUNT] = +const SQRNetworkManager_Vita::eSQRNetworkManagerState SQRNetworkManager_Vita::m_INTtoEXTStateMappings[SQRNetworkManager_Vita::SNM_INT_STATE_COUNT] = { SNM_STATE_INITIALISING, // SNM_INT_STATE_UNINITIALISED SNM_STATE_INITIALISING, // SNM_INT_STATE_SIGNING_IN @@ -116,7 +116,7 @@ SQRNetworkManager_Vita::SQRNetworkManager_Vita(ISQRNetworkManagerListener *liste // assert(ret == SCE_OK); // ret = sceKernelAddUserEvent(m_basicEventQueue, sc_UserEventHandle); // assert(ret == SCE_OK); - // + // // m_basicEventThread = new C4JThread(&BasicEventThreadProc,this,"Basic Event Handler"); // m_basicEventThread->Run(); } @@ -171,7 +171,7 @@ void SQRNetworkManager_Vita::Initialise() // npConf.commPassphrase = &s_npCommunicationPassphrase; // npConf.commSignature = &s_npCommunicationSignature; // ret = sceNpInit(&npConf, NULL); - // if (ret < 0 && ret != SCE_NP_ERROR_ALREADY_INITIALIZED) + // if (ret < 0 && ret != SCE_NP_ERROR_ALREADY_INITIALIZED) // { // app.DebugPrintf("sceNpInit failed, ret=%x\n", ret); // assert(0); @@ -179,7 +179,7 @@ void SQRNetworkManager_Vita::Initialise() app.DebugPrintf("sceRudpEnableInternalIOThread\n"); ret = sceRudpEnableInternalIOThread(RUDP_THREAD_STACK_SIZE, SCE_KERNEL_DEFAULT_PRIORITY); - if(ret < 0) + if(ret < 0) { app.DebugPrintf("sceRudpEnableInternalIOThread failed with error code 0x%08x\n", ret); assert(0); @@ -418,7 +418,7 @@ void SQRNetworkManager_Vita::Tick() { // make sure we've removed all the remote players and killed the udp connections before we bail out if(m_RudpCtxToPlayerMap.size() == 0) - ResetToIdle(); + ResetToIdle(); } EnterCriticalSection(&m_csStateChangeQueue); @@ -565,7 +565,7 @@ void SQRNetworkManager_Vita::UpdateExternalRoomData() { if( m_offlineGame ) return; if( m_isHosting ) - { + { SceNpMatching2SetRoomDataExternalRequest reqParam; memset( &reqParam, 0, sizeof(reqParam) ); reqParam.roomId = m_room; @@ -688,21 +688,21 @@ int SQRNetworkManager_Vita::BasicEventThreadProc( void *lpParameter ) PSVITA_STUBBED; return 0; // SQRNetworkManager_Vita *manager = (SQRNetworkManager_Vita *)lpParameter; - // + // // int ret = SCE_OK; // SceKernelEvent event; // int outEv; - // + // // do // { // ret = sceKernelWaitEqueue(manager->m_basicEventQueue, &event, 1, &outEv, NULL); - // + // // // If the sys_event_t we've sent here from the handler has a non-zero data1 element, this is to signify that we should terminate the thread // if( event.udata == 0 ) // { // // int iEvent; // // SceNpUserInfo from; - // // uint8_t buffer[SCE_NP_BASIC_MAX_MESSAGE_SIZE]; + // // uint8_t buffer[SCE_NP_BASIC_MAX_MESSAGE_SIZE]; // // size_t bufferSize = SCE_NP_BASIC_MAX_MESSAGE_SIZE; // // int ret = sceNpBasicGetEvent(&iEvent, &from, &buffer, &bufferSize); // // if( ret == 0 ) @@ -710,7 +710,7 @@ int SQRNetworkManager_Vita::BasicEventThreadProc( void *lpParameter ) // // if( iEvent == SCE_NP_BASIC_EVENT_INCOMING_BOOTABLE_INVITATION ) // // { // // // 4J Stu - Don't do this here as it can be very disruptive to gameplay. Players can bring this up from LoadOrJoinMenu, PauseMenu and InGameInfoMenu - // // //sceNpBasicRecvMessageCustom(SCE_NP_BASIC_MESSAGE_MAIN_TYPE_INVITE, SCE_NP_BASIC_RECV_MESSAGE_OPTIONS_INCLUDE_BOOTABLE, SYS_MEMORY_CONTAINER_ID_INVALID); + // // //sceNpBasicRecvMessageCustom(SCE_NP_BASIC_MESSAGE_MAIN_TYPE_INVITE, SCE_NP_BASIC_RECV_MESSAGE_OPTIONS_INCLUDE_BOOTABLE, SYS_MEMORY_CONTAINER_ID_INVALID); // // } // // if( iEvent == SCE_NP_BASIC_EVENT_RECV_INVITATION_RESULT ) // // { @@ -723,7 +723,7 @@ int SQRNetworkManager_Vita::BasicEventThreadProc( void *lpParameter ) // // app.DebugPrintf("Incoming basic event of type %d\n",iEvent); // // } // } - // + // // } while(event.udata == 0 ); // return 0; } @@ -760,7 +760,7 @@ int SQRNetworkManager_Vita::GetFriendsThreadProc( void* lpParameter ) friendIDs = new SceNpId[manager->m_friendCount]; SceSize numRecieved; ret = sceNpBasicGetFriendListEntries(0, friendIDs, manager->m_friendCount, &numRecieved); - if (ret < 0) + if (ret < 0) { app.DebugPrintf("sceNpBasicGetFriendListEntries() failed: ret = 0x%x\n", ret); manager->m_friendCount = 0; @@ -778,7 +778,7 @@ int SQRNetworkManager_Vita::GetFriendsThreadProc( void* lpParameter ) static SceNpBasicGamePresence presenceDetails; static SceNpBasicFriendContextState contextState; int ret = sceNpBasicGetFriendContextState(&friendIDs[i], &contextState); - if (ret < 0) + if (ret < 0) { app.DebugPrintf("sceNpBasicGetFriendContextState() failed: ret = 0x%x\n", ret); contextState = SCE_NP_BASIC_FRIEND_CONTEXT_STATE_UNKNOWN; @@ -855,7 +855,7 @@ bool SQRNetworkManager_Vita::IsReadyToPlayOrIdle() // Consider as "in session" from the moment that a game is created or joined, until the point where the game itself has been told via state change that we are now idle. The -// game code requires IsInSession to return true as soon as it has asked to do one of these things (even if the state system hasn't really caught up with this request yet), and +// game code requires IsInSession to return true as soon as it has asked to do one of these things (even if the state system hasn't really caught up with this request yet), and // it also requires that it is informed of the state changes leading up to not being in the session, before this should report false. bool SQRNetworkManager_Vita::IsInSession() { @@ -1318,7 +1318,7 @@ bool SQRNetworkManager_Vita::RemoveLocalPlayerByUserIndex(int idx) extern uint8_t *mallocAndCreateUTF8ArrayFromString(int iID); -// Bring up a Gui to send an invite so a player that the user can select. This invite will contain the room Id so that +// Bring up a Gui to send an invite so a player that the user can select. This invite will contain the room Id so that void SQRNetworkManager_Vita::SendInviteGUI() { if(ProfileManager.IsSystemUIDisplayed()) @@ -1348,7 +1348,7 @@ void SQRNetworkManager_Vita::SendInviteGUI() messData.expireMinutes = 0; int ret = sce::Toolkit::NP::Messaging::Interface::sendMessage(&messData, SCE_TOOLKIT_NP_MESSAGE_TYPE_CUSTOM_DATA); - if(ret < SCE_TOOLKIT_NP_SUCCESS ) + if(ret < SCE_TOOLKIT_NP_SUCCESS ) { app.DebugPrintf("Send Message failed 0x%x ...\n",ret); assert(0); @@ -1371,7 +1371,7 @@ void SQRNetworkManager_Vita::RecvInviteGUI() } int ret = sce::Toolkit::NP::Messaging::Interface::displayReceivedMessages(SCE_TOOLKIT_NP_MESSAGE_TYPE_CUSTOM_DATA); - if(ret < SCE_TOOLKIT_NP_SUCCESS ) + if(ret < SCE_TOOLKIT_NP_SUCCESS ) { app.DebugPrintf("displayReceivedMessages 0x%x ...\n",ret); assert(0); @@ -1390,17 +1390,17 @@ void SQRNetworkManager_Vita::RecvInviteGUI() // } // else // { - // + // // SceGameCustomDataDialogParam dialogParam; // SceGameCustomDataDialogDataParam dataParam; - // + // // sceGameCustomDataDialogParamInit( &dialogParam ); // memset( &dataParam, 0x00, sizeof( SceGameCustomDataDialogDataParam ) ); // dialogParam.mode = SCE_GAME_CUSTOM_DATA_DIALOG_MODE_RECV; // dialogParam.dataParam = &dataParam; // dialogParam.userId = ProfileManager.getUserID(ProfileManager.GetPrimaryPad()); // ret = sceGameCustomDataDialogOpen( &dialogParam ); - // + // // if( SCE_OK != ret ) // { // app.DebugPrintf("sceGameCustomDataDialogOpen() failed. ret = 0x%x\n", ret); @@ -1419,7 +1419,7 @@ void SQRNetworkManager_Vita::TickInviteGUI() // if(b_inviteRecvGUIRunning) // { // SceCommonDialogStatus status = sceGameCustomDataDialogUpdateStatus(); - // + // // if( SCE_COMMON_DIALOG_STATUS_FINISHED == status ) // { // SceGameCustomDataDialogOnlineIdList sentOnlineIdList; @@ -1427,11 +1427,11 @@ void SQRNetworkManager_Vita::TickInviteGUI() // SceGameCustomDataDialogResult dialogResult; // memset( &dialogResult, 0x0, sizeof(SceGameCustomDataDialogResult) ); // dialogResult.sentOnlineIds = &sentOnlineIdList; - // + // // int32_t ret = sceGameCustomDataDialogGetResult( &dialogResult ); - // + // // if( SCE_OK != ret ) - // { + // { // app.DebugPrintf( "***** sceGameCustomDataDialogGetResult error:0x%x\n", ret); // } // sceGameCustomDataDialogClose(); @@ -1458,7 +1458,7 @@ void SQRNetworkManager_Vita::GetJoinablePresenceDataAndProcess(SceAppUtilNpBasic { memcpy(&m_joinablePresenceParam, pJoinablePresenceData, sizeof(SceAppUtilNpBasicJoinablePresenceParam)); if(s_safeToRespondToGameBootInvite && ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())) - { + { ProcessJoinablePresenceData(); } else @@ -1487,7 +1487,7 @@ void SQRNetworkManager_Vita::ProcessJoinablePresenceData() // The pair of methods MustSignInReturned_1 & PSNSignInReturned_1 handle this int MustSignInReturnedPresenceInvite(void *pParam,int iPad,C4JStorage::EMessageResult result) { - if(result==C4JStorage::EMessage_ResultAccept) + if(result==C4JStorage::EMessage_ResultAccept) { SQRNetworkManager_Vita::AttemptPSNSignIn(&SQRNetworkManager_Vita::PSNSignInReturnedPresenceInvite, pParam,true); } @@ -1529,7 +1529,7 @@ void SQRNetworkManager_Vita::TickJoinablePresenceData() // ui.RequestMessageBox( IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, NULL, app.GetStringTable()); // } // else - { + { // Not signed in to PSN UINT uiIDA[1]; uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; @@ -1559,8 +1559,8 @@ bool SQRNetworkManager_Vita::UpdateInviteData(SQRNetworkManager_Vita::PresenceSy // and there's a period when starting up the host game where it doesn't accurately know the memberId for its own local players void SQRNetworkManager_Vita::FindOrCreateNonNetworkPlayer(int slot, int playerType, SceNpMatching2RoomMemberId memberId, int localPlayerIdx, int smallId) { - for(AUTO_VAR(it, m_vecTempPlayers.begin()); it != m_vecTempPlayers.end(); it++ ) - { + for (auto it = m_vecTempPlayers.begin(); it != m_vecTempPlayers.end(); it++) + { if( ((*it)->m_type == playerType ) && ( (*it)->m_localPlayerIdx == localPlayerIdx ) ) { if( ( playerType != SQRNetworkPlayer::SNP_TYPE_REMOTE ) || ( (*it)->m_roomMemberId == memberId ) ) @@ -1618,7 +1618,7 @@ void SQRNetworkManager_Vita::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) { EnterCriticalSection(&m_csRoomSyncData); - // If we pass an explicit roomSlotPlayerCount, it is because we are removing a player, and this is the count of slots that there were *before* the removal. + // If we pass an explicit roomSlotPlayerCount, it is because we are removing a player, and this is the count of slots that there were *before* the removal. bool zeroLastSlot = false; if( roomSlotPlayerCount == -1 ) { @@ -1722,7 +1722,7 @@ void SQRNetworkManager_Vita::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) } else { - FindOrCreateNonNetworkPlayer( i, SQRNetworkPlayer::SNP_TYPE_REMOTE, m_roomSyncData.players[i].m_roomMemberId, m_roomSyncData.players[i].m_localIdx, m_roomSyncData.players[i].m_smallId); + FindOrCreateNonNetworkPlayer( i, SQRNetworkPlayer::SNP_TYPE_REMOTE, m_roomSyncData.players[i].m_roomMemberId, m_roomSyncData.players[i].m_localIdx, m_roomSyncData.players[i].m_smallId); m_aRoomSlotPlayers[i]->SetUID(m_roomSyncData.players[i].m_UID); // On client, UIDs flow from m_roomSyncData->player data } } @@ -1730,8 +1730,8 @@ void SQRNetworkManager_Vita::MapRoomSlotPlayers(int roomSlotPlayerCount/*=-1*/) } // Clear up any non-network players that are no longer required - this would be a good point to notify of players leaving when we support that // FindOrCreateNonNetworkPlayer will have pulled any players that we Do need out of m_vecTempPlayers, so the ones that are remaining are no longer in the game - for(AUTO_VAR(it, m_vecTempPlayers.begin()); it != m_vecTempPlayers.end(); it++ ) - { + for (auto it = m_vecTempPlayers.begin(); it != m_vecTempPlayers.end(); it++) + { if( m_listener ) { m_listener->HandlePlayerLeaving(*it); @@ -1815,7 +1815,7 @@ bool SQRNetworkManager_Vita::AddRemotePlayersAndSync( SceNpMatching2RoomMemberId } // We want to keep all players from a particular machine together, so search through the room sync data to see if we can find - // any pre-existing players from this machine. + // any pre-existing players from this machine. int firstIdx = -1; for( int i = 0; i < m_roomSyncData.getPlayerCount(); i++ ) { @@ -1933,8 +1933,8 @@ void SQRNetworkManager_Vita::RemoveNetworkPlayers( int mask ) { assert( !m_isHosting ); - for(AUTO_VAR(it, m_RudpCtxToPlayerMap.begin()); it != m_RudpCtxToPlayerMap.end(); ) - { + for (auto it = m_RudpCtxToPlayerMap.begin(); it != m_RudpCtxToPlayerMap.end();) + { SQRNetworkPlayer *player = it->second; if( (player->m_roomMemberId == m_localMemberId ) && ( ( 1 << player->m_localPlayerIdx ) & mask ) ) { @@ -1960,7 +1960,7 @@ void SQRNetworkManager_Vita::RemoveNetworkPlayers( int mask ) removePlayerFromVoiceChat(player); // Delete the player itself and the mapping from context to player map as this context is no longer valid - delete player; + delete player; } else { @@ -2071,7 +2071,7 @@ bool SQRNetworkManager_Vita::GetMatchingContext(eSQRNetworkManagerInternalState // Starts the process of obtaining a server context. This is an asynchronous operation, at the end of which (if successful), we'll be creating // a room. General procedure followed here is as suggested by Sony - we get a list of servers, then pick a random one, and see if it is available. -// If not we just cycle round trying other random ones until we either find an available one or fail. +// If not we just cycle round trying other random ones until we either find an available one or fail. bool SQRNetworkManager_Vita::GetServerContext() { assert(m_state == SNM_INT_STATE_IDLE); @@ -2143,7 +2143,7 @@ bool SQRNetworkManager_Vita::GetServerContext(SceNpMatching2ServerId serverId) // ( serverCount == SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED ) ) // Also checking for this as a means of simulating the previous error // { // sceNpMatching2DestroyContext(m_matchingContext); - // m_matchingContextValid = false; + // m_matchingContextValid = false; // if( !GetMatchingContext(SNM_INT_STATE_JOINING_STARTING_MATCHING_CONTEXT) ) return false; // } // } @@ -2278,7 +2278,7 @@ void SQRNetworkManager_Vita::NetworkPlayerConnectionComplete(SQRNetworkPlayer *p if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2304,7 +2304,7 @@ void SQRNetworkManager_Vita::NetworkPlayerSmallIdAllocated(SQRNetworkPlayer *pla if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2322,7 +2322,7 @@ void SQRNetworkManager_Vita::NetworkPlayerInitialDataReceived(SQRNetworkPlayer * if( ( !wasReady ) && ( isReady ) ) { - HandlePlayerJoined( player ); + HandlePlayerJoined( player ); } } @@ -2338,7 +2338,7 @@ void SQRNetworkManager_Vita::HandlePlayerJoined(SQRNetworkPlayer *player) { if( m_listener ) { - m_listener->HandlePlayerJoined( player ); + m_listener->HandlePlayerJoined( player ); } // On client, keep a count of how many local players we have told the game about. We can only transition to telling the game that we are playing once the room is set up And all the local players are valid to use. if( !m_isHosting ) @@ -2400,7 +2400,7 @@ static std::string getIPAddressString(SceNetInAddr add) { char str[32]; unsigned char *vals = (unsigned char*)&add.s_addr; - sprintf(str, "%d.%d.%d.%d", (int)vals[0], (int)vals[1], (int)vals[2], (int)vals[3]); + sprintf(str, "%d.%d.%d.%d", (int)vals[0], (int)vals[1], (int)vals[2], (int)vals[3]); return std::string(str); } @@ -2519,7 +2519,7 @@ bool SQRNetworkManager_Vita::CreateRudpConnections(SceNpMatching2RoomId roomId, int ret = sceNpMatching2SignalingGetConnectionStatus(m_matchingContext, roomId, peerMemberId, &connStatus, &sinp2pPeer.sin_addr, &sinp2pPeer.sin_port); app.DebugPrintf(CMinecraftApp::USER_RR,"sceNpMatching2SignalingGetConnectionStatus returned 0x%x, connStatus %d peer add:%s peer port:0x%x\n",ret, connStatus,getIPAddressString(sinp2pPeer.sin_addr).c_str(),sinp2pPeer.sin_port); - // Set vport + // Set vport sinp2pPeer.sin_vport = sceNetHtons(1); // Create socket & bind, if we don't already have one @@ -2571,8 +2571,8 @@ bool SQRNetworkManager_Vita::CreateRudpConnections(SceNpMatching2RoomId roomId, SQRNetworkPlayer *SQRNetworkManager_Vita::GetPlayerFromRudpCtx(int rudpCtx) { - AUTO_VAR(it,m_RudpCtxToPlayerMap.find(rudpCtx)); - if( it != m_RudpCtxToPlayerMap.end() ) + auto it = m_RudpCtxToPlayerMap.find(rudpCtx); + if( it != m_RudpCtxToPlayerMap.end() ) { return it->second; } @@ -2583,8 +2583,8 @@ SQRNetworkPlayer *SQRNetworkManager_Vita::GetPlayerFromRudpCtx(int rudpCtx) SQRNetworkPlayer *SQRNetworkManager_Vita::GetPlayerFromRoomMemberAndLocalIdx(int roomMember, int localIdx) { - for(AUTO_VAR(it, m_RudpCtxToPlayerMap.begin()); it != m_RudpCtxToPlayerMap.end(); it++ ) - { + for (auto it = m_RudpCtxToPlayerMap.begin(); it != m_RudpCtxToPlayerMap.end(); it++) + { if( (it->second->m_roomMemberId == roomMember ) && ( it->second->m_localPlayerIdx == localIdx ) ) { return it->second; @@ -2681,7 +2681,7 @@ void SQRNetworkManager_Vita::ContextCallback(SceNpMatching2ContextId id, SceNpM manager->m_state == SNM_INT_STATE_HOSTING_STARTING_MATCHING_CONTEXT || manager->m_state == SNM_INT_STATE_JOINING_STARTING_MATCHING_CONTEXT) { - // matching context failed to start (this can happen when you block the IP addresses of the matching servers on your router + // matching context failed to start (this can happen when you block the IP addresses of the matching servers on your router // agent-0101.ww.sp-int.matching.playstation.net (198.107.157.191) // static-resource.sp-int.community.playstation.net (203.105.77.140) manager->SetState(SNM_INT_STATE_INITIALISE_FAILED); @@ -2740,7 +2740,7 @@ void SQRNetworkManager_Vita::ContextCallback(SceNpMatching2ContextId id, SceNpM // unsigned int type, attributes; // CellGameContentSize gameSize;` // char dirName[CELL_GAME_DIRNAME_SIZE]; - // + // // if( g_bBootedFromInvite ) // { // manager->GetInviteDataAndProcess(SCE_NP_BASIC_SELECTED_INVITATION_DATA); @@ -2748,7 +2748,7 @@ void SQRNetworkManager_Vita::ContextCallback(SceNpMatching2ContextId id, SceNpM // } } } - break; + break; case SCE_NP_MATCHING2_CONTEXT_EVENT_STOPPED: app.DebugPrintf("SCE_NP_MATCHING2_CONTEXT_EVENT_STOPPED\n"); // Can happen when we stop the PSN to switch to adhoc mode @@ -2791,7 +2791,7 @@ void SQRNetworkManager_Vita::DefaultRequestCallback(SceNpMatching2ContextId id, SQRNetworkManager_Vita *manager = (SQRNetworkManager_Vita *)arg; EnterCriticalSection(&manager->m_csMatching); // int ret; - if( id != manager->m_matchingContext ) + if( id != manager->m_matchingContext ) { LeaveCriticalSection(&manager->m_csMatching); return; @@ -2803,7 +2803,7 @@ void SQRNetworkManager_Vita::DefaultRequestCallback(SceNpMatching2ContextId id, // This is the response to sceNpMatching2GetWorldInfoList, which is called as part of the process to create a room (which needs a world to be created in). We aren't anticipating // using worlds in a meaningful way so just getting the first world we find on the server here, and then advancing the state so that the tick can get on with the rest of the process. case SCE_NP_MATCHING2_REQUEST_EVENT_GET_WORLD_INFO_LIST: - { + { app.DebugPrintf("SCE_NP_MATCHING2_REQUEST_EVENT_GET_WORLD_INFO_LIST\n"); SceNpServiceState serviceState; int retVal = sceNpGetServiceState(&serviceState); @@ -2828,7 +2828,7 @@ void SQRNetworkManager_Vita::DefaultRequestCallback(SceNpMatching2ContextId id, manager->SetState(SNM_INT_STATE_HOSTING_CREATE_ROOM_WORLD_FOUND); break; } - } + } } // We get this error when starting a new game after a disconnect occurred in a previous game with at least one remote player. Fix by stopping/starting the matching context. // We stop the context here, which is picked up in the callback, and started again. Then the start event is picked up and reattempts the sceNpMatching2GetWorldInfoList. @@ -2928,7 +2928,7 @@ void SQRNetworkManager_Vita::DefaultRequestCallback(SceNpMatching2ContextId id, { // MGH - I've caught this being triggered after join has already failed, and then UDP connections are created that aren't killed off // so just break out here if we're not in the expected state - // fixes devtrack #5807 + // fixes devtrack #5807 app.DebugPrintf("SCE_NP_MATCHING2_REQUEST_EVENT_GET_ROOM_MEMBER_DATA_INTERNAL - manager->GetState() : %d\n", manager->GetState() ); break; } @@ -2950,7 +2950,7 @@ void SQRNetworkManager_Vita::DefaultRequestCallback(SceNpMatching2ContextId id, if( success1 ) { success2 = manager->CreateRudpConnections(manager->m_room, pRoomMemberData->roomMemberDataInternal->memberId, playerMask, pRoomMemberData->roomMemberDataInternal->memberId); - if( success2 ) + if( success2 ) { bool ret = manager->CreateVoiceRudpConnections( manager->m_room, pRoomMemberData->roomMemberDataInternal->memberId, 0); assert(ret == true); @@ -3302,14 +3302,14 @@ void SQRNetworkManager_Vita::SignallingCallback(SceNpMatching2ContextId ctxId, S // Remove any players associated with this peer manager->RemoveRemotePlayersAndSync( peerMemberId, 15 ); } - else + else { SQRVoiceConnection* pVoice = SonyVoiceChat_Vita::getVoiceConnectionFromRoomMemberID(peerMemberId); if(pVoice) { SonyVoiceChat_Vita::disconnectRemoteConnection(pVoice); } - if(peerMemberId == manager->m_hostMemberId || pVoice == NULL) // MGH - added check for voice, as we sometime get here before m_hostMemberId has been filled in + if(peerMemberId == manager->m_hostMemberId || pVoice == NULL) // MGH - added check for voice, as we sometime get here before m_hostMemberId has been filled in { // Host has left the game... so its all over for this client too. Finish everything up now, including deleting the server context which belongs to this gaming session // This also might be a response to a request to leave the game from our end too so don't need to do anything in that case @@ -3412,7 +3412,7 @@ void SQRNetworkManager_Vita::SysUtilCallback(uint64_t status, uint64_t param, vo // } // return; // } - // + // // if( netstart_result.result != 0 ) // { // // Failed, or user may have decided not to sign in - maybe need to differentiate here @@ -3426,7 +3426,7 @@ void SQRNetworkManager_Vita::SysUtilCallback(uint64_t status, uint64_t param, vo // s_SignInCompleteCallbackFn = NULL; // } // } - // + // // break; // case CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED: // break; @@ -3447,7 +3447,7 @@ void SQRNetworkManager_Vita::updateNetCheckDialog() { //Check for errors SceNetCheckDialogResult netCheckResult; - int ret = sceNetCheckDialogGetResult(&netCheckResult); + int ret = sceNetCheckDialogGetResult(&netCheckResult); app.DebugPrintf("NetCheckDialogResult = 0x%x\n", netCheckResult.result); ret = sceNetCheckDialogTerm(); app.DebugPrintf("NetCheckDialogTerm ret = 0x%x\n", ret); @@ -3811,7 +3811,7 @@ void SQRNetworkManager_Vita::GetExtDataForRoom( SceNpMatching2RoomId roomId, voi if( ret == SCE_NP_MATCHING2_ERROR_CONTEXT_NOT_STARTED ) // Also checking for this as a means of simulating the previous error { sceNpMatching2DestroyContext(m_matchingContext); - m_matchingContextValid = false; + m_matchingContextValid = false; if( !GetMatchingContext(SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT) ) { // No matching context, and failed to try and make one. We're really broken here. @@ -3838,7 +3838,7 @@ bool SQRNetworkManager_Vita::ForceErrorPoint(eSQRForceError error) return false; } #else -bool SQRNetworkManager_Vita::aForceError[SNM_FORCE_ERROR_COUNT] = +bool SQRNetworkManager_Vita::aForceError[SNM_FORCE_ERROR_COUNT] = { false, // SNM_FORCE_ERROR_NP2_INIT false, // SNM_FORCE_ERROR_NET_INITIALIZE_NETWORK @@ -3915,7 +3915,7 @@ void SQRNetworkManager_Vita::AttemptPSNSignIn(int (*SignInCompleteCallbackFn)(vo // MGH - this code is duplicated in the adhoc manager now too, so any changes will have to be made there too // ------------------------------------------------------------- //CD - Only add if EU sku, not SCEA or SCEJ - if( app.GetProductSKU() == e_sku_SCEE ) + if( app.GetProductSKU() == e_sku_SCEE ) { //CD - Added Country age restrictions SceNetCheckDialogAgeRestriction restrictions[5]; @@ -4010,7 +4010,7 @@ void SQRNetworkManager_Vita::SendLastPresenceInfo() // Don't attempt to send if we are already waiting to resend if( s_resendPresenceCountdown ) return; - // MGH - On Vita, change this to use SCE_NP_BASIC_IN_GAME_PRESENCE_TYPE_GAME_JOINING at some point + // MGH - On Vita, change this to use SCE_NP_BASIC_IN_GAME_PRESENCE_TYPE_GAME_JOINING at some point // On PS4 we can't set the status and the data at the same time if( s_presenceStatusDirty == false) diff --git a/Minecraft.Client/PSVita/PSVitaExtras/PSVitaTypes.h b/Minecraft.Client/PSVita/PSVitaExtras/PSVitaTypes.h index cc2ddddb..bb3d3503 100644 --- a/Minecraft.Client/PSVita/PSVitaExtras/PSVitaTypes.h +++ b/Minecraft.Client/PSVita/PSVitaExtras/PSVitaTypes.h @@ -170,7 +170,3 @@ typedef LPVOID LPSECURITY_ATTRIBUTES; #define __in_ecount(a) #define __in_bcount(a) - -#ifndef AUTO_VAR -#define AUTO_VAR(_var, _val) auto _var = _val -#endif
\ No newline at end of file diff --git a/Minecraft.Client/PSVita/PSVita_App.cpp b/Minecraft.Client/PSVita/PSVita_App.cpp index 48aa25c4..956e10b6 100644 --- a/Minecraft.Client/PSVita/PSVita_App.cpp +++ b/Minecraft.Client/PSVita/PSVita_App.cpp @@ -96,8 +96,8 @@ SONYDLC *CConsoleMinecraftApp::GetSONYDLCInfo(char *pchTitle) { wstring wstrTemp=convStringToWstring(pchTitle); - AUTO_VAR(it, m_SONYDLCMap.find(wstrTemp)); - if(it == m_SONYDLCMap.end()) + auto it = m_SONYDLCMap.find(wstrTemp); + if(it == m_SONYDLCMap.end()) { app.DebugPrintf("Couldn't find DLC info for %s\n", pchTitle); assert(0); @@ -113,8 +113,8 @@ SONYDLC *CConsoleMinecraftApp::GetSONYDLCInfo(char *pchTitle) SONYDLC *CConsoleMinecraftApp::GetSONYDLCInfo(int iTexturePackID) { - for ( AUTO_VAR(it, m_SONYDLCMap.begin()); it != m_SONYDLCMap.end(); ++it ) - { + for (auto it = m_SONYDLCMap.begin(); it != m_SONYDLCMap.end(); ++it) + { if(it->second->iConfig == iTexturePackID) return it->second; } @@ -331,7 +331,7 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() app.SetGameHostOption(eGameHostOption_Gamertags,1); app.SetGameHostOption(eGameHostOption_BedrockFog,1); - app.SetGameHostOption(eGameHostOption_GameType,GameType::CREATIVE->getId()); + app.SetGameHostOption(eGameHostOption_GameType,GameType::CREATIVE->getId()); app.SetGameHostOption(eGameHostOption_LevelType, 0 ); app.SetGameHostOption(eGameHostOption_Structures, 1 ); app.SetGameHostOption(eGameHostOption_BonusChest, 0 ); @@ -410,7 +410,7 @@ void CConsoleMinecraftApp::CommerceTick() break; case eCommerce_State_GetProductList: - { + { m_eCommerce_State=eCommerce_State_GetProductList_Pending; SonyCommerce::CategoryInfo *pCategories=app.GetCategoryInfo(); std::list<SonyCommerce::CategoryInfoSub>::iterator iter = pCategories->subCategories.begin(); @@ -426,7 +426,7 @@ void CConsoleMinecraftApp::CommerceTick() break; case eCommerce_State_AddProductInfoDetailed: - { + { m_eCommerce_State=eCommerce_State_AddProductInfoDetailed_Pending; // for each of the products in the categories, get the detailed info. We really only need the long description and price info. @@ -463,7 +463,7 @@ void CConsoleMinecraftApp::CommerceTick() break; case eCommerce_State_RegisterDLC: - { + { m_eCommerce_State=eCommerce_State_Online; // register the DLC info SonyCommerce::CategoryInfo *pCategories=app.GetCategoryInfo(); @@ -550,20 +550,20 @@ SonyCommerce::CategoryInfo *CConsoleMinecraftApp::GetCategoryInfo() return &m_CategoryInfo; } -#endif +#endif void CConsoleMinecraftApp::ClearCommerceDetails() { #ifdef VITA_COMMERCE_ENABLED for(int i=0;i<m_ProductListCategoriesC;i++) { - std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; + std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; pProductList->clear(); } if(m_ProductListA!=NULL) { - delete [] m_ProductListA; + delete [] m_ProductListA; m_ProductListA=NULL; } @@ -593,17 +593,17 @@ void CConsoleMinecraftApp::GetDLCSkuIDFromProductList(char * pchDLCProductID, ch for(int j=0;j<m_ProductListA[i].size();j++) { std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; - AUTO_VAR(itEnd, pProductList->end()); + auto itEnd = pProductList->end(); - for (AUTO_VAR(it, pProductList->begin()); it != itEnd; it++) - { + for (auto it = pProductList->begin(); it != itEnd; it++) + { SonyCommerce::ProductInfo Info=*it; if(strcmp(pchDLCProductID,Info.productId)==0) - { + { memcpy(pchSkuID,Info.skuId,SCE_NP_COMMERCE2_SKU_ID_LEN); return; } - } + } } } return; @@ -620,24 +620,24 @@ void CConsoleMinecraftApp::Checkout(char *pchSkuID) for(int j=0;j<m_ProductListA[i].size();j++) { std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; - AUTO_VAR(itEnd, pProductList->end()); + auto itEnd = pProductList->end(); - for (AUTO_VAR(it, pProductList->begin()); it != itEnd; it++) - { + for (auto it = pProductList->begin(); it != itEnd; it++) + { SonyCommerce::ProductInfo Info=*it; if(strcmp(pchSkuID,Info.skuId)==0) - { + { productInfo = &(*it); break; } - } + } } } if(productInfo) { if(m_eCommerce_State==eCommerce_State_Online) - { + { strcpy(m_pchSkuID,productInfo->skuId); m_pCheckoutProductInfo = productInfo; m_eCommerce_State=eCommerce_State_Checkout; @@ -652,7 +652,7 @@ void CConsoleMinecraftApp::Checkout(char *pchSkuID) void CConsoleMinecraftApp::DownloadAlreadyPurchased(char *pchSkuID) { if(m_eCommerce_State==eCommerce_State_Online) - { + { strcpy(m_pchSkuID,pchSkuID); m_eCommerce_State=eCommerce_State_DownloadAlreadyPurchased; } @@ -661,7 +661,7 @@ void CConsoleMinecraftApp::DownloadAlreadyPurchased(char *pchSkuID) bool CConsoleMinecraftApp::UpgradeTrial() { if(m_eCommerce_State==eCommerce_State_Online) - { + { m_eCommerce_State=eCommerce_State_UpgradeTrial; return true; } @@ -700,13 +700,13 @@ bool CConsoleMinecraftApp::DLCAlreadyPurchased(char *pchTitle) for(int j=0;j<m_ProductListA[i].size();j++) { std::vector<SonyCommerce::ProductInfo>* pProductList=&m_ProductListA[i]; - AUTO_VAR(itEnd, pProductList->end()); + auto itEnd = pProductList->end(); - for (AUTO_VAR(it, pProductList->begin()); it != itEnd; it++) - { + for (auto it = pProductList->begin(); it != itEnd; it++) + { SonyCommerce::ProductInfo Info=*it; if(strcmp(pchTitle,Info.skuId)==0) - { + { if(Info.purchasabilityFlag==SCE_TOOLKIT_NP_COMMERCE_NOT_PURCHASED) { return false; @@ -716,7 +716,7 @@ bool CConsoleMinecraftApp::DLCAlreadyPurchased(char *pchTitle) return true; } } - } + } } } #endif //#ifdef VITA_COMMERCE_ENABLED @@ -753,7 +753,7 @@ void CConsoleMinecraftApp::CommerceGetCategoriesCallback(LPVOID lpParam,int err) if(err==0) { pClass->m_ProductListCategoriesC=pClass->m_CategoryInfo.countOfSubCategories; - // allocate the memory for the product info for each categories + // allocate the memory for the product info for each categories if(pClass->m_CategoryInfo.countOfSubCategories>0) { pClass->m_ProductListA = (std::vector<SonyCommerce::ProductInfo> *) new std::vector<SonyCommerce::ProductInfo> [pClass->m_CategoryInfo.countOfSubCategories]; @@ -787,7 +787,7 @@ void CConsoleMinecraftApp::CommerceGetProductListCallback(LPVOID lpParam,int err { // we're done, so now retrieve the additional product details for each product pClass->m_eCommerce_State=eCommerce_State_AddProductInfoDetailed; - pClass->m_bCommerceProductListRetrieved=true; + pClass->m_bCommerceProductListRetrieved=true; } else { @@ -797,21 +797,21 @@ void CConsoleMinecraftApp::CommerceGetProductListCallback(LPVOID lpParam,int err else { pClass->m_eCommerce_State=eCommerce_State_Error; - pClass->m_bCommerceProductListRetrieved=true; + pClass->m_bCommerceProductListRetrieved=true; } } // void CConsoleMinecraftApp::CommerceGetDetailedProductInfoCallback(LPVOID lpParam,int err) // { // CConsoleMinecraftApp *pScene=(CConsoleMinecraftApp *)lpParam; -// +// // if(err==0) // { // pScene->m_eCommerce_State=eCommerce_State_Idle; -// //pScene->m_bCommerceProductListRetrieved=true; +// //pScene->m_bCommerceProductListRetrieved=true; // } // //printf("Callback hit, error 0x%08x\n", err); -// +// // } void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam,int err) @@ -831,7 +831,7 @@ void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam { // MGH - change this to a while loop so we can skip empty categories. do - { + { pClass->m_iCurrentCategory++; }while(pClass->m_ProductListA[pClass->m_iCurrentCategory].size() == 0 && pClass->m_iCurrentCategory<pClass->m_ProductListCategoriesC); @@ -840,12 +840,12 @@ void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam { // there are no more categories, so we're done pClass->m_eCommerce_State=eCommerce_State_RegisterDLC; - pClass->m_bProductListAdditionalDetailsRetrieved=true; + pClass->m_bProductListAdditionalDetailsRetrieved=true; } else { // continue with the next category - pClass->m_eCommerce_State=eCommerce_State_AddProductInfoDetailed; + pClass->m_eCommerce_State=eCommerce_State_AddProductInfoDetailed; } } else @@ -857,7 +857,7 @@ void CConsoleMinecraftApp::CommerceAddDetailedProductInfoCallback(LPVOID lpParam else { pClass->m_eCommerce_State=eCommerce_State_Error; - pClass->m_bProductListAdditionalDetailsRetrieved=true; + pClass->m_bProductListAdditionalDetailsRetrieved=true; pClass->m_iCurrentProduct=0; pClass->m_iCurrentCategory=0; } @@ -1077,7 +1077,7 @@ bool CConsoleMinecraftApp::CheckForEmptyStore(int iPad) bool bEmptyStore=true; if(pCategories!=NULL) - { + { if(pCategories->countOfProducts>0) { bEmptyStore=false; @@ -1131,7 +1131,7 @@ void printSaveState() case C4JStorage::ESaveGame_SaveCache: strState = "ESaveGame_SaveCache"; break; case C4JStorage::ESaveGame_ReconstructCache: strState = "ESaveGame_ReconstructCache"; break; } - + app.DebugPrintf("[printSaveState] GetSaveState == %s.\n", strState.c_str()); #endif } @@ -1178,7 +1178,7 @@ void CConsoleMinecraftApp::SaveDataTick() { app.DebugPrintf("[SaveDataTick] eSaveDataDeleteState_abort.\n"); StorageManager.CancelIncompleteOperation(); - } + } else if (m_bSaveDataDeleteDialogState == eSaveDataDeleteState_continue) { app.DebugPrintf("[SaveDataTick] eSaveDataDeleteState_continue.\n"); @@ -1262,7 +1262,7 @@ void CConsoleMinecraftApp::Callback_SaveGameIncomplete(void *pParam, C4JStorage: int CConsoleMinecraftApp::NoSaveSpaceReturned(void *pParam,int iPad,C4JStorage::EMessageResult result) { - if(result==C4JStorage::EMessage_ResultAccept && !UIScene_LoadOrJoinMenu::isSaveTransferRunning()) // MGH - we won't try to save again during a save tranfer + if(result==C4JStorage::EMessage_ResultAccept && !UIScene_LoadOrJoinMenu::isSaveTransferRunning()) // MGH - we won't try to save again during a save tranfer { int blocksRequired = (int)pParam; if(blocksRequired > 0) @@ -1290,7 +1290,7 @@ int CConsoleMinecraftApp::cbConfirmDeleteMessageBox(void *pParam, int iPad, cons if (pClass != NULL && pClass->m_pSaveToDelete != NULL) { - if (result == C4JStorage::EMessage_ResultDecline) + if (result == C4JStorage::EMessage_ResultDecline) { pClass->m_bSaveDataDeleteDialogState = eSaveDataDeleteState_deleting; C4JStorage::ESaveGameState eDeleteStatus = StorageManager.DeleteSaveData(pClass->m_pSaveToDelete, cbSaveDataDeleted, pClass); @@ -1324,7 +1324,7 @@ void CConsoleMinecraftApp::initSaveIncompleteDialog(int spaceNeeded) param.sysMsgParam->sysMsgType = SCE_SAVEDATA_DIALOG_SYSMSG_TYPE_NOSPACE_CONTINUABLE; param.sysMsgParam->value = (SceInt32) spaceNeeded; - + SceInt32 ret = sceSaveDataDialogInit(¶m); if (ret == SCE_OK) { @@ -1410,13 +1410,13 @@ void CConsoleMinecraftApp::initSaveDataDeleteDialog() // Start getting saves data to use when deleting. if (StorageManager.ReturnSavesInfo() == NULL) { - C4JStorage::ESaveGameState eSGIStatus - = StorageManager.GetSavesInfo( + C4JStorage::ESaveGameState eSGIStatus + = StorageManager.GetSavesInfo( ProfileManager.GetPrimaryPad(), - NULL, - this, + NULL, + this, "save" - ); + ); } // Dim background because sony doesn't do that. @@ -1448,7 +1448,7 @@ void CConsoleMinecraftApp::updateSaveDataDeleteDialog() { SceSaveDataDialogResult dialogResult; ZeroMemory(&dialogResult, sizeof(SceSaveDataDialogResult)); - + SceInt32 ret = sceSaveDataDialogGetResult(&dialogResult); if (ret == SCE_OK) { @@ -1472,7 +1472,7 @@ void CConsoleMinecraftApp::updateSaveDataDeleteDialog() { SceAppUtilSaveDataSlotParam slotParam; ret = sceAppUtilSaveDataSlotGetParam( dialogResult.slotId, &slotParam, NULL ); - + if (ret == SCE_OK) { int saveindex = -1; @@ -1503,12 +1503,12 @@ void CConsoleMinecraftApp::updateSaveDataDeleteDialog() { app.DebugPrintf("[SaveDataDeleteDialog] ERROR: PERFORMING DELETE OPERATION, pSavesDetails is null.\n"); } - + if (pSaveInfo != NULL) { app.DebugPrintf( "[SaveDataDeleteDialog] User wishes to delete slot_%d:\n\t" - "4jsaveindex=%d, filename='%s', title='%s', subtitle='%s', size=%dKiB.\n", + "4jsaveindex=%d, filename='%s', title='%s', subtitle='%s', size=%dKiB.\n", dialogResult.slotId, saveindex, pSaveInfo->UTF8SaveFilename, @@ -1524,14 +1524,14 @@ void CConsoleMinecraftApp::updateSaveDataDeleteDialog() }; ui.RequestErrorMessage( - IDS_TOOLTIPS_DELETESAVE, IDS_TEXT_DELETE_SAVE, + IDS_TOOLTIPS_DELETESAVE, IDS_TEXT_DELETE_SAVE, uiIDA, 2, 0, &cbConfirmDeleteMessageBox, this ); m_bSaveDataDeleteDialogState = eSaveDataDeleteState_userConfirmation; - + m_pSaveToDelete = pSaveInfo; } else @@ -1604,7 +1604,7 @@ void CConsoleMinecraftApp::getSaveDataDeleteDialogParam(SceSaveDataDialogParam * { SceAppUtilSaveDataSlotParam slotParam; int ret = sceAppUtilSaveDataSlotGetParam( i, &slotParam, NULL ); - + if (ret == SCE_OK) { SceAppUtilSaveDataSlot slot; @@ -1617,7 +1617,7 @@ void CConsoleMinecraftApp::getSaveDataDeleteDialogParam(SceSaveDataDialogParam * slots.push_back( slot ); } } - + SceAppUtilSaveDataSlot *pSavesList = new SceAppUtilSaveDataSlot[slots.size()]; int slotIndex = 0; @@ -1651,7 +1651,7 @@ void CConsoleMinecraftApp::getSaveDataDeleteDialogParam(SceSaveDataDialogParam * listParam.listTitle = (const SceChar8 *) strPtr; listParam.itemStyle = SCE_SAVEDATA_DIALOG_LIST_ITEM_STYLE_TITLE_SUBTITLE_DATE; - + baseParam->mode = SCE_SAVEDATA_DIALOG_MODE_LIST; baseParam->dispType = SCE_SAVEDATA_DIALOG_TYPE_DELETE; baseParam->listParam = &listParam; @@ -1692,10 +1692,10 @@ int CConsoleMinecraftApp::cbSaveDataDeleted( void *pParam, const bool success ) void CConsoleMinecraftApp::finishedDeletingSaves(bool bContinue) { app.DebugPrintf( "[finishedDeletingSaves] %s.\n", (bContinue?"Continuing":"Aborting") ); - + StorageManager.SetSaveDisabled(false); LeaveSaveNotificationSection(); - + StorageManager.ClearSaveError(); StorageManager.ClearOptionsSaveError(); diff --git a/Minecraft.Client/ParticleEngine.cpp b/Minecraft.Client/ParticleEngine.cpp index a6f65fa6..7fe26063 100644 --- a/Minecraft.Client/ParticleEngine.cpp +++ b/Minecraft.Client/ParticleEngine.cpp @@ -22,7 +22,7 @@ ParticleEngine::ParticleEngine(Level *level, Textures *textures) this->level = level; } this->textures = textures; - + this->random = new Random(); } @@ -256,8 +256,8 @@ void ParticleEngine::moveParticleInList(shared_ptr<Particle> particle, int sourc int l = particle->level->dimension->id == 0 ? 0 : ( particle->level->dimension->id == -1 ? 1 : 2); for (int tt = 0; tt < TEXTURE_COUNT; tt++) { - AUTO_VAR(it, find(particles[l][tt][source].begin(), particles[l][tt][source].end(), particle) ); - if(it != particles[l][tt][source].end() ) + auto it = find(particles[l][tt][source].begin(), particles[l][tt][source].end(), particle); + if(it != particles[l][tt][source].end() ) { (*it) = particles[l][tt][source].back(); particles[l][tt][source].pop_back(); @@ -277,5 +277,5 @@ wstring ParticleEngine::countParticles() total += particles[l][tt][list].size(); } } - return _toString<int>(total); + return std::to_wstring(total); } diff --git a/Minecraft.Client/PendingConnection.cpp b/Minecraft.Client/PendingConnection.cpp index 8034dff2..b50669e5 100644 --- a/Minecraft.Client/PendingConnection.cpp +++ b/Minecraft.Client/PendingConnection.cpp @@ -105,15 +105,14 @@ void PendingConnection::sendPreLoginResponse() StorageManager.GetSaveUniqueFilename(szUniqueMapName); PlayerList *playerList = MinecraftServer::getInstance()->getPlayers(); - for(AUTO_VAR(it, playerList->players.begin()); it != playerList->players.end(); ++it) + for(auto& player : playerList->players) { - shared_ptr<ServerPlayer> player = *it; // If the offline Xuid is invalid but the online one is not then that's guest which we should ignore // If the online Xuid is invalid but the offline one is not then we are definitely an offline game so dont care about UGC // PADDY - this is failing when a local player with chat restrictions joins an online game - if( player != NULL && player->connection->m_offlineXUID != INVALID_XUID && player->connection->m_onlineXUID != INVALID_XUID ) + if( player != nullptr && player->connection->m_offlineXUID != INVALID_XUID && player->connection->m_onlineXUID != INVALID_XUID ) { if( player->connection->m_friendsOnlyUGC ) { @@ -175,9 +174,9 @@ void PendingConnection::handleLogin(shared_ptr<LoginPacket> packet) { bool nameTaken = false; vector<shared_ptr<ServerPlayer> >& pl = server->getPlayers()->players; - for (unsigned int i = 0; i < pl.size(); i++) + for (const auto& i : pl) { - if (pl[i] != NULL && pl[i]->name == name) + if (i != NULL && i->name == name) { nameTaken = true; break; @@ -201,7 +200,7 @@ void PendingConnection::handleLogin(shared_ptr<LoginPacket> packet) //else { //4J - removed -#if 0 +#if 0 new Thread() { public void run() { try { @@ -258,7 +257,7 @@ void PendingConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, void PendingConnection::handleGetInfo(shared_ptr<GetInfoPacket> packet) { //try { - //String message = server->motd + "§" + server->players->getPlayerCount() + "§" + server->players->getMaxPlayers(); + //String message = server->motd + "�" + server->players->getPlayerCount() + "�" + server->players->getMaxPlayers(); //connection->send(new DisconnectPacket(message)); connection->send(shared_ptr<DisconnectPacket>(new DisconnectPacket(DisconnectPacket::eDisconnect_ServerFull) ) ); connection->sendAndQuit(); diff --git a/Minecraft.Client/PlayerChunkMap.cpp b/Minecraft.Client/PlayerChunkMap.cpp index acf6edc3..ae81bd69 100644 --- a/Minecraft.Client/PlayerChunkMap.cpp +++ b/Minecraft.Client/PlayerChunkMap.cpp @@ -40,10 +40,10 @@ PlayerChunkMap::PlayerChunk::~PlayerChunk() // flag array and adds to it for this ServerPlayer. void PlayerChunkMap::flagEntitiesToBeRemoved(unsigned int *flags, bool *flagToBeRemoved) { - for(AUTO_VAR(it,players.begin()); it != players.end(); it++) + for(auto& serverPlayer : players) { - shared_ptr<ServerPlayer> serverPlayer = *it; - serverPlayer->flagEntitiesToBeRemoved(flags, flagToBeRemoved); + if ( serverPlayer ) + serverPlayer->flagEntitiesToBeRemoved(flags, flagToBeRemoved); } } @@ -52,7 +52,7 @@ void PlayerChunkMap::PlayerChunk::add(shared_ptr<ServerPlayer> player, bool send //app.DebugPrintf("--- Adding player to chunk x=%d\tz=%d\n",x, z); if (find(players.begin(),players.end(),player) != players.end()) { - // 4J-PB - At the start of the game, lots of chunks are added, and we can then move into an area that is outside the diameter of our starting area, + // 4J-PB - At the start of the game, lots of chunks are added, and we can then move into an area that is outside the diameter of our starting area, // but is inside the area loaded at the start. app.DebugPrintf("--- Adding player to chunk x=%d\t z=%d, but they are already in there!\n",pos.x, pos.z); return; @@ -72,7 +72,7 @@ void PlayerChunkMap::PlayerChunk::add(shared_ptr<ServerPlayer> player, bool send } players.push_back(player); - + player->chunksToSend.push_back(pos); #ifdef _LARGE_WORLDS @@ -85,8 +85,8 @@ void PlayerChunkMap::PlayerChunk::remove(shared_ptr<ServerPlayer> player) PlayerChunkMap::PlayerChunk *toDelete = NULL; //app.DebugPrintf("--- PlayerChunkMap::PlayerChunk::remove x=%d\tz=%d\n",x,z); - AUTO_VAR(it, find(players.begin(),players.end(),player)); - if ( it == players.end()) + auto it = find(players.begin(), players.end(), player); + if ( it == players.end()) { app.DebugPrintf("--- INFO - Removing player from chunk x=%d\t z=%d, but they are not in that chunk!\n",pos.x, pos.z); @@ -99,20 +99,20 @@ void PlayerChunkMap::PlayerChunk::remove(shared_ptr<ServerPlayer> player) { LevelChunk *chunk = parent->level->getChunk(pos.x, pos.z); updateInhabitedTime(chunk); - AUTO_VAR(it, find(parent->knownChunks.begin(), parent->knownChunks.end(),this)); - if(it != parent->knownChunks.end()) parent->knownChunks.erase(it); + auto it = find(parent->knownChunks.begin(), parent->knownChunks.end(), this); + if(it != parent->knownChunks.end()) parent->knownChunks.erase(it); } __int64 id = (pos.x + 0x7fffffffLL) | ((pos.z + 0x7fffffffLL) << 32); - AUTO_VAR(it, parent->chunks.find(id)); - if( it != parent->chunks.end() ) + auto it = parent->chunks.find(id); + if( it != parent->chunks.end() ) { toDelete = it->second; // Don't delete until the end of the function, as this might be this instance parent->chunks.erase(it); } if (changes > 0) { - AUTO_VAR(it, find(parent->changedChunks.begin(),parent->changedChunks.end(),this)); - parent->changedChunks.erase(it); + auto it = find(parent->changedChunks.begin(), parent->changedChunks.end(), this); + parent->changedChunks.erase(it); } parent->getLevel()->cache->drop(pos.x, pos.z); } @@ -125,17 +125,19 @@ void PlayerChunkMap::PlayerChunk::remove(shared_ptr<ServerPlayer> player) { INetworkPlayer *thisNetPlayer = player->connection->getNetworkPlayer(); bool noOtherPlayersFound = true; - - if( thisNetPlayer != NULL ) + + if( thisNetPlayer != nullptr ) { - for( AUTO_VAR(it, players.begin()); it < players.end(); ++it ) - { - shared_ptr<ServerPlayer> currPlayer = *it; - INetworkPlayer *currNetPlayer = currPlayer->connection->getNetworkPlayer(); - if( currNetPlayer != NULL && currNetPlayer->IsSameSystem( thisNetPlayer ) && currPlayer->seenChunks.find(pos) != currPlayer->seenChunks.end() ) + for (auto& currPlayer : players ) + { + if ( currPlayer ) { - noOtherPlayersFound = false; - break; + INetworkPlayer *currNetPlayer = currPlayer->connection->getNetworkPlayer(); + if( currNetPlayer != NULL && currNetPlayer->IsSameSystem( thisNetPlayer ) && currPlayer->seenChunks.find(pos) != currPlayer->seenChunks.end() ) + { + noOtherPlayersFound = false; + break; + } } } if(noOtherPlayersFound) @@ -224,7 +226,7 @@ void PlayerChunkMap::PlayerChunk::broadcast(shared_ptr<Packet> packet) } else { - for(unsigned int j = 0; j < sentTo.size(); j++ ) + for(unsigned int j = 0; j < sentTo.size(); j++ ) { shared_ptr<ServerPlayer> player2 = sentTo[j]; INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); @@ -286,7 +288,7 @@ void PlayerChunkMap::PlayerChunk::broadcast(shared_ptr<Packet> packet) } else { - for(unsigned int j = 0; j < sentTo.size(); j++ ) + for(unsigned int j = 0; j < sentTo.size(); j++ ) { shared_ptr<ServerPlayer> player2 = sentTo[j]; INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); @@ -348,7 +350,7 @@ bool PlayerChunkMap::PlayerChunk::broadcastChanges(bool allowRegionUpdate) // Fix for buf #95007 : TCR #001 BAS Game Stability: TU12: Code: Compliance: More than 192 dropped items causes game to freeze or crash. // Block region update packets can only encode ys in a range of 1 - 256 - if( ys > 256 ) ys = 256; + if( ys > 256 ) ys = 256; broadcast( shared_ptr<BlockRegionUpdatePacket>( new BlockRegionUpdatePacket(xp, yp, zp, xs, ys, zs, level) ) ); vector<shared_ptr<TileEntity> > *tes = level->getTileEntitiesInRegion(xp, yp, zp, xp + xs, yp + ys, zp + zs); @@ -406,9 +408,9 @@ PlayerChunkMap::PlayerChunkMap(ServerLevel *level, int dimension, int radius) PlayerChunkMap::~PlayerChunkMap() { - for( AUTO_VAR(it, chunks.begin()); it != chunks.end(); it++ ) + for(auto& chunk : chunks) { - delete it->second; + delete chunk.second; } } @@ -479,9 +481,9 @@ bool PlayerChunkMap::hasChunk(int x, int z) PlayerChunkMap::PlayerChunk *PlayerChunkMap::getChunk(int x, int z, bool create) { __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - AUTO_VAR(it, chunks.find(id)); + auto it = chunks.find(id); - PlayerChunk *chunk = NULL; + PlayerChunk *chunk = nullptr; if( it != chunks.end() ) { chunk = it->second; @@ -501,9 +503,9 @@ PlayerChunkMap::PlayerChunk *PlayerChunkMap::getChunk(int x, int z, bool create) void PlayerChunkMap::getChunkAndAddPlayer(int x, int z, shared_ptr<ServerPlayer> player) { __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - AUTO_VAR(it, chunks.find(id)); + auto it = chunks.find(id); - if( it != chunks.end() ) + if( it != chunks.end() ) { it->second->add(player); } @@ -517,8 +519,8 @@ void PlayerChunkMap::getChunkAndAddPlayer(int x, int z, shared_ptr<ServerPlayer> // attempt to remove from main chunk map. void PlayerChunkMap::getChunkAndRemovePlayer(int x, int z, shared_ptr<ServerPlayer> player) { - for( AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); it++ ) - { + for (auto it = addRequests.begin(); it != addRequests.end(); it++) + { if( ( it->x == x ) && ( it->z == z ) && ( it->player == player ) ) @@ -528,9 +530,9 @@ void PlayerChunkMap::getChunkAndRemovePlayer(int x, int z, shared_ptr<ServerPlay } } __int64 id = (x + 0x7fffffffLL) | ((z + 0x7fffffffLL) << 32); - AUTO_VAR(it, chunks.find(id)); + auto it = chunks.find(id); - if( it != chunks.end() ) + if( it != chunks.end() ) { it->second->remove(player); } @@ -545,10 +547,10 @@ void PlayerChunkMap::tickAddRequests(shared_ptr<ServerPlayer> player) int px = (int)player->x; int pz = (int)player->z; int minDistSq = -1; - - AUTO_VAR(itNearest, addRequests.end()); - for( AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); it++ ) - { + + auto itNearest = addRequests.end(); + for (auto it = addRequests.begin(); it != addRequests.end(); it++) + { if( it->player == player ) { int xm = ( it->x * 16 ) + 8; @@ -732,13 +734,13 @@ void PlayerChunkMap::remove(shared_ptr<ServerPlayer> player) if (playerChunk != NULL) playerChunk->remove(player); } - AUTO_VAR(it, find(players.begin(),players.end(),player)); - if( players.size() > 0 && it != players.end() ) + auto it = find(players.begin(), players.end(), player); + if( players.size() > 0 && it != players.end() ) players.erase(find(players.begin(),players.end(),player)); // 4J - added - also remove any queued requests to be added to playerchunks here - for( AUTO_VAR(it, addRequests.begin()); it != addRequests.end(); ) - { + for (auto it = addRequests.begin(); it != addRequests.end();) + { if( it->player == player ) { it = addRequests.erase(it); @@ -782,7 +784,7 @@ void PlayerChunkMap::move(shared_ptr<ServerPlayer> player) for (int x = xc - radius; x <= xc + radius; x++) for (int z = zc - radius; z <= zc + radius; z++) - { + { if (!chunkInRange(x, z, last_xc, last_zc)) { // 4J - changed from separate getChunk & add so we can wrap these operations up and queue @@ -815,9 +817,9 @@ bool PlayerChunkMap::isPlayerIn(shared_ptr<ServerPlayer> player, int xChunk, int } else { - AUTO_VAR(it1, find(chunk->players.begin(), chunk->players.end(), player)); - AUTO_VAR(it2, find(player->chunksToSend.begin(), player->chunksToSend.end(), chunk->pos)); - return it1 != chunk->players.end() && it2 == player->chunksToSend.end(); + auto it1 = find(chunk->players.begin(), chunk->players.end(), player); + auto it2 = find(player->chunksToSend.begin(), player->chunksToSend.end(), chunk->pos); + return it1 != chunk->players.end() && it2 == player->chunksToSend.end(); } //return chunk == NULL ? false : chunk->players->contains(player) && !player->chunksToSend->contains(chunk->pos); @@ -844,7 +846,7 @@ void PlayerChunkMap::setRadius(int newRadius) for (int x = xc - newRadius; x <= xc + newRadius; x++) for (int z = zc - newRadius; z <= zc + newRadius; z++) - { + { // check if this chunk is outside the old radius area if ( x < xc - radius || x > xc + radius || z < zc - radius || z > zc + radius ) { diff --git a/Minecraft.Client/PlayerConnection.cpp b/Minecraft.Client/PlayerConnection.cpp index 4928f65b..266cae36 100644 --- a/Minecraft.Client/PlayerConnection.cpp +++ b/Minecraft.Client/PlayerConnection.cpp @@ -124,7 +124,7 @@ void PlayerConnection::disconnect(DisconnectPacket::eDisconnectReason reason) send( shared_ptr<DisconnectPacket>( new DisconnectPacket(reason) )); connection->sendAndQuit(); // 4J-PB - removed, since it needs to be localised in the language the client is in - //server->players->broadcastAll( shared_ptr<ChatPacket>( new ChatPacket(L"§e" + player->name + L" left the game.") ) ); + //server->players->broadcastAll( shared_ptr<ChatPacket>( new ChatPacket(L"�e" + player->name + L" left the game.") ) ); if(getWasKicked()) { server->getPlayers()->broadcastAll( shared_ptr<ChatPacket>( new ChatPacket(player->name, ChatPacket::e_ChatPlayerKickedFromGame) ) ); @@ -182,7 +182,7 @@ void PlayerConnection::handleMovePlayer(shared_ptr<MovePlayerPacket> packet) player->onGround = packet->onGround; - player->doTick(false); + player->doTick(false); player->ySlideOffset = 0; player->absMoveTo(xt, yt, zt, yRotT, xRotT); if (player->riding != NULL) player->riding->positionRider(); @@ -539,7 +539,7 @@ void PlayerConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, if( done ) return; // logger.info(player.name + " lost connection: " + reason); // 4J-PB - removed, since it needs to be localised in the language the client is in - //server->players->broadcastAll( shared_ptr<ChatPacket>( new ChatPacket(L"§e" + player->name + L" left the game.") ) ); + //server->players->broadcastAll( shared_ptr<ChatPacket>( new ChatPacket(L"�e" + player->name + L" left the game.") ) ); if(getWasKicked()) { server->getPlayers()->broadcastAll( shared_ptr<ChatPacket>( new ChatPacket(player->name, ChatPacket::e_ChatPlayerKickedFromGame) ) ); @@ -728,13 +728,13 @@ int PlayerConnection::countDelayedPackets() void PlayerConnection::info(const wstring& string) { // 4J-PB - removed, since it needs to be localised in the language the client is in - //send( shared_ptr<ChatPacket>( new ChatPacket(L"§7" + string) ) ); + //send( shared_ptr<ChatPacket>( new ChatPacket(L"�7" + string) ) ); } void PlayerConnection::warn(const wstring& string) { // 4J-PB - removed, since it needs to be localised in the language the client is in - //send( shared_ptr<ChatPacket>( new ChatPacket(L"§9" + string) ) ); + //send( shared_ptr<ChatPacket>( new ChatPacket(L"�9" + string) ) ); } wstring PlayerConnection::getConsoleName() @@ -798,7 +798,7 @@ void PlayerConnection::handleTexture(shared_ptr<TexturePacket> packet) wprintf(L"Server received request for custom texture %ls\n",packet->textureName.c_str()); #endif PBYTE pbData=NULL; - DWORD dwBytes=0; + DWORD dwBytes=0; app.GetMemFileDetails(packet->textureName,&pbData,&dwBytes); if(dwBytes!=0) @@ -832,7 +832,7 @@ void PlayerConnection::handleTextureAndGeometry(shared_ptr<TextureAndGeometryPac wprintf(L"Server received request for custom texture %ls\n",packet->textureName.c_str()); #endif PBYTE pbData=NULL; - DWORD dwTextureBytes=0; + DWORD dwTextureBytes=0; app.GetMemFileDetails(packet->textureName,&pbData,&dwTextureBytes); DLCSkinFile *pDLCSkinFile = app.m_dlcManager.getSkinFile(packet->textureName); @@ -892,11 +892,11 @@ void PlayerConnection::handleTextureAndGeometry(shared_ptr<TextureAndGeometryPac void PlayerConnection::handleTextureReceived(const wstring &textureName) { // This sends the server received texture out to any other players waiting for the data - AUTO_VAR(it, find( m_texturesRequested.begin(), m_texturesRequested.end(), textureName )); - if( it != m_texturesRequested.end() ) + auto it = find(m_texturesRequested.begin(), m_texturesRequested.end(), textureName); + if( it != m_texturesRequested.end() ) { PBYTE pbData=NULL; - DWORD dwBytes=0; + DWORD dwBytes=0; app.GetMemFileDetails(textureName,&pbData,&dwBytes); if(dwBytes!=0) @@ -910,11 +910,11 @@ void PlayerConnection::handleTextureReceived(const wstring &textureName) void PlayerConnection::handleTextureAndGeometryReceived(const wstring &textureName) { // This sends the server received texture out to any other players waiting for the data - AUTO_VAR(it, find( m_texturesRequested.begin(), m_texturesRequested.end(), textureName )); - if( it != m_texturesRequested.end() ) + auto it = find(m_texturesRequested.begin(), m_texturesRequested.end(), textureName); + if( it != m_texturesRequested.end() ) { PBYTE pbData=NULL; - DWORD dwTextureBytes=0; + DWORD dwTextureBytes=0; app.GetMemFileDetails(textureName,&pbData,&dwTextureBytes); DLCSkinFile *pDLCSkinFile=app.m_dlcManager.getSkinFile(textureName); @@ -933,7 +933,7 @@ void PlayerConnection::handleTextureAndGeometryReceived(const wstring &textureNa send( shared_ptr<TextureAndGeometryPacket>( new TextureAndGeometryPacket(textureName,pbData,dwTextureBytes, pvSkinBoxes, uiAnimOverrideBitmask) ) ); } - m_texturesRequested.erase(it); + m_texturesRequested.erase(it); } } } @@ -967,7 +967,7 @@ void PlayerConnection::handleTextureChange(shared_ptr<TextureChangePacket> packe } } else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) - { + { // Update the ref count on the memory texture data app.AddMemoryTextureFile(packet->path,NULL,0); } @@ -994,7 +994,7 @@ void PlayerConnection::handleTextureAndGeometryChange(shared_ptr<TextureAndGeome } } else if(!packet->path.empty() && app.IsFileInMemoryTextures(packet->path)) - { + { // Update the ref count on the memory texture data app.AddMemoryTextureFile(packet->path,NULL,0); @@ -1017,7 +1017,7 @@ void PlayerConnection::handleServerSettingsChanged(shared_ptr<ServerSettingsChan if( (networkPlayer != NULL && networkPlayer->IsHost()) || player->isModerator()) { app.SetGameHostOption(eGameHostOption_FireSpreads, app.GetGameHostOption(packet->data,eGameHostOption_FireSpreads)); - app.SetGameHostOption(eGameHostOption_TNT, app.GetGameHostOption(packet->data,eGameHostOption_TNT)); + app.SetGameHostOption(eGameHostOption_TNT, app.GetGameHostOption(packet->data,eGameHostOption_TNT)); app.SetGameHostOption(eGameHostOption_MobGriefing, app.GetGameHostOption(packet->data, eGameHostOption_MobGriefing)); app.SetGameHostOption(eGameHostOption_KeepInventory, app.GetGameHostOption(packet->data, eGameHostOption_KeepInventory)); app.SetGameHostOption(eGameHostOption_DoMobSpawning, app.GetGameHostOption(packet->data, eGameHostOption_DoMobSpawning)); @@ -1038,7 +1038,7 @@ void PlayerConnection::handleKickPlayer(shared_ptr<KickPlayerPacket> packet) { INetworkPlayer *networkPlayer = getNetworkPlayer(); if( (networkPlayer != NULL && networkPlayer->IsHost()) || player->isModerator()) - { + { server->getPlayers()->kickPlayerByShortId(packet->m_networkSmallId); } } @@ -1090,7 +1090,7 @@ void PlayerConnection::handleContainerClose(shared_ptr<ContainerClosePacket> pac player->doCloseContainer(); } -#ifndef _CONTENT_PACKAGE +#ifndef _CONTENT_PACKAGE void PlayerConnection::handleContainerSetSlot(shared_ptr<ContainerSetSlotPacket> packet) { if (packet->containerId == AbstractContainerMenu::CONTAINER_ID_CARRIED ) @@ -1192,7 +1192,7 @@ void PlayerConnection::handleSetCreativeModeSlot(shared_ptr<SetCreativeModeSlotP int centreXC = 0; int centreZC = 0; #endif - item->setAuxValue( player->level->getAuxValueForMap(player->getXuid(), player->dimension, centreXC, centreZC, mapScale) ); + item->setAuxValue( player->level->getAuxValueForMap(player->getXuid(), player->dimension, centreXC, centreZC, mapScale) ); shared_ptr<MapItemSavedData> data = MapItem::getSavedData(item->getAuxValue(), player->level); // 4J Stu - We only have one map per player per dimension, so don't reset the one that they have @@ -1261,9 +1261,9 @@ void PlayerConnection::handleSetCreativeModeSlot(shared_ptr<SetCreativeModeSlotP void PlayerConnection::handleContainerAck(shared_ptr<ContainerAckPacket> packet) { - AUTO_VAR(it, expectedAcks.find(player->containerMenu->containerId)); + auto it = expectedAcks.find(player->containerMenu->containerId); - if (it != expectedAcks.end() && packet->uid == it->second && player->containerMenu->containerId == packet->containerId && !player->containerMenu->isSynched(player)) + if (it != expectedAcks.end() && packet->uid == it->second && player->containerMenu->containerId == packet->containerId && !player->containerMenu->isSynched(player)) { player->containerMenu->setSynched(player, true); } @@ -1319,7 +1319,7 @@ void PlayerConnection::handleKeepAlive(shared_ptr<KeepAlivePacket> packet) } void PlayerConnection::handlePlayerInfo(shared_ptr<PlayerInfoPacket> packet) -{ +{ // Need to check that this player has permission to change each individual setting? INetworkPlayer *networkPlayer = getNetworkPlayer(); @@ -1327,9 +1327,8 @@ void PlayerConnection::handlePlayerInfo(shared_ptr<PlayerInfoPacket> packet) { shared_ptr<ServerPlayer> serverPlayer; // Find the player being edited - for(AUTO_VAR(it, server->getPlayers()->players.begin()); it != server->getPlayers()->players.end(); ++it) + for(auto& checkingPlayer : server->getPlayers()->players) { - shared_ptr<ServerPlayer> checkingPlayer = *it; if(checkingPlayer->connection->getNetworkPlayer() != NULL && checkingPlayer->connection->getNetworkPlayer()->GetSmallId() == packet->m_networkSmallId) { serverPlayer = checkingPlayer; @@ -1350,7 +1349,7 @@ void PlayerConnection::handlePlayerInfo(shared_ptr<PlayerInfoPacket> packet) if (serverPlayer->gameMode->getGameModeForPlayer() != gameType) { #ifndef _CONTENT_PACKAGE - wprintf(L"Setting %ls to game mode %d\n", serverPlayer->name.c_str(), gameType); + wprintf(L"Setting %ls to game mode %d\n", serverPlayer->name.c_str(), gameType->getId()); #endif serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CreativeMode,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CreativeMode) ); serverPlayer->gameMode->setGameModeForPlayer(gameType); @@ -1382,7 +1381,7 @@ void PlayerConnection::handlePlayerInfo(shared_ptr<PlayerInfoPacket> packet) } else { - // Editing someone else + // Editing someone else if(!trustPlayers && !serverPlayer->connection->getNetworkPlayer()->IsHost()) { serverPlayer->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_CannotMine,Player::getPlayerGamePrivilege(packet->m_playerPrivileges,Player::ePlayerGamePrivilege_CannotMine) ); @@ -1609,7 +1608,7 @@ void PlayerConnection::handleCraftItem(shared_ptr<CraftItemPacket> packet) // TODO 4J Stu - Assume at the moment that the client can work this out for us... - //if(pRecipeIngredientsRequired[iRecipe].bCanMake) + //if(pRecipeIngredientsRequired[iRecipe].bCanMake) //{ pTempItemInst->onCraftedBy(player->level, dynamic_pointer_cast<Player>( player->shared_from_this() ), pTempItemInst->count ); @@ -1756,7 +1755,7 @@ INetworkPlayer *PlayerConnection::getNetworkPlayer() bool PlayerConnection::isLocal() { - if( connection->getSocket() == NULL ) + if( connection->getSocket() == NULL ) { return false; } @@ -1769,7 +1768,7 @@ bool PlayerConnection::isLocal() bool PlayerConnection::isGuest() { - if( connection->getSocket() == NULL ) + if( connection->getSocket() == NULL ) { return false; } diff --git a/Minecraft.Client/PlayerList.cpp b/Minecraft.Client/PlayerList.cpp index 0de0c36b..c1ccfe14 100644 --- a/Minecraft.Client/PlayerList.cpp +++ b/Minecraft.Client/PlayerList.cpp @@ -1,5 +1,7 @@ #include "stdafx.h" #include "PlayerList.h" + +#include <memory> #include "PlayerChunkMap.h" #include "MinecraftServer.h" #include "Settings.h" @@ -65,11 +67,11 @@ PlayerList::PlayerList(MinecraftServer *server) PlayerList::~PlayerList() { - for( AUTO_VAR(it, players.begin()); it < players.end(); it++ ) - { - (*it)->connection = nullptr; // Must remove reference to connection, or else there is a circular dependency - delete (*it)->gameMode; // Gamemode also needs deleted as it references back to this player - (*it)->gameMode = NULL; + for (auto& player : players) + { + player->connection = nullptr; // Must remove reference to connection, or else there is a circular dependency + delete player->gameMode; // Gamemode also needs deleted as it references back to this player + player->gameMode = nullptr; } DeleteCriticalSection(&m_kickPlayersCS); @@ -89,7 +91,7 @@ void PlayerList::placeNewPlayer(Connection *connection, shared_ptr<ServerPlayer> INetworkPlayer *networkPlayer = connection->getSocket()->getPlayer(); if(networkPlayer != NULL && networkPlayer->IsHost()) { - player->enableAllPlayerPrivileges(true); + player->enableAllPlayerPrivileges(true); player->setPlayerGamePrivilege(Player::ePlayerGamePrivilege_HOST,1); } @@ -123,9 +125,9 @@ void PlayerList::placeNewPlayer(Connection *connection, shared_ptr<ServerPlayer> { bool usedIndexes[MINECRAFT_NET_MAX_PLAYERS]; ZeroMemory( &usedIndexes, MINECRAFT_NET_MAX_PLAYERS * sizeof(bool) ); - for(AUTO_VAR(it, players.begin()); it < players.end(); ++it) - { - usedIndexes[ (int)(*it)->getPlayerIndex() ] = true; + for (auto& player : players ) + { + usedIndexes[player->getPlayerIndex()] = true; } for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) { @@ -175,7 +177,7 @@ void PlayerList::placeNewPlayer(Connection *connection, shared_ptr<ServerPlayer> } } else if(!player->customTextureUrl.empty() && app.IsFileInMemoryTextures(player->customTextureUrl)) - { + { // Update the ref count on the memory texture data app.AddMemoryTextureFile(player->customTextureUrl,NULL,0); } @@ -191,7 +193,7 @@ void PlayerList::placeNewPlayer(Connection *connection, shared_ptr<ServerPlayer> } } else if(!player->customTextureUrl2.empty() && app.IsFileInMemoryTextures(player->customTextureUrl2)) - { + { // Update the ref count on the memory texture data app.AddMemoryTextureFile(player->customTextureUrl2,NULL,0); } @@ -250,10 +252,9 @@ void PlayerList::placeNewPlayer(Connection *connection, shared_ptr<ServerPlayer> server->getConnection()->addPlayerConnection(playerConnection); playerConnection->send( shared_ptr<SetTimePacket>( new SetTimePacket(level->getGameTime(), level->getDayTime(), level->getGameRules()->getBoolean(GameRules::RULE_DAYLIGHT)) ) ); - AUTO_VAR(activeEffects, player->getActiveEffects()); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) + auto activeEffects = player->getActiveEffects(); + for(MobEffectInstance *effect : *player->getActiveEffects()) { - MobEffectInstance *effect = *it; playerConnection->send(shared_ptr<UpdateMobEffectPacket>( new UpdateMobEffectPacket(player->entityId, effect) ) ); } @@ -275,13 +276,12 @@ void PlayerList::placeNewPlayer(Connection *connection, shared_ptr<ServerPlayer> // If we are joining at the same time as someone in the end on this system is travelling through the win portal, // then we should set our wonGame flag to true so that respawning works when the EndPoem is closed INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer != NULL ) + if( thisPlayer ) { - for(AUTO_VAR(it, players.begin()); it != players.end(); ++it) + for(auto& servPlayer : players) { - shared_ptr<ServerPlayer> servPlayer = *it; - INetworkPlayer *checkPlayer = servPlayer->connection->getNetworkPlayer(); - if(thisPlayer != checkPlayer && checkPlayer != NULL && thisPlayer->IsSameSystem( checkPlayer ) && servPlayer->wonGame ) + INetworkPlayer* checkPlayer = servPlayer->connection->getNetworkPlayer(); + if(thisPlayer != checkPlayer && checkPlayer && thisPlayer->IsSameSystem( checkPlayer ) && servPlayer->wonGame ) { player->wonGame = true; break; @@ -460,7 +460,7 @@ void PlayerList::add(shared_ptr<ServerPlayer> player) shared_ptr<ServerPlayer> thisPlayer = players[i]; if(thisPlayer->isSleeping()) { - if(firstSleepingPlayer == NULL) firstSleepingPlayer = thisPlayer; + if(firstSleepingPlayer == NULL) firstSleepingPlayer = thisPlayer; thisPlayer->connection->send(shared_ptr<ChatPacket>( new ChatPacket(thisPlayer->name, ChatPacket::e_ChatBedMeSleep))); } } @@ -487,12 +487,12 @@ if (player->riding != NULL) level->getTracker()->removeEntity(player); level->removeEntity(player); level->getChunkMap()->remove(player); - AUTO_VAR(it, find(players.begin(),players.end(),player)); - if( it != players.end() ) + auto it = find(players.begin(), players.end(), player); + if( it != players.end() ) { players.erase(it); } - //broadcastAll(shared_ptr<PlayerInfoPacket>( new PlayerInfoPacket(player->name, false, 9999) ) ); + //broadcastAll(shared_ptr<PlayerInfoPacket>( new PlayerInfoPacket(player->name, false, 9999) ) ); removePlayerFromReceiving(player); player->connection = nullptr; // Must remove reference to connection, or else there is a circular dependency @@ -548,7 +548,7 @@ shared_ptr<ServerPlayer> PlayerList::getPlayerForLogin(PendingConnection *pendin shared_ptr<ServerPlayer> PlayerList::respawn(shared_ptr<ServerPlayer> serverPlayer, int targetDimension, bool keepAllPlayerData) { - // How we handle the entity tracker depends on whether we are the primary player currently, and whether there will be any player in the same system in the same dimension once we finish respawning. + // How we handle the entity tracker depends on whether we are the primary player currently, and whether there will be any player in the same system in the same dimension once we finish respawning. bool isPrimary = canReceiveAllPackets(serverPlayer); // Is this the primary player in its current dimension? int oldDimension = serverPlayer->dimension; bool isEmptying = ( targetDimension != oldDimension); // We're not emptying this dimension on this machine if this player is going back into the same dimension @@ -599,8 +599,8 @@ shared_ptr<ServerPlayer> PlayerList::respawn(shared_ptr<ServerPlayer> serverPlay } serverPlayer->getLevel()->getChunkMap()->remove(serverPlayer); - AUTO_VAR(it, find(players.begin(),players.end(),serverPlayer)); - if( it != players.end() ) + auto it = find(players.begin(), players.end(), serverPlayer); + if( it != players.end() ) { players.erase(it); } @@ -689,20 +689,18 @@ shared_ptr<ServerPlayer> PlayerList::respawn(shared_ptr<ServerPlayer> serverPlay player->setPos(player->x, player->y + 1, player->z); } - player->connection->send( shared_ptr<RespawnPacket>( new RespawnPacket((char) player->dimension, player->level->getSeed(), player->level->getMaxBuildHeight(), + player->connection->send( std::make_shared<RespawnPacket>( (char) player->dimension, player->level->getSeed(), player->level->getMaxBuildHeight(), player->gameMode->getGameModeForPlayer(), level->difficulty, level->getLevelData()->getGenerator(), - player->level->useNewSeaLevel(), player->entityId, level->getLevelData()->getXZSize(), level->getLevelData()->getHellScale()) ) ); + player->level->useNewSeaLevel(), player->entityId, level->getLevelData()->getXZSize(), level->getLevelData()->getHellScale() ) ); player->connection->teleport(player->x, player->y, player->z, player->yRot, player->xRot); - player->connection->send( shared_ptr<SetExperiencePacket>( new SetExperiencePacket(player->experienceProgress, player->totalExperience, player->experienceLevel)) ); + player->connection->send( std::make_shared<SetExperiencePacket>( player->experienceProgress, player->totalExperience, player->experienceLevel) ); if(keepAllPlayerData) { vector<MobEffectInstance *> *activeEffects = player->getActiveEffects(); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) + for(MobEffectInstance *effect : *activeEffects) { - MobEffectInstance *effect = *it; - - player->connection->send(shared_ptr<UpdateMobEffectPacket>( new UpdateMobEffectPacket(player->entityId, effect) ) ); + player->connection->send(std::make_shared<UpdateMobEffectPacket>( player->entityId, effect ) ); } delete activeEffects; player->getEntityData()->markDirty(Mob::DATA_EFFECT_COLOR_ID); @@ -719,7 +717,7 @@ shared_ptr<ServerPlayer> PlayerList::respawn(shared_ptr<ServerPlayer> serverPlay // 4J-JEV - Dying before this point in the tutorial is pretty annoying, // making sure to remove health/hunger and give you back your meat. - if( Minecraft::GetInstance()->isTutorial() + if( Minecraft::GetInstance()->isTutorial() && (!Minecraft::GetInstance()->gameMode->getTutorial()->isStateCompleted(e_Tutorial_State_Food_Bar)) ) { app.getGameRuleDefinitions()->postProcessPlayer(player); @@ -737,7 +735,7 @@ shared_ptr<ServerPlayer> PlayerList::respawn(shared_ptr<ServerPlayer> serverPlay void PlayerList::toggleDimension(shared_ptr<ServerPlayer> player, int targetDimension) { int lastDimension = player->dimension; - // How we handle the entity tracker depends on whether we are the primary player currently, and whether there will be any player in the same system in the same dimension once we finish respawning. + // How we handle the entity tracker depends on whether we are the primary player currently, and whether there will be any player in the same system in the same dimension once we finish respawning. bool isPrimary = canReceiveAllPackets(player); // Is this the primary player in its current dimension? bool isEmptying = true; @@ -832,11 +830,9 @@ void PlayerList::toggleDimension(shared_ptr<ServerPlayer> player, int targetDime // 4J Stu - Fix for #64683 - Customer Encountered: TU7: Content: Gameplay: Potion effects are removed after using the Nether Portal vector<MobEffectInstance *> *activeEffects = player->getActiveEffects(); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) + for(MobEffectInstance *effect : *activeEffects) { - MobEffectInstance *effect = *it; - - player->connection->send(shared_ptr<UpdateMobEffectPacket>( new UpdateMobEffectPacket(player->entityId, effect) ) ); + player->connection->send(std::make_shared<UpdateMobEffectPacket>( player->entityId, effect ) ); } delete activeEffects; player->getEntityData()->markDirty(Mob::DATA_EFFECT_COLOR_ID); @@ -933,10 +929,10 @@ void PlayerList::tick() sendAllPlayerInfoIn = 0; } - if (sendAllPlayerInfoIn < players.size()) + if (sendAllPlayerInfoIn < players.size()) { shared_ptr<ServerPlayer> op = players[sendAllPlayerInfoIn]; - //broadcastAll(shared_ptr<PlayerInfoPacket>( new PlayerInfoPacket(op->name, true, op->latency) ) ); + //broadcastAll(shared_ptr<PlayerInfoPacket>( new PlayerInfoPacket(op->name, true, op->latency) ) ); if( op->connection->getNetworkPlayer() ) { broadcastAll(shared_ptr<PlayerInfoPacket>( new PlayerInfoPacket( op ) ) ); @@ -1091,7 +1087,7 @@ bool PlayerList::isOp(shared_ptr<ServerPlayer> player) shared_ptr<ServerPlayer> PlayerList::getPlayer(const wstring& name) { - for (unsigned int i = 0; i < players.size(); i++) + for (unsigned int i = 0; i < players.size(); i++) { shared_ptr<ServerPlayer> p = players[i]; if (p->name == name) // 4J - used to be case insensitive (using equalsIgnoreCase) - imagine we'll be shifting to XUIDs anyway @@ -1105,7 +1101,7 @@ shared_ptr<ServerPlayer> PlayerList::getPlayer(const wstring& name) // 4J Added shared_ptr<ServerPlayer> PlayerList::getPlayer(PlayerUID uid) { - for (unsigned int i = 0; i < players.size(); i++) + for (unsigned int i = 0; i < players.size(); i++) { shared_ptr<ServerPlayer> p = players[i]; if (p->getXuid() == uid || p->getOnlineXuid() == uid) // 4J - used to be case insensitive (using equalsIgnoreCase) - imagine we'll be shifting to XUIDs anyway @@ -1264,7 +1260,7 @@ void PlayerList::broadcast(shared_ptr<Player> except, double x, double y, double } else { - for(unsigned int j = 0; j < sentTo.size(); j++ ) + for(unsigned int j = 0; j < sentTo.size(); j++ ) { shared_ptr<ServerPlayer> player2 = sentTo[j]; INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); @@ -1351,7 +1347,7 @@ void PlayerList::sendLevelInfo(shared_ptr<ServerPlayer> player, ServerLevel *lev player->connection->send( shared_ptr<GameEventPacket>( new GameEventPacket(GameEventPacket::STOP_RAINING, 0) ) ); } - // send the stronghold position if there is one + // send the stronghold position if there is one if((level->dimension->id==0) && level->getLevelData()->getHasStronghold()) { player->connection->send( shared_ptr<XZPacket>( new XZPacket(XZPacket::STRONGHOLD,level->getLevelData()->getXStronghold(),level->getLevelData()->getZStronghold()) ) ); @@ -1374,9 +1370,9 @@ int PlayerList::getPlayerCount(ServerLevel *level) { int count = 0; - for(AUTO_VAR(it, players.begin()); it != players.end(); ++it) + for(auto& player : players) { - if( (*it)->level == level ) ++count; + if( player->level == level ) ++count; } return count; @@ -1431,18 +1427,16 @@ shared_ptr<ServerPlayer> PlayerList::findAlivePlayerOnSystem(shared_ptr<ServerPl else if( dimIndex == 1) dimIndex = 2; INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer != NULL ) + if( thisPlayer ) { - for(AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) + for(auto& newPlayer : players) { - shared_ptr<ServerPlayer> newPlayer = *itP; - INetworkPlayer *otherPlayer = newPlayer->connection->getNetworkPlayer(); if( !newPlayer->removed && newPlayer != player && newPlayer->dimension == playerDim && - otherPlayer != NULL && + otherPlayer && otherPlayer->IsSameSystem( thisPlayer ) ) { @@ -1466,8 +1460,8 @@ void PlayerList::removePlayerFromReceiving(shared_ptr<ServerPlayer> player, bool #endif bool playerRemoved = false; - AUTO_VAR(it, find( receiveAllPlayers[dimIndex].begin(), receiveAllPlayers[dimIndex].end(), player)); - if( it != receiveAllPlayers[dimIndex].end() ) + auto it = find(receiveAllPlayers[dimIndex].begin(), receiveAllPlayers[dimIndex].end(), player); + if( it != receiveAllPlayers[dimIndex].end() ) { #ifndef _CONTENT_PACKAGE app.DebugPrintf("Remove: Removing player %ls as primary in dimension %d\n", player->name.c_str(), dimIndex); @@ -1477,17 +1471,15 @@ void PlayerList::removePlayerFromReceiving(shared_ptr<ServerPlayer> player, bool } INetworkPlayer *thisPlayer = player->connection->getNetworkPlayer(); - if( thisPlayer != NULL && playerRemoved ) + if( thisPlayer && playerRemoved ) { - for(AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) + for(auto& newPlayer : players) { - shared_ptr<ServerPlayer> newPlayer = *itP; - INetworkPlayer *otherPlayer = newPlayer->connection->getNetworkPlayer(); if( newPlayer != player && newPlayer->dimension == playerDim && - otherPlayer != NULL && + otherPlayer && otherPlayer->IsSameSystem( thisPlayer ) ) { @@ -1506,20 +1498,18 @@ void PlayerList::removePlayerFromReceiving(shared_ptr<ServerPlayer> player, bool #endif // 4J Stu - Something went wrong, or possibly the QNet player left before we got here. // Re-check all active players and make sure they have someone on their system to receive all packets - for(AUTO_VAR(itP, players.begin()); itP != players.end(); ++itP) + for(auto& newPlayer : players) { - shared_ptr<ServerPlayer> newPlayer = *itP; INetworkPlayer *checkingPlayer = newPlayer->connection->getNetworkPlayer(); - if( checkingPlayer != NULL ) + if( checkingPlayer ) { int newPlayerDim = 0; if( newPlayer->dimension == -1 ) newPlayerDim = 1; else if( newPlayer->dimension == 1) newPlayerDim = 2; bool foundPrimary = false; - for(AUTO_VAR(it, receiveAllPlayers[newPlayerDim].begin()); it != receiveAllPlayers[newPlayerDim].end(); ++it) + for(auto& primaryPlayer : receiveAllPlayers[newPlayerDim]) { - shared_ptr<ServerPlayer> primaryPlayer = *it; INetworkPlayer *primPlayer = primaryPlayer->connection->getNetworkPlayer(); if(primPlayer != NULL && checkingPlayer->IsSameSystem( primPlayer ) ) { @@ -1562,11 +1552,10 @@ void PlayerList::addPlayerToReceiving(shared_ptr<ServerPlayer> player) } else { - for(AUTO_VAR(it, receiveAllPlayers[playerDim].begin()); it != receiveAllPlayers[playerDim].end(); ++it) + for(auto& oldPlayer : receiveAllPlayers[playerDim]) { - shared_ptr<ServerPlayer> oldPlayer = *it; INetworkPlayer *checkingPlayer = oldPlayer->connection->getNetworkPlayer(); - if(checkingPlayer != NULL && checkingPlayer->IsSameSystem( thisPlayer ) ) + if(checkingPlayer != NULL && checkingPlayer->IsSameSystem( thisPlayer ) ) { shouldAddPlayer = false; break; @@ -1588,9 +1577,8 @@ bool PlayerList::canReceiveAllPackets(shared_ptr<ServerPlayer> player) int playerDim = 0; if( player->dimension == -1 ) playerDim = 1; else if( player->dimension == 1) playerDim = 2; - for(AUTO_VAR(it, receiveAllPlayers[playerDim].begin()); it != receiveAllPlayers[playerDim].end(); ++it) + for(const auto& newPlayer : receiveAllPlayers[playerDim]) { - shared_ptr<ServerPlayer> newPlayer = *it; if(newPlayer == player) { return true; @@ -1619,9 +1607,9 @@ bool PlayerList::isXuidBanned(PlayerUID xuid) bool banned = false; - for( AUTO_VAR(it, m_bannedXuids.begin()); it != m_bannedXuids.end(); ++it ) + for(PlayerUID it : m_bannedXuids) { - if( ProfileManager.AreXUIDSEqual( xuid, *it ) ) + if( ProfileManager.AreXUIDSEqual( xuid, it ) ) { banned = true; break; diff --git a/Minecraft.Client/PlayerRenderer.cpp b/Minecraft.Client/PlayerRenderer.cpp index 7d135c2b..71c05067 100644 --- a/Minecraft.Client/PlayerRenderer.cpp +++ b/Minecraft.Client/PlayerRenderer.cpp @@ -14,7 +14,7 @@ #include "..\Minecraft.World\net.minecraft.h" #include "..\Minecraft.World\StringHelpers.h" -const unsigned int PlayerRenderer::s_nametagColors[MINECRAFT_NET_MAX_PLAYERS] = +const unsigned int PlayerRenderer::s_nametagColors[MINECRAFT_NET_MAX_PLAYERS] = { 0xff000000, // WHITE (represents the "white" player, but using black as the colour) 0xff33cc33, // GREEN @@ -201,12 +201,10 @@ void PlayerRenderer::render(shared_ptr<Entity> _mob, double x, double y, double // 4J-PB - any additional parts to turn on for this player (skin dependent) vector<ModelPart *> *pAdditionalModelParts=mob->GetAdditionalModelParts(); //turn them on - if(pAdditionalModelParts!=NULL) + if(pAdditionalModelParts!=nullptr) { - for(AUTO_VAR(it, pAdditionalModelParts->begin()); it != pAdditionalModelParts->end(); ++it) + for(ModelPart *pModelPart : *pAdditionalModelParts) { - ModelPart *pModelPart=*it; - pModelPart->visible=true; } } @@ -216,10 +214,8 @@ void PlayerRenderer::render(shared_ptr<Entity> _mob, double x, double y, double // turn them off again if(pAdditionalModelParts && pAdditionalModelParts->size()!=0) { - for(AUTO_VAR(it, pAdditionalModelParts->begin()); it != pAdditionalModelParts->end(); ++it) + for(ModelPart *pModelPart : *pAdditionalModelParts) { - ModelPart *pModelPart=*it; - pModelPart->visible=false; } } @@ -346,7 +342,7 @@ void PlayerRenderer::additionalRendering(shared_ptr<LivingEntity> _mob, float a) humanoidModel->renderCloak(1 / 16.0f,true); glPopMatrix(); } - + shared_ptr<ItemInstance> item = mob->inventory->getSelected(); if (item != NULL) diff --git a/Minecraft.Client/PreStitchedTextureMap.cpp b/Minecraft.Client/PreStitchedTextureMap.cpp index 5ea7bc59..eeccb628 100644 --- a/Minecraft.Client/PreStitchedTextureMap.cpp +++ b/Minecraft.Client/PreStitchedTextureMap.cpp @@ -36,9 +36,8 @@ PreStitchedTextureMap::PreStitchedTextureMap(int type, const wstring &name, cons void PreStitchedTextureMap::stitch() { // Animated StitchedTextures store a vector of textures for each frame of the animation. Free any pre-existing ones here. - for(AUTO_VAR(it, animatedTextures.begin()); it != animatedTextures.end(); ++it) + for(StitchedTexture *animatedStitchedTexture : animatedTextures) { - StitchedTexture *animatedStitchedTexture = *it; animatedStitchedTexture->freeFrameTextures(); } @@ -133,24 +132,24 @@ void PreStitchedTextureMap::stitch() TextureManager::getInstance()->registerName(name, stitchResult); //stitchResult = stitcher->constructTexture(m_mipMap); - for(AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); ++it) + for(auto & it : texturesByName) { - StitchedTexture *preStitched = (StitchedTexture *)it->second; + auto *preStitched = static_cast<StitchedTexture *>(it.second); int x = preStitched->getU0() * stitchResult->getWidth(); int y = preStitched->getV0() * stitchResult->getHeight(); int width = (preStitched->getU1() * stitchResult->getWidth()) - x; int height = (preStitched->getV1() * stitchResult->getHeight()) - y; - preStitched->init(stitchResult, NULL, x, y, width, height, false); + preStitched->init(stitchResult, nullptr, x, y, width, height, false); } MemSect(52); - for(AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); ++it) + for(auto& it : texturesByName) { - StitchedTexture *preStitched = (StitchedTexture *)(it->second); + auto *preStitched = static_cast<StitchedTexture *>(it.second); - makeTextureAnimated(texturePack, preStitched); + makeTextureAnimated(texturePack, preStitched); } MemSect(0); //missingPosition = (StitchedTexture *)texturesByName.find(NAME_MISSING_TEXTURE)->second; @@ -164,7 +163,7 @@ void PreStitchedTextureMap::stitch() DWORD *data = (DWORD*) this->getStitchedTexture()->getData()->getBuffer(); int Width = this->getStitchedTexture()->getWidth(); int Height = this->getStitchedTexture()->getHeight(); - for(AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); ++it) + for( auto it = texturesByName.begin(); it != texturesByName.end(); ++it) { StitchedTexture *preStitched = (StitchedTexture *)it->second; @@ -208,7 +207,7 @@ void PreStitchedTextureMap::makeTextureAnimated(TexturePack *texturePack, Stitch } wstring textureFileName = tex->m_fileName; - + wstring animString = texturePack->getAnimationString(textureFileName, path, true); if(!animString.empty()) @@ -259,10 +258,8 @@ StitchedTexture *PreStitchedTextureMap::getTexture(const wstring &name) void PreStitchedTextureMap::cycleAnimationFrames() { - //for (StitchedTexture texture : animatedTextures) - for(AUTO_VAR(it, animatedTextures.begin() ); it != animatedTextures.end(); ++it) + for(StitchedTexture* texture : animatedTextures) { - StitchedTexture *texture = *it; texture->cycleFrames(); } } @@ -286,10 +283,10 @@ Icon *PreStitchedTextureMap::registerIcon(const wstring &name) //new RuntimeException("Don't register null!").printStackTrace(); } - AUTO_VAR(it, texturesByName.find(name)); - if(it != texturesByName.end()) result = it->second; + auto it = texturesByName.find(name); + if(it != texturesByName.end()) result = it->second; - if (result == NULL) + if (result == nullptr) { #ifndef _CONTENT_PACKAGE app.DebugPrintf("Could not find uv data for icon %ls\n", name.c_str() ); @@ -325,9 +322,9 @@ void PreStitchedTextureMap::loadUVs() return; } - for(AUTO_VAR(it, texturesByName.begin()); it != texturesByName.end(); ++it) + for(auto& it : texturesByName) { - delete it->second; + delete it.second; } texturesByName.clear(); @@ -972,7 +969,7 @@ void PreStitchedTextureMap::loadUVs() ADD_ICON(18, 13, L"glass_silver"); ADD_ICON(18, 14, L"glass_white"); ADD_ICON(18, 15, L"glass_yellow"); - + ADD_ICON(19, 0, L"glass_pane_top_black"); ADD_ICON(19, 1, L"glass_pane_top_blue"); ADD_ICON(19, 2, L"glass_pane_top_brown"); diff --git a/Minecraft.Client/Screen.cpp b/Minecraft.Client/Screen.cpp index e69b7373..131cf013 100644 --- a/Minecraft.Client/Screen.cpp +++ b/Minecraft.Client/Screen.cpp @@ -24,11 +24,10 @@ Screen::Screen() // 4J added void Screen::render(int xm, int ym, float a) { - AUTO_VAR(itEnd, buttons.end()); - for (AUTO_VAR(it, buttons.begin()); it != itEnd; it++) + for (Button* button : buttons) { - Button *button = *it; //buttons[i]; - button->render(minecraft, xm, ym); + if ( button ) + button->render(minecraft, xm, ym); } } @@ -56,11 +55,9 @@ void Screen::mouseClicked(int x, int y, int buttonNum) { if (buttonNum == 0) { - AUTO_VAR(itEnd, buttons.end()); - for (AUTO_VAR(it, buttons.begin()); it != itEnd; it++) + for (Button* button : buttons) { - Button *button = *it; //buttons[i]; - if (button->clicked(minecraft, x, y)) + if ( button && button->clicked(minecraft, x, y) ) { clickedButton = button; minecraft->soundEngine->playUI(eSoundType_RANDOM_CLICK, 1, 1); diff --git a/Minecraft.Client/SelectWorldScreen.cpp b/Minecraft.Client/SelectWorldScreen.cpp index a07eb7b2..0481f1e5 100644 --- a/Minecraft.Client/SelectWorldScreen.cpp +++ b/Minecraft.Client/SelectWorldScreen.cpp @@ -60,7 +60,7 @@ wstring SelectWorldScreen::getWorldName(int id) if ( levelName.length() == 0 ) { Language *language = Language::getInstance(); - levelName = language->getElement(L"selectWorld.world") + L" " + _toString<int>(id + 1); + levelName = language->getElement(L"selectWorld.world") + L" " + std::to_wstring(id + 1); } return levelName; @@ -150,7 +150,7 @@ void SelectWorldScreen::worldSelected(int id) wstring worldFolderName = getWorldId(id); if (worldFolderName == L"") // 4J - was NULL comparison { - worldFolderName = L"World" + _toString<int>(id); + worldFolderName = L"World" + std::to_wstring(id); } // 4J Stu - Not used, so commenting to stop the build failing #if 0 @@ -246,7 +246,7 @@ void SelectWorldScreen::WorldSelectionList::selectItem(int item, bool doubleClic parent->deleteButton->active = active; parent->renameButton->active = active; - if (doubleClick && active) + if (doubleClick && active) { parent->worldSelected(item); } @@ -274,7 +274,7 @@ void SelectWorldScreen::WorldSelectionList::renderItem(int i, int x, int y, int wstring name = levelSummary->getLevelName(); if (name.length()==0) { - name = parent->worldLang + L" " + _toString<int>(i + 1); + name = parent->worldLang + L" " + std::to_wstring(i + 1); } wstring id = levelSummary->getLevelId(); @@ -295,7 +295,7 @@ void SelectWorldScreen::WorldSelectionList::renderItem(int i, int x, int y, int id = id + L" (" + buffer; __int64 size = levelSummary->getSizeOnDisk(); - id = id + L", " + _toString<float>(size / 1024 * 100 / 1024 / 100.0f) + L" MB)"; + id = id + L", " + std::to_wstring(static_cast<float>(size / 1024 * 100 / 1024 / 100.0f)) + L" MB)"; wstring info; if (levelSummary->isRequiresConversion()) diff --git a/Minecraft.Client/ServerChunkCache.cpp b/Minecraft.Client/ServerChunkCache.cpp index 619efa98..3af98ca6 100644 --- a/Minecraft.Client/ServerChunkCache.cpp +++ b/Minecraft.Client/ServerChunkCache.cpp @@ -19,7 +19,7 @@ ServerChunkCache::ServerChunkCache(ServerLevel *level, ChunkStorage *storage, Ch XZOFFSET = XZSIZE/2; // 4J Added autoCreate = false; // 4J added - + emptyChunk = new EmptyLevelChunk(level, byteArray( Level::CHUNK_TILE_COUNT ), 0, 0); this->level = level; @@ -54,9 +54,8 @@ ServerChunkCache::~ServerChunkCache() delete m_unloadedCache; #endif - AUTO_VAR(itEnd, m_loadedChunkList.end()); - for (AUTO_VAR(it, m_loadedChunkList.begin()); it != itEnd; it++) - delete *it; + for (auto& it : m_loadedChunkList) + delete it; DeleteCriticalSection(&m_csLoadCreate); } @@ -510,7 +509,7 @@ void ServerChunkCache::flagPostProcessComplete(short flag, int x, int z) lc->compressLighting(); if( !lc->isLowerDataStorageCompressed() ) lc->compressData(); - + PIXEndNamedEvent(); } @@ -542,7 +541,7 @@ void ServerChunkCache::postProcess(ChunkSource *parent, int x, int z ) { LevelChunk *chunk = getChunk(x, z); if ( (chunk->terrainPopulated & LevelChunk::sTerrainPopulatedFromHere) == 0 ) - { + { if (source != NULL) { PIXBeginNamedEvent(0,"Main post processing"); @@ -603,9 +602,9 @@ bool ServerChunkCache::saveAllEntities() PIXBeginNamedEvent(0, "saving to NBT"); EnterCriticalSection(&m_csLoadCreate); - for(AUTO_VAR(it,m_loadedChunkList.begin()); it != m_loadedChunkList.end(); ++it) + for(auto& it : m_loadedChunkList) { - storage->saveEntities(level, *it); + storage->saveEntities(level, it); } LeaveCriticalSection(&m_csLoadCreate); PIXEndNamedEvent(); @@ -625,13 +624,11 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) // 4J - added this to support progressListner int count = 0; - if (progressListener != NULL) + if (progressListener) { - AUTO_VAR(itEnd, m_loadedChunkList.end()); - for (AUTO_VAR(it, m_loadedChunkList.begin()); it != itEnd; it++) + for (LevelChunk *chunk : m_loadedChunkList) { - LevelChunk *chunk = *it; - if (chunk->shouldSave(force)) + if ( chunk && chunk->shouldSave(force)) { count++; } @@ -745,12 +742,12 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) for(unsigned int i = 0; i < 3; ++i) { saveThreads[i] = NULL; - + threadData[i].cache = this; wakeEvent[i] = new C4JThread::Event(); //CreateEvent(NULL,FALSE,FALSE,NULL); threadData[i].wakeEvent = wakeEvent[i]; - + notificationEvent[i] = new C4JThread::Event(); //CreateEvent(NULL,FALSE,FALSE,NULL); threadData[i].notificationEvent = notificationEvent[i]; @@ -783,7 +780,7 @@ bool ServerChunkCache::save(bool force, ProgressListener *progressListener) { if( ( m_loadedChunkList[i]->x < 0 ) && ( m_loadedChunkList[i]->z >= 0 ) ) sortedChunkList.push_back(m_loadedChunkList[i]); } - + for (unsigned int i = 0; i < sortedChunkList.size();) { workingThreads = 0; @@ -951,8 +948,8 @@ bool ServerChunkCache::tick() //loadedChunks.remove(cp); //loadedChunkList.remove(chunk); - AUTO_VAR(it, std::find( m_loadedChunkList.begin(), m_loadedChunkList.end(), chunk) ); - if(it != m_loadedChunkList.end()) m_loadedChunkList.erase(it); + auto it = std::find(m_loadedChunkList.begin(), m_loadedChunkList.end(), chunk); + if(it != m_loadedChunkList.end()) m_loadedChunkList.erase(it); int ix = chunk->x + XZOFFSET; int iz = chunk->z + XZOFFSET; @@ -979,7 +976,7 @@ bool ServerChunkCache::shouldSave() wstring ServerChunkCache::gatherStats() { - return L"ServerChunkCache: ";// + _toString<int>(loadedChunks.size()) + L" Drop: " + _toString<int>(toDrop.size()); + return L"ServerChunkCache: ";// + std::to_wstring(loadedChunks.size()) + L" Drop: " + std::to_wstring(toDrop.size()); } vector<Biome::MobSpawnerData *> *ServerChunkCache::getMobsAt(MobCategory *mobCategory, int x, int y, int z) diff --git a/Minecraft.Client/ServerCommandDispatcher.cpp b/Minecraft.Client/ServerCommandDispatcher.cpp index 51dd42fe..0c98aed5 100644 --- a/Minecraft.Client/ServerCommandDispatcher.cpp +++ b/Minecraft.Client/ServerCommandDispatcher.cpp @@ -56,10 +56,9 @@ void ServerCommandDispatcher::logAdminCommand(shared_ptr<CommandSender> source, { PlayerList *playerList = MinecraftServer::getInstance()->getPlayers(); //for (Player player : MinecraftServer.getInstance().getPlayers().players) - for(AUTO_VAR(it, playerList->players.begin()); it != playerList->players.end(); ++it) - { - shared_ptr<ServerPlayer> player = *it; - if (player != source && playerList->isOp(player)) + for (auto& player : playerList->players ) + { + if ( player && player != source && playerList->isOp(player)) { // TODO: Change chat packet to be able to send more bits of data // 4J Stu - Take this out until we can add the name of the player performing the action. Also if the target is a mod then maybe don't need the message? diff --git a/Minecraft.Client/ServerConnection.cpp b/Minecraft.Client/ServerConnection.cpp index 21d77f22..07616aa4 100644 --- a/Minecraft.Client/ServerConnection.cpp +++ b/Minecraft.Client/ServerConnection.cpp @@ -1,6 +1,8 @@ #include "stdafx.h" #include "Options.h" #include "ServerConnection.h" + +#include <memory> #include "PendingConnection.h" #include "PlayerConnection.h" #include "ServerPlayer.h" @@ -26,8 +28,8 @@ ServerConnection::~ServerConnection() // 4J - added to handle incoming connections, to replace thread that original used to have void ServerConnection::NewIncomingSocket(Socket *socket) { - shared_ptr<PendingConnection> unconnectedClient = shared_ptr<PendingConnection>(new PendingConnection(server, socket, L"Connection #" + _toString<int>(connectionCounter++))); - handleConnection(unconnectedClient); + shared_ptr<PendingConnection> unconnectedClient = std::make_shared<PendingConnection>(server, socket, L"Connection #" + std::to_wstring(connectionCounter++)); + handleConnection(unconnectedClient); } void ServerConnection::addPlayerConnection(shared_ptr<PlayerConnection> uc) @@ -112,8 +114,8 @@ void ServerConnection::tick() bool ServerConnection::addPendingTextureRequest(const wstring &textureName) { - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it == m_pendingTextureRequests.end() ) + auto it = find(m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName); + if( it == m_pendingTextureRequests.end() ) { m_pendingTextureRequests.push_back(textureName); return true; @@ -127,14 +129,13 @@ bool ServerConnection::addPendingTextureRequest(const wstring &textureName) void ServerConnection::handleTextureReceived(const wstring &textureName) { - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it != m_pendingTextureRequests.end() ) + auto it = find(m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName); + if( it != m_pendingTextureRequests.end() ) { m_pendingTextureRequests.erase(it); } - for (unsigned int i = 0; i < players.size(); i++) + for (auto& player : players) { - shared_ptr<PlayerConnection> player = players[i]; if (!player->done) { player->handleTextureReceived(textureName); @@ -144,14 +145,13 @@ void ServerConnection::handleTextureReceived(const wstring &textureName) void ServerConnection::handleTextureAndGeometryReceived(const wstring &textureName) { - AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); - if( it != m_pendingTextureRequests.end() ) + auto it = find(m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName); + if( it != m_pendingTextureRequests.end() ) { m_pendingTextureRequests.erase(it); } - for (unsigned int i = 0; i < players.size(); i++) + for (auto& player : players) { - shared_ptr<PlayerConnection> player = players[i]; if (!player->done) { player->handleTextureAndGeometryReceived(textureName); @@ -172,7 +172,7 @@ void ServerConnection::handleServerSettingsChanged(shared_ptr<ServerSettingsChan app.DebugPrintf("ClientConnection::handleServerSettingsChanged - Difficulty = %d",packet->data); pMinecraft->levels[i]->difficulty = packet->data; } - } + } } // else if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS)// options // { @@ -190,11 +190,11 @@ void ServerConnection::handleServerSettingsChanged(shared_ptr<ServerSettingsChan // { // pMinecraft->options->SetGamertagSetting(false); // } -// +// // for (unsigned int i = 0; i < players.size(); i++) // { // shared_ptr<PlayerConnection> playerconnection = players[i]; -// playerconnection->setShowOnMaps(pMinecraft->options->GetGamertagSetting()); +// playerconnection->setShowOnMaps(pMinecraft->options->GetGamertagSetting()); // } // } } diff --git a/Minecraft.Client/ServerLevel.cpp b/Minecraft.Client/ServerLevel.cpp index 8501cbf9..1e00b591 100644 --- a/Minecraft.Client/ServerLevel.cpp +++ b/Minecraft.Client/ServerLevel.cpp @@ -1,5 +1,7 @@ #include "stdafx.h" #include "ServerLevel.h" + +#include <memory> #include "MinecraftServer.h" #include "ServerChunkCache.h" #include "PlayerList.h" @@ -96,8 +98,8 @@ void ServerLevel::staticCtor() ServerLevel::ServerLevel(MinecraftServer *server, shared_ptr<LevelStorage>levelStorage, const wstring& levelName, int dimension, LevelSettings *levelSettings) : Level(levelStorage, levelName, levelSettings, Dimension::getNew(dimension), false) { - InitializeCriticalSection(&m_limiterCS); - InitializeCriticalSection(&m_tickNextTickCS); + InitializeCriticalSection(&m_limiterCS); + InitializeCriticalSection(&m_tickNextTickCS); InitializeCriticalSection(&m_csQueueSendTileUpdates); m_fallingTileCount = 0; m_primedTntCount = 0; @@ -165,9 +167,8 @@ ServerLevel::~ServerLevel() delete mobSpawner; EnterCriticalSection(&m_csQueueSendTileUpdates); - for(AUTO_VAR(it, m_queuedSendTileUpdates.begin()); it != m_queuedSendTileUpdates.end(); ++it) + for(Pos* p : m_queuedSendTileUpdates) { - Pos *p = *it; delete p; } m_queuedSendTileUpdates.clear(); @@ -238,10 +239,9 @@ void ServerLevel::tick() skyDarken = newDark; if (!SharedConstants::TEXTURE_LIGHTING) // 4J - change brought forward from 1.8.2 { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->skyColorChanged(); + listener->skyColorChanged(); } } } @@ -268,7 +268,7 @@ void ServerLevel::tick() if (getGameRules()->getBoolean(GameRules::RULE_DAYLIGHT)) { // 4J: Debug setting added to keep it at day time -#ifndef _FINAL_BUILD +#ifndef _FINAL_BUILD bool freezeTime = app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<<eDebugSetting_FreezeTime); if (!freezeTime) #endif @@ -323,10 +323,9 @@ void ServerLevel::updateSleepingPlayerList() allPlayersSleeping = !players.empty(); m_bAtLeastOnePlayerSleeping = false; - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& player : players) { - if (!(*it)->isSleeping()) + if (!player->isSleeping()) { allPlayersSleeping = false; //break; @@ -344,12 +343,11 @@ void ServerLevel::awakenAllPlayers() allPlayersSleeping = false; m_bAtLeastOnePlayerSleeping = false; - AUTO_VAR(itEnd, players.end()); - for (vector<shared_ptr<Player> >::iterator it = players.begin(); it != itEnd; it++) + for (auto& player : players) { - if ((*it)->isSleeping()) + if (player->isSleeping()) { - (*it)->stopSleepInBed(false, false, true); + player->stopSleepInBed(false, false, true); } } @@ -369,11 +367,10 @@ bool ServerLevel::allPlayersAreSleeping() if (allPlayersSleeping && !isClientSide) { // all players are sleeping, but have they slept long enough? - AUTO_VAR(itEnd, players.end()); - for (vector<shared_ptr<Player> >::iterator it = players.begin(); it != itEnd; it++ ) + for (auto& player : players) { // System.out.println(player->entityId + ": " + player->getSleepTimer()); - if (! (*it)->isSleepingLongEnough()) + if (!player->isSleepingLongEnough()) { return false; } @@ -462,10 +459,8 @@ void ServerLevel::tickTiles() { ChunkPos cp = chunksToPoll.get(i); #else - AUTO_VAR(itEndCtp, chunksToPoll.end()); - for (AUTO_VAR(it, chunksToPoll.begin()); it != itEndCtp; it++) + for (ChunkPos cp : chunksToPoll) { - ChunkPos cp = *it; #endif int xo = cp.x * 16; int zo = cp.z * 16; @@ -526,7 +521,7 @@ void ServerLevel::tickTiles() { Biome *b = getBiome(x + xo, z + zo); if (b->hasRain()) - { + { int tile = getTile(x + xo, yy - 1, z + zo); if (tile != 0) { @@ -654,8 +649,8 @@ bool ServerLevel::tickPendingTicks(bool force) } if (count > MAX_TICK_TILES_PER_TICK) count = MAX_TICK_TILES_PER_TICK; - AUTO_VAR(itTickList, tickNextTickList.begin()); - for (int i = 0; i < count; i++) + auto itTickList = tickNextTickList.begin(); + for (int i = 0; i < count; i++) { TickNextTickData td = *(itTickList); if (!force && td.m_delay > levelData->getGameTime()) @@ -668,8 +663,8 @@ bool ServerLevel::tickPendingTicks(bool force) toBeTicked.push_back(td); } - for(AUTO_VAR(it,toBeTicked.begin()); it != toBeTicked.end();) - { + for (auto it = toBeTicked.begin(); it != toBeTicked.end();) + { TickNextTickData td = *it; it = toBeTicked.erase(it); @@ -715,8 +710,8 @@ vector<TickNextTickData> *ServerLevel::fetchTicksInChunk(LevelChunk *chunk, bool { if (i == 0) { - for( AUTO_VAR(it, tickNextTickList.begin()); it != tickNextTickList.end(); ) - { + for (auto it = tickNextTickList.begin(); it != tickNextTickList.end();) + { TickNextTickData td = *it; if (td.x >= xMin && td.x < xMax && td.z >= zMin && td.z < zMax) @@ -745,8 +740,8 @@ vector<TickNextTickData> *ServerLevel::fetchTicksInChunk(LevelChunk *chunk, bool { app.DebugPrintf("To be ticked size: %d\n",toBeTicked.size()); } - for( AUTO_VAR(it, toBeTicked.begin()); it != toBeTicked.end();) - { + for (auto it = toBeTicked.begin(); it != toBeTicked.end();) + { TickNextTickData td = *it; if (td.x >= xMin && td.x < xMax && td.z >= zMin && td.z < zMax) @@ -965,7 +960,7 @@ void ServerLevel::save(bool force, ProgressListener *progressListener, bool bAut if(StorageManager.GetSaveDisabled()) return; - if (progressListener != NULL) + if (progressListener != NULL) { if(bAutosave) { @@ -1001,10 +996,9 @@ void ServerLevel::save(bool force, ProgressListener *progressListener, bool bAut // 4J Stu - This will come in a later change anyway // clean cache vector<LevelChunk *> *loadedChunkList = cache->getLoadedChunkList(); - for (AUTO_VAR(it, loadedChunkList->begin()); it != loadedChunkList->end(); ++it) + for ( LevelChunk *lc : *loadedChunkList ) { - LevelChunk *lc = *it; - if (!chunkMap->hasChunk(lc->x, lc->z) ) + if ( lc && !chunkMap->hasChunk(lc->x, lc->z) ) { cache->drop(lc->x, lc->z); } @@ -1035,7 +1029,7 @@ void ServerLevel::saveToDisc(ProgressListener *progressListener, bool autosave) DLCPack * pDLCPack=pDLCTexPack->getDLCInfoParentPack(); if(!pDLCPack->hasPurchasedFile( DLCManager::e_DLCType_Texture, L"" )) - { + { return; } } @@ -1057,12 +1051,11 @@ void ServerLevel::entityAdded(shared_ptr<Entity> e) Level::entityAdded(e); entitiesById[e->entityId] = e; vector<shared_ptr<Entity> > *es = e->getSubEntities(); - if (es != NULL) + if (es) { - //for (int i = 0; i < es.length; i++) - for(AUTO_VAR(it, es->begin()); it != es->end(); ++it) + for(auto& i : *es) { - entitiesById.insert( intEntityMap::value_type( (*it)->entityId, (*it) )); + entitiesById.emplace(i->entityId, i); } } entityAddedExtra(e); // 4J added @@ -1073,12 +1066,11 @@ void ServerLevel::entityRemoved(shared_ptr<Entity> e) Level::entityRemoved(e); entitiesById.erase(e->entityId); vector<shared_ptr<Entity> > *es = e->getSubEntities(); - if (es != NULL) + if (es) { - //for (int i = 0; i < es.length; i++) - for(AUTO_VAR(it, es->begin()); it != es->end(); ++it) + for(auto& i : *es) { - entitiesById.erase((*it)->entityId); + entitiesById.erase(i->entityId); } } entityRemovedExtra(e); // 4J added @@ -1121,9 +1113,9 @@ shared_ptr<Explosion> ServerLevel::explode(shared_ptr<Entity> source, double x, } vector<shared_ptr<ServerPlayer> > sentTo; - for(AUTO_VAR(it, players.begin()); it != players.end(); ++it) + for(auto& it : players) { - shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(*it); + shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(it); if (player->dimension != dimension->id) continue; bool knockbackOnly = false; @@ -1136,9 +1128,8 @@ shared_ptr<Explosion> ServerLevel::explode(shared_ptr<Entity> source, double x, } else { - for(unsigned int j = 0; j < sentTo.size(); j++ ) + for(auto& player2 : sentTo) { - shared_ptr<ServerPlayer> player2 = sentTo[j]; INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) { @@ -1167,9 +1158,9 @@ void ServerLevel::tileEvent(int x, int y, int z, int tile, int b0, int b1) // server.getPlayers().broadcast(x, y, z, 64, dimension.id, new TileEventPacket(x, y, z, b0, b1)); TileEventData newEvent(x, y, z, tile, b0, b1); //for (TileEventData te : tileEvents[activeTileEventsList]) - for(AUTO_VAR(it, tileEvents[activeTileEventsList].begin()); it != tileEvents[activeTileEventsList].end(); ++it) + for(auto& it : tileEvents[activeTileEventsList]) { - if ((*it).equals(newEvent)) + if (it.equals(newEvent)) { return; } @@ -1186,12 +1177,11 @@ void ServerLevel::runTileEvents() int runList = activeTileEventsList; activeTileEventsList ^= 1; - //for (TileEventData te : tileEvents[runList]) - for(AUTO_VAR(it, tileEvents[runList].begin()); it != tileEvents[runList].end(); ++it) + for(auto& it : tileEvents[runList]) { - if (doTileEvent(&(*it))) + if (doTileEvent(&it)) { - TileEventData te = *it; + TileEventData te = it; server->getPlayers()->broadcast(te.getX(), te.getY(), te.getZ(), 64, dimension->id, shared_ptr<TileEventPacket>( new TileEventPacket(te.getX(), te.getY(), te.getZ(), te.getTile(), te.getParamA(), te.getParamB()))); } } @@ -1248,15 +1238,15 @@ void ServerLevel::setTimeAndAdjustTileTicks(__int64 newTime) // 4J - can't directly adjust m_delay in a set as it has a const interator, since changing values in here might change the ordering of the elements in the set. // Instead move to a vector, do the adjustment, put back in the set. vector<TickNextTickData> temp; - for(AUTO_VAR(it, tickNextTickList.begin()); it != tickNextTickList.end(); ++it) + for(const auto& it : tickNextTickList) { - temp.push_back(*it); + temp.push_back(it); temp.back().m_delay += delta; } tickNextTickList.clear(); - for(unsigned int i = 0; i < temp.size(); i++ ) + for(const auto& it : temp) { - tickNextTickList.insert(temp[i]); + tickNextTickList.insert(it); } setGameTime(newTime); } @@ -1278,12 +1268,11 @@ void ServerLevel::sendParticles(const wstring &name, double x, double y, double void ServerLevel::sendParticles(const wstring &name, double x, double y, double z, int count, double xDist, double yDist, double zDist, double speed) { - shared_ptr<Packet> packet = shared_ptr<LevelParticlesPacket>( new LevelParticlesPacket(name, (float) x, (float) y, (float) z, (float) xDist, (float) yDist, (float) zDist, (float) speed, count) ); + shared_ptr<Packet> packet = std::make_shared<LevelParticlesPacket>( name, (float) x, (float) y, (float) z, (float) xDist, (float) yDist, (float) zDist, (float) speed, count ); - - for(AUTO_VAR(it, players.begin()); it != players.end(); ++it) + for(auto& it : players) { - shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(*it); + shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(it); player->connection->send(packet); } } @@ -1299,9 +1288,8 @@ void ServerLevel::queueSendTileUpdate(int x, int y, int z) void ServerLevel::runQueuedSendTileUpdates() { EnterCriticalSection(&m_csQueueSendTileUpdates); - for(AUTO_VAR(it, m_queuedSendTileUpdates.begin()); it != m_queuedSendTileUpdates.end(); ++it) + for(Pos* p : m_queuedSendTileUpdates) { - Pos *p = *it; sendTileUpdated(p->x, p->y, p->z); delete p; } @@ -1455,54 +1443,54 @@ void ServerLevel::entityRemovedExtra(shared_ptr<Entity> e) { EnterCriticalSection(&m_limiterCS); // printf("entity removed: item entity count %d\n",m_itemEntities.size()); - AUTO_VAR(it, find(m_itemEntities.begin(),m_itemEntities.end(),e)); - if( it != m_itemEntities.end() ) + auto it = find(m_itemEntities.begin(), m_itemEntities.end(), e); + if( it != m_itemEntities.end() ) { // printf("Item to remove found\n"); m_itemEntities.erase(it); } // printf("entity removed: item entity count now %d\n",m_itemEntities.size()); LeaveCriticalSection(&m_limiterCS); - } + } else if( e->instanceof(eTYPE_HANGING_ENTITY) ) { EnterCriticalSection(&m_limiterCS); // printf("entity removed: item entity count %d\n",m_itemEntities.size()); - AUTO_VAR(it, find(m_hangingEntities.begin(),m_hangingEntities.end(),e)); - if( it != m_hangingEntities.end() ) + auto it = find(m_hangingEntities.begin(), m_hangingEntities.end(), e); + if( it != m_hangingEntities.end() ) { // printf("Item to remove found\n"); m_hangingEntities.erase(it); } // printf("entity removed: item entity count now %d\n",m_itemEntities.size()); LeaveCriticalSection(&m_limiterCS); - } + } else if( e->instanceof(eTYPE_ARROW) ) { EnterCriticalSection(&m_limiterCS); // printf("entity removed: arrow entity count %d\n",m_arrowEntities.size()); - AUTO_VAR(it, find(m_arrowEntities.begin(),m_arrowEntities.end(),e)); - if( it != m_arrowEntities.end() ) + auto it = find(m_arrowEntities.begin(), m_arrowEntities.end(), e); + if( it != m_arrowEntities.end() ) { // printf("Item to remove found\n"); m_arrowEntities.erase(it); } // printf("entity removed: arrow entity count now %d\n",m_arrowEntities.size()); LeaveCriticalSection(&m_limiterCS); - } + } else if( e->instanceof(eTYPE_EXPERIENCEORB) ) { EnterCriticalSection(&m_limiterCS); // printf("entity removed: experience orb entity count %d\n",m_arrowEntities.size()); - AUTO_VAR(it, find(m_experienceOrbEntities.begin(),m_experienceOrbEntities.end(),e)); - if( it != m_experienceOrbEntities.end() ) + auto it = find(m_experienceOrbEntities.begin(), m_experienceOrbEntities.end(), e); + if( it != m_experienceOrbEntities.end() ) { // printf("Item to remove found\n"); m_experienceOrbEntities.erase(it); } // printf("entity removed: experience orb entity count now %d\n",m_arrowEntities.size()); LeaveCriticalSection(&m_limiterCS); - } + } else if( e->instanceof(eTYPE_PRIMEDTNT) ) { EnterCriticalSection(&m_limiterCS); diff --git a/Minecraft.Client/ServerLevelListener.cpp b/Minecraft.Client/ServerLevelListener.cpp index b95f6fa7..c191b1a9 100644 --- a/Minecraft.Client/ServerLevelListener.cpp +++ b/Minecraft.Client/ServerLevelListener.cpp @@ -1,5 +1,6 @@ #include "stdafx.h" #include "ServerLevelListener.h" + #include "EntityTracker.h" #include "MinecraftServer.h" #include "ServerLevel.h" @@ -18,7 +19,7 @@ ServerLevelListener::ServerLevelListener(MinecraftServer *server, ServerLevel *l this->level = level; } -// 4J removed - +// 4J removed - /* void ServerLevelListener::addParticle(const wstring& name, double x, double y, double z, double xa, double ya, double za) { @@ -48,8 +49,7 @@ void ServerLevelListener::entityRemoved(shared_ptr<Entity> entity) // 4J added void ServerLevelListener::playerRemoved(shared_ptr<Entity> entity) { - shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(entity); - player->getLevel()->getTracker()->removePlayer(entity); + dynamic_pointer_cast<ServerPlayer>(entity)->getLevel()->getTracker()->removePlayer(entity); } void ServerLevelListener::playSound(int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist) @@ -59,10 +59,10 @@ void ServerLevelListener::playSound(int iSound, double x, double y, double z, fl app.DebugPrintf("ServerLevelListener received request for sound less than 0, so ignoring\n"); } else - { + { // 4J-PB - I don't want to broadcast player sounds to my local machine, since we're already playing these in the LevelRenderer::playSound. // The PC version does seem to do this and the result is I can stop walking , and then I'll hear my footstep sound with a delay - server->getPlayers()->broadcast(x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, shared_ptr<LevelSoundPacket>(new LevelSoundPacket(iSound, x, y, z, volume, pitch))); + server->getPlayers()->broadcast(x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, std::make_shared<LevelSoundPacket>(iSound, x, y, z, volume, pitch)); } } @@ -73,10 +73,10 @@ void ServerLevelListener::playSoundExceptPlayer(shared_ptr<Player> player, int i app.DebugPrintf("ServerLevelListener received request for sound less than 0, so ignoring\n"); } else - { + { // 4J-PB - I don't want to broadcast player sounds to my local machine, since we're already playing these in the LevelRenderer::playSound. // The PC version does seem to do this and the result is I can stop walking , and then I'll hear my footstep sound with a delay - server->getPlayers()->broadcast(player,x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, shared_ptr<LevelSoundPacket>(new LevelSoundPacket(iSound, x, y, z, volume, pitch))); + server->getPlayers()->broadcast(player,x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, std::make_shared<LevelSoundPacket>(iSound, x, y, z, volume, pitch)); } } @@ -103,28 +103,27 @@ void ServerLevelListener::playStreamingMusic(const wstring& name, int x, int y, void ServerLevelListener::levelEvent(shared_ptr<Player> source, int type, int x, int y, int z, int data) { - server->getPlayers()->broadcast(source, x, y, z, 64, level->dimension->id, shared_ptr<LevelEventPacket>( new LevelEventPacket(type, x, y, z, data, false) ) ); + server->getPlayers()->broadcast(source, x, y, z, 64, level->dimension->id, std::make_shared<LevelEventPacket>( type, x, y, z, data, false ) ); } void ServerLevelListener::globalLevelEvent(int type, int sourceX, int sourceY, int sourceZ, int data) { - server->getPlayers()->broadcastAll( shared_ptr<LevelEventPacket>( new LevelEventPacket(type, sourceX, sourceY, sourceZ, data, true)) ); + server->getPlayers()->broadcastAll( std::make_shared<LevelEventPacket>( type, sourceX, sourceY, sourceZ, data, true) ); } void ServerLevelListener::destroyTileProgress(int id, int x, int y, int z, int progress) { //for (ServerPlayer p : server->getPlayers()->players) - for(AUTO_VAR(it, server->getPlayers()->players.begin()); it != server->getPlayers()->players.end(); ++it) + for(auto& p : server->getPlayers()->players) { - shared_ptr<ServerPlayer> p = *it; - if (p == NULL || p->level != level || p->entityId == id) continue; + if (p == nullptr || p->level != level || p->entityId == id) continue; double xd = (double) x - p->x; double yd = (double) y - p->y; double zd = (double) z - p->z; if (xd * xd + yd * yd + zd * zd < 32 * 32) { - p->connection->send(shared_ptr<TileDestructionPacket>(new TileDestructionPacket(id, x, y, z, progress))); + p->connection->send(std::make_shared<TileDestructionPacket>(id, x, y, z, progress)); } } }
\ No newline at end of file diff --git a/Minecraft.Client/ServerPlayer.cpp b/Minecraft.Client/ServerPlayer.cpp index 10fde77b..76332358 100644 --- a/Minecraft.Client/ServerPlayer.cpp +++ b/Minecraft.Client/ServerPlayer.cpp @@ -149,17 +149,15 @@ void ServerPlayer::flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFou memset(flags, 0, 2048/32); } - AUTO_VAR(it, entitiesToRemove.begin() ); - for( AUTO_VAR(it, entitiesToRemove.begin()); it != entitiesToRemove.end(); it++ ) + for(int index : entitiesToRemove) { - int index = *it; if( index < 2048 ) { unsigned int i = index / 32; unsigned int j = index % 32; unsigned int uiMask = 0x80000000 >> j; - flags[i] |= uiMask; + flags[i] |= uiMask; } } } @@ -275,8 +273,8 @@ void ServerPlayer::flushEntitiesToRemove() intArray ids(amount); int pos = 0; - AUTO_VAR(it, entitiesToRemove.begin() ); - while (it != entitiesToRemove.end() && pos < amount) + auto it = entitiesToRemove.begin(); + while (it != entitiesToRemove.end() && pos < amount) { ids[pos++] = *it; it = entitiesToRemove.erase(it); @@ -340,9 +338,8 @@ void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) // the player can quickly wander away from the centre of the spiral of chunks that that method creates, long before transmission // of them is complete. double dist = DBL_MAX; - for( AUTO_VAR(it, chunksToSend.begin()); it != chunksToSend.end(); it++ ) + for(ChunkPos chunk : chunksToSend) { - ChunkPos chunk = *it; if( level->isChunkFinalised(chunk.x, chunk.z) ) { double newDist = chunk.distanceToSqr(x, z); @@ -378,8 +375,8 @@ void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) // g_NetworkManager.GetHostPlayer()->GetSendQueueSizeMessages( NULL, true ), // connection->done); // } - - if( dontDelayChunks || + + if( dontDelayChunks || (canSendToPlayer && #ifdef _XBOX_ONE // The network manager on xbox one doesn't currently split data into slow & fast queues - since we can only measure @@ -390,7 +387,7 @@ void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) #else (connection->countDelayedPackets() < 4 )&& (g_NetworkManager.GetHostPlayer()->GetSendQueueSizeMessages( NULL, true ) < 4 )&& -#endif +#endif //(tickCount - lastBrupSendTickCount) > (connection->getNetworkPlayer()->GetCurrentRtt()>>4) && !connection->done) ) { @@ -477,7 +474,7 @@ void ServerPlayer::doChunkSendingTick(bool dontDelayChunks) for (unsigned int i = 0; i < tes->size(); i++) { // 4J Stu - Added delay param to ensure that these arrive after the BRUPs from above - // Fix for #9169 - ART : Sign text is replaced with the words “Awaiting approval”. + // Fix for #9169 - ART : Sign text is replaced with the words �Awaiting approval�. broadcast(tes->at(i), !connection->isLocal() && !dontDelayChunks); } delete tes; @@ -504,7 +501,7 @@ void ServerPlayer::doTickB() // else if (app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<<eDebugSetting_GoToEnd)) // { // if(level->dimension->id == 0 ) - // { + // { // server->players->toggleDimension( dynamic_pointer_cast<ServerPlayer>( shared_from_this() ), 1 ); // } // unsigned int uiVal=app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()); @@ -542,9 +539,8 @@ void ServerPlayer::doTickB() vector< shared_ptr<Player> > players = vector< shared_ptr<Player> >(); players.push_back(dynamic_pointer_cast<Player>(shared_from_this())); - for (AUTO_VAR(it,objectives->begin()); it != objectives->end(); ++it) + for (Objective *objective : *objectives) { - Objective *objective = *it; getScoreboard()->getPlayerScore(getAName(), objective)->updateFor(&players); } delete objectives; @@ -624,7 +620,7 @@ bool ServerPlayer::hurt(DamageSource *dmgSource, float dmg) bool returnVal = Player::hurt(dmgSource, dmg); if( returnVal ) - { + { // 4J Stu - Work out the source of this damage for telemetry m_lastDamageSource = eTelemetryChallenges_Unknown; @@ -696,7 +692,7 @@ bool ServerPlayer::hurt(DamageSource *dmgSource, float dmg) m_lastDamageSource = eTelemetryPlayerDeathSource_Ghast; break; }; - } + } }; } @@ -748,15 +744,14 @@ void ServerPlayer::changeDimension(int i) connection->send( shared_ptr<GameEventPacket>( new GameEventPacket(GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex()) ) ); app.DebugPrintf("Sending packet to %d\n", thisPlayer->GetUserIndex()); } - if(thisPlayer != NULL) + if(thisPlayer) { - for(AUTO_VAR(it, MinecraftServer::getInstance()->getPlayers()->players.begin()); it != MinecraftServer::getInstance()->getPlayers()->players.end(); ++it) + for(auto& servPlayer : MinecraftServer::getInstance()->getPlayers()->players) { - shared_ptr<ServerPlayer> servPlayer = *it; INetworkPlayer *checkPlayer = servPlayer->connection->getNetworkPlayer(); if(thisPlayer != checkPlayer && checkPlayer != NULL && thisPlayer->IsSameSystem( checkPlayer ) && !servPlayer->wonGame ) { - servPlayer->wonGame = true; + servPlayer->wonGame = true; servPlayer->connection->send( shared_ptr<GameEventPacket>( new GameEventPacket(GameEventPacket::WIN_GAME, thisPlayer->GetUserIndex() ) ) ); app.DebugPrintf("Sending packet to %d\n", thisPlayer->GetUserIndex()); } @@ -899,7 +894,7 @@ bool ServerPlayer::openFireworks(int x, int y, int z) containerMenu->addSlotListener(this); } else if(dynamic_cast<CraftingMenu *>(containerMenu) != NULL) - { + { closeContainer(); nextContainerCounter(); @@ -929,7 +924,7 @@ bool ServerPlayer::startEnchanting(int x, int y, int z, const wstring &name) else { app.DebugPrintf("ServerPlayer tried to open enchanting container when one was already open\n"); - } + } return true; } @@ -947,7 +942,7 @@ bool ServerPlayer::startRepairing(int x, int y, int z) else { app.DebugPrintf("ServerPlayer tried to open enchanting container when one was already open\n"); - } + } return true; } @@ -1384,7 +1379,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr<ServerPlayer> player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxEnemies))); + player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxEnemies))); } } break; @@ -1395,7 +1390,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr<ServerPlayer> player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxVillagers))); + player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxVillagers))); } } break; @@ -1405,7 +1400,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr<ServerPlayer> player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredPigsSheepCows))); + player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredPigsSheepCows))); } } break; @@ -1415,7 +1410,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr<ServerPlayer> player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredChickens))); + player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredChickens))); } } break; @@ -1425,7 +1420,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr<ServerPlayer> player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredMooshrooms))); + player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredMooshrooms))); } } break; @@ -1436,7 +1431,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr<ServerPlayer> player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredWolves))); + player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBredWolves))); } } break; @@ -1447,7 +1442,7 @@ void ServerPlayer::displayClientMessage(int messageId) shared_ptr<ServerPlayer> player = server->getPlayers()->players[i]; if(shared_from_this()==player) { - player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerCantShearMooshroom))); + player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerCantShearMooshroom))); } } break; @@ -1471,7 +1466,7 @@ void ServerPlayer::displayClientMessage(int messageId) { player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerCantSpawnInPeaceful))); } - } + } break; case IDS_MAX_BOATS: @@ -1482,7 +1477,7 @@ void ServerPlayer::displayClientMessage(int messageId) { player->connection->send(shared_ptr<ChatPacket>( new ChatPacket(name, ChatPacket::e_ChatPlayerMaxBoats))); } - } + } break; default: @@ -1541,7 +1536,7 @@ void ServerPlayer::onEffectRemoved(MobEffectInstance *effect) connection->send(shared_ptr<RemoveMobEffectPacket>( new RemoveMobEffectPacket(entityId, effect) ) ); } -void ServerPlayer::teleportTo(double x, double y, double z) +void ServerPlayer::teleportTo(double x, double y, double z) { connection->teleport(x, y, z, yRot, xRot); } @@ -1675,7 +1670,7 @@ void ServerPlayer::handleCollectItem(shared_ptr<ItemInstance> item) } #ifndef _CONTENT_PACKAGE -void ServerPlayer::debug_setPosition(double x, double y, double z, double nYRot, double nXRot) +void ServerPlayer::debug_setPosition(double x, double y, double z, double nYRot, double nXRot) { connection->teleport(x, y, z, nYRot, nXRot); } diff --git a/Minecraft.Client/Settings.cpp b/Minecraft.Client/Settings.cpp index 4223b001..658d641d 100644 --- a/Minecraft.Client/Settings.cpp +++ b/Minecraft.Client/Settings.cpp @@ -101,7 +101,7 @@ int Settings::getInt(const wstring& key, int defaultValue) { if(properties.find(key) == properties.end()) { - properties[key] = _toString<int>(defaultValue); + properties[key] = std::to_wstring(defaultValue); saveProperties(); } return _fromString<int>(properties[key]); diff --git a/Minecraft.Client/StitchSlot.cpp b/Minecraft.Client/StitchSlot.cpp index 5e9700b0..cdce6128 100644 --- a/Minecraft.Client/StitchSlot.cpp +++ b/Minecraft.Client/StitchSlot.cpp @@ -120,9 +120,8 @@ bool StitchSlot::add(TextureHolder *textureHolder) } //for (final StitchSlot subSlot : subSlots) - for(AUTO_VAR(it, subSlots->begin()); it != subSlots->end(); ++it) + for ( StitchSlot *subSlot : *subSlots ) { - StitchSlot *subSlot = *it; if (subSlot->add(textureHolder)) { return true; @@ -134,23 +133,15 @@ bool StitchSlot::add(TextureHolder *textureHolder) void StitchSlot::collectAssignments(vector<StitchSlot *> *result) { - if (textureHolder != NULL) + if (textureHolder) { result->push_back(this); } - else if (subSlots != NULL) + else if (subSlots) { - //for (StitchSlot subSlot : subSlots) - for(AUTO_VAR(it, subSlots->begin()); it != subSlots->end(); ++it) + for(StitchSlot *subSlot : *subSlots) { - StitchSlot *subSlot = *it; subSlot->collectAssignments(result); } } -} - -//@Override -wstring StitchSlot::toString() -{ - return L"Slot{originX=" + _toString(originX) + L", originY=" + _toString(originY) + L", width=" + _toString(width) + L", height=" + _toString(height) + L", texture=" + _toString(textureHolder) + L", subSlots=" + _toString(subSlots) + L'}'; }
\ No newline at end of file diff --git a/Minecraft.Client/StitchSlot.h b/Minecraft.Client/StitchSlot.h index 0990a06e..e01d7441 100644 --- a/Minecraft.Client/StitchSlot.h +++ b/Minecraft.Client/StitchSlot.h @@ -22,7 +22,4 @@ public: int getY(); bool add(TextureHolder *textureHolder); void collectAssignments(vector<StitchSlot *> *result); - - //@Override - wstring toString(); };
\ No newline at end of file diff --git a/Minecraft.Client/StitchedTexture.cpp b/Minecraft.Client/StitchedTexture.cpp index c17f3db5..64ab2f36 100644 --- a/Minecraft.Client/StitchedTexture.cpp +++ b/Minecraft.Client/StitchedTexture.cpp @@ -48,12 +48,15 @@ StitchedTexture::StitchedTexture(const wstring &name, const wstring &filename) : void StitchedTexture::freeFrameTextures() { - if( frames ) + if ( frames ) { - for(AUTO_VAR(it, frames->begin()); it != frames->end(); ++it) + for (auto& frame : *frames) { - TextureManager::getInstance()->unregisterTexture(L"", *it); - delete *it; + if ( frame ) + { + TextureManager::getInstance()->unregisterTexture(L"", frame); + delete frame; + } } delete frames; } @@ -61,9 +64,10 @@ void StitchedTexture::freeFrameTextures() StitchedTexture::~StitchedTexture() { - for(AUTO_VAR(it, frames->begin()); it != frames->end(); ++it) + for(auto& frame : *frames) { - delete *it; + if ( frame ) + delete frame; } delete frames; } @@ -241,7 +245,7 @@ int StitchedTexture::getFrames() * 4*10,3,2,1, * 0 * </code> or similar -* +* * @param bufferedReader */ void StitchedTexture::loadAnimationFrames(BufferedReader *bufferedReader) @@ -265,20 +269,19 @@ void StitchedTexture::loadAnimationFrames(BufferedReader *bufferedReader) { std::vector<std::wstring> tokens = stringSplit(line, L','); //for (String token : tokens) - for(AUTO_VAR(it, tokens.begin()); it != tokens.end(); ++it) + for( const auto& token : tokens) { - wstring token = *it; int multiPos = token.find_first_of('*'); if (multiPos > 0) { int frame = _fromString<int>(token.substr(0, multiPos)); int count = _fromString<int>(token.substr(multiPos + 1)); - results->push_back( intPairVector::value_type(frame, count)); + results->emplace_back(frame, count); } else { int tokenVal = _fromString<int>(token); - results->push_back( intPairVector::value_type(tokenVal, 1)); + results->emplace_back(tokenVal, 1); } } } @@ -311,21 +314,22 @@ void StitchedTexture::loadAnimationFrames(const wstring &string) intPairVector *results = new intPairVector(); std::vector<std::wstring> tokens = stringSplit(trimString(string), L','); - //for (String token : tokens) - for(AUTO_VAR(it, tokens.begin()); it != tokens.end(); ++it) + + wstring token; + for(auto& it : tokens) { - wstring token = trimString(*it); + token = trimString(it); int multiPos = token.find_first_of('*'); if (multiPos > 0) { int frame = _fromString<int>(token.substr(0, multiPos)); int count = _fromString<int>(token.substr(multiPos + 1)); - results->push_back( intPairVector::value_type(frame, count)); + results->emplace_back(frame, count); } else if(!token.empty()) { int tokenVal = _fromString<int>(token); - results->push_back( intPairVector::value_type(tokenVal, 1)); + results->emplace_back(tokenVal, 1); } } diff --git a/Minecraft.Client/Stitcher.cpp b/Minecraft.Client/Stitcher.cpp index 5888d4f8..d52954c4 100644 --- a/Minecraft.Client/Stitcher.cpp +++ b/Minecraft.Client/Stitcher.cpp @@ -81,10 +81,8 @@ void Stitcher::stitch() stitchedTexture = NULL; //for (int i = 0; i < textureHolders.length; i++) - for(AUTO_VAR(it, texturesToBeStitched.begin()); it != texturesToBeStitched.end(); ++it) + for( TextureHolder *textureHolder : texturesToBeStitched ) { - TextureHolder *textureHolder = *it; //textureHolders[i]; - if (!addToStorage(textureHolder)) { app.DebugPrintf("Stitcher exception!\n"); @@ -101,10 +99,10 @@ vector<StitchSlot *> *Stitcher::gatherAreas() vector<StitchSlot *> *result = new vector<StitchSlot *>(); //for (StitchSlot slot : storage) - for(AUTO_VAR(it, storage.begin()); it != storage.end(); ++it) + for( StitchSlot *slot : storage ) { - StitchSlot *slot = *it; - slot->collectAssignments(result); + if ( slot ) + slot->collectAssignments(result); } return result; diff --git a/Minecraft.Client/StringTable.cpp b/Minecraft.Client/StringTable.cpp index a29da179..e4baecac 100644 --- a/Minecraft.Client/StringTable.cpp +++ b/Minecraft.Client/StringTable.cpp @@ -48,24 +48,23 @@ void StringTable::ProcessStringTableData(void) int dataSize = 0; // - for( AUTO_VAR(it_locales, locales.begin()); - it_locales!=locales.end() && (!foundLang); - it_locales++ - ) - { + for (auto it_locales = locales.begin(); + it_locales != locales.end() && (!foundLang); + ++it_locales) + { bytesToSkip = 0; - for(AUTO_VAR(it, langSizeMap.begin()); it != langSizeMap.end(); ++it) + for(auto& it : langSizeMap) { - if(it->first.compare(*it_locales) == 0) + if(it.first.compare(*it_locales) == 0) { app.DebugPrintf("StringTable:: Found language '%ls'.\n", it_locales->c_str()); - dataSize = it->second; + dataSize = it.second; foundLang = true; break; } - bytesToSkip += it->second; + bytesToSkip += it.second; } if (!foundLang) @@ -87,7 +86,7 @@ void StringTable::ProcessStringTableData(void) // Read the language file for the selected language int langVersion = dis2.readInt(); - isStatic = false; // 4J-JEV: Versions 1 and up could use + isStatic = false; // 4J-JEV: Versions 1 and up could use if (langVersion > 0) // integers rather than wstrings as keys. isStatic = dis2.readBoolean(); @@ -152,9 +151,9 @@ LPCWSTR StringTable::getString(const wstring &id) } #endif - AUTO_VAR(it, m_stringsMap.find(id) ); + auto it = m_stringsMap.find(id); - if(it != m_stringsMap.end()) + if(it != m_stringsMap.end()) { return it->second.c_str(); } diff --git a/Minecraft.Client/TextureHolder.cpp b/Minecraft.Client/TextureHolder.cpp index 9cbf5c46..0f10272c 100644 --- a/Minecraft.Client/TextureHolder.cpp +++ b/Minecraft.Client/TextureHolder.cpp @@ -58,7 +58,7 @@ void TextureHolder::setForcedScale(int targetSize) //@Override wstring TextureHolder::toString() { - return L"TextureHolder{width=" + _toString(width) + L", height=" + _toString(height) + L'}'; + return L"TextureHolder{width=" + std::to_wstring(width) + L", height=" + std::to_wstring(height) + L'}'; } int TextureHolder::compareTo(const TextureHolder *other) const diff --git a/Minecraft.Client/TextureManager.cpp b/Minecraft.Client/TextureManager.cpp index 84b164b4..542b9499 100644 --- a/Minecraft.Client/TextureManager.cpp +++ b/Minecraft.Client/TextureManager.cpp @@ -51,9 +51,9 @@ void TextureManager::registerName(const wstring &name, Texture *texture) void TextureManager::registerTexture(Texture *texture) { - for(AUTO_VAR(it, idToTextureMap.begin()); it != idToTextureMap.end(); ++it) + for(auto& it : idToTextureMap) { - if(it->second == texture) + if(it.second == texture) { //Minecraft.getInstance().getLogger().warning("TextureManager.registerTexture called, but this texture has " + "already been registered. ignoring."); app.DebugPrintf("TextureManager.registerTexture called, but this texture has already been registered. ignoring."); @@ -66,11 +66,11 @@ void TextureManager::registerTexture(Texture *texture) void TextureManager::unregisterTexture(const wstring &name, Texture *texture) { - AUTO_VAR(it, idToTextureMap.find(texture->getManagerId())); - if(it != idToTextureMap.end()) idToTextureMap.erase(it); + auto it = idToTextureMap.find(texture->getManagerId()); + if(it != idToTextureMap.end()) idToTextureMap.erase(it); - AUTO_VAR(it2, stringToIDMap.find(name)); - if(it2 != stringToIDMap.end()) stringToIDMap.erase(it2); + auto it2 = stringToIDMap.find(name); + if(it2 != stringToIDMap.end()) stringToIDMap.erase(it2); } Stitcher *TextureManager::createStitcher(const wstring &name) @@ -110,7 +110,7 @@ vector<Texture *> *TextureManager::createTextures(const wstring &filename, bool drive= wstr + L"\\Common\\res\\TitleUpdate\\"; } else -#endif +#endif { drive = Minecraft::GetInstance()->skins->getDefault()->getPath(true); } diff --git a/Minecraft.Client/TextureMap.cpp b/Minecraft.Client/TextureMap.cpp index 836a853e..9aefbb63 100644 --- a/Minecraft.Client/TextureMap.cpp +++ b/Minecraft.Client/TextureMap.cpp @@ -61,10 +61,10 @@ void TextureMap::stitch() unordered_map<TextureHolder *, vector<Texture *> * > textures; // = new HashMap<TextureHolder, List<Texture>>(); Stitcher *stitcher = TextureManager::getInstance()->createStitcher(name); - - for(AUTO_VAR(it,texturesByName.begin()); it != texturesByName.end(); ++it) + + for(auto& it : texturesByName) { - delete it->second; + delete it.second; } texturesByName.clear(); animatedTextures.clear(); @@ -80,9 +80,9 @@ void TextureMap::stitch() // Extract frames from textures and add them to the stitchers //for (final String name : texturesToRegister.keySet()) - for(AUTO_VAR(it, texturesToRegister.begin()); it != texturesToRegister.end(); ++it) + for(auto& it : texturesToRegister) { - wstring name = it->first; + wstring name = it.first; wstring filename = path + name + extension; @@ -113,11 +113,10 @@ void TextureMap::stitch() stitchResult = stitcher->constructTexture(m_mipMap); // Extract all the final positions and store them - AUTO_VAR(areas, stitcher->gatherAreas()); - //for (StitchSlot slot : stitcher.gatherAreas()) - for(AUTO_VAR(it, areas->begin()); it != areas->end(); ++it) + auto areas = stitcher->gatherAreas(); + //for (StitchSlot slot : stitcher.gatherAreas()) + for(auto& slot : *areas) { - StitchSlot *slot = *it; TextureHolder *textureHolder = slot->getHolder(); Texture *texture = textureHolder->getTexture(); @@ -126,13 +125,13 @@ void TextureMap::stitch() vector<Texture *> *frames = textures.find(textureHolder)->second; StitchedTexture *stored = NULL; - - AUTO_VAR(itTex, texturesToRegister.find(textureName) ); - if(itTex != texturesToRegister.end() ) stored = itTex->second; + + auto itTex = texturesToRegister.find(textureName); + if(itTex != texturesToRegister.end() ) stored = itTex->second; // [EB]: What is this code for? debug warnings for when during transition? bool missing = false; - if (stored == NULL) + if (stored) { missing = true; stored = StitchedTexture::create(textureName); @@ -159,7 +158,6 @@ void TextureMap::stitch() TexturePack *texturePack = Minecraft::GetInstance()->skins->getSelected(); bool requiresFallback = !texturePack->hasFile(L"\\" + textureName + L".png", false); - //try { InputStream *fileStream = texturePack->getResource(L"\\" + path + animationDefinitionFile, requiresFallback); //Minecraft::getInstance()->getLogger().info("Found animation info for: " + animationDefinitionFile); @@ -170,8 +168,6 @@ void TextureMap::stitch() BufferedReader br(&isr); stored->loadAnimationFrames(&br); delete fileStream; - //} catch (IOException ignored) { - //} } } delete areas; @@ -179,9 +175,9 @@ void TextureMap::stitch() missingPosition = texturesByName.find(NAME_MISSING_TEXTURE)->second; //for (StitchedTexture texture : texturesToRegister.values()) - for(AUTO_VAR(it, texturesToRegister.begin() ); it != texturesToRegister.end(); ++it) + for(auto& it : texturesToRegister) { - StitchedTexture *texture = it->second; + StitchedTexture *texture = it.second; texture->replaceWith(missingPosition); } @@ -199,10 +195,10 @@ StitchedTexture *TextureMap::getTexture(const wstring &name) void TextureMap::cycleAnimationFrames() { //for (StitchedTexture texture : animatedTextures) - for(AUTO_VAR(it, animatedTextures.begin() ); it != animatedTextures.end(); ++it) + for(auto& texture : animatedTextures) { - StitchedTexture *texture = *it; - texture->cycleFrames(); + if ( texture ) + texture->cycleFrames(); } } @@ -225,8 +221,8 @@ Icon *TextureMap::registerIcon(const wstring &name) // TODO: [EB]: Why do we allow multiple registrations? StitchedTexture *result = NULL; - AUTO_VAR(it, texturesToRegister.find(name)); - if(it != texturesToRegister.end()) result = it->second; + auto it = texturesToRegister.find(name); + if(it != texturesToRegister.end()) result = it->second; if (result == NULL) { diff --git a/Minecraft.Client/TexturePackRepository.cpp b/Minecraft.Client/TexturePackRepository.cpp index 163ec7ba..6bb3cccc 100644 --- a/Minecraft.Client/TexturePackRepository.cpp +++ b/Minecraft.Client/TexturePackRepository.cpp @@ -40,7 +40,7 @@ void TexturePackRepository::addDebugPacks() #ifndef _CONTENT_PACKAGE //File *file = new File(L"DummyTexturePack"); // Path to the test texture pack //m_dummyTexturePack = new FolderTexturePack(FOLDER_TEST_TEXTURE_PACK_ID, L"FolderTestPack", file, DEFAULT_TEXTURE_PACK); - //texturePacks->push_back(m_dummyTexturePack); + //texturePacks->push_back(m_dummyTexturePack); //cacheById[m_dummyTexturePack->getId()] = m_dummyTexturePack; #ifdef _XBOX @@ -96,7 +96,7 @@ void TexturePackRepository::createWorkingDirecoryUnlessExists() bool TexturePackRepository::selectSkin(TexturePack *skin) { if (skin==selected) return false; - + lastSelected = selected; usingWeb = false; selected = skin; @@ -161,7 +161,7 @@ void TexturePackRepository::updateList() currentPacks->push_back(DEFAULT_TEXTURE_PACK); cacheById[DEFAULT_TEXTURE_PACK->getId()] = DEFAULT_TEXTURE_PACK; #ifndef _CONTENT_PACKAGE - currentPacks->push_back(m_dummyTexturePack); + currentPacks->push_back(m_dummyTexturePack); cacheById[m_dummyTexturePack->getId()] = m_dummyTexturePack; if(m_dummyDLCTexturePack != NULL) @@ -194,10 +194,9 @@ void TexturePackRepository::updateList() } // 4J - was texturePacks.removeAll(currentPacks); - AUTO_VAR(itEnd, currentPacks->end()); - for( vector<TexturePack *>::iterator it1 = currentPacks->begin(); it1 != itEnd; it1++ ) + for( auto it1 = currentPacks->begin(); it1 != currentPacks->end(); it1++ ) { - for( vector<TexturePack *>::iterator it2 = texturePacks->begin(); it2 != texturePacks->end(); it2++ ) + for( auto it2 = texturePacks->begin(); it2 != texturePacks->end(); it2++ ) { if( *it1 == *it2 ) { @@ -206,8 +205,7 @@ void TexturePackRepository::updateList() } } - itEnd = texturePacks->end(); - for( vector<TexturePack *>::iterator it = texturePacks->begin(); it != itEnd; it++ ) + for( auto it = texturePacks->begin(); it != texturePacks->end(); it++ ) { TexturePack *pack = *it; pack->unload(minecraft->textures); @@ -295,10 +293,9 @@ vector< pair<DWORD,wstring> > *TexturePackRepository::getTexturePackIdNames() { vector< pair<DWORD,wstring> > *packList = new vector< pair<DWORD,wstring> >(); - for(AUTO_VAR(it,texturePacks->begin()); it != texturePacks->end(); ++it) + for(auto& pack : *texturePacks) { - TexturePack *pack = *it; - packList->push_back( pair<DWORD,wstring>(pack->getId(),pack->getName()) ); + packList->emplace_back(pack->getId(), pack->getName()); } return packList; } @@ -311,8 +308,8 @@ bool TexturePackRepository::selectTexturePackById(DWORD id) // (where they don't have the texture pack) can check this when the texture pack is installed app.SetRequiredTexturePackID(id); - AUTO_VAR(it, cacheById.find(id)); - if(it != cacheById.end()) + auto it = cacheById.find(id); + if(it != cacheById.end()) { TexturePack *newPack = it->second; if(newPack != selected) @@ -354,8 +351,8 @@ bool TexturePackRepository::selectTexturePackById(DWORD id) TexturePack *TexturePackRepository::getTexturePackById(DWORD id) { - AUTO_VAR(it, cacheById.find(id)); - if(it != cacheById.end()) + auto it = cacheById.find(id); + if(it != cacheById.end()) { return it->second; } @@ -392,21 +389,21 @@ TexturePack *TexturePackRepository::addTexturePackFromDLC(DLCPack *dlcPack, DWOR void TexturePackRepository::clearInvalidTexturePacks() { - for(AUTO_VAR(it, m_texturePacksToDelete.begin()); it != m_texturePacksToDelete.end(); ++it) + for(auto& it : m_texturePacksToDelete) { - delete *it; + delete it; } } void TexturePackRepository::removeTexturePackById(DWORD id) { - AUTO_VAR(it, cacheById.find(id)); - if(it != cacheById.end()) + auto it = cacheById.find(id); + if(it != cacheById.end()) { TexturePack *oldPack = it->second; - AUTO_VAR(it2, find(texturePacks->begin(), texturePacks->end(),oldPack) ); - if(it2 != texturePacks->end()) + auto it2 = find(texturePacks->begin(), texturePacks->end(), oldPack); + if(it2 != texturePacks->end()) { texturePacks->erase(it2); if(lastSelected == oldPack) @@ -453,10 +450,10 @@ TexturePack *TexturePackRepository::getTexturePackByIndex(unsigned int index) unsigned int TexturePackRepository::getTexturePackIndex(unsigned int id) { int currentIndex = 0; - for(AUTO_VAR(it,texturePacks->begin()); it != texturePacks->end(); ++it) + for(auto& pack : *texturePacks) { - TexturePack *pack = *it; - if(pack->getId() == id) break; + if(pack->getId() == id) + break; ++currentIndex; } if(currentIndex >= texturePacks->size()) currentIndex = 0; diff --git a/Minecraft.Client/Textures.cpp b/Minecraft.Client/Textures.cpp index b4817ee3..cd6e0bae 100644 --- a/Minecraft.Client/Textures.cpp +++ b/Minecraft.Client/Textures.cpp @@ -145,7 +145,7 @@ wchar_t *Textures::preLoaded[TN_COUNT] = L"mob/horse/horse_white", L"mob/horse/horse_zombie", L"mob/horse/mule", - + L"mob/horse/armor/horse_armor_diamond", L"mob/horse/armor/horse_armor_gold", L"mob/horse/armor/horse_armor_iron", @@ -194,7 +194,7 @@ wchar_t *Textures::preLoaded[TN_COUNT] = L"/GPSE", // avatar items - + L"/AH_0006", L"/AH_0003", L"/AH_0007", @@ -246,7 +246,7 @@ wchar_t *Textures::preLoaded[TN_COUNT] = L"/AH_0008", L"/AH_0009",*/ - L"gui/items", + L"gui/items", L"terrain", }; @@ -354,7 +354,7 @@ int Textures::loadTexture(int idx) return 0; } else - { + { if ( idx == TN_TERRAIN ) { terrain->getStitchedTexture()->bind(0); @@ -597,7 +597,7 @@ int Textures::loadTexture(TEXTURE_NAME texId, const wstring& resourceName) (resourceName == L"%blur%misc/pumpkinblur.png") || (resourceName == L"%clamp%misc/shadow.png") || (resourceName == L"gui/icons.png" ) || - (resourceName == L"gui/gui.png" ) || + (resourceName == L"gui/gui.png" ) || (resourceName == L"misc/footprint.png") ) { MIPMAP = false; @@ -694,7 +694,7 @@ void Textures::loadTexture(BufferedImage *img, int id, bool blur, bool clamp) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } - if (clamp) + if (clamp) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); @@ -716,7 +716,7 @@ void Textures::loadTexture(BufferedImage *img, int id, bool blur, bool clamp) rawPixels = anaglyph(rawPixels); } - byteArray newPixels(w * h * 4); + byteArray newPixels(w * h * 4); for (unsigned int i = 0; i < rawPixels.length; i++) { int a = (rawPixels[i] >> 24) & 0xff; @@ -744,15 +744,15 @@ void Textures::loadTexture(BufferedImage *img, int id, bool blur, bool clamp) delete[] rawPixels.data; delete[] newPixels.data; - - if (MIPMAP) + + if (MIPMAP) { // 4J-PB - In the new XDK, the CreateTexture will fail if the number of mipmaps is higher than the width & height passed in will allow! int iWidthMips=1; int iHeightMips=1; while((8<<iWidthMips)<w) iWidthMips++; while((8<<iHeightMips)<h) iHeightMips++; - + iMipLevels=(iWidthMips<iHeightMips)?iWidthMips:iHeightMips; //RenderManager.TextureSetTextureLevels(5); // 4J added if(iMipLevels>5)iMipLevels = 5; @@ -912,7 +912,7 @@ void Textures::replaceTexture(intArray rawPixels, int w, int h, int id) delete [] newPixels.data; // New - // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); + // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); #ifdef _XBOX RenderManager.TextureDataUpdate(pixels->getBuffer(),0); #else @@ -1089,8 +1089,8 @@ void Textures::removeHttpTexture(const wstring& url) int Textures::loadMemTexture(const wstring& url, const wstring& backup) { MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(url) ); - if (it != memTextures.end()) + auto it = memTextures.find(url); + if (it != memTextures.end()) { texture = (*it).second; } @@ -1133,8 +1133,8 @@ int Textures::loadMemTexture(const wstring& url, const wstring& backup) int Textures::loadMemTexture(const wstring& url, int backup) { MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(url) ); - if (it != memTextures.end()) + auto it = memTextures.find(url); + if (it != memTextures.end()) { texture = (*it).second; } @@ -1176,8 +1176,8 @@ int Textures::loadMemTexture(const wstring& url, int backup) MemTexture *Textures::addMemTexture(const wstring& name,MemTextureProcessor *processor) { MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(name) ); - if (it != memTextures.end()) + auto it = memTextures.find(name); + if (it != memTextures.end()) { texture = (*it).second; } @@ -1185,7 +1185,7 @@ MemTexture *Textures::addMemTexture(const wstring& name,MemTextureProcessor *pro { // can we find it in the app mem files? PBYTE pbData=NULL; - DWORD dwBytes=0; + DWORD dwBytes=0; app.GetMemFileDetails(name,&pbData,&dwBytes); if(dwBytes!=0) @@ -1222,8 +1222,8 @@ MemTexture *Textures::addMemTexture(const wstring& name,MemTextureProcessor *pro void Textures::removeMemTexture(const wstring& url) { MemTexture *texture = NULL; - AUTO_VAR(it, memTextures.find(url) ); - if (it != memTextures.end()) + auto it = memTextures.find(url); + if (it != memTextures.end()) { texture = (*it).second; @@ -1256,7 +1256,7 @@ void Textures::tick(bool updateTextures, bool tickDynamics) // 4J added updateTe } // 4J - added - tell renderer that we're about to do a block of dynamic texture updates, so we can unlock the resources after they are done rather than a series of locks/unlocks - //RenderManager.TextureDynamicUpdateStart(); + //RenderManager.TextureDynamicUpdateStart(); terrain->cycleAnimationFrames(); items->cycleAnimationFrames(); //RenderManager.TextureDynamicUpdateEnd(); // 4J added - see comment above @@ -1264,8 +1264,8 @@ void Textures::tick(bool updateTextures, bool tickDynamics) // 4J added updateTe // 4J - go over all the memory textures once per frame, and free any that haven't been used for a while. Ones that are being used will // have their ticksSinceLastUse reset in Textures::loadMemTexture. - for( AUTO_VAR(it, memTextures.begin() ); it != memTextures.end(); ) - { + for (auto it = memTextures.begin(); it != memTextures.end();) + { MemTexture *tex = it->second; if( tex && ( ++tex->ticksSinceLastUse > MemTexture::UNUSED_TICKS_TO_FREE ) ) @@ -1308,28 +1308,24 @@ void Textures::reloadAll() skins->clearInvalidTexturePacks(); #if 0 - AUTO_VAR(itEndLI, loadedImages.end() ); - for(unordered_map<int, BufferedImage *>::iterator it = loadedImages.begin(); it != itEndLI; it++ ) + for(auto it = loadedImages.begin(); it != loadedImages.end(); it++ ) { BufferedImage *image = it->second; loadTexture(image, it->first); } - AUTO_VAR(itEndHT, httpTextures.end()); - for(unordered_map<wstring, HttpTexture *>::iterator it = httpTextures.begin(); it != itEndHT; it++ ) + for(auto it = httpTextures.begin(); it != httpTextures.end(); it++ ) { it->second->isLoaded = false; } - AUTO_VAR(itEndMT, memTextures.end()); - for(unordered_map<wstring, MemTexture *>::iterator it = memTextures.begin(); it != itEndMT; it++ ) + for(auto it = memTextures.begin(); it != memTextures.end(); it++ ) { it->second->isLoaded = false; } - AUTO_VAR(itEndIM, idMap.end()); - for( unordered_map<wstring, int>::iterator it = idMap.begin(); it != itEndIM; it++ ) + for( auto it = idMap.begin(); it != idMap.end(); it++ ) { wstring name = it->first; @@ -1349,8 +1345,7 @@ void Textures::reloadAll() loadTexture(image, id, blur, clamp); delete image; } - AUTO_VAR(itEndPM, pixelsMap.end()); - for( unordered_map<wstring, intArray>::iterator it = pixelsMap.begin(); it != itEndPM; it++ ) + for( auto it = pixelsMap.begin(); it != pixelsMap.end(); it++ ) { wstring name = it->first; BufferedImage *image = readImage(skin->getResource(name)); @@ -1388,7 +1383,7 @@ BufferedImage *Textures::readImage(TEXTURE_NAME texId, const wstring& name) // 4 BufferedImage *img=NULL; MemSect(32); // is this image one of the Title Update ones? - bool isTu = IsTUImage(texId, name); + bool isTu = IsTUImage(texId, name); wstring drive = L""; if(!skins->isUsingDefaultSkin() && skins->getSelected()->hasFile(L"res/" + name,false)) @@ -1427,7 +1422,7 @@ BufferedImage *Textures::readImage(TEXTURE_NAME texId, const wstring& name) // 4 { img = skins->getDefault()->getImageResource(name,false,isTu,drive); //new BufferedImage(name,false,isTu,drive); } - else + else { img = skins->getDefault()->getImageResource(L"1_2_2/" + name, false, isTu, drive); //new BufferedImage(L"/1_2_2" + name,false,isTu,drive); } @@ -1510,7 +1505,7 @@ TEXTURE_NAME TUImages[] = TN_TILE_TRAP_CHEST, TN_TILE_LARGE_TRAP_CHEST, - //TN_TILE_XMAS_CHEST, + //TN_TILE_XMAS_CHEST, //TN_TILE_LARGE_XMAS_CHEST, #ifdef _LARGE_WORLDS @@ -1521,7 +1516,7 @@ TEXTURE_NAME TUImages[] = TN_DEFAULT_FONT, // TN_ALT_FONT, // Not in TU yet - TN_COUNT // Why is this here? + TN_COUNT // Why is this here? }; // This is for any TU textures that aren't part of our enum indexed preload set @@ -1583,7 +1578,7 @@ TEXTURE_NAME OriginalImages[] = TN_COUNT }; - + wchar_t *OriginalImagesPaths[] = { L"misc/watercolor.png", diff --git a/Minecraft.Client/TileEntityRenderDispatcher.cpp b/Minecraft.Client/TileEntityRenderDispatcher.cpp index f9ecfea4..887663fe 100644 --- a/Minecraft.Client/TileEntityRenderDispatcher.cpp +++ b/Minecraft.Client/TileEntityRenderDispatcher.cpp @@ -49,10 +49,9 @@ TileEntityRenderDispatcher::TileEntityRenderDispatcher() renderers[eTYPE_BEACONTILEENTITY] = new BeaconRenderer(); glDisable(GL_LIGHTING); - AUTO_VAR(itEnd, renderers.end()); - for( classToTileRendererMap::iterator it = renderers.begin(); it != itEnd; it++ ) + for(auto& renderer : renderers) { - if(it->second) it->second->init(this); + if(renderer.second) renderer.second->init(this); } } @@ -60,9 +59,9 @@ TileEntityRenderer *TileEntityRenderDispatcher::getRenderer(eINSTANCEOF e) { TileEntityRenderer *r = NULL; //TileEntityRenderer *r = renderers[e]; - AUTO_VAR(it, renderers.find( e )); // 4J Stu - The .at and [] accessors insert elements if they don't exist + auto it = renderers.find(e); // 4J Stu - The .at and [] accessors insert elements if they don't exist - if( it == renderers.end() ) + if( it == renderers.end() ) { return NULL; } @@ -146,9 +145,9 @@ void TileEntityRenderDispatcher::setLevel(Level *level) { this->level = level; - for( AUTO_VAR(it, renderers.begin()); it != renderers.end(); it++ ) + for(auto& renderer : renderers) { - if(it->second) it->second->onNewLevel(level); + if(renderer.second) renderer.second->onNewLevel(level); } } diff --git a/Minecraft.Client/TrackedEntity.cpp b/Minecraft.Client/TrackedEntity.cpp index 6e956b15..0a5a02bf 100644 --- a/Minecraft.Client/TrackedEntity.cpp +++ b/Minecraft.Client/TrackedEntity.cpp @@ -21,6 +21,8 @@ #include "PlayerChunkMap.h" #include <qnet.h> +#include <memory> + TrackedEntity::TrackedEntity(shared_ptr<Entity> e, int range, int updateInterval, bool trackDelta) { // 4J added initialisers @@ -68,20 +70,20 @@ void TrackedEntity::tick(EntityTracker *tracker, vector<shared_ptr<Player> > *pl } // Moving forward special case for item frames - if (e->GetType()== eTYPE_ITEM_FRAME && tickCount % 10 == 0) + if (e->GetType()== eTYPE_ITEM_FRAME && tickCount % 10 == 0) { shared_ptr<ItemFrame> frame = dynamic_pointer_cast<ItemFrame> (e); shared_ptr<ItemInstance> item = frame->getItem(); - if (item != NULL && item->getItem()->id == Item::map_Id && !e->removed) + if (item != NULL && item->getItem()->id == Item::map_Id && !e->removed) { shared_ptr<MapItemSavedData> data = Item::map->getSavedData(item, e->level); - for (AUTO_VAR(it,players->begin() ); it != players->end(); ++it) + for (auto& it : *players) { - shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(*it); + shared_ptr<ServerPlayer> player = dynamic_pointer_cast<ServerPlayer>(it); data->tickCarriedBy(player, item); - if (!player->removed && player->connection && player->connection->countDelayedPackets() <= 5) + if (!player->removed && player->connection && player->connection->countDelayedPackets() <= 5) { shared_ptr<Packet> packet = Item::map->getUpdatePacket(item, e->level, player); if (packet != NULL) player->connection->send(packet); @@ -90,7 +92,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector<shared_ptr<Player> > *pl } shared_ptr<SynchedEntityData> entityData = e->getEntityData(); - if (entityData->isDirty()) + if (entityData->isDirty()) { broadcastAndSend( shared_ptr<SetEntityDataPacket>( new SetEntityDataPacket(e->entityId, entityData, false) ) ); } @@ -112,7 +114,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector<shared_ptr<Player> > *pl int xn = Mth::floor(e->x * 32.0); int yn = Mth::floor(e->y * 32.0); int zn = Mth::floor(e->z * 32.0); - + int xa = xn - xp; int ya = yn - yp; int za = zn - zp; @@ -122,7 +124,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector<shared_ptr<Player> > *pl // 4J - this pos flag used to be set based on abs(xn) etc. but that just seems wrong bool pos = abs(xa) >= TOLERANCE_LEVEL || abs(ya) >= TOLERANCE_LEVEL || abs(za) >= TOLERANCE_LEVEL || (tickCount % (SharedConstants::TICKS_PER_SECOND * 3) == 0); - // Keep rotation deltas in +/- 180 degree range + // Keep rotation deltas in +/- 180 degree range while( yRota > 127 ) yRota -= 256; while( yRota < -128 ) yRota += 256; while( xRota > 127 ) xRota -= 256; @@ -293,7 +295,7 @@ void TrackedEntity::tick(EntityTracker *tracker, vector<shared_ptr<Player> > *pl yRotp = yRotn; xRotp = xRotn; } - + xp = Mth::floor(e->x * 32.0); yp = Mth::floor(e->y * 32.0); zp = Mth::floor(e->z * 32.0); @@ -354,15 +356,14 @@ void TrackedEntity::broadcast(shared_ptr<Packet> packet) // 4J-PB - due to the knockback on a player being hit, we need to send to all players, but limit the network traffic here to players that have not already had it sent to their system vector< shared_ptr<ServerPlayer> > sentTo; - // 4J - don't send to a player we've already sent this data to that shares the same machine. + // 4J - don't send to a player we've already sent this data to that shares the same machine. // EntityMotionPacket used to limit themselves to sending once to each machine // by only sending to the primary player on each machine. This was causing trouble for split screen // as only the primary player would get a knockback velocity. Now these packets can be sent to any // player, but we try to restrict the network impact this has by not resending to the one machine - for( AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++ ) + for( auto& player : seenBy) { - shared_ptr<ServerPlayer> player = *it; bool dontSend = false; if( sentTo.size() ) { @@ -373,20 +374,12 @@ void TrackedEntity::broadcast(shared_ptr<Packet> packet) } else { - for(unsigned int j = 0; j < sentTo.size(); j++ ) + for(auto& player2 : sentTo) { - shared_ptr<ServerPlayer> player2 = sentTo[j]; INetworkPlayer *otherPlayer = player2->connection->getNetworkPlayer(); if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) ) { dontSend = true; - // #ifdef _DEBUG - // shared_ptr<SetEntityMotionPacket> emp= dynamic_pointer_cast<SetEntityMotionPacket> (packet); - // if(emp!=NULL) - // { - // app.DebugPrintf("Not sending this SetEntityMotionPacket to player - it's already been sent to a player on their console\n"); - // } - // #endif } } } @@ -397,7 +390,7 @@ void TrackedEntity::broadcast(shared_ptr<Packet> packet) } - (*it)->connection->send(packet); + player->connection->send(packet); sentTo.push_back(player); } } @@ -405,9 +398,9 @@ void TrackedEntity::broadcast(shared_ptr<Packet> packet) { // This packet hasn't got canSendToAnyClient set, so just send to everyone here, and it - for( AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++ ) + for(auto& it : seenBy) { - (*it)->connection->send(packet); + it->connection->send(packet); } } } @@ -425,16 +418,16 @@ void TrackedEntity::broadcastAndSend(shared_ptr<Packet> packet) void TrackedEntity::broadcastRemoved() { - for( AUTO_VAR(it, seenBy.begin()); it != seenBy.end(); it++ ) + for(const auto& it : seenBy) { - (*it)->entitiesToRemove.push_back(e->entityId); + it->entitiesToRemove.push_back(e->entityId); } } void TrackedEntity::removePlayer(shared_ptr<ServerPlayer> sp) { - AUTO_VAR(it, seenBy.find( sp )); - if( it != seenBy.end() ) + auto it = seenBy.find(sp); + if( it != seenBy.end() ) { sp->entitiesToRemove.push_back(e->entityId); seenBy.erase( it ); @@ -598,19 +591,17 @@ void TrackedEntity::updatePlayer(EntityTracker *tracker, shared_ptr<ServerPlayer { shared_ptr<LivingEntity> mob = dynamic_pointer_cast<LivingEntity>(e); vector<MobEffectInstance *> *activeEffects = mob->getActiveEffects(); - for(AUTO_VAR(it, activeEffects->begin()); it != activeEffects->end(); ++it) + for(auto& effect : *activeEffects) { - MobEffectInstance *effect = *it; - - sp->connection->send(shared_ptr<UpdateMobEffectPacket>( new UpdateMobEffectPacket(e->entityId, effect) ) ); + sp->connection->send(std::make_shared<UpdateMobEffectPacket>( e->entityId, effect ) ); } delete activeEffects; } } else if (visibility == eVisibility_NotVisible) { - AUTO_VAR(it, seenBy.find(sp)); - if (it != seenBy.end()) + auto it = seenBy.find(sp); + if (it != seenBy.end()) { seenBy.erase(it); sp->entitiesToRemove.push_back(e->entityId); @@ -774,7 +765,7 @@ shared_ptr<Packet> TrackedEntity::getAddEntityPacket() else if (e->instanceof(eTYPE_ITEM_FRAME)) { shared_ptr<ItemFrame> frame = dynamic_pointer_cast<ItemFrame>(e); - + { int ix= (int)frame->xTile; @@ -812,8 +803,8 @@ shared_ptr<Packet> TrackedEntity::getAddEntityPacket() void TrackedEntity::clear(shared_ptr<ServerPlayer> sp) { - AUTO_VAR(it, seenBy.find(sp)); - if (it != seenBy.end()) + auto it = seenBy.find(sp); + if (it != seenBy.end()) { seenBy.erase(it); sp->entitiesToRemove.push_back(e->entityId); diff --git a/Minecraft.Client/Windows64/Windows64_Minecraft.cpp b/Minecraft.Client/Windows64/Windows64_Minecraft.cpp index d38ad442..f5989c42 100644 --- a/Minecraft.Client/Windows64/Windows64_Minecraft.cpp +++ b/Minecraft.Client/Windows64/Windows64_Minecraft.cpp @@ -1812,7 +1812,7 @@ SIZE_T WINAPI XMemSize( void DumpMem() { int totalLeak = 0; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) + for( auto it = allocCounts.begin(); it != allocCounts.end(); it++ ) { if(it->second > 0 ) { @@ -1860,7 +1860,7 @@ void MemPixStuff() int totals[MAX_SECT] = {0}; - for(AUTO_VAR(it, allocCounts.begin()); it != allocCounts.end(); it++ ) + for( auto it = allocCounts.begin(); it != allocCounts.end(); it++ ) { if(it->second > 0 ) { diff --git a/Minecraft.Client/Xbox/Font/XUI_FontRenderer.cpp b/Minecraft.Client/Xbox/Font/XUI_FontRenderer.cpp index 48581905..d708af79 100644 --- a/Minecraft.Client/Xbox/Font/XUI_FontRenderer.cpp +++ b/Minecraft.Client/Xbox/Font/XUI_FontRenderer.cpp @@ -13,7 +13,7 @@ XUI_FontRenderer::XUI_FontRenderer() ZeroMemory(m_loadedFontData, sizeof(XUI_FontData*) * eFontData_MAX); //XuiFontSetRenderer(this); - + //Minecraft *pMinecraft=Minecraft::GetInstance(); //ScreenSizeCalculator ssc(pMinecraft->options, pMinecraft->width_phys, pMinecraft->height_phys); @@ -113,8 +113,8 @@ VOID XUI_FontRenderer::ReleaseFont( HFONTOBJ hFont ) xuiFont->DecRefCount(); if (xuiFont->refCount <= 0) { - AUTO_VAR(it, m_loadedFonts[xuiFont->m_iFontData].find(xuiFont->m_fScaleFactor) ); - if (it != m_loadedFonts[xuiFont->m_iFontData].end()) m_loadedFonts[xuiFont->m_iFontData].erase(it); + auto it = m_loadedFonts[xuiFont->m_iFontData].find(xuiFont->m_fScaleFactor); + if (it != m_loadedFonts[xuiFont->m_iFontData].end()) m_loadedFonts[xuiFont->m_iFontData].erase(it); delete hFont; } } @@ -175,7 +175,7 @@ HRESULT XUI_FontRenderer::DrawCharsToDevice( HFONTOBJ hFont, CharData * pCharDat if(!RenderManager.IsHiDef()) { if(RenderManager.IsWidescreen()) - { + { float fScaleX, fScaleY; font->GetScaleFactors(&fScaleX,&fScaleY); int iScaleX=fScaleX; @@ -230,8 +230,8 @@ HRESULT XUI_FontRenderer::DrawCharsToDevice( HFONTOBJ hFont, CharData * pCharDat matrixCopy[14] = floor(matrixCopy[14] + 0.5f); matrixCopy[15] = 1.0f; glMultMatrixf(matrixCopy); - - + + float lineXPos = 0.0f; float lineYPos = 0.0f; DWORD colour = 0; @@ -262,7 +262,7 @@ HRESULT XUI_FontRenderer::DrawCharsToDevice( HFONTOBJ hFont, CharData * pCharDat lineXPos = pCharData[i].x; colour = pCharData[i].dwColor; style = pCharData[i].dwStyle; - + while(i < dwCount && pCharData[i].y == lineYPos) { string.push_back(pCharData[i].wch); @@ -300,7 +300,7 @@ HRESULT XUI_FontRenderer::DrawCharsToDevice( HFONTOBJ hFont, CharData * pCharDat g_pD3DDevice->SetRenderState(D3DRS_HALFPIXELOFFSET, FALSE); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); - + XuiRenderRestoreState(hDC); return( S_OK ); diff --git a/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.cpp b/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.cpp index a551725b..da6bf20f 100644 --- a/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.cpp +++ b/Minecraft.Client/Xbox/Network/PlatformNetworkManagerXbox.cpp @@ -48,7 +48,7 @@ VOID CPlatformNetworkManagerXbox::NotifyStateChanged( else if( NewState == QNET_STATE_IDLE && OldState == QNET_STATE_SESSION_JOINING ) { // 4J-PB - now and then we get ERROR_DEVICE_REMOVED when qnet says - // " Couldn't join, removed from session!" or + // " Couldn't join, removed from session!" or //[qnet]: Received data change notification from partially connected player! //[qnet]: Couldn't join, removed from session! // instead of a QNET_E_SESSION_FULL as should be reported @@ -150,8 +150,8 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerJoined( { // Do we already have a primary player for this system? bool systemHasPrimaryPlayer = false; - for(AUTO_VAR(it, m_machineQNetPrimaryPlayers.begin()); it < m_machineQNetPrimaryPlayers.end(); ++it) - { + for (auto it = m_machineQNetPrimaryPlayers.begin(); it < m_machineQNetPrimaryPlayers.end(); ++it) + { IQNetPlayer *pQNetPrimaryPlayer = *it; if( pQNetPlayer->IsSameSystem(pQNetPrimaryPlayer) ) { @@ -164,7 +164,7 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerJoined( } } g_NetworkManager.PlayerJoining( networkPlayer ); - + if( createFakeSocket == true && !m_bHostChanged ) { g_NetworkManager.CreateSocket( networkPlayer, localPlayer ); @@ -184,7 +184,7 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerJoined( g_NetworkManager.UpdateAndSetGameSessionData(); SystemFlagAddPlayer( networkPlayer ); } - + for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { if(playerChangedCallback[idx] != NULL) @@ -255,8 +255,8 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerLeaving( break; } } - AUTO_VAR(it, find( m_machineQNetPrimaryPlayers.begin(), m_machineQNetPrimaryPlayers.end(), pQNetPlayer)); - if( it != m_machineQNetPrimaryPlayers.end() ) + auto it = find(m_machineQNetPrimaryPlayers.begin(), m_machineQNetPrimaryPlayers.end(), pQNetPlayer); + if( it != m_machineQNetPrimaryPlayers.end() ) { m_machineQNetPrimaryPlayers.erase( it ); } @@ -271,7 +271,7 @@ VOID CPlatformNetworkManagerXbox::NotifyPlayerLeaving( } g_NetworkManager.PlayerLeaving( networkPlayer ); - + for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { if(playerChangedCallback[idx] != NULL) @@ -334,7 +334,7 @@ VOID CPlatformNetworkManagerXbox::NotifyDataReceived( dwDataSize, pPlayerFrom->GetGamertag(), apPlayersTo[ dwPlayer ]->GetGamertag()); - + } */ @@ -434,7 +434,7 @@ bool CPlatformNetworkManagerXbox::Initialise(CGameNetworkManager *pGameNetworkMa { playerChangedCallback[ i ] = NULL; } - + HRESULT hr; int iResult; DWORD dwResult; @@ -475,7 +475,7 @@ bool CPlatformNetworkManagerXbox::Initialise(CGameNetworkManager *pGameNetworkMa m_pIQNet->SetOpt( QNET_OPTION_INVITES_ALLOWED, &enableInv, sizeof BOOL ); BOOL enablePres = FALSE; m_pIQNet->SetOpt( QNET_OPTION_PRESENCE_JOIN_MODE, &enablePres, sizeof BOOL ); - + // We DO NOT want QNet to handle XN_SYS_SIGNINCHANGED but so far everything else should be fine // We DO WANT QNet to handle XN_LIVE_INVITE_ACCEPTED at a minimum // Receive all types that QNet needs, and filter out the specific ones we don't want later @@ -526,8 +526,8 @@ int CPlatformNetworkManagerXbox::CorrectErrorIDS(int IDS) bool CPlatformNetworkManagerXbox::isSystemPrimaryPlayer(IQNetPlayer *pQNetPlayer) { bool playerIsSystemPrimary = false; - for(AUTO_VAR(it, m_machineQNetPrimaryPlayers.begin()); it < m_machineQNetPrimaryPlayers.end(); ++it) - { + for (auto it = m_machineQNetPrimaryPlayers.begin(); it < m_machineQNetPrimaryPlayers.end(); ++it) + { IQNetPlayer *pQNetPrimaryPlayer = *it; if( pQNetPrimaryPlayer == pQNetPlayer ) { @@ -548,7 +548,7 @@ void CPlatformNetworkManagerXbox::DoWork() m_notificationListener, 0, // Any notification &dwNotifyId, - &ulpNotifyParam) + &ulpNotifyParam) ) { @@ -655,7 +655,7 @@ bool CPlatformNetworkManagerXbox::IsInStatsEnabledSession() DWORD dataSize = sizeof(QNET_LIVE_STATS_MODE); QNET_LIVE_STATS_MODE statsMode; m_pIQNet->GetOpt(QNET_OPTION_LIVE_STATS_MODE, &statsMode , &dataSize ); - + // Use QNET_LIVE_STATS_MODE_AUTO if there is another way to check if stats are enabled or not bool statsEnabled = statsMode == QNET_LIVE_STATS_MODE_ENABLED; return m_pIQNet->GetState() != QNET_STATE_IDLE && statsEnabled; @@ -778,7 +778,7 @@ void CPlatformNetworkManagerXbox::_HostGame(int usersMask, unsigned char publicS if(publicSlots==1 && privateSlots==0) privateSlots = 1; - //printf("Hosting game with %d public slots and %d private slots\n", publicSlots, privateSlots); + //printf("Hosting game with %d public slots and %d private slots\n", publicSlots, privateSlots); BOOL enableJip = FALSE; m_pIQNet->SetOpt( QNET_OPTION_JOIN_IN_PROGRESS_ALLOWED, &enableJip, sizeof BOOL ); @@ -838,10 +838,10 @@ int CPlatformNetworkManagerXbox::JoinGame(FriendSessionInfo *searchResult, int l localUsersMask, // dwUserMask &searchResultCopy ); // pSearchResult - + if( FAILED( hr ) ) { - app.DebugPrintf( "Failed joining game (err = 0x%08x)!\n", hr ); + app.DebugPrintf( "Failed joining game (err = 0x%08x)!\n", hr ); } switch( hr ) @@ -906,7 +906,7 @@ void CPlatformNetworkManagerXbox::UnRegisterPlayerChangedCallback(int iPad, void void CPlatformNetworkManagerXbox::HandleSignInChange() { - return; + return; } bool CPlatformNetworkManagerXbox::_RunNetworkGame() @@ -1099,8 +1099,8 @@ bool CPlatformNetworkManagerXbox::SystemFlagGet(INetworkPlayer *pNetworkPlayer, wstring CPlatformNetworkManagerXbox::GatherStats() { - return L"Queue messages: " + _toString(((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_MESSAGES ) ) - + L" Queue bytes: " + _toString( ((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_BYTES ) ); + return L"Queue messages: " + std::to_wstring(((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_MESSAGES ) ) + + L" Queue bytes: " + std::to_wstring( ((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_BYTES ) ); } wstring CPlatformNetworkManagerXbox::GatherRTTStats() @@ -1136,7 +1136,7 @@ void CPlatformNetworkManagerXbox::TickSearch() { delete m_pCurrentSearchResults[m_lastSearchPad]; m_pCurrentSearchResults[m_lastSearchPad] = NULL; - } + } m_pCurrentSearchResults[m_lastSearchPad] = m_pSearchResults[m_lastSearchPad]; m_pSearchResults[m_lastSearchPad] = NULL; @@ -1174,17 +1174,17 @@ void CPlatformNetworkManagerXbox::SearchForGames() m_bSearchPending = true; m_bSearchResultsReady = false; - for(AUTO_VAR(it, friendsSessions[m_lastSearchPad].begin()); it < friendsSessions[m_lastSearchPad].end(); ++it) - { + for (auto it = friendsSessions[m_lastSearchPad].begin(); it < friendsSessions[m_lastSearchPad].end(); ++it) + { delete (*it); } - friendsSessions[m_lastSearchPad].clear(); - + friendsSessions[m_lastSearchPad].clear(); + if( m_pSearchResults[m_lastSearchPad] != NULL ) { delete m_pSearchResults[m_lastSearchPad]; m_pSearchResults[m_lastSearchPad] = NULL; - } + } if( m_pQoSResult[m_lastSearchPad] != NULL ) { XNetQosRelease(m_pQoSResult[m_lastSearchPad]); @@ -1202,15 +1202,15 @@ void CPlatformNetworkManagerXbox::SearchForGames() { for(unsigned int i = 0; i<partyUserList.dwUserCount; i++) { - if( + if( ( (partyUserList.Users[i].dwFlags & XPARTY_USER_ISLOCAL ) != XPARTY_USER_ISLOCAL ) && ( (partyUserList.Users[i].dwFlags & XPARTY_USER_ISINGAMESESSION) == XPARTY_USER_ISINGAMESESSION ) && partyUserList.Users[i].dwTitleId == TITLEID_MINECRAFT ) { bool sessionAlreadyAdded = false; - for(AUTO_VAR(it, friendsSessions[m_lastSearchPad].begin()); it < friendsSessions[m_lastSearchPad].end(); ++it) - { + for (auto it = friendsSessions[m_lastSearchPad].begin(); it < friendsSessions[m_lastSearchPad].end(); ++it) + { FriendSessionInfo *current = *it; if( memcmp( &partyUserList.Users[i].SessionInfo.sessionID, ¤t->sessionId, sizeof(SessionID) ) == 0 ) { @@ -1268,8 +1268,8 @@ void CPlatformNetworkManagerXbox::SearchForGames() //printf("Valid game to join\n"); bool sessionAlreadyAdded = false; - for(AUTO_VAR(it, friendsSessions[m_lastSearchPad].begin()); it < friendsSessions[m_lastSearchPad].end(); ++it) - { + for (auto it = friendsSessions[m_lastSearchPad].begin(); it < friendsSessions[m_lastSearchPad].end(); ++it) + { FriendSessionInfo *current = *it; if( memcmp( &friends[i].sessionID, ¤t->sessionId, sizeof(SessionID) ) == 0 ) { @@ -1426,10 +1426,10 @@ int CPlatformNetworkManagerXbox::SearchForGamesThreadProc( void* lpParameter ) HANDLE QoSLookupHandle = CreateEvent(NULL, false, false, NULL); *threadData->ppQos = new XNQOS(); - + INT iRet = XNetQosLookup( pSearchResults->dwSearchResults, // Number of remote Xbox 360 consoles to probe - QoSxnaddr, // Array of pointers to XNADDR structures + QoSxnaddr, // Array of pointers to XNADDR structures QoSxnkid, // Array of pointers to XNKID structures that contain session IDs for the remote Xbox 360 consoles QoSxnkey, // Array of pointers to XNKEY structures that contain key-exchange keys for the remote Xbox 360 consoles 0, // Number of security gateways to probe @@ -1440,7 +1440,7 @@ int CPlatformNetworkManagerXbox::SearchForGamesThreadProc( void* lpParameter ) 0, // Flags QoSLookupHandle, // Event handle threadData->ppQos ); // Pointer to a pointer to an XNQOS structure that receives the results from the QoS probes - + if( 0 != iRet ) { app.DebugPrintf( "XNetQosLookup failed with error 0x%08x", iRet); @@ -1448,9 +1448,9 @@ int CPlatformNetworkManagerXbox::SearchForGamesThreadProc( void* lpParameter ) } else { - + //m_bQoSTesting = TRUE; - + // Wait for results to all complete. cxnqosPending will eventually hit zero. // Pause thread waiting for QosLookup events to be triggered. while ( (*threadData->ppQos)->cxnqosPending != 0 ) @@ -1458,7 +1458,7 @@ int CPlatformNetworkManagerXbox::SearchForGamesThreadProc( void* lpParameter ) // 4J Stu - We could wait for INFINITE if we weren't watching for the kill flag WaitForSingleObject(QoSLookupHandle, 100); } - + // Close handle CloseHandle( QoSLookupHandle ); @@ -1487,15 +1487,15 @@ vector<FriendSessionInfo *> *CPlatformNetworkManagerXbox::GetSessionList(int iPa for( DWORD dwResult = 0; dwResult < m_currentSearchResultsCount[iPad]; dwResult++ ) { pSearchResult = &m_pCurrentSearchResults[iPad]->pResults[dwResult]; - + // No room for us, so ignore it // 4J Stu - pSearchResult should never be NULL, but just in case... if(pSearchResult == NULL || pSearchResult->dwOpenPublicSlots < localPlayers) continue; bool foundSession = false; FriendSessionInfo *sessionInfo = NULL; - AUTO_VAR(itFriendSession, friendsSessions[iPad].begin()); - for(itFriendSession = friendsSessions[iPad].begin(); itFriendSession < friendsSessions[iPad].end(); ++itFriendSession) + auto itFriendSession = friendsSessions[iPad].begin(); + for(itFriendSession = friendsSessions[iPad].begin(); itFriendSession < friendsSessions[iPad].end(); ++itFriendSession) { sessionInfo = *itFriendSession; if(memcmp( &pSearchResult->info.sessionID, &sessionInfo->sessionId, sizeof(SessionID) ) == 0 && (!partyOnly || (partyOnly && sessionInfo->hasPartyMember) ) ) @@ -1628,7 +1628,7 @@ bool CPlatformNetworkManagerXbox::GetGameSessionInfo(int iPad, SessionID session else { swprintf(sessionInfo->displayLabel,app.GetString(IDS_GAME_HOST_NAME_UNKNOWN)); - } + } sessionInfo->displayLabelLength = wcslen( sessionInfo->displayLabel ); // If this host wasn't disabled use this one. @@ -1705,7 +1705,7 @@ INetworkPlayer *CPlatformNetworkManagerXbox::getNetworkPlayer(IQNetPlayer *pQNet INetworkPlayer *CPlatformNetworkManagerXbox::GetLocalPlayerByUserIndex(int userIndex ) { - return getNetworkPlayer(m_pIQNet->GetLocalPlayerByUserIndex(userIndex)); + return getNetworkPlayer(m_pIQNet->GetLocalPlayerByUserIndex(userIndex)); } INetworkPlayer *CPlatformNetworkManagerXbox::GetPlayerByIndex(int playerIndex) diff --git a/Minecraft.Client/Xbox/Xbox_App.cpp b/Minecraft.Client/Xbox/Xbox_App.cpp index a342d8c2..eebeb827 100644 --- a/Minecraft.Client/Xbox/Xbox_App.cpp +++ b/Minecraft.Client/Xbox/Xbox_App.cpp @@ -7,7 +7,7 @@ #include "..\Common\XUI\XUI_NewUpdateMessage.h" #include "..\Common\XUI\XUI_HelpAndOptions.h" #include "..\Common\XUI\XUI_TextEntry.h" -#include "..\Common\XUI\XUI_HelpHowToPlay.h" +#include "..\Common\XUI\XUI_HelpHowToPlay.h" #include "..\Common\XUI\XUI_HowToPlayMenu.h" #include "..\Common\XUI\XUI_HelpControls.h" #include "..\Common\XUI\XUI_TextEntry.h" @@ -117,7 +117,7 @@ #include "..\Common\XUI\XUI_NewUpdateMessage.h" #include "..\Common\XUI\XUI_HelpAndOptions.h" #include "..\Common\XUI\XUI_TextEntry.h" -#include "..\Common\XUI\XUI_HelpHowToPlay.h" +#include "..\Common\XUI\XUI_HelpHowToPlay.h" #include "..\Common\XUI\XUI_HowToPlayMenu.h" #include "..\Common\XUI\XUI_HelpControls.h" #include "..\Common\XUI\XUI_TextEntry.h" @@ -212,7 +212,7 @@ WCHAR *CConsoleMinecraftApp::wchSceneA[]= L"xuiscene_intro", L"xuiscene_savemessage", L"xuiscene_main", - L"xuiscene_fullscreenprogress", + L"xuiscene_fullscreenprogress", L"xuiscene_pause", L"xuiscene_craftingpanel_2x2", L"xuiscene_craftingpanel_3x3", @@ -224,7 +224,7 @@ WCHAR *CConsoleMinecraftApp::wchSceneA[]= L"xuiscene_debug", L"xuiScene_DebugTips", L"xuiscene_helpandoptions", - L"xuiscene_howtoplay", + L"xuiscene_howtoplay", L"xuiscene_howtoplay_menu", L"xuiscene_controls", L"xuiscene_settings_options", @@ -288,7 +288,7 @@ CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() m_dwXuidsFileSize=0; ZeroMemory(m_ScreenshotBuffer,sizeof(LPD3DXBUFFER)*XUSER_MAX_COUNT); m_ThumbnailBuffer=NULL; -#ifdef _DEBUG_MENUS_ENABLED +#ifdef _DEBUG_MENUS_ENABLED debugOverlayCreated = false; #endif @@ -361,7 +361,7 @@ HRESULT CConsoleMinecraftApp::RegisterXuiClasses() hr = CScene_NewUpdateMessage::Register(); if( FAILED( hr ) ) return hr; -#ifdef _DEBUG_MENUS_ENABLED +#ifdef _DEBUG_MENUS_ENABLED hr = CScene_DebugItemEditor::Register(); if( FAILED( hr ) ) return hr; hr = CScene_DebugTips::Register(); @@ -388,7 +388,7 @@ HRESULT CConsoleMinecraftApp::RegisterXuiClasses() if( FAILED( hr ) ) return hr; hr = CScene_HelpAndOptions::Register(); if( FAILED( hr ) ) return hr; - hr = CScene_HowToPlay::Register(); + hr = CScene_HowToPlay::Register(); if( FAILED( hr ) ) return hr; hr = CScene_HowToPlayMenu::Register(); if( FAILED( hr ) ) return hr; @@ -430,7 +430,7 @@ HRESULT CConsoleMinecraftApp::RegisterXuiClasses() hr = CXuiCtrlSlotItemListItem::Register(); if( FAILED( hr ) ) return hr; hr = CXuiSceneContainer::Register(); - if( FAILED( hr ) ) return hr; + if( FAILED( hr ) ) return hr; hr = CXuiSceneFurnace::Register(); if( FAILED( hr ) ) return hr; hr = CXuiSceneInventory::Register(); @@ -442,9 +442,9 @@ HRESULT CConsoleMinecraftApp::RegisterXuiClasses() hr = CScene_FullscreenProgress::Register(); if( FAILED( hr ) ) return hr; hr = CXuiCtrlLoadingProgress::Register(); - if( FAILED( hr ) ) return hr; + if( FAILED( hr ) ) return hr; hr = CXuiCtrlMinecraftSlot::Register(); - if( FAILED( hr ) ) return hr; + if( FAILED( hr ) ) return hr; hr = CXuiCtrlMinecraftPlayer::Register(); if( FAILED( hr ) ) return hr; hr = CScene_Death::Register(); @@ -472,7 +472,7 @@ HRESULT CConsoleMinecraftApp::RegisterXuiClasses() hr = CScene_InGameInfo::Register(); if( FAILED( hr ) ) return hr; hr = CScene_ConnectingProgress::Register(); - if( FAILED( hr ) ) return hr; + if( FAILED( hr ) ) return hr; hr = CXuiSceneBasePlayer::Register(); if( FAILED( hr ) ) return hr; hr = CScene_DLCOffers::Register(); @@ -525,7 +525,7 @@ HRESULT CConsoleMinecraftApp::RegisterXuiClasses() if( FAILED( hr) ) return hr; hr = CScene_Teleport::Register(); if( FAILED( hr) ) return hr; - + hr = CXuiCtrl4JIcon::Register(); if( FAILED( hr ) ) return hr; @@ -554,7 +554,7 @@ HRESULT CConsoleMinecraftApp::UnregisterXuiClasses() CScene_DebugSchematicCreator::Unregister(); CScene_DebugSetCamera::Unregister(); #endif -#ifdef _DEBUG_MENUS_ENABLED +#ifdef _DEBUG_MENUS_ENABLED CScene_DebugItemEditor::Unregister(); CScene_DebugTips::Unregister(); CScene_DebugOverlay::Unregister(); @@ -618,12 +618,12 @@ HRESULT CConsoleMinecraftApp::UnregisterXuiClasses() CScene_Credits::Unregister(); CScene_Leaderboards::Unregister(); CScene_Controls::Unregister(); - CScene_HowToPlay::Unregister(); + CScene_HowToPlay::Unregister(); CScene_HowToPlayMenu::Unregister(); CScene_HelpAndOptions::Unregister(); CScene_Main::Unregister(); CScene_Debug::Unregister(); - CScene_Intro::Unregister(); + CScene_Intro::Unregister(); CScene_SaveMessage::Unregister(); CScene_Reinstall::Unregister(); CScene_DLCMain::Unregister(); @@ -673,7 +673,7 @@ HRESULT CConsoleMinecraftApp::LoadXuiResources() OverrideFontRenderer(true); - const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string + const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; HRESULT hr; @@ -759,7 +759,7 @@ HRESULT CConsoleMinecraftApp::LoadXuiResources() } if(bOverrideLanguage==false) - { + { switch(dwLanguage) { case XC_LANGUAGE_ENGLISH: @@ -893,7 +893,7 @@ HRESULT CConsoleMinecraftApp::LoadXuiResources() // // dump out the text // int iStringC=0; // LPCWSTR lpTempString; - // + // // while((lpTempString=StringTable.Lookup(iStringC))!=NULL) // { // DebugPrintf("STRING %d = ",iStringC); @@ -948,7 +948,7 @@ HRESULT CConsoleMinecraftApp::LoadXuiResources() WCHAR szResourceLocator[ LOCATOR_SIZE ]; wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", L"media/"); HXUIOBJ hScene; - HRESULT hr = XuiSceneCreate(szResourceLocator,app.GetSceneName(eUIComponent_Chat, true,false), &idx, &hScene); + HRESULT hr = XuiSceneCreate(szResourceLocator,app.GetSceneName(eUIComponent_Chat, true,false), &idx, &hScene); if( FAILED(hr) ) app.FatalLoadError(); hr = XuiSceneNavigateForward(m_hCurrentChatScene[idx], FALSE, hScene, idx); @@ -987,7 +987,7 @@ HRESULT CConsoleMinecraftApp::LoadXuiResources() HRESULT CConsoleMinecraftApp::RegisterFont(eFont eFontLanguage,eFont eFontFallback, bool bSetAsDefault) { HRESULT hr=S_OK; - const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string + const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); @@ -997,7 +997,7 @@ HRESULT CConsoleMinecraftApp::RegisterFont(eFont eFontLanguage,eFont eFontFallba BOOL isMemoryResource; hr = XuiResourceOpenNoLoc(szResourceLocator, &fontTempResource, &isMemoryResource); if( FAILED(hr) ) app.FatalLoadError(); - XuiResourceClose(fontTempResource); + XuiResourceClose(fontTempResource); if(bSetAsDefault) { @@ -1112,7 +1112,7 @@ int CConsoleMinecraftApp::Callback_TMSPPReadXuidsFile(void *pParam,int iPad, int xmlParser.ParseXMLBuffer((CHAR *)pFileData->pbData,pFileData->dwSize); delete [] pFileData->pbData; delete [] pFileData; - } + } // change the state to the next action pClass->SetTMSAction(iPad,(eTMSAction)iUserData); @@ -1157,7 +1157,7 @@ int CConsoleMinecraftApp::Callback_TMSPPReadConfigFile(void *pParam,int iPad, in xmlParser.ParseXMLBuffer((CHAR *)pFileData->pbData,pFileData->dwSize); delete [] pFileData->pbData; delete [] pFileData; - } + } // change the state to the next action pClass->SetTMSAction(iPad,(eTMSAction)iUserData); @@ -1214,7 +1214,7 @@ bool CConsoleMinecraftApp::TMSPP_ReadBannedList(int iPad,eTMSAction NextAction) int CConsoleMinecraftApp::Callback_TMSPPReadBannedList(void *pParam,int iPad, int iUserData, C4JStorage::PTMSPP_FILEDATA pFileData,LPCSTR szFilename) { app.DebugPrintf("CConsoleMinecraftApp::Callback_TMSPPReadBannedList\n"); - + CConsoleMinecraftApp* pClass = (CConsoleMinecraftApp*)pParam; if(pFileData) @@ -1235,7 +1235,7 @@ int CConsoleMinecraftApp::Callback_TMSPPReadBannedList(void *pParam,int iPad, in delete [] pFileData; } ui.HandleTMSBanFileRetrieved(iPad); - + // change the state to the next action pClass->SetTMSAction(iPad,(eTMSAction)iUserData); @@ -1303,7 +1303,7 @@ int CConsoleMinecraftApp::Callback_TMSPPReadDLCFile(void *pParam,int iPad, int i } ui.HandleTMSDLCFileRetrieved(iPad); - + // change the state to the next action pClass->SetTMSAction(iPad,(eTMSAction)iUserData); @@ -1379,7 +1379,7 @@ int CConsoleMinecraftApp::CallbackBannedListFileFromTMS(LPVOID lpParam, WCHAR *w } app.SetTMSAction(iPad,(eTMSAction)iAction); - + ui.HandleTMSBanFileRetrieved(iPad); return 0; @@ -1485,7 +1485,7 @@ void CConsoleMinecraftApp::GetScreenshot(int iPad,PBYTE *pbData,DWORD *pdwSize) } } -#ifdef _DEBUG_MENUS_ENABLED +#ifdef _DEBUG_MENUS_ENABLED void CConsoleMinecraftApp::EnableDebugOverlay(bool enable,int iPad) { HRESULT hr = S_OK; @@ -1494,7 +1494,7 @@ void CConsoleMinecraftApp::EnableDebugOverlay(bool enable,int iPad) { const ULONG_PTR c_ModuleHandle = (ULONG_PTR)GetModuleHandle(NULL); - const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string + const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", L"media/"); @@ -1505,7 +1505,7 @@ void CConsoleMinecraftApp::EnableDebugOverlay(bool enable,int iPad) debugOverlayCreated = true; } if(enable) - { + { XuiElementSetUserFocus(m_hDebugOverlay, iPad); } else @@ -1596,9 +1596,8 @@ bool CConsoleMinecraftApp::IsSceneInStack(int iPad, EUIScene eScene) // If the game isn't running treat as user 0, otherwise map index directly from pad if( ( iPad != 255 ) && ( iPad >= 0 ) ) idx = iPad; } - AUTO_VAR(itEnd, m_sceneStack[idx].end()); - for (AUTO_VAR(it, m_sceneStack[idx].begin()); it != itEnd; it++) - //for(auto it = m_sceneStack[iPad].begin(), end = m_sceneStack[iPad].end(); it != end; ++it) + auto itEnd = m_sceneStack[idx].end(); + for (auto it = m_sceneStack[idx].begin(); it != itEnd; it++) { if(it->first == eScene) { @@ -1614,7 +1613,7 @@ WCHAR *CConsoleMinecraftApp::GetSceneName(EUIScene eScene,bool bAppendToName,boo { wcscpy(m_SceneName,wchSceneA[eScene]); if(bAppendToName) - { + { if(RenderManager.IsHiDef()) { if(bSplitscreenScene) @@ -1624,7 +1623,7 @@ WCHAR *CConsoleMinecraftApp::GetSceneName(EUIScene eScene,bool bAppendToName,boo } else { - // if it's low def, but widescreen, then use the small scenes + // if it's low def, but widescreen, then use the small scenes if(!RenderManager.IsWidescreen()) { wcscat(m_SceneName,L"_480"); @@ -1695,7 +1694,7 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in HXUIOBJ hScene; HRESULT hr; - const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string + const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; wsprintfW(szResourceLocator,L"section://%X,%s#%s",c_ModuleHandle,L"media", L"media/"); @@ -1780,7 +1779,7 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in XuiElementSetScale(hScene,&test); #endif - if( eScene == eUIComponent_TutorialPopup ) + if( eScene == eUIComponent_TutorialPopup ) { hr = XuiSceneNavigateForward(m_hCurrentTutorialScene[iPad], FALSE, hScene, XUSER_INDEX_NONE); if (FAILED(hr)) @@ -1841,7 +1840,7 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in { case eUIScene_PauseMenu: { - m_bPauseMenuDisplayed[iPad] = true; + m_bPauseMenuDisplayed[iPad] = true; Minecraft *pMinecraft = Minecraft::GetInstance(); if(pMinecraft != NULL && pMinecraft->localgameModes[iPad] != NULL ) @@ -1851,7 +1850,7 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in // This just allows it to be shown gameMode->getTutorial()->showTutorialPopup(false); } - } + } break; case eUIScene_Crafting2x2Menu: case eUIScene_Crafting3x3Menu: @@ -1869,7 +1868,7 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in // Intentional fall-through case eUIScene_DeathMenu: - case eUIScene_FullscreenProgress: + case eUIScene_FullscreenProgress: case eUIScene_SignEntryMenu: case eUIScene_EndPoem: m_bIgnoreAutosaveMenuDisplayed[iPad] = true; @@ -1878,7 +1877,7 @@ HRESULT CConsoleMinecraftApp::NavigateToScene(int iPad,EUIScene eScene, void *in switch(eScene) { - case eUIScene_FullscreenProgress: + case eUIScene_FullscreenProgress: case eUIScene_EndPoem: m_bIgnorePlayerJoinMenuDisplayed[iPad] = true; break; @@ -1992,7 +1991,7 @@ HRESULT CConsoleMinecraftApp::CloseXuiScenes(int iPad, bool forceUsePad /*= fals SetMenuDisplayed(iPad,false); // Hide the tutorial popup for this player - if(m_bGameStarted) + if(m_bGameStarted) { CScene_TutorialPopup::SetSceneVisible(iPad,FALSE); } @@ -2011,9 +2010,9 @@ HRESULT CConsoleMinecraftApp::CloseXuiScenes(int iPad, bool forceUsePad /*= fals if(g_NetworkManager.GetPlayerCount()>1) { for(int i=0;i<XUSER_MAX_COUNT;i++) - { + { if(pMinecraft->localplayers[i]) - { + { if(g_NetworkManager.IsLocalGame()) { ProfileManager.SetCurrentGameActivity(i,CONTEXT_PRESENCE_MULTIPLAYEROFFLINE,false); @@ -2064,7 +2063,7 @@ HRESULT CConsoleMinecraftApp::CloseAllPlayersXuiScenes() for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { CloseXuiScenes(idx, true); - ReloadChatScene(idx, false, true); + ReloadChatScene(idx, false, true); ReloadHudScene(idx, false, true); } @@ -2083,7 +2082,7 @@ HRESULT CConsoleMinecraftApp::CloseXuiScenesAndNavigateToScene(int iPad,EUIScene } hr=XuiSceneNavigateBackToFirst(m_hCurrentScene[idx],iPad); - m_hCurrentScene[idx]=m_hFirstScene[idx]; + m_hCurrentScene[idx]=m_hFirstScene[idx]; m_sceneStack[idx].clear(); CXuiSceneBase::ShowBackground(iPad, FALSE ); @@ -2280,7 +2279,7 @@ void CConsoleMinecraftApp::ReloadChatScene(int iPad, bool bJoining /*= false*/, textXOffset = 0; sceneWidth = XUI_BASE_SCENE_WIDTH_HALF; break; - default: + default: textXOffset = SAFEZONE_HALF_WIDTH; break; } @@ -2342,12 +2341,12 @@ void CConsoleMinecraftApp::AdjustSplitscreenScene(HXUIOBJ hScene,D3DXVECTOR3 *pv // move the scene down vec.y+=fSafeZoneY; break; - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: break; case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - // move the scene left + // move the scene left if(bAdjustXForSafeArea) vec.x-=fSafeZoneX; break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: @@ -2382,7 +2381,7 @@ void CConsoleMinecraftApp::AdjustSplitscreenScene(HXUIOBJ hScene,D3DXVECTOR3 *pv XuiElementGetPosition(hScene,pvOriginalPosition); vec=*pvOriginalPosition; - + if( pMinecraft->localplayers[iPad] != NULL ) { switch( pMinecraft->localplayers[iPad]->m_iScreenSection) @@ -2393,7 +2392,7 @@ void CConsoleMinecraftApp::AdjustSplitscreenScene(HXUIOBJ hScene,D3DXVECTOR3 *pv // 4J-PB - don't adjust things in horizontal splitscreen //vec.x+=fXAdjust; break; - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: // 4J-PB - don't adjust things in horizontal splitscreen //vec.x+=fXAdjust; break; @@ -2401,7 +2400,7 @@ void CConsoleMinecraftApp::AdjustSplitscreenScene(HXUIOBJ hScene,D3DXVECTOR3 *pv vec.x+=fXAdjust; break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - // move the scene left + // move the scene left vec.x-=fSafeZoneX-fXAdjust; break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: @@ -2462,12 +2461,12 @@ HRESULT CConsoleMinecraftApp::AdjustSplitscreenScene_PlayerChanged(HXUIOBJ hScen // move the scene down vec.y+=fSafeZoneY; break; - case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: + case C4JRender::VIEWPORT_TYPE_SPLIT_BOTTOM: break; case C4JRender::VIEWPORT_TYPE_SPLIT_LEFT: break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - // move the scene left + // move the scene left if(bAdjustXForSafeArea) vec.x-=fSafeZoneX; break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: @@ -2486,7 +2485,7 @@ HRESULT CConsoleMinecraftApp::AdjustSplitscreenScene_PlayerChanged(HXUIOBJ hScen // move the scene left if(bAdjustXForSafeArea) vec.x-=fSafeZoneX; break; - } + } XuiElementSetPosition(hScene,&vec); } @@ -2531,7 +2530,7 @@ HRESULT CConsoleMinecraftApp::AdjustSplitscreenScene_PlayerChanged(HXUIOBJ hScen vec.x+=fXAdjust; break; case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: - // move the scene left + // move the scene left vec.x-=fSafeZoneX-fXAdjust; break; case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_LEFT: @@ -2552,7 +2551,7 @@ HRESULT CConsoleMinecraftApp::AdjustSplitscreenScene_PlayerChanged(HXUIOBJ hScen // move the scene left vec.x-=fSafeZoneX-fXAdjust; break; - } + } XuiElementSetPosition(hScene,&vec); } @@ -2668,7 +2667,7 @@ void CConsoleMinecraftApp::FatalLoadError(void) aStrings[2] = L"Sair do Jogo"; } break; - case XC_LANGUAGE_TCHINESE: + case XC_LANGUAGE_TCHINESE: aStrings[0] = L"載入錯誤"; aStrings[1] = L"無法載入 Minecraft: Xbox 360 Editionï¼Œå› æ¤ç„¡æ³•繼續。"; aStrings[2] = L"é›¢é–‹éŠæˆ²"; @@ -2742,7 +2741,7 @@ int CConsoleMinecraftApp::RetrieveTMSFileListIndex(WCHAR *wchTMSFile) iIndex++; } wTemp[iIndex]=0; - + for(int i=0;i<MAX_EXTENSION_TYPES;i++) { if(wcscmp(&wchTMSFile[iIndex+1],wchExt[i])==0) @@ -2764,7 +2763,7 @@ int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR *wchTMSFile, eFileExtensionType int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR *wchTMSFile) { - const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string + const DWORD LOCATOR_SIZE = 256; // Use this to allocate space to hold a ResourceLocator string WCHAR szResourceLocator[ LOCATOR_SIZE ]; HRESULT hr; int iTMSFileIndex; @@ -2821,14 +2820,14 @@ TMS_FILE CConsoleMinecraftApp::TMSFileA[TMS_COUNT] = { L"SPM", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, { L"SPI", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, { L"SPG", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - + //themes { L"ThSt", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, { L"ThIr", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, { L"ThGo", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, { L"ThDi", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, { L"ThAw", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0}, - + //gamerpics { L"GPAn", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, { L"GPCo", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, @@ -2841,16 +2840,16 @@ TMS_FILE CConsoleMinecraftApp::TMSFileA[TMS_COUNT] = { L"GPMF", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, { L"GPMM", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, { L"GPSE", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, - + { L"GPOr", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, { L"GPMi", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, { L"GPMB", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, { L"GPBr", eFileExtensionType_PNG , eTMSFileType_MinecraftStore, NULL, 0, 0}, - + { L"GPM1", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0}, { L"GPM2", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0}, { L"GPM3", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0}, - + //avatar items { L"AH_0001", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AH_0002", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, @@ -2865,7 +2864,7 @@ TMS_FILE CConsoleMinecraftApp::TMSFileA[TMS_COUNT] = { L"AH_0011", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AH_0012", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AH_0013", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - + { L"AT_0001", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AT_0002", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AT_0003", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, @@ -2892,7 +2891,7 @@ TMS_FILE CConsoleMinecraftApp::TMSFileA[TMS_COUNT] = { L"AT_0024", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AT_0025", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AT_0026", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - + { L"AP_0001", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AP_0002", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AP_0003", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, @@ -2910,7 +2909,7 @@ TMS_FILE CConsoleMinecraftApp::TMSFileA[TMS_COUNT] = { L"AP_0016", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AP_0017", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AP_0018", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - + { L"AP_0019", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AP_0020", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AP_0021", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, @@ -2926,9 +2925,9 @@ TMS_FILE CConsoleMinecraftApp::TMSFileA[TMS_COUNT] = { L"AP_0031", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AP_0032", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"AP_0033", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, - + { L"AA_0001", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0 , 0 }, - + // Mash-up Packs { L"MPMA", eFileExtensionType_PNG, eTMSFileType_MinecraftStore, NULL, 0, 0 }, { L"MPMA", eFileExtensionType_DAT, eTMSFileType_TexturePack, NULL, 0, 1024 }, @@ -2989,7 +2988,7 @@ void CConsoleMinecraftApp::GetFileFromTPD(eTPDFileType eType,PBYTE pbData,DWORD uiDecompSize=*(unsigned int *)pbPos; uiCompSize=((unsigned int *)pbPos)[1]; - // second is the icon + // second is the icon if(eType==eTPDFileType_Icon) { *pdwBytes= uiDecompSize; @@ -3008,7 +3007,7 @@ void CConsoleMinecraftApp::GetFileFromTPD(eTPDFileType eType,PBYTE pbData,DWORD uiDecompSize=*(unsigned int *)pbPos; uiCompSize=((unsigned int *)pbPos)[1]; - // third is the comparison + // third is the comparison if(eType==eTPDFileType_Comparison) { *pdwBytes= uiDecompSize; @@ -3024,11 +3023,11 @@ void CConsoleMinecraftApp::GetFileFromTPD(eTPDFileType eType,PBYTE pbData,DWORD LPCWSTR CConsoleMinecraftApp::GetString(int iID) -{ +{ return StringTable.Lookup(iID); } -CXuiStringTable *CConsoleMinecraftApp::GetStringTable() -{ +CXuiStringTable *CConsoleMinecraftApp::GetStringTable() +{ return &StringTable; } diff --git a/Minecraft.Client/compile_flags.txt b/Minecraft.Client/compile_flags.txt new file mode 100644 index 00000000..5aa08a43 --- /dev/null +++ b/Minecraft.Client/compile_flags.txt @@ -0,0 +1,22 @@ +-xc++ +-m64 +-std=c++14 +-Wno-unused-includes +-Wno-unsafe-buffer-usage-in-libc-call +-Wno-unsafe-buffer-usage +-Wno-unused-macros +-Wno-c++98-compat +-Wno-c++98-compat-pedantic +-Wno-pre-c++14-compat +-D_LARGE_WORLDS +-D_DEBUG_MENUS_ENABLED +-D_LIB +-D_CRT_NON_CONFORMING_SWPRINTFS +-D_CRT_SECURE_NO_WARNINGS +-D_WINDOWS64 +-I +./Xbox/Sentient/Include +-I +../Minecraft.World/x64headers +-I +./ diff --git a/Minecraft.Client/stdafx.h b/Minecraft.Client/stdafx.h index 25d93572..7614d058 100644 --- a/Minecraft.Client/stdafx.h +++ b/Minecraft.Client/stdafx.h @@ -27,14 +27,13 @@ #include "PS3Maths.h" #elif defined __ORBIS__ -#define AUTO_VAR(_var, _val) auto _var = _val #include <stdio.h> #include <stdlib.h> #include <scebase.h> #include <kernel.h> #include <unordered_map> #include <unordered_set> -#include <vector> +#include <vector> #include <fios2.h> #include <message_dialog.h> #include <game_live_streaming.h> @@ -49,13 +48,12 @@ #include <kernel.h> #include <unordered_map> #include <unordered_set> -#include <vector> +#include <vector> #include <touch.h> #include "PSVitaTypes.h" #include "PSVitaStubs.h" #include "PSVitaMaths.h" #else -#define AUTO_VAR(_var, _val) auto _var = _val #include <unordered_map> #include <unordered_set> #include <vector> @@ -72,7 +70,7 @@ typedef unsigned __int64 __uint64; // TODO: reference additional headers your program requires here #include <d3d11.h> #include <DirectXMath.h> -using namespace DirectX; +using namespace DirectX; #define HRESULT_SUCCEEDED(hr) (((HRESULT)(hr)) >= 0) @@ -87,7 +85,7 @@ using namespace DirectX; #include <DirectXMath.h> #include <ppltasks.h> #include <collection.h> -using namespace DirectX; +using namespace DirectX; #include <pix.h> #include "DurangoStubs.h" #define HRESULT_SUCCEEDED(hr) (((HRESULT)(hr)) >= 0) @@ -182,12 +180,12 @@ typedef XUID GameSessionUID; #include "Windows64\4JLibs\inc\4J_Storage.h" #include "Windows64\KeyboardMouseInput.h" #elif defined __PSVITA__ - #include "PSVita\4JLibs\inc\4J_Input.h" + #include "PSVita\4JLibs\inc\4J_Input.h" #include "PSVita\4JLibs\inc\4J_Profile.h" #include "PSVita\4JLibs\inc\4J_Render.h" #include "PSVita\4JLibs\inc\4J_Storage.h" #else - #include "Orbis\4JLibs\inc\4J_Input.h" + #include "Orbis\4JLibs\inc\4J_Input.h" #include "Orbis\4JLibs\inc\4J_Profile.h" #include "Orbis\4JLibs\inc\4J_Render.h" #include "Orbis\4JLibs\inc\4J_Storage.h" @@ -258,7 +256,7 @@ typedef XUID GameSessionUID; #include "Durango\Sentient\MinecraftTelemetry.h" #include "DurangoMedia\strings.h" #include "Durango\Durango_App.h" - #include "Durango\Sentient\DynamicConfigurations.h" + #include "Durango\Sentient\DynamicConfigurations.h" #include "Durango\Sentient\TelemetryEnum.h" #include "Durango\Sentient\SentientTelemetryCommon.h" #include "Durango\PresenceIds.h" @@ -276,7 +274,7 @@ typedef XUID GameSessionUID; #include "Windows64\Sentient\DynamicConfigurations.h" #include "Windows64\Sentient\SentientTelemetryCommon.h" #include "Windows64\GameConfig\Minecraft.spa.h" - #include "Windows64\XML\ATGXmlParser.h" + #include "Windows64\XML\ATGXmlParser.h" #include "Windows64\Social\SocialManager.h" #include "Common\Audio\SoundEngine.h" #include "Windows64\Iggy\include\iggy.h" @@ -303,7 +301,7 @@ typedef XUID GameSessionUID; #include "Orbis\Sentient\DynamicConfigurations.h" #include "Orbis\GameConfig\Minecraft.spa.h" #include "OrbisMedia\4J_strings.h" - #include "Orbis\XML\ATGXmlParser.h" + #include "Orbis\XML\ATGXmlParser.h" #include "Windows64\Social\SocialManager.h" #include "Common\Audio\SoundEngine.h" #include "Orbis\Iggy\include\iggy.h" diff --git a/Minecraft.World/AABB.cpp b/Minecraft.World/AABB.cpp index 8bc8e140..f8e13497 100644 --- a/Minecraft.World/AABB.cpp +++ b/Minecraft.World/AABB.cpp @@ -47,20 +47,20 @@ void AABB::ReleaseThreadStorage() delete tls; } -AABB *AABB::newPermanent(double x0, double y0, double z0, double x1, double y1, double z1) +AABB *AABB::newPermanent(double x0, double y0, double z0, double x1, double y1, double z1) { return new AABB(x0, y0, z0, x1, y1, z1); } -void AABB::clearPool() +void AABB::clearPool() { } -void AABB::resetPool() +void AABB::resetPool() { } -AABB *AABB::newTemp(double x0, double y0, double z0, double x1, double y1, double z1) +AABB *AABB::newTemp(double x0, double y0, double z0, double x1, double y1, double z1) { ThreadStorage *tls = (ThreadStorage *)TlsGetValue(tlsIdx); AABB *thisAABB = &tls->pool[tls->poolPointer]; @@ -69,7 +69,7 @@ AABB *AABB::newTemp(double x0, double y0, double z0, double x1, double y1, doubl return thisAABB; } -AABB::AABB(double x0, double y0, double z0, double x1, double y1, double z1) +AABB::AABB(double x0, double y0, double z0, double x1, double y1, double z1) { this->x0 = x0; this->y0 = y0; @@ -80,7 +80,7 @@ AABB::AABB(double x0, double y0, double z0, double x1, double y1, double z1) } -AABB *AABB::set(double x0, double y0, double z0, double x1, double y1, double z1) +AABB *AABB::set(double x0, double y0, double z0, double x1, double y1, double z1) { this->x0 = x0; this->y0 = y0; @@ -91,7 +91,7 @@ AABB *AABB::set(double x0, double y0, double z0, double x1, double y1, double z1 return this; } -AABB *AABB::expand(double xa, double ya, double za) +AABB *AABB::expand(double xa, double ya, double za) { double _x0 = x0; double _y0 = y0; @@ -112,7 +112,7 @@ AABB *AABB::expand(double xa, double ya, double za) return AABB::newTemp(_x0, _y0, _z0, _x1, _y1, _z1); } -AABB *AABB::grow(double xa, double ya, double za) +AABB *AABB::grow(double xa, double ya, double za) { double _x0 = x0 - xa; double _y0 = y0 - ya; @@ -136,22 +136,22 @@ AABB *AABB::minmax(AABB *other) return newTemp(_x0, _y0, _z0, _x1, _y1, _z1); } -AABB *AABB::cloneMove(double xa, double ya, double za) +AABB *AABB::cloneMove(double xa, double ya, double za) { return AABB::newTemp(x0 + xa, y0 + ya, z0 + za, x1 + xa, y1 + ya, z1 + za); } -double AABB::clipXCollide(AABB *c, double xa) +double AABB::clipXCollide(AABB *c, double xa) { if (c->y1 <= y0 || c->y0 >= y1) return xa; if (c->z1 <= z0 || c->z0 >= z1) return xa; - if (xa > 0 && c->x1 <= x0) + if (xa > 0 && c->x1 <= x0) { double max = x0 - c->x1; if (max < xa) xa = max; } - if (xa < 0 && c->x0 >= x1) + if (xa < 0 && c->x0 >= x1) { double max = x1 - c->x0; if (max > xa) xa = max; @@ -165,12 +165,12 @@ double AABB::clipYCollide(AABB *c, double ya) if (c->x1 <= x0 || c->x0 >= x1) return ya; if (c->z1 <= z0 || c->z0 >= z1) return ya; - if (ya > 0 && c->y1 <= y0) + if (ya > 0 && c->y1 <= y0) { double max = y0 - c->y1; if (max < ya) ya = max; } - if (ya < 0 && c->y0 >= y1) + if (ya < 0 && c->y0 >= y1) { double max = y1 - c->y0; if (max > ya) ya = max; @@ -179,17 +179,17 @@ double AABB::clipYCollide(AABB *c, double ya) return ya; } -double AABB::clipZCollide(AABB *c, double za) +double AABB::clipZCollide(AABB *c, double za) { if (c->x1 <= x0 || c->x0 >= x1) return za; if (c->y1 <= y0 || c->y0 >= y1) return za; - if (za > 0 && c->z1 <= z0) + if (za > 0 && c->z1 <= z0) { double max = z0 - c->z1; if (max < za) za = max; } - if (za < 0 && c->z0 >= z1) + if (za < 0 && c->z0 >= z1) { double max = z1 - c->z0; if (max > za) za = max; @@ -198,7 +198,7 @@ double AABB::clipZCollide(AABB *c, double za) return za; } -bool AABB::intersects(AABB *c) +bool AABB::intersects(AABB *c) { if (c->x1 <= x0 || c->x0 >= x1) return false; if (c->y1 <= y0 || c->y0 >= y1) return false; @@ -206,7 +206,7 @@ bool AABB::intersects(AABB *c) return true; } -bool AABB::intersectsInner(AABB *c) +bool AABB::intersectsInner(AABB *c) { if (c->x1 < x0 || c->x0 > x1) return false; if (c->y1 < y0 || c->y0 > y1) return false; @@ -214,7 +214,7 @@ bool AABB::intersectsInner(AABB *c) return true; } -AABB *AABB::move(double xa, double ya, double za) +AABB *AABB::move(double xa, double ya, double za) { x0 += xa; y0 += ya; @@ -225,7 +225,7 @@ AABB *AABB::move(double xa, double ya, double za) return this; } -bool AABB::intersects(double x02, double y02, double z02, double x12, double y12, double z12) +bool AABB::intersects(double x02, double y02, double z02, double x12, double y12, double z12) { if (x12 <= x0 || x02 >= x1) return false; if (y12 <= y0 || y02 >= y1) return false; @@ -233,7 +233,7 @@ bool AABB::intersects(double x02, double y02, double z02, double x12, double y12 return true; } -bool AABB::contains(Vec3 *p) +bool AABB::contains(Vec3 *p) { if (p->x <= x0 || p->x >= x1) return false; if (p->y <= y0 || p->y >= y1) return false; @@ -242,7 +242,7 @@ bool AABB::contains(Vec3 *p) } // 4J Added -bool AABB::containsIncludingLowerBound(Vec3 *p) +bool AABB::containsIncludingLowerBound(Vec3 *p) { if (p->x < x0 || p->x >= x1) return false; if (p->y < y0 || p->y >= y1) return false; @@ -250,7 +250,7 @@ bool AABB::containsIncludingLowerBound(Vec3 *p) return true; } -double AABB::getSize() +double AABB::getSize() { double xs = x1 - x0; double ys = y1 - y0; @@ -258,7 +258,7 @@ double AABB::getSize() return (xs + ys + zs) / 3.0f; } -AABB *AABB::shrink(double xa, double ya, double za) +AABB *AABB::shrink(double xa, double ya, double za) { double _x0 = x0 + xa; double _y0 = y0 + ya; @@ -270,12 +270,12 @@ AABB *AABB::shrink(double xa, double ya, double za) return AABB::newTemp(_x0, _y0, _z0, _x1, _y1, _z1); } -AABB *AABB::copy() +AABB *AABB::copy() { return AABB::newTemp(x0, y0, z0, x1, y1, z1); } -HitResult *AABB::clip(Vec3 *a, Vec3 *b) +HitResult *AABB::clip(Vec3 *a, Vec3 *b) { Vec3 *xh0 = a->clipX(b, x0); Vec3 *xh1 = a->clipX(b, x1); @@ -317,26 +317,26 @@ HitResult *AABB::clip(Vec3 *a, Vec3 *b) } -bool AABB::containsX(Vec3 *v) +bool AABB::containsX(Vec3 *v) { if (v == NULL) return false; return v->y >= y0 && v->y <= y1 && v->z >= z0 && v->z <= z1; } -bool AABB::containsY(Vec3 *v) +bool AABB::containsY(Vec3 *v) { if (v == NULL) return false; return v->x >= x0 && v->x <= x1 && v->z >= z0 && v->z <= z1; } -bool AABB::containsZ(Vec3 *v) +bool AABB::containsZ(Vec3 *v) { if (v == NULL) return false; return v->x >= x0 && v->x <= x1 && v->y >= y0 && v->y <= y1; } -void AABB::set(AABB *b) +void AABB::set(AABB *b) { x0 = b->x0; y0 = b->y0; @@ -346,9 +346,9 @@ void AABB::set(AABB *b) z1 = b->z1; } -wstring AABB::toString() +wstring AABB::toString() { - return L"box[" + _toString<double>(x0) + L", " + _toString<double>(y0) + L", " + _toString<double>(z0) + L" -> " + - _toString<double>(x1) + L", " + _toString<double>(y1) + L", " + _toString<double>(z1) + L"]"; + return L"box[" + std::to_wstring(x0) + L", " + std::to_wstring(y0) + L", " + std::to_wstring(z0) + L" -> " + + std::to_wstring(x1) + L", " + std::to_wstring(y1) + L", " + std::to_wstring(z1) + L"]"; } diff --git a/Minecraft.World/AbstractContainerMenu.cpp b/Minecraft.World/AbstractContainerMenu.cpp index 082e8008..57b0b177 100644 --- a/Minecraft.World/AbstractContainerMenu.cpp +++ b/Minecraft.World/AbstractContainerMenu.cpp @@ -48,27 +48,25 @@ void AbstractContainerMenu::addSlotListener(ContainerListener *listener) void AbstractContainerMenu::removeSlotListener(ContainerListener *listener) { - AUTO_VAR(it, std::find(containerListeners.begin(), containerListeners.end(), listener) ); + auto it = std::find(containerListeners.begin(), containerListeners.end(), listener); if(it != containerListeners.end()) containerListeners.erase(it); } vector<shared_ptr<ItemInstance> > *AbstractContainerMenu::getItems() { vector<shared_ptr<ItemInstance> > *items = new vector<shared_ptr<ItemInstance> >(); - AUTO_VAR(itEnd, slots.end()); - for (AUTO_VAR(it, slots.begin()); it != itEnd; it++) + for ( Slot* it : slots ) { - items->push_back((*it)->getItem()); + items->push_back(it->getItem()); } return items; } void AbstractContainerMenu::sendData(int id, int value) { - AUTO_VAR(itEnd, containerListeners.end()); - for (AUTO_VAR(it, containerListeners.begin()); it != itEnd; it++) + for ( auto& it : containerListeners ) { - (*it)->setContainerData(this, id, value); + it->setContainerData(this, id, value); } } @@ -86,10 +84,9 @@ void AbstractContainerMenu::broadcastChanges() lastSlots[i] = expected; m_bNeedsRendered = true; - AUTO_VAR(itEnd, containerListeners.end()); - for (AUTO_VAR(it, containerListeners.begin()); it != itEnd; it++) + for ( auto& it : containerListeners ) { - (*it)->slotChanged(this, i, expected); + it->slotChanged(this, i, expected); } } } @@ -122,10 +119,8 @@ bool AbstractContainerMenu::clickMenuButton(shared_ptr<Player> player, int butto Slot *AbstractContainerMenu::getSlotFor(shared_ptr<Container> c, int index) { - AUTO_VAR(itEnd, slots.end()); - for (AUTO_VAR(it, slots.begin()); it != itEnd; it++) + for ( Slot *slot : slots ) { - Slot *slot = *it; //slots->at(i); if (slot->isAt(c, index)) { return slot; @@ -197,10 +192,9 @@ shared_ptr<ItemInstance> AbstractContainerMenu::clicked(int slotIndex, int butto shared_ptr<ItemInstance> source = inventory->getCarried()->copy(); int remaining = inventory->getCarried()->count; - for(AUTO_VAR(it, quickcraftSlots.begin()); it != quickcraftSlots.end(); ++it) + for ( Slot *slot : quickcraftSlots ) { - Slot *slot = *it; - if (slot != NULL && canItemQuickReplace(slot, inventory->getCarried(), true) && slot->mayPlace(inventory->getCarried()) && inventory->getCarried()->count >= quickcraftSlots.size() && canDragTo(slot)) + if (slot != nullptr && canItemQuickReplace(slot, inventory->getCarried(), true) && slot->mayPlace(inventory->getCarried()) && inventory->getCarried()->count >= quickcraftSlots.size() && canDragTo(slot)) { shared_ptr<ItemInstance> copy = source->copy(); int carry = slot->hasItem() ? slot->getItem()->count : 0; @@ -582,7 +576,7 @@ void AbstractContainerMenu::setSynched(shared_ptr<Player> player, bool synched) { if (synched) { - AUTO_VAR(it, unSynchedPlayers.find(player)); + auto it = unSynchedPlayers.find(player); if(it != unSynchedPlayers.end()) unSynchedPlayers.erase( it ); } diff --git a/Minecraft.World/Animal.cpp b/Minecraft.World/Animal.cpp index 31de7d75..ecda8fc5 100644 --- a/Minecraft.World/Animal.cpp +++ b/Minecraft.World/Animal.cpp @@ -229,51 +229,58 @@ shared_ptr<Entity> Animal::findAttackTarget() if (getInLoveValue() > 0) { vector<shared_ptr<Entity> > *others = level->getEntitiesOfClass(typeid(*this), bb->grow(r, r, r)); - //for (int i = 0; i < others->size(); i++) - for(AUTO_VAR(it, others->begin()); it != others->end(); ++it) + if ( others ) { - shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(*it); - if (p != shared_from_this() && p->getInLoveValue() > 0) + for (auto& it : *others) { - delete others; - return p; + shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(it); + if (p != shared_from_this() && p->getInLoveValue() > 0) + { + delete others; + return p; + } } + delete others; } - delete others; } else { if (getAge() == 0) { vector<shared_ptr<Entity> > *players = level->getEntitiesOfClass(typeid(Player), bb->grow(r, r, r)); - //for (int i = 0; i < players.size(); i++) - for(AUTO_VAR(it, players->begin()); it != players->end(); ++it) + if ( players ) { - setDespawnProtected(); - - shared_ptr<Player> p = dynamic_pointer_cast<Player>(*it); - if (p->getSelectedItem() != NULL && this->isFood(p->getSelectedItem())) + for (auto& it : *players) { - delete players; - return p; + setDespawnProtected(); + + shared_ptr<Player> p = dynamic_pointer_cast<Player>(it); + if (p->getSelectedItem() != NULL && this->isFood(p->getSelectedItem())) + { + delete players; + return p; + } } + delete players; } - delete players; } else if (getAge() > 0) { vector<shared_ptr<Entity> > *others = level->getEntitiesOfClass(typeid(*this), bb->grow(r, r, r)); - //for (int i = 0; i < others.size(); i++) - for(AUTO_VAR(it, others->begin()); it != others->end(); ++it) + + if ( others ) { - shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(*it); - if (p != shared_from_this() && p->getAge() < 0) + for (auto& it : *others) { - delete others; - return p; + shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(it); + if (p != shared_from_this() && p->getAge() < 0) + { + delete others; + return p; + } } + delete others; } - delete others; } } return nullptr; diff --git a/Minecraft.World/AnvilMenu.cpp b/Minecraft.World/AnvilMenu.cpp index 2ef00e3e..83d38142 100644 --- a/Minecraft.World/AnvilMenu.cpp +++ b/Minecraft.World/AnvilMenu.cpp @@ -134,64 +134,67 @@ void AnvilMenu::createResult() unordered_map<int, int> *additionalEnchantments = EnchantmentHelper::getEnchantments(addition); - for(AUTO_VAR(it, additionalEnchantments->begin()); it != additionalEnchantments->end(); ++it) + if ( additionalEnchantments ) { - int id = it->first; - Enchantment *enchantment = Enchantment::enchantments[id]; - AUTO_VAR(localIt, enchantments->find(id)); - int current = localIt != enchantments->end() ? localIt->second : 0; - int level = it->second; - level = (current == level) ? level += 1 : max(level, current); - int extra = level - current; - bool compatible = enchantment->canEnchant(input); - - if (player->abilities.instabuild || input->id == EnchantedBookItem::enchantedBook_Id) compatible = true; - - for(AUTO_VAR(it2, enchantments->begin()); it2 != enchantments->end(); ++it2) + for (const auto& it : *additionalEnchantments) { - int other = it2->first; - if (other != id && !enchantment->isCompatibleWith(Enchantment::enchantments[other])) + int id = it.first; + Enchantment* enchantment = Enchantment::enchantments[id]; + auto localIt = enchantments->find(id); + int current = localIt != enchantments->end() ? localIt->second : 0; + int level = it.second; + level = (current == level) ? level += 1 : std::max<int>(level, current); + int extra = level - current; + bool compatible = enchantment->canEnchant(input); + + if (player->abilities.instabuild || input->id == EnchantedBookItem::enchantedBook_Id) compatible = true; + + for (auto& it2 : *enchantments) { - compatible = false; - - price += extra; - if (DEBUG_COST) + int other = it2.first; + if (other != id && !enchantment->isCompatibleWith(Enchantment::enchantments[other])) { - app.DebugPrintf("Enchantment incompatibility fee; price is now %d (went up by %d)\n", price, extra); + compatible = false; + + price += extra; + if (DEBUG_COST) + { + app.DebugPrintf("Enchantment incompatibility fee; price is now %d (went up by %d)\n", price, extra); + } } } - } - if (!compatible) continue; - if (level > enchantment->getMaxLevel()) level = enchantment->getMaxLevel(); - (*enchantments)[id] = level; - int fee = 0; + if (!compatible) continue; + if (level > enchantment->getMaxLevel()) level = enchantment->getMaxLevel(); + (*enchantments)[id] = level; + int fee = 0; - switch (enchantment->getFrequency()) - { - case Enchantment::FREQ_COMMON: - fee = 1; - break; - case Enchantment::FREQ_UNCOMMON: - fee = 2; - break; - case Enchantment::FREQ_RARE: - fee = 4; - break; - case Enchantment::FREQ_VERY_RARE: - fee = 8; - break; - } + switch (enchantment->getFrequency()) + { + case Enchantment::FREQ_COMMON: + fee = 1; + break; + case Enchantment::FREQ_UNCOMMON: + fee = 2; + break; + case Enchantment::FREQ_RARE: + fee = 4; + break; + case Enchantment::FREQ_VERY_RARE: + fee = 8; + break; + } - if (usingBook) fee = max(1, fee / 2); + if (usingBook) fee = max(1, fee / 2); - price += fee * extra; - if (DEBUG_COST) - { - app.DebugPrintf("Enchantment increase fee; price is now %d (went up by %d)\n", price, fee*extra); + price += fee * extra; + if (DEBUG_COST) + { + app.DebugPrintf("Enchantment increase fee; price is now %d (went up by %d)\n", price, fee * extra); + } } + delete additionalEnchantments; } - delete additionalEnchantments; } } @@ -233,11 +236,11 @@ void AnvilMenu::createResult() } int count = 0; - for(AUTO_VAR(it, enchantments->begin()); it != enchantments->end(); ++it) + for( const auto& it : *enchantments ) { - int id = it->first; + int id = it.first; Enchantment *enchantment = Enchantment::enchantments[id]; - int level = it->second; + int level = it.second; int fee = 0; count++; @@ -258,7 +261,7 @@ void AnvilMenu::createResult() break; } - if (usingBook) fee = max(1, fee / 2); + if (usingBook) fee = std::max<int>(1, fee / 2); tax += count + level * fee; if (DEBUG_COST) diff --git a/Minecraft.World/ArmorDyeRecipe.cpp b/Minecraft.World/ArmorDyeRecipe.cpp index 0f9c8955..c2f681fa 100644 --- a/Minecraft.World/ArmorDyeRecipe.cpp +++ b/Minecraft.World/ArmorDyeRecipe.cpp @@ -173,15 +173,11 @@ void ArmorDyeRecipe::requires(INGREDIENTS_REQUIRED *pIngReq) ZeroMemory(TempIngReq.uiGridA,sizeof(unsigned int)*9); #if 0 - AUTO_VAR(citEnd, ingredients->end()); - - for (vector<ItemInstance *>::const_iterator ingredient = ingredients->begin(); ingredient != citEnd; ingredient++) + for ( ItemInstance *expected : *ingredients ) { - ItemInstance *expected = *ingredient; - if (expected!=NULL) { - int iAuxVal = (*ingredient)->getAuxValue(); + int iAuxVal = expected->getAuxValue(); TempIngReq.uiGridA[iCount++]=expected->id | iAuxVal<<24; // 4J-PB - put the ingredients in boxes 1,2,4,5 so we can see them in a 2x2 crafting screen if(iCount==2) iCount=3; diff --git a/Minecraft.World/Arrow.cpp b/Minecraft.World/Arrow.cpp index 743f966b..ab942aac 100644 --- a/Minecraft.World/Arrow.cpp +++ b/Minecraft.World/Arrow.cpp @@ -249,10 +249,8 @@ void Arrow::tick() shared_ptr<Entity> hitEntity = nullptr; vector<shared_ptr<Entity> > *objects = level->getEntities(shared_from_this(), this->bb->expand(xd, yd, zd)->grow(1, 1, 1)); double nearest = 0; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) + for ( auto& e : *objects ) { - shared_ptr<Entity> e = *it; //objects->at(i); if (!e->isPickable() || (e == owner && flightTime < 5)) continue; float rr = 0.3f; diff --git a/Minecraft.World/BaseAttributeMap.cpp b/Minecraft.World/BaseAttributeMap.cpp index 5a920f24..8fb1b1f1 100644 --- a/Minecraft.World/BaseAttributeMap.cpp +++ b/Minecraft.World/BaseAttributeMap.cpp @@ -4,9 +4,9 @@ BaseAttributeMap::~BaseAttributeMap() { - for(AUTO_VAR(it,attributesById.begin()); it != attributesById.end(); ++it) + for( auto& it : attributesById ) { - delete it->second; + delete it.second; } } @@ -17,7 +17,7 @@ AttributeInstance *BaseAttributeMap::getInstance(Attribute *attribute) AttributeInstance *BaseAttributeMap::getInstance(eATTRIBUTE_ID id) { - AUTO_VAR(it,attributesById.find(id)); + auto it = attributesById.find(id); if(it != attributesById.end()) { return it->second; @@ -30,9 +30,9 @@ AttributeInstance *BaseAttributeMap::getInstance(eATTRIBUTE_ID id) void BaseAttributeMap::getAttributes(vector<AttributeInstance *>& atts) { - for(AUTO_VAR(it,attributesById.begin()); it != attributesById.end(); ++it) + for( auto& it : attributesById ) { - atts.push_back(it->second); + atts.push_back(it.second); } } @@ -43,40 +43,44 @@ void BaseAttributeMap::onAttributeModified(ModifiableAttributeInstance *attribut void BaseAttributeMap::removeItemModifiers(shared_ptr<ItemInstance> item) { attrAttrModMap *modifiers = item->getAttributeModifiers(); - - for(AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + if ( modifiers ) { - AttributeInstance *attribute = getInstance(it->first); - AttributeModifier *modifier = it->second; - - if (attribute != NULL) + for (auto& it : *modifiers) { - attribute->removeModifier(modifier); + AttributeInstance* attribute = getInstance(it.first); + AttributeModifier* modifier = it.second; + + if (attribute != NULL) + { + attribute->removeModifier(modifier); + } + + delete modifier; } - delete modifier; + delete modifiers; } - - delete modifiers; } void BaseAttributeMap::addItemModifiers(shared_ptr<ItemInstance> item) { attrAttrModMap *modifiers = item->getAttributeModifiers(); - - for(AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + if ( modifiers ) { - AttributeInstance *attribute = getInstance(it->first); - AttributeModifier *modifier = it->second; - - if (attribute != NULL) + for (auto& it : *modifiers) { - attribute->removeModifier(modifier); - attribute->addModifier(new AttributeModifier(*modifier)); + AttributeInstance* attribute = getInstance(it.first); + AttributeModifier* modifier = it.second; + + if (attribute != NULL) + { + attribute->removeModifier(modifier); + attribute->addModifier(new AttributeModifier(*modifier)); + } + + delete modifier; } - - delete modifier; - } - delete modifiers; + delete modifiers; + } } diff --git a/Minecraft.World/BaseMobSpawner.cpp b/Minecraft.World/BaseMobSpawner.cpp index 887177ed..0e37e444 100644 --- a/Minecraft.World/BaseMobSpawner.cpp +++ b/Minecraft.World/BaseMobSpawner.cpp @@ -27,9 +27,9 @@ BaseMobSpawner::~BaseMobSpawner() { if(spawnPotentials) { - for(AUTO_VAR(it,spawnPotentials->begin()); it != spawnPotentials->end(); ++it) + for( auto& it : *spawnPotentials ) { - delete *it; + delete it; } delete spawnPotentials; } @@ -137,12 +137,14 @@ shared_ptr<Entity> BaseMobSpawner::loadDataAndAddEntity(shared_ptr<Entity> entit entity->save(data); vector<Tag *> *tags = getNextSpawnData()->tag->getAllTags(); - for (AUTO_VAR(it, tags->begin()); it != tags->end(); ++it) + if ( tags ) { - Tag *tag = *it; - data->put(tag->getName(), tag->copy()); + for (auto& tag : *tags) + { + data->put(tag->getName(), tag->copy()); + } + delete tags; } - delete tags; entity->load(data); if (entity->level != NULL) entity->level->addEntity(entity); @@ -159,12 +161,14 @@ shared_ptr<Entity> BaseMobSpawner::loadDataAndAddEntity(shared_ptr<Entity> entit mount->save(mountData); vector<Tag *> *ridingTags = ridingTag->getAllTags(); - for (AUTO_VAR(it, ridingTags->begin()); it != ridingTags->end(); ++it) + if ( ridingTags ) { - Tag *tag = *it; - mountData->put(tag->getName(), tag->copy()); + for (auto& tag : *ridingTags) + { + mountData->put(tag->getName(), tag->copy()); + } + delete ridingTags; } - delete ridingTags; mount->load(mountData); mount->moveTo(rider->x, rider->y, rider->z, rider->yRot, rider->xRot); @@ -274,11 +278,10 @@ void BaseMobSpawner::save(CompoundTag *tag) { ListTag<CompoundTag> *list = new ListTag<CompoundTag>(); - if (spawnPotentials != NULL && spawnPotentials->size() > 0) + if (spawnPotentials && spawnPotentials->size() > 0) { - for (AUTO_VAR(it, spawnPotentials->begin()); it != spawnPotentials->end(); ++it) + for ( auto& data : *spawnPotentials ) { - SpawnData *data = *it; list->add(data->save()); } } diff --git a/Minecraft.World/BaseRailTile.cpp b/Minecraft.World/BaseRailTile.cpp index 8ec23fd6..db854bb3 100644 --- a/Minecraft.World/BaseRailTile.cpp +++ b/Minecraft.World/BaseRailTile.cpp @@ -142,10 +142,8 @@ bool BaseRailTile::Rail::connectsTo(Rail *rail) { if(m_bValidRail) { - AUTO_VAR(itEnd, connections.end()); - for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) + for ( const auto& p : connections ) { - TilePos *p = *it; //connections[i]; if (p->x == rail->x && p->z == rail->z) { return true; @@ -159,10 +157,8 @@ bool BaseRailTile::Rail::hasConnection(int x, int y, int z) { if(m_bValidRail) { - AUTO_VAR(itEnd, connections.end()); - for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) + for ( const auto& p : connections ) { - TilePos *p = *it; //connections[i]; if (p->x == x && p->z == z) { return true; @@ -332,10 +328,9 @@ void BaseRailTile::Rail::place(bool hasSignal, bool first) { level->setData(x, y, z, data, Tile::UPDATE_ALL); - AUTO_VAR(itEnd, connections.end()); - for (AUTO_VAR(it, connections.begin()); it != itEnd; it++) + for ( auto& it : connections ) { - Rail *neighbor = getRail(*it); + Rail *neighbor = getRail(it); if (neighbor == NULL) continue; neighbor->removeSoftConnections(); diff --git a/Minecraft.World/BeaconTileEntity.cpp b/Minecraft.World/BeaconTileEntity.cpp index 9cfb0d67..d80eb906 100644 --- a/Minecraft.World/BeaconTileEntity.cpp +++ b/Minecraft.World/BeaconTileEntity.cpp @@ -80,21 +80,26 @@ void BeaconTileEntity::applyEffects() AABB *bb = AABB::newTemp(x, y, z, x + 1, y + 1, z + 1)->grow(range, range, range); bb->y1 = level->getMaxBuildHeight(); vector<shared_ptr<Entity> > *players = level->getEntitiesOfClass(typeid(Player), bb); - for (AUTO_VAR(it,players->begin()); it != players->end(); ++it) + if ( players ) { - shared_ptr<Player> player = dynamic_pointer_cast<Player>(*it); - player->addEffect(new MobEffectInstance(primaryPower, SharedConstants::TICKS_PER_SECOND * 9, baseAmp, true)); - } + for (auto& it : *players) + { + shared_ptr<Player> player = dynamic_pointer_cast<Player>(it); + if ( player ) + player->addEffect(new MobEffectInstance(primaryPower, SharedConstants::TICKS_PER_SECOND * 9, baseAmp, true)); + } - if (levels >= 4 && primaryPower != secondaryPower && secondaryPower > 0) - { - for (AUTO_VAR(it,players->begin()); it != players->end(); ++it) + if (levels >= 4 && primaryPower != secondaryPower && secondaryPower > 0) { - shared_ptr<Player> player = dynamic_pointer_cast<Player>(*it); - player->addEffect(new MobEffectInstance(secondaryPower, SharedConstants::TICKS_PER_SECOND * 9, 0, true)); + for ( auto& it : *players ) + { + shared_ptr<Player> player = dynamic_pointer_cast<Player>(it); + if ( player ) + player->addEffect(new MobEffectInstance(secondaryPower, SharedConstants::TICKS_PER_SECOND * 9, 0, true)); + } } + delete players; } - delete players; } } diff --git a/Minecraft.World/BedTile.cpp b/Minecraft.World/BedTile.cpp index 2023e23f..039943bd 100644 --- a/Minecraft.World/BedTile.cpp +++ b/Minecraft.World/BedTile.cpp @@ -108,10 +108,8 @@ bool BedTile::use(Level *level, int x, int y, int z, shared_ptr<Player> player, if (isOccupied(data)) { shared_ptr<Player> sleepingPlayer = nullptr; - AUTO_VAR(itEnd, level->players.end()); - for (AUTO_VAR(it, level->players.begin()); it != itEnd; it++ ) + for ( auto& p : level->players ) { - shared_ptr<Player> p = *it; if (p->isSleeping()) { Pos pos = p->bedPosition; diff --git a/Minecraft.World/BehaviorRegistry.cpp b/Minecraft.World/BehaviorRegistry.cpp index 8689f129..5c314ad0 100644 --- a/Minecraft.World/BehaviorRegistry.cpp +++ b/Minecraft.World/BehaviorRegistry.cpp @@ -9,9 +9,9 @@ BehaviorRegistry::BehaviorRegistry(DispenseItemBehavior *defaultValue) BehaviorRegistry::~BehaviorRegistry() { - for(AUTO_VAR(it, storage.begin()); it != storage.end(); ++it) + for( auto& it : storage ) { - delete it->second; + delete it.second; } delete defaultBehavior; @@ -19,7 +19,7 @@ BehaviorRegistry::~BehaviorRegistry() DispenseItemBehavior *BehaviorRegistry::get(Item *key) { - AUTO_VAR(it, storage.find(key)); + auto it = storage.find(key); return (it == storage.end()) ? defaultBehavior : it->second; } diff --git a/Minecraft.World/BiomeCache.cpp b/Minecraft.World/BiomeCache.cpp index 0d9c017c..b93ce32e 100644 --- a/Minecraft.World/BiomeCache.cpp +++ b/Minecraft.World/BiomeCache.cpp @@ -72,9 +72,9 @@ BiomeCache::~BiomeCache() // 4J Stu - Delete source? // delete source; - for(AUTO_VAR(it, all.begin()); it != all.end(); ++it) + for( auto& it : all ) { - delete (*it); + delete it; } DeleteCriticalSection(&m_CS); } @@ -86,7 +86,7 @@ BiomeCache::Block *BiomeCache::getBlockAt(int x, int z) x >>= ZONE_SIZE_BITS; z >>= ZONE_SIZE_BITS; __int64 slot = (((__int64) x) & 0xffffffffl) | ((((__int64) z) & 0xffffffffl) << 32l); - AUTO_VAR(it, cached.find(slot)); + auto it = cached.find(slot); Block *block = NULL; if (it == cached.end()) { @@ -130,7 +130,7 @@ void BiomeCache::update() { lastUpdateTime = now; - for (AUTO_VAR(it, all.begin()); it != all.end();) + for (auto it = all.begin(); it != all.end();) { Block *block = *it; __int64 time = now - block->lastUse; diff --git a/Minecraft.World/Boat.cpp b/Minecraft.World/Boat.cpp index c0c6a2cf..e39bd7f3 100644 --- a/Minecraft.World/Boat.cpp +++ b/Minecraft.World/Boat.cpp @@ -405,13 +405,12 @@ void Boat::tick() if(level->isClientSide) return; vector<shared_ptr<Entity> > *entities = level->getEntities(shared_from_this(), bb->grow(0.2f, 0, 0.2f)); - if (entities != NULL && !entities->empty()) + if (entities && !entities->empty()) { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + auto riderPtr = rider.lock(); + for ( auto& e : *entities ) { - shared_ptr<Entity> e = (*it); // entities->at(i); - if (e != rider.lock() && e->isPushable() && e->GetType() == eTYPE_BOAT) + if (e != riderPtr && e->isPushable() && e->GetType() == eTYPE_BOAT) { e->push(shared_from_this()); } diff --git a/Minecraft.World/BoatItem.cpp b/Minecraft.World/BoatItem.cpp index d5628f09..d2bb75b5 100644 --- a/Minecraft.World/BoatItem.cpp +++ b/Minecraft.World/BoatItem.cpp @@ -81,10 +81,9 @@ shared_ptr<ItemInstance> BoatItem::use(shared_ptr<ItemInstance> itemInstance, Le bool hitEntity = false; float overlap = 1; vector<shared_ptr<Entity> > *objects = level->getEntities(player, player->bb->expand(b->x * (range), b->y * (range), b->z * (range))->grow(overlap, overlap, overlap)); - //for (int i = 0; i < objects.size(); i++) { - for(AUTO_VAR(it, objects->begin()); it != objects->end(); ++it) + + for( auto& e : *objects ) { - shared_ptr<Entity> e = *it; //objects.get(i); if (!e->isPickable()) continue; float rr = e->getPickRadius(); diff --git a/Minecraft.World/BoundingBox.cpp b/Minecraft.World/BoundingBox.cpp index 24972bf9..74dba470 100644 --- a/Minecraft.World/BoundingBox.cpp +++ b/Minecraft.World/BoundingBox.cpp @@ -175,7 +175,7 @@ int BoundingBox::getZCenter() wstring BoundingBox::toString() { - return L"(" + _toString<int>(x0) + L", " + _toString<int>(y0) + L", " + _toString<int>(z0) + L"; " + _toString<int>(x1) + L", " + _toString<int>(y1) + L", " + _toString<int>(z1) + L")"; + return L"(" + std::to_wstring(x0) + L", " + std::to_wstring(y0) + L", " + std::to_wstring(z0) + L"; " + std::to_wstring(x1) + L", " + std::to_wstring(y1) + L", " + std::to_wstring(z1) + L")"; } IntArrayTag *BoundingBox::createTag(const wstring &name) diff --git a/Minecraft.World/BreedGoal.cpp b/Minecraft.World/BreedGoal.cpp index ce2d8fff..1c46fd90 100644 --- a/Minecraft.World/BreedGoal.cpp +++ b/Minecraft.World/BreedGoal.cpp @@ -53,16 +53,19 @@ shared_ptr<Animal> BreedGoal::getFreePartner() vector<shared_ptr<Entity> > *others = level->getEntitiesOfClass(typeid(*animal), animal->bb->grow(r, r, r)); double dist = Double::MAX_VALUE; shared_ptr<Animal> partner = nullptr; - for(AUTO_VAR(it, others->begin()); it != others->end(); ++it) + if ( others ) { - shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(*it); - if (animal->canMate(p) && animal->distanceToSqr(p) < dist) + for ( auto& it : *others ) { - partner = p; - dist = animal->distanceToSqr(p); + shared_ptr<Animal> p = dynamic_pointer_cast<Animal>(it); + if ( p && animal->canMate(p) && animal->distanceToSqr(p) < dist) + { + partner = p; + dist = animal->distanceToSqr(p); + } } + delete others; } - delete others; return partner; } diff --git a/Minecraft.World/BrewingStandMenu.cpp b/Minecraft.World/BrewingStandMenu.cpp index eaf78329..4f9e2ac3 100644 --- a/Minecraft.World/BrewingStandMenu.cpp +++ b/Minecraft.World/BrewingStandMenu.cpp @@ -40,10 +40,8 @@ void BrewingStandMenu::broadcastChanges() { AbstractContainerMenu::broadcastChanges(); - //for (int i = 0; i < containerListeners->size(); i++) - for(AUTO_VAR(it, containerListeners.begin()); it != containerListeners.end(); ++it) + for( auto& listener : containerListeners ) { - ContainerListener *listener = *it; //containerListeners.at(i); if (tc != brewingStand->getBrewTime()) { listener->setContainerData(this, 0, brewingStand->getBrewTime()); diff --git a/Minecraft.World/C4JThread.cpp b/Minecraft.World/C4JThread.cpp index 4b9760c1..d0794f06 100644 --- a/Minecraft.World/C4JThread.cpp +++ b/Minecraft.World/C4JThread.cpp @@ -183,7 +183,7 @@ C4JThread::~C4JThread() EnterCriticalSection(&ms_threadListCS); - for( AUTO_VAR(it,ms_threadList.begin()); it != ms_threadList.end(); it++ ) + for (auto it = ms_threadList.begin(); it != ms_threadList.end(); it++) { if( (*it) == this ) { diff --git a/Minecraft.World/CarrotTile.cpp b/Minecraft.World/CarrotTile.cpp index 677ab78a..8841e199 100644 --- a/Minecraft.World/CarrotTile.cpp +++ b/Minecraft.World/CarrotTile.cpp @@ -37,6 +37,6 @@ void CarrotTile::registerIcons(IconRegister *iconRegister) { for (int i = 0; i < 4; i++) { - icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + _toString(i)); + icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + std::to_wstring(i)); } }
\ No newline at end of file diff --git a/Minecraft.World/CaveFeature.cpp b/Minecraft.World/CaveFeature.cpp index 698ee3da..adb5d446 100644 --- a/Minecraft.World/CaveFeature.cpp +++ b/Minecraft.World/CaveFeature.cpp @@ -70,17 +70,13 @@ bool CaveFeature::place(Level *level, Random *random, int x, int y, int z) } } - AUTO_VAR(itEnd, toRemove.end()); - for (AUTO_VAR(it, toRemove.begin()); it != itEnd; it++) + for ( auto& p : toRemove ) { - TilePos *p = *it; //toRemove[i]; level->setTileAndData(p->x, p->y, p->z, 0, 0, Tile::UPDATE_CLIENTS); } - itEnd = toRemove.end(); - for (AUTO_VAR(it, toRemove.begin()); it != itEnd; it++) + for ( auto& p : toRemove ) { - TilePos *p = *it; //toRemove[i]; if (level->getTile(p->x, p->y - 1, p->z) == Tile::dirt_Id && level->getDaytimeRawBrightness(p->x, p->y, p->z) > 8) { level->setTileAndData(p->x, p->y - 1, p->z, Tile::grass_Id, 0, Tile::UPDATE_CLIENTS); diff --git a/Minecraft.World/ChestTile.cpp b/Minecraft.World/ChestTile.cpp index a4894c86..11178b8a 100644 --- a/Minecraft.World/ChestTile.cpp +++ b/Minecraft.World/ChestTile.cpp @@ -337,16 +337,19 @@ int ChestTile::getDirectSignal(LevelSource *level, int x, int y, int z, int dir) bool ChestTile::isCatSittingOnChest(Level *level, int x, int y, int z) { vector<shared_ptr<Entity> > *entities = level->getEntitiesOfClass(typeid(Ocelot), AABB::newTemp(x, y + 1, z, x + 1, y + 2, z + 1)); - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + if ( entities ) { - shared_ptr<Ocelot> ocelot = dynamic_pointer_cast<Ocelot>(*it); - if(ocelot->isSitting()) + for (auto& it : *entities) { - delete entities; - return true; + shared_ptr<Ocelot> ocelot = dynamic_pointer_cast<Ocelot>(it); + if ( ocelot && ocelot->isSitting()) + { + delete entities; + return true; + } } + delete entities; } - delete entities; return false; } diff --git a/Minecraft.World/ChestTileEntity.cpp b/Minecraft.World/ChestTileEntity.cpp index fded7d28..b8f323f4 100644 --- a/Minecraft.World/ChestTileEntity.cpp +++ b/Minecraft.World/ChestTileEntity.cpp @@ -271,23 +271,26 @@ void ChestTileEntity::tick() float range = 5; vector<shared_ptr<Entity> > *players = level->getEntitiesOfClass(typeid(Player), AABB::newTemp(x - range, y - range, z - range, x + 1 + range, y + 1 + range, z + 1 + range)); - for (AUTO_VAR(it,players->begin()); it != players->end(); ++it) + if ( players ) { - shared_ptr<Player> player = dynamic_pointer_cast<Player>(*it); - - ContainerMenu *containerMenu = dynamic_cast<ContainerMenu*>(player->containerMenu); - if (containerMenu != NULL) + for (auto& it : *players) { - shared_ptr<Container> container = containerMenu->getContainer(); - shared_ptr<Container> thisContainer = dynamic_pointer_cast<Container>(shared_from_this()); - shared_ptr<CompoundContainer> compoundContainer = dynamic_pointer_cast<CompoundContainer>( container ); - if ( (container == thisContainer) || (compoundContainer != NULL && compoundContainer->contains(thisContainer)) ) + shared_ptr<Player> player = dynamic_pointer_cast<Player>(it); + + ContainerMenu* containerMenu = dynamic_cast<ContainerMenu*>(player->containerMenu); + if (containerMenu) { - openCount++; + shared_ptr<Container> container = containerMenu->getContainer(); + shared_ptr<Container> thisContainer = dynamic_pointer_cast<Container>(shared_from_this()); + shared_ptr<CompoundContainer> compoundContainer = dynamic_pointer_cast<CompoundContainer>(container); + if ((container == thisContainer) || (compoundContainer != NULL && compoundContainer->contains(thisContainer))) + { + openCount++; + } } } + delete players; } - delete players; } oOpenness = openness; diff --git a/Minecraft.World/ChunkPos.cpp b/Minecraft.World/ChunkPos.cpp index 3f9674a7..ff1c34f0 100644 --- a/Minecraft.World/ChunkPos.cpp +++ b/Minecraft.World/ChunkPos.cpp @@ -53,14 +53,14 @@ int ChunkPos::getMiddleBlockZ() return ( z << 4 ) + 8; } -TilePos ChunkPos::getMiddleBlockPosition(int y) +TilePos ChunkPos::getMiddleBlockPosition(int y) { return TilePos(getMiddleBlockX(), y, getMiddleBlockZ()); } wstring ChunkPos::toString() { - return L"[" + _toString<int>(x) + L", " + _toString<int>(z) + L"]"; + return L"[" + std::to_wstring(x) + L", " + std::to_wstring(z) + L"]"; } __int64 ChunkPos::hash_fnct(const ChunkPos &k) diff --git a/Minecraft.World/Class.h b/Minecraft.World/Class.h index 31fc4dad..25802c3f 100644 --- a/Minecraft.World/Class.h +++ b/Minecraft.World/Class.h @@ -371,9 +371,9 @@ public: m_parents.push_back(id); - for (AUTO_VAR(itr, parent->m_parents.begin()); itr != parent->m_parents.end(); itr++) + for ( auto& it : parent->m_parents ) { - m_parents.push_back(*itr); + m_parents.push_back(it); } return this; diff --git a/Minecraft.World/ClothTile.cpp b/Minecraft.World/ClothTile.cpp index 70ba4837..8c18b01c 100644 --- a/Minecraft.World/ClothTile.cpp +++ b/Minecraft.World/ClothTile.cpp @@ -33,6 +33,6 @@ void ClothTile::registerIcons(IconRegister *iconRegister) for (int i = 0; i < 16; i++) { - icons[i] = iconRegister->registerIcon(L"cloth_" + _toString(i) ); + icons[i] = iconRegister->registerIcon(L"cloth_" + std::to_wstring(i) ); } }
\ No newline at end of file diff --git a/Minecraft.World/CombatTracker.cpp b/Minecraft.World/CombatTracker.cpp index 77aac68a..2d35913c 100644 --- a/Minecraft.World/CombatTracker.cpp +++ b/Minecraft.World/CombatTracker.cpp @@ -13,9 +13,9 @@ CombatTracker::CombatTracker(LivingEntity *mob) CombatTracker::~CombatTracker() { - for (AUTO_VAR(it,entries.begin()); it != entries.end(); ++it) + for ( auto& it : entries ) { - delete (*it); + delete it; } } @@ -138,9 +138,8 @@ shared_ptr<LivingEntity> CombatTracker::getKiller() float bestMobDamage = 0; float bestPlayerDamage = 0; - for (AUTO_VAR(it,entries.begin()); it != entries.end(); ++it) + for ( CombatEntry *entry : entries ) { - CombatEntry *entry = *it; if ( entry->getSource() != NULL && entry->getSource()->getEntity() != NULL && entry->getSource()->getEntity()->instanceof(eTYPE_PLAYER) && (bestPlayer == NULL || entry->getDamage() > bestPlayerDamage)) { bestPlayerDamage = entry->getDamage(); @@ -241,9 +240,9 @@ void CombatTracker::recheckStatus() if (takingDamage && mob->tickCount - lastDamageTime > reset) { - for (AUTO_VAR(it,entries.begin()); it != entries.end(); ++it) + for ( auto& it : entries ) { - delete (*it); + delete it; } entries.clear(); takingDamage = false; diff --git a/Minecraft.World/CommandDispatcher.cpp b/Minecraft.World/CommandDispatcher.cpp index 545063db..45b3f5fe 100644 --- a/Minecraft.World/CommandDispatcher.cpp +++ b/Minecraft.World/CommandDispatcher.cpp @@ -4,7 +4,7 @@ int CommandDispatcher::performCommand(shared_ptr<CommandSender> sender, EGameCommand command, byteArray commandData) { - AUTO_VAR(it, commandsById.find(command)); + auto it = commandsById.find(command); if(it != commandsById.end()) { diff --git a/Minecraft.World/CompoundTag.h b/Minecraft.World/CompoundTag.h index 29d35041..f3a711d2 100644 --- a/Minecraft.World/CompoundTag.h +++ b/Minecraft.World/CompoundTag.h @@ -22,10 +22,9 @@ public: void write(DataOutput *dos) { - AUTO_VAR(itEnd, tags.end()); - for( unordered_map<wstring, Tag *>::iterator it = tags.begin(); it != itEnd; it++ ) + for( auto& tag : tags ) { - Tag::writeNamedTag(it->second, dos); + Tag::writeNamedTag(tag.second, dos); } dos->writeByte(Tag::TAG_End); } @@ -55,10 +54,9 @@ public: // 4J - was return tags.values(); vector<Tag *> *ret = new vector<Tag *>; - AUTO_VAR(itEnd, tags.end()); - for( unordered_map<wstring, Tag *>::iterator it = tags.begin(); it != itEnd; it++ ) + for( auto& tag : tags ) { - ret->push_back(it->second); + ret->push_back(tag.second); } return ret; } @@ -130,7 +128,7 @@ public: Tag *get(const wstring &name) { - AUTO_VAR(it, tags.find(name)); + auto it = tags.find(name); if(it != tags.end()) return it->second; return NULL; } @@ -213,7 +211,7 @@ public: void remove(const wstring &name) { - AUTO_VAR(it, tags.find(name)); + auto it = tags.find(name); if(it != tags.end()) tags.erase(it); //tags.remove(name); } @@ -222,7 +220,7 @@ public: { static const int bufSize = 32; static wchar_t buf[bufSize]; - swprintf(buf,bufSize,L"%d entries",tags.size()); + swprintf(buf,bufSize,L"%zu entries",tags.size()); return wstring( buf ); } @@ -236,10 +234,9 @@ public: strcpy( newPrefix, prefix); strcat( newPrefix, " "); - AUTO_VAR(itEnd, tags.end()); - for( unordered_map<string, Tag *>::iterator it = tags.begin(); it != itEnd; it++ ) + for( auto& it : tags ) { - it->second->print(newPrefix, out); + it.second->print(newPrefix, out); } delete[] newPrefix; out << prefix << "}" << endl; @@ -253,10 +250,9 @@ public: virtual ~CompoundTag() { - AUTO_VAR(itEnd, tags.end()); - for( AUTO_VAR(it, tags.begin()); it != itEnd; it++ ) + for( auto& tag : tags ) { - delete it->second; + delete tag.second; } } @@ -264,10 +260,9 @@ public: { CompoundTag *tag = new CompoundTag(getName()); - AUTO_VAR(itEnd, tags.end()); - for( AUTO_VAR(it, tags.begin()); it != itEnd; it++ ) + for( auto& it : tags ) { - tag->put((wchar_t *)it->first.c_str(), it->second->copy()); + tag->put((wchar_t *)it.first.c_str(), it.second->copy()); } return tag; } @@ -281,11 +276,10 @@ public: if(tags.size() == o->tags.size()) { bool equal = true; - AUTO_VAR(itEnd, tags.end()); - for( AUTO_VAR(it, tags.begin()); it != itEnd; it++ ) + for( auto& it : tags ) { - AUTO_VAR(itFind, o->tags.find(it->first)); - if(itFind == o->tags.end() || !it->second->equals(itFind->second) ) + auto itFind = o->tags.find(it.first); + if(itFind == o->tags.end() || !it.second->equals(itFind->second) ) { equal = false; break; diff --git a/Minecraft.World/ConsoleSaveFileConverter.cpp b/Minecraft.World/ConsoleSaveFileConverter.cpp index 16b025a5..21de3cbe 100644 --- a/Minecraft.World/ConsoleSaveFileConverter.cpp +++ b/Minecraft.World/ConsoleSaveFileConverter.cpp @@ -273,27 +273,29 @@ void ConsoleSaveFileConverter::ConvertSave(ConsoleSaveFile *sourceSave, ConsoleS // 4J Stu - Old version that just changes the compression of chunks, not usable for XboxOne style split saves or compressed tile formats // Process region files vector<FileEntry *> *allFilesInSave = sourceSave->getFilesWithPrefix(wstring(L"")); - for(AUTO_VAR(it, allFilesInSave->begin()); it < allFilesInSave->end(); ++it) + if ( allFilesInSave ) { - FileEntry *fe = *it; - if( fe != sourceLdatFe ) + for ( FileEntry* fe : *allFilesInSave ) { - wstring fName( fe->data.filename ); - wstring suffix(L".mcr"); - if( fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0 ) + if (fe != sourceLdatFe) { + wstring fName(fe->data.filename); + wstring suffix(L".mcr"); + if (fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0) + { #ifndef _CONTENT_PACKAGE - wprintf(L"Processing a region file: %s\n", fe->data.filename); + wprintf(L"Processing a region file: %s\n", fe->data.filename); #endif - ProcessStandardRegionFile(sourceSave, File(fe->data.filename), targetSave, File(fe->data.filename) ); - } - else - { + ProcessStandardRegionFile(sourceSave, File(fe->data.filename), targetSave, File(fe->data.filename)); + } + else + { #ifndef _CONTENT_PACKAGE - wprintf(L"%s is not a region file, ignoring\n", fe->data.filename); + wprintf(L"%s is not a region file, ignoring\n", fe->data.filename); #endif + } } } - } #endif + } }
\ No newline at end of file diff --git a/Minecraft.World/ConsoleSaveFileOriginal.cpp b/Minecraft.World/ConsoleSaveFileOriginal.cpp index 8e6f58c6..3a2b5ef1 100644 --- a/Minecraft.World/ConsoleSaveFileOriginal.cpp +++ b/Minecraft.World/ConsoleSaveFileOriginal.cpp @@ -1043,19 +1043,21 @@ void ConsoleSaveFileOriginal::ConvertToLocalPlatform() } // convert each of the region files to the local platform vector<FileEntry *> *allFilesInSave = getFilesWithPrefix(wstring(L"")); - for(AUTO_VAR(it, allFilesInSave->begin()); it < allFilesInSave->end(); ++it) + if ( allFilesInSave ) { - FileEntry *fe = *it; - wstring fName( fe->data.filename ); - wstring suffix(L".mcr"); - if( fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0 ) + for (FileEntry* fe : *allFilesInSave) { - app.DebugPrintf("Processing a region file: %ls\n",fName.c_str()); - ConvertRegionFile(File(fe->data.filename) ); - } - else - { - app.DebugPrintf("%ls is not a region file, ignoring\n", fName.c_str()); + wstring fName(fe->data.filename); + wstring suffix(L".mcr"); + if (fName.compare(fName.length() - suffix.length(), suffix.length(), suffix) == 0) + { + app.DebugPrintf("Processing a region file: %ls\n", fName.c_str()); + ConvertRegionFile(File(fe->data.filename)); + } + else + { + app.DebugPrintf("%ls is not a region file, ignoring\n", fName.c_str()); + } } } diff --git a/Minecraft.World/CropTile.cpp b/Minecraft.World/CropTile.cpp index 29c5b1c9..0df71924 100644 --- a/Minecraft.World/CropTile.cpp +++ b/Minecraft.World/CropTile.cpp @@ -167,6 +167,6 @@ void CropTile::registerIcons(IconRegister *iconRegister) for (int i = 0; i < 8; i++) { - icons[i] = iconRegister->registerIcon(L"crops_" + _toString(i)); + icons[i] = iconRegister->registerIcon(L"crops_" + std::to_wstring(i)); } }
\ No newline at end of file diff --git a/Minecraft.World/DirectoryLevelStorage.cpp b/Minecraft.World/DirectoryLevelStorage.cpp index ba9bec6a..facd949a 100644 --- a/Minecraft.World/DirectoryLevelStorage.cpp +++ b/Minecraft.World/DirectoryLevelStorage.cpp @@ -121,7 +121,7 @@ bool DirectoryLevelStorage::PlayerMappings::getMapping(int &id, int centreX, int //__int64 xShifted = xMasked << 5; //app.DebugPrintf("xShifted = %d (0x%016x), zShifted = %I64d (0x%016llx)\n", xShifted, xShifted, zShifted, zShifted); __int64 index = ( ((__int64)(centreZ & 0x1FFFFFFF)) << 34) | ( ((__int64)(centreX & 0x1FFFFFFF)) << 5) | ( (scale & 0x7) << 2) | (dimension & 0x3); - AUTO_VAR(it,m_mappings.find(index)); + auto it = m_mappings.find(index); if(it != m_mappings.end()) { id = it->second; @@ -138,11 +138,11 @@ bool DirectoryLevelStorage::PlayerMappings::getMapping(int &id, int centreX, int void DirectoryLevelStorage::PlayerMappings::writeMappings(DataOutputStream *dos) { dos->writeInt(m_mappings.size()); - for(AUTO_VAR(it, m_mappings.begin()); it != m_mappings.end(); ++it) + for ( auto& it : m_mappings ) { - app.DebugPrintf(" -- %lld (0x%016llx) = %d\n", it->first, it->first, it->second); - dos->writeLong(it->first); - dos->writeInt(it->second); + app.DebugPrintf(" -- %lld (0x%016llx) = %d\n", it.first, it.first, it.second); + dos->writeLong(it.first); + dos->writeInt(it.second); } } @@ -174,9 +174,9 @@ DirectoryLevelStorage::~DirectoryLevelStorage() { delete m_saveFile; - for(AUTO_VAR(it,m_cachedSaveData.begin()); it != m_cachedSaveData.end(); ++it) + for( auto& it : m_cachedSaveData ) { - delete it->second; + delete it.second; } #ifdef _LARGE_WORLDS @@ -233,7 +233,7 @@ ChunkStorage *DirectoryLevelStorage::createChunkStorage(Dimension *dimension) return new OldChunkStorage(dir, true); } -LevelData *DirectoryLevelStorage::prepareLevel() +LevelData *DirectoryLevelStorage::prepareLevel() { // 4J Stu Added #ifdef _LARGE_WORLDS @@ -295,7 +295,7 @@ LevelData *DirectoryLevelStorage::prepareLevel() #else if(getSaveFile()->getSaveVersion() < END_DIMENSION_MAP_MAPPINGS_SAVE_VERSION) - { + { MapDataMappings_old oldMapDataMappings; getSaveFile()->readFile( fileEntry, &oldMapDataMappings, // data buffer @@ -334,7 +334,7 @@ LevelData *DirectoryLevelStorage::prepareLevel() ConsoleSavePath dataFile = ConsoleSavePath( wstring( L"level.dat" ) ); - if ( m_saveFile->doesFileExist( dataFile ) ) + if ( m_saveFile->doesFileExist( dataFile ) ) { ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(m_saveFile, dataFile); CompoundTag *root = NbtIo::readCompressed(&fis); @@ -398,7 +398,7 @@ void DirectoryLevelStorage::save(shared_ptr<Player> player) #elif defined(_DURANGO) ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + player->getXuid().toString() + L".dat" ); #else - ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + _toString( player->getXuid() ) + L".dat" ); + ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + std::to_wstring( player->getXuid() ) + L".dat" ); #endif // If saves are disabled (e.g. because we are writing the save buffer to disk) then cache this player data if(StorageManager.GetSaveDisabled()) @@ -406,7 +406,7 @@ void DirectoryLevelStorage::save(shared_ptr<Player> player) ByteArrayOutputStream *bos = new ByteArrayOutputStream(); NbtIo::writeCompressed(tag,bos); - AUTO_VAR(it, m_cachedSaveData.find(realFile.getName())); + auto it = m_cachedSaveData.find(realFile.getName()); if(it != m_cachedSaveData.end() ) { delete it->second; @@ -429,7 +429,7 @@ void DirectoryLevelStorage::save(shared_ptr<Player> player) } // 4J Changed return val to bool to check if new player or loaded player -CompoundTag *DirectoryLevelStorage::load(shared_ptr<Player> player) +CompoundTag *DirectoryLevelStorage::load(shared_ptr<Player> player) { CompoundTag *tag = loadPlayerDataTag( player->getXuid() ); if (tag != NULL) @@ -447,9 +447,9 @@ CompoundTag *DirectoryLevelStorage::loadPlayerDataTag(PlayerUID xuid) #elif defined(_DURANGO) ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + xuid.toString() + L".dat" ); #else - ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + _toString( xuid ) + L".dat" ); + ConsoleSavePath realFile = ConsoleSavePath( playerDir.getName() + std::to_wstring( xuid ) + L".dat" ); #endif - AUTO_VAR(it, m_cachedSaveData.find(realFile.getName())); + auto it = m_cachedSaveData.find(realFile.getName()); if(it != m_cachedSaveData.end() ) { ByteArrayOutputStream *bos = it->second; @@ -496,7 +496,7 @@ void DirectoryLevelStorage::clearOldPlayerFiles() m_saveFile->deleteFile( playerFiles->at(i) ); } } - else + else #endif if( playerFiles->size() > MAX_PLAYER_DATA_SAVES ) { @@ -520,12 +520,12 @@ void DirectoryLevelStorage::clearOldPlayerFiles() } } -PlayerIO *DirectoryLevelStorage::getPlayerIO() +PlayerIO *DirectoryLevelStorage::getPlayerIO() { return this; } -void DirectoryLevelStorage::closeAll() +void DirectoryLevelStorage::closeAll() { } @@ -567,11 +567,10 @@ void DirectoryLevelStorage::resetNetherPlayerPositions() vector<FileEntry *> *playerFiles = m_saveFile->getFilesWithPrefix( playerDir.getName() ); #endif - if( playerFiles != NULL ) + if ( playerFiles ) { - for( AUTO_VAR(it, playerFiles->begin()); it != playerFiles->end(); ++it) + for ( FileEntry * realFile : *playerFiles ) { - FileEntry * realFile = *it; ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(m_saveFile, realFile); CompoundTag *tag = NbtIo::readCompressed(&fis); if (tag != NULL) @@ -579,7 +578,7 @@ void DirectoryLevelStorage::resetNetherPlayerPositions() // If the player is in the nether, set their y position above the top of the nether // This will force the player to be spawned in a valid position in the overworld when they are loaded if(tag->contains(L"Dimension") && tag->getInt(L"Dimension") == LevelData::DIMENSION_NETHER && tag->contains(L"Pos")) - { + { ListTag<DoubleTag> *pos = (ListTag<DoubleTag> *) tag->getList(L"Pos"); pos->get(1)->data = DBL_MAX; @@ -600,7 +599,7 @@ int DirectoryLevelStorage::getAuxValueForMap(PlayerUID xuid, int dimension, int bool foundMapping = false; #ifdef _LARGE_WORLDS - AUTO_VAR(it, m_playerMappings.find(xuid) ); + auto it = m_playerMappings.find(xuid); if(it != m_playerMappings.end()) { foundMapping = it->second.getMapping(mapId, centreXC, centreZC, dimension, scale); @@ -647,12 +646,12 @@ int DirectoryLevelStorage::getAuxValueForMap(PlayerUID xuid, int dimension, int m_saveableMapDataMappings.setMapping(mapId, xuid, dimension); // If we had an old map file for a mapping that is no longer valid, delete it - std::wstring id = wstring( L"map_" ) + _toString(mapId); + std::wstring id = wstring( L"map_" ) + std::to_wstring(mapId); ConsoleSavePath file = getDataFile(id); if(m_saveFile->doesFileExist(file) ) { - AUTO_VAR(it, find(m_mapFilesToDelete.begin(), m_mapFilesToDelete.end(), mapId)); + auto it = find(m_mapFilesToDelete.begin(), m_mapFilesToDelete.end(), mapId); if(it != m_mapFilesToDelete.end()) m_mapFilesToDelete.erase(it); m_saveFile->deleteFile( m_saveFile->createFile(file) ); @@ -683,15 +682,15 @@ void DirectoryLevelStorage::saveMapIdLookup() DataOutputStream dos(&baos); dos.writeInt(m_playerMappings.size()); app.DebugPrintf("Saving %d mappings\n", m_playerMappings.size()); - for(AUTO_VAR(it,m_playerMappings.begin()); it != m_playerMappings.end(); ++it) + for ( auto& it : m_playerMappings ) { #ifdef _WINDOWS64 - app.DebugPrintf(" -- %d\n", it->first); + app.DebugPrintf(" -- %d\n", it.first); #else - app.DebugPrintf(" -- %ls\n", it->first.toString().c_str()); + app.DebugPrintf(" -- %ls\n", it.first.toString().c_str()); #endif - dos.writePlayerUID(it->first); - it->second.writeMappings(&dos); + dos.writePlayerUID(it.first); + it.second.writeMappings(&dos); } dos.write(m_usedMappings); m_saveFile->writeFile( fileEntry, @@ -713,10 +712,10 @@ void DirectoryLevelStorage::saveMapIdLookup() void DirectoryLevelStorage::dontSaveMapMappingForPlayer(PlayerUID xuid) { #ifdef _LARGE_WORLDS - AUTO_VAR(it, m_playerMappings.find(xuid) ); + auto it = m_playerMappings.find(xuid); if(it != m_playerMappings.end()) { - for(AUTO_VAR(itMap, it->second.m_mappings.begin()); itMap != it->second.m_mappings.end(); ++itMap) + for (auto itMap = it->second.m_mappings.begin(); itMap != it->second.m_mappings.end(); ++itMap) { int index = itMap->second / 8; int offset = itMap->second % 8; @@ -744,12 +743,12 @@ void DirectoryLevelStorage::deleteMapFilesForPlayer(shared_ptr<Player> player) void DirectoryLevelStorage::deleteMapFilesForPlayer(PlayerUID xuid) { #ifdef _LARGE_WORLDS - AUTO_VAR(it, m_playerMappings.find(xuid) ); + auto it = m_playerMappings.find(xuid); if(it != m_playerMappings.end()) { - for(AUTO_VAR(itMap, it->second.m_mappings.begin()); itMap != it->second.m_mappings.end(); ++itMap) + for (auto itMap = it->second.m_mappings.begin(); itMap != it->second.m_mappings.end(); ++itMap) { - std::wstring id = wstring( L"map_" ) + _toString(itMap->second); + std::wstring id = wstring( L"map_" ) + std::to_wstring(itMap->second); ConsoleSavePath file = getDataFile(id); if(m_saveFile->doesFileExist(file) ) @@ -773,7 +772,7 @@ void DirectoryLevelStorage::deleteMapFilesForPlayer(PlayerUID xuid) { changed = true; - std::wstring id = wstring( L"map_" ) + _toString(i); + std::wstring id = wstring( L"map_" ) + std::to_wstring(i); ConsoleSavePath file = getDataFile(id); if(m_saveFile->doesFileExist(file) ) @@ -795,22 +794,22 @@ void DirectoryLevelStorage::saveAllCachedData() if(StorageManager.GetSaveDisabled() ) return; // Save any files that were saved while saving was disabled - for(AUTO_VAR(it, m_cachedSaveData.begin()); it != m_cachedSaveData.end(); ++it) + for ( auto& it : m_cachedSaveData ) { - ByteArrayOutputStream *bos = it->second; + ByteArrayOutputStream *bos = it.second; - ConsoleSavePath realFile = ConsoleSavePath( it->first ); + ConsoleSavePath realFile = ConsoleSavePath( it.first ); ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream( m_saveFile, realFile ); - app.DebugPrintf("Actually writing cached file %ls\n",it->first.c_str() ); + app.DebugPrintf("Actually writing cached file %ls\n",it.first.c_str() ); fos.write(bos->buf, 0, bos->size() ); delete bos; } m_cachedSaveData.clear(); - for(AUTO_VAR(it, m_mapFilesToDelete.begin()); it != m_mapFilesToDelete.end(); ++it) + for (auto& it : m_mapFilesToDelete ) { - std::wstring id = wstring( L"map_" ) + _toString(*it); + std::wstring id = wstring( L"map_" ) + std::to_wstring(it); ConsoleSavePath file = getDataFile(id); if(m_saveFile->doesFileExist(file) ) { diff --git a/Minecraft.World/DirectoryLevelStorageSource.cpp b/Minecraft.World/DirectoryLevelStorageSource.cpp index b4beb8b5..e229232b 100644 --- a/Minecraft.World/DirectoryLevelStorageSource.cpp +++ b/Minecraft.World/DirectoryLevelStorageSource.cpp @@ -27,12 +27,12 @@ vector<LevelSummary *> *DirectoryLevelStorageSource::getLevelList() // 4J Stu - We don't use directory list with the Xbox save locations vector<LevelSummary *> *levels = new vector<LevelSummary *>; #if 0 - for (int i = 0; i < 5; i++) + for (int i = 0; i < 5; i++) { - wstring levelId = wstring(L"World").append( _toString( (i+1) ) ); + wstring levelId = wstring(L"World").append( std::to_wstring( (i+1) ) ); LevelData *levelData = getDataTagFor(saveFile, levelId); - if (levelData != NULL) + if (levelData != NULL) { levels->push_back(new LevelSummary(levelId, L"", levelData->getLastPlayed(), levelData->getSizeOnDisk(), levelData.getGameType(), false, levelData->isHardcore())); } @@ -45,7 +45,7 @@ void DirectoryLevelStorageSource::clearAll() { } -LevelData *DirectoryLevelStorageSource::getDataTagFor(ConsoleSaveFile *saveFile, const wstring& levelId) +LevelData *DirectoryLevelStorageSource::getDataTagFor(ConsoleSaveFile *saveFile, const wstring& levelId) { //File dataFile(dir, L"level.dat"); ConsoleSavePath dataFile = ConsoleSavePath( wstring( L"level.dat" ) ); @@ -63,12 +63,12 @@ LevelData *DirectoryLevelStorageSource::getDataTagFor(ConsoleSaveFile *saveFile, } void DirectoryLevelStorageSource::renameLevel(const wstring& levelId, const wstring& newLevelName) -{ +{ ConsoleSaveFileOriginal tempSave(levelId); //File dataFile = File(dir, L"level.dat"); ConsoleSavePath dataFile = ConsoleSavePath( wstring( L"level.dat" ) ); - if ( tempSave.doesFileExist( dataFile ) ) + if ( tempSave.doesFileExist( dataFile ) ) { ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream(&tempSave, dataFile); CompoundTag *root = NbtIo::readCompressed(&fis); @@ -80,7 +80,7 @@ void DirectoryLevelStorageSource::renameLevel(const wstring& levelId, const wstr } } -bool DirectoryLevelStorageSource::isNewLevelIdAcceptable(const wstring& levelId) +bool DirectoryLevelStorageSource::isNewLevelIdAcceptable(const wstring& levelId) { // 4J Jev, removed try/catch. @@ -95,7 +95,7 @@ bool DirectoryLevelStorageSource::isNewLevelIdAcceptable(const wstring& levelId) return true; } -void DirectoryLevelStorageSource::deleteLevel(const wstring& levelId) +void DirectoryLevelStorageSource::deleteLevel(const wstring& levelId) { File dir = File(baseDir, levelId); if (!dir.exists()) return; @@ -106,15 +106,16 @@ void DirectoryLevelStorageSource::deleteLevel(const wstring& levelId) void DirectoryLevelStorageSource::deleteRecursive(vector<File *> *files) { - AUTO_VAR(itEnd, files->end()); - for (AUTO_VAR(it, files->begin()); it != itEnd; it++) + if ( files ) { - File *file = *it; - if (file->isDirectory()) + for (File* file : *files) { - deleteRecursive(file->listFiles()); + if (file->isDirectory()) + { + deleteRecursive(file->listFiles()); + } + file->_delete(); } - file->_delete(); } } @@ -133,7 +134,7 @@ bool DirectoryLevelStorageSource::requiresConversion(ConsoleSaveFile *saveFile, return false; } -bool DirectoryLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const wstring& levelId, ProgressListener *progress) +bool DirectoryLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const wstring& levelId, ProgressListener *progress) { return false; } diff --git a/Minecraft.World/DragonFireball.cpp b/Minecraft.World/DragonFireball.cpp index 32524592..335b345f 100644 --- a/Minecraft.World/DragonFireball.cpp +++ b/Minecraft.World/DragonFireball.cpp @@ -33,27 +33,27 @@ void DragonFireball::onHit(HitResult *res) { AABB *aoe = bb->grow(SPLASH_RANGE, SPLASH_RANGE / 2, SPLASH_RANGE); vector<shared_ptr<Entity> > *entitiesOfClass = level->getEntitiesOfClass(typeid(LivingEntity), aoe); - - if (entitiesOfClass != NULL && !entitiesOfClass->empty()) + if ( entitiesOfClass ) { - //for (Entity e : entitiesOfClass) - for( AUTO_VAR(it, entitiesOfClass->begin()); it != entitiesOfClass->end(); ++it) + if (!entitiesOfClass->empty()) { - //shared_ptr<Entity> e = *it; - shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( *it ); - double dist = distanceToSqr(e); - if (dist < SPLASH_RANGE_SQ) + for (auto& it : *entitiesOfClass) { - double scale = 1.0 - (sqrt(dist) / SPLASH_RANGE); - if (e == res->entity) + shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>(it); + double dist = distanceToSqr(e); + if (dist < SPLASH_RANGE_SQ) { - scale = 1; + double scale = 1.0 - (sqrt(dist) / SPLASH_RANGE); + if (e == res->entity) + { + scale = 1; + } + e->hurt(DamageSource::dragonbreath, 8 * scale); } - e->hurt(DamageSource::dragonbreath, 8*scale); } } + delete entitiesOfClass; } - delete entitiesOfClass; level->levelEvent(LevelEvent::ENDERDRAGON_FIREBALL_SPLASH, (int) Math::round(x), (int) Math::round(y), (int) Math::round(z), 0); remove(); diff --git a/Minecraft.World/EnchantmentHelper.cpp b/Minecraft.World/EnchantmentHelper.cpp index da784d5a..7abc9856 100644 --- a/Minecraft.World/EnchantmentHelper.cpp +++ b/Minecraft.World/EnchantmentHelper.cpp @@ -57,19 +57,19 @@ void EnchantmentHelper::setEnchantments(unordered_map<int, int> *enchantments, s ListTag<CompoundTag> *list = new ListTag<CompoundTag>(); //for (int id : enchantments.keySet()) - for(AUTO_VAR(it, enchantments->begin()); it != enchantments->end(); ++it) + for ( const auto& it : *enchantments ) { - int id = it->first; + int id = it.first; CompoundTag *tag = new CompoundTag(); tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_ID, (short) id); - tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL, (short)(int)it->second); + tag->putShort((wchar_t *)ItemInstance::TAG_ENCH_LEVEL, (short)(int)it.second); list->add(tag); if (item->id == Item::enchantedBook_Id) { - Item::enchantedBook->addEnchantment(item, new EnchantmentInstance(id, it->second)); + Item::enchantedBook->addEnchantment(item, new EnchantmentInstance(id, it.second)); } } @@ -301,20 +301,22 @@ shared_ptr<ItemInstance> EnchantmentHelper::enchantItem(Random *random, shared_p if (isBook) itemInstance->id = Item::enchantedBook_Id; - if (newEnchantment != NULL) + if ( newEnchantment ) { - for(AUTO_VAR(it, newEnchantment->begin()); it != newEnchantment->end(); ++it) + for ( EnchantmentInstance *e : *newEnchantment ) { - EnchantmentInstance *e = *it; - if (isBook) + if ( e ) { - Item::enchantedBook->addEnchantment(itemInstance, e); - } - else - { - itemInstance->enchant(e->enchantment, e->level); + if (isBook) + { + Item::enchantedBook->addEnchantment(itemInstance, e); + } + else + { + itemInstance->enchant(e->enchantment, e->level); + } + delete e; } - delete e; } delete newEnchantment; } @@ -355,17 +357,17 @@ vector<EnchantmentInstance *> *EnchantmentHelper::selectEnchantment(Random *rand vector<EnchantmentInstance *> *results = NULL; unordered_map<int, EnchantmentInstance *> *availableEnchantments = getAvailableEnchantmentResults(realValue, itemInstance); - if (availableEnchantments != NULL && !availableEnchantments->empty()) + if (availableEnchantments && !availableEnchantments->empty()) { vector<WeighedRandomItem *> values; - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end(); ++it) + for( auto& it : *availableEnchantments ) { - values.push_back(it->second); + values.push_back(it.second); } EnchantmentInstance *instance = (EnchantmentInstance *) WeighedRandom::getRandomItem(random, &values); values.clear(); - if (instance != NULL) + if (instance) { results = new vector<EnchantmentInstance *>(); results->push_back( instance->copy() ); // 4J Stu - Inserting a copy so we can clear memory from the availableEnchantments collection @@ -377,14 +379,12 @@ vector<EnchantmentInstance *> *EnchantmentHelper::selectEnchantment(Random *rand // remove incompatible enchantments from previous result //final Iterator<Integer> mapIter = availableEnchantments.keySet().iterator(); //while (mapIter.hasNext()) - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end();) + for (auto it = availableEnchantments->begin(); it != availableEnchantments->end();) { int nextEnchantment = it->first;//mapIter.next(); bool valid = true; - //for (EnchantmentInstance *current : results) - for(AUTO_VAR(resIt, results->begin()); resIt != results->end(); ++resIt) + for ( const EnchantmentInstance *current : *results ) { - EnchantmentInstance *current = *resIt; if (!current->enchantment->isCompatibleWith(Enchantment::enchantments[nextEnchantment])) { valid = false; @@ -405,9 +405,9 @@ vector<EnchantmentInstance *> *EnchantmentHelper::selectEnchantment(Random *rand if (!availableEnchantments->empty()) { - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end(); ++it) + for (auto& it : *availableEnchantments ) { - values.push_back(it->second); + values.push_back(it.second); } EnchantmentInstance *nextInstance = (EnchantmentInstance *) WeighedRandom::getRandomItem(random, &values); values.clear(); @@ -418,11 +418,11 @@ vector<EnchantmentInstance *> *EnchantmentHelper::selectEnchantment(Random *rand } } } - if(availableEnchantments != NULL) + if( availableEnchantments ) { - for(AUTO_VAR(it, availableEnchantments->begin()); it != availableEnchantments->end(); ++it) + for (auto& it : *availableEnchantments ) { - delete it->second; + delete it.second; } delete availableEnchantments; } @@ -460,7 +460,7 @@ unordered_map<int, EnchantmentInstance *> *EnchantmentHelper::getAvailableEnchan { results = new unordered_map<int, EnchantmentInstance *>(); } - AUTO_VAR(it, results->find(e->id)); + auto it = results->find(e->id); if(it != results->end()) { delete it->second; diff --git a/Minecraft.World/EnderCrystal.cpp b/Minecraft.World/EnderCrystal.cpp index 78e00419..5e7a9edb 100644 --- a/Minecraft.World/EnderCrystal.cpp +++ b/Minecraft.World/EnderCrystal.cpp @@ -110,12 +110,10 @@ bool EnderCrystal::hurt(DamageSource *source, float damage) vector<shared_ptr<Entity> > entities = level->getAllEntities(); shared_ptr<EnderDragon> dragon = nullptr; - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) + for ( auto& e : entities ) { - shared_ptr<Entity> e = *it; //entities->at(i); dragon = dynamic_pointer_cast<EnderDragon>(e); - if(dragon != NULL) + if ( dragon ) { dragon->handleCrystalDestroyed(source); break; diff --git a/Minecraft.World/EnderDragon.cpp b/Minecraft.World/EnderDragon.cpp index 2dc0c434..e1dea172 100644 --- a/Minecraft.World/EnderDragon.cpp +++ b/Minecraft.World/EnderDragon.cpp @@ -444,13 +444,16 @@ void EnderDragon::aiStep() { vector<shared_ptr<Entity> > *targets = level->getEntities(shared_from_this(), m_acidArea); - for( AUTO_VAR(it, targets->begin() ); it != targets->end(); ++it) + if ( targets ) { - if ( (*it)->instanceof(eTYPE_LIVINGENTITY) ) + for (auto& it : *targets ) { - //app.DebugPrintf("Attacking entity with acid\n"); - shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( *it ); - e->hurt(DamageSource::dragonbreath, 2); + if ( it->instanceof(eTYPE_LIVINGENTITY)) + { + //app.DebugPrintf("Attacking entity with acid\n"); + shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>(it); + e->hurt(DamageSource::dragonbreath, 2); + } } } } @@ -796,24 +799,23 @@ void EnderDragon::checkCrystals() { float maxDist = 32; vector<shared_ptr<Entity> > *crystals = level->getEntitiesOfClass(typeid(EnderCrystal), bb->grow(maxDist, maxDist, maxDist)); - - shared_ptr<EnderCrystal> crystal = nullptr; - double nearest = Double::MAX_VALUE; - //for (Entity ec : crystals) - for(AUTO_VAR(it, crystals->begin()); it != crystals->end(); ++it) + if ( crystals ) { - shared_ptr<EnderCrystal> ec = dynamic_pointer_cast<EnderCrystal>( *it ); - double dist = ec->distanceToSqr(shared_from_this() ); - if (dist < nearest) + shared_ptr<EnderCrystal> crystal = nullptr; + double nearest = Double::MAX_VALUE; + for (auto& it : *crystals ) { - nearest = dist; - crystal = ec; + shared_ptr<EnderCrystal> ec = dynamic_pointer_cast<EnderCrystal>(it); + double dist = ec->distanceToSqr(shared_from_this()); + if (dist < nearest) + { + nearest = dist; + crystal = ec; + } } + delete crystals; + nearestCrystal = crystal; } - delete crystals; - - - nearestCrystal = crystal; } } @@ -839,33 +841,39 @@ void EnderDragon::knockBack(vector<shared_ptr<Entity> > *entities) // double ym = (body.bb.y0 + body.bb.y1) / 2; double zm = (body->bb->z0 + body->bb->z1) / 2; - //for (Entity e : entities) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + if ( entities ) { - - if ( (*it)->instanceof(eTYPE_LIVINGENTITY) )//(e instanceof Mob) + for ( auto& it : *entities ) { - shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( *it ); - double xd = e->x - xm; - double zd = e->z - zm; - double dd = xd * xd + zd * zd; - e->push(xd / dd * 4, 0.2f, zd / dd * 4); + if (it->instanceof(eTYPE_LIVINGENTITY)) + { + shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>(it); + double xd = e->x - xm; + double zd = e->z - zm; + double dd = xd * xd + zd * zd; + e->push(xd / dd * 4, 0.2f, zd / dd * 4); + } } } } void EnderDragon::hurt(vector<shared_ptr<Entity> > *entities) { - //for (int i = 0; i < entities->size(); i++) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + if ( entities ) { - - if ( (*it)->instanceof(eTYPE_LIVINGENTITY) ) //(e instanceof Mob) + for ( auto& it : *entities ) { - shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( *it );//entities.get(i); - DamageSource *damageSource = DamageSource::mobAttack( dynamic_pointer_cast<LivingEntity>( shared_from_this() )); - e->hurt(damageSource, 10); - delete damageSource; + + if ( it->instanceof(eTYPE_LIVINGENTITY)) + { + shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>(it); + DamageSource* damageSource = DamageSource::mobAttack(dynamic_pointer_cast<LivingEntity>(shared_from_this())); + if ( damageSource ) + { + e->hurt(damageSource, 10); + delete damageSource; + } + } } } } diff --git a/Minecraft.World/Entity.cpp b/Minecraft.World/Entity.cpp index cfae1772..e8233140 100644 --- a/Minecraft.World/Entity.cpp +++ b/Minecraft.World/Entity.cpp @@ -753,9 +753,6 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - AABBList *aABBs = level->getCubes(shared_from_this(), bb->expand(xa, ya, za), noEntityCubes, true); - // LAND FIRST, then x and z - AUTO_VAR(itEndAABB, aABBs->end()); - // 4J Stu - Particles (and possibly other entities) don't have xChunk and zChunk set, so calculate the chunk instead int xc = Mth::floor(x / 16); int zc = Mth::floor(z / 16); @@ -763,8 +760,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - { // 4J Stu - It's horrible that the client is doing any movement at all! But if we don't have the chunk // data then all the collision info will be incorrect as well - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - ya = (*it)->clipYCollide(bb, ya); + for ( auto& it : *aABBs ) + ya = it->clipYCollide(bb, ya); bb->move(0, ya, 0); } @@ -775,9 +772,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - bool og = onGround || (yaOrg != ya && yaOrg < 0); - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - xa = (*it)->clipXCollide(bb, xa); + for ( auto& it : *aABBs ) + xa = it->clipXCollide(bb, xa); bb->move(xa, 0, 0); @@ -786,9 +782,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - xa = ya = za = 0; } - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - za = (*it)->clipZCollide(bb, za); + for ( auto& it : *aABBs ) + za = it->clipZCollide(bb, za); bb->move(0, 0, za); if (!slide && zaOrg != za) @@ -812,15 +807,12 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - // so we'd better include cubes under our feet in this list of things we might possibly collide with aABBs = level->getCubes(shared_from_this(), bb->expand(xa, ya, za)->expand(0,-ya,0),false,true); - // LAND FIRST, then x and z - itEndAABB = aABBs->end(); - if(!level->isClientSide || level->reallyHasChunk(xc, zc)) { // 4J Stu - It's horrible that the client is doing any movement at all! But if we don't have the chunk // data then all the collision info will be incorrect as well - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - ya = (*it)->clipYCollide(bb, ya); + for ( auto& it : *aABBs ) + ya = it->clipYCollide(bb, ya); bb->move(0, ya, 0); } @@ -830,9 +822,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - } - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - xa = (*it)->clipXCollide(bb, xa); + for ( auto& it : *aABBs ) + xa = it->clipXCollide(bb, xa); bb->move(xa, 0, 0); if (!slide && xaOrg != xa) @@ -840,9 +831,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - xa = ya = za = 0; } - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - za = (*it)->clipZCollide(bb, za); + for ( auto& it : *aABBs ) + za = it->clipZCollide(bb, za); bb->move(0, 0, za); if (!slide && zaOrg != za) @@ -859,9 +849,8 @@ void Entity::move(double xa, double ya, double za, bool noEntityCubes) // 4J - { ya = -footSize; // LAND FIRST, then x and z - itEndAABB = aABBs->end(); - for (AUTO_VAR(it, aABBs->begin()); it != itEndAABB; it++) - ya = (*it)->clipYCollide(bb, ya); + for ( auto& it : *aABBs ) + ya = it->clipYCollide(bb, ya); bb->move(0, ya, 0); } @@ -1667,14 +1656,12 @@ void Entity::lerpTo(double x, double y, double z, float yRot, float xRot, int st if( GetType() != eTYPE_ARROW ) { AABBList *collisions = level->getCubes(shared_from_this(), bb->shrink(1 / 32.0, 0, 1 / 32.0)); - if (!collisions->empty()) + if ( collisions && !collisions->empty()) { double yTop = 0; - AUTO_VAR(itEnd, collisions->end()); - for (AUTO_VAR(it, collisions->begin()); it != itEnd; it++) + for ( const AABB *ab : *collisions ) { - AABB *ab = *it; //collisions->at(i); - if (ab->y1 > yTop) yTop = ab->y1; + if ( ab && ab->y1 > yTop) yTop = ab->y1; } y += yTop - bb->y0; @@ -1942,7 +1929,7 @@ wstring Entity::getAName() #ifdef _DEBUG wstring id = EntityIO::getEncodeId(shared_from_this()); if (id.empty()) id = L"generic"; - return L"entity." + id + _toString(entityId); + return L"entity." + id + std::to_wstring(entityId); #else return L""; #endif diff --git a/Minecraft.World/EntityHorse.cpp b/Minecraft.World/EntityHorse.cpp index d7250087..90c2a6b9 100644 --- a/Minecraft.World/EntityHorse.cpp +++ b/Minecraft.World/EntityHorse.cpp @@ -440,7 +440,7 @@ void EntityHorse::causeFallDamage(float fallDistance) /** * Different inventory sizes depending on the kind of horse -* +* * @return */ int EntityHorse::getInventorySize() @@ -523,9 +523,8 @@ shared_ptr<EntityHorse> EntityHorse::getClosestMommy(shared_ptr<Entity> baby, do shared_ptr<Entity> mommy = nullptr; vector<shared_ptr<Entity> > *list = level->getEntities(baby, baby->bb->expand(searchRadius, searchRadius, searchRadius), PARENT_HORSE_SELECTOR); - for(AUTO_VAR(it,list->begin()); it != list->end(); ++it) + for( auto& horse : *list ) { - shared_ptr<Entity> horse = *it; double distanceSquared = horse->distanceToSqr(baby->x, baby->y, baby->z); if (distanceSquared < closestDistance) @@ -767,7 +766,7 @@ void EntityHorse::rebuildLayeredTextureInfo() else { layerTextureLayers[0] = -1; - layerTextureHashName += L"_" + _toString<int>(type) + L"_"; + layerTextureHashName += L"_" + std::to_wstring(type) + L"_"; armorIndex = 1; } @@ -1036,7 +1035,7 @@ bool EntityHorse::canWearArmor() /** * able to carry bags -* +* * @return */ bool EntityHorse::canWearBags() @@ -1065,7 +1064,7 @@ bool EntityHorse::isPureBreed() /** * Is this an Undead Horse? -* +* * @return */ bool EntityHorse::isUndead() @@ -1675,7 +1674,7 @@ MobGroupData *EntityHorse::finalizeMobSpawn(MobGroupData *groupData, int extraDa setAge(AgableMob::BABY_START_AGE); } - if (type == TYPE_SKELETON || type == TYPE_UNDEAD) + if (type == TYPE_SKELETON || type == TYPE_UNDEAD) { getAttribute(SharedMonsterAttributes::MAX_HEALTH)->setBaseValue(15); getAttribute(SharedMonsterAttributes::MOVEMENT_SPEED)->setBaseValue(0.2f); @@ -1791,7 +1790,7 @@ void EntityHorse::positionRider() float height = .15f * standAnimO; rider.lock()->setPos(x + dist * sin, y + getRideHeight() + rider.lock()->getRidingHeight() + height, z - dist * cos); - + if ( rider.lock()->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr<LivingEntity> livingRider = dynamic_pointer_cast<LivingEntity>(rider.lock()); diff --git a/Minecraft.World/EntityIO.cpp b/Minecraft.World/EntityIO.cpp index 4532e8dd..086015dc 100644 --- a/Minecraft.World/EntityIO.cpp +++ b/Minecraft.World/EntityIO.cpp @@ -131,7 +131,7 @@ shared_ptr<Entity> EntityIO::newEntity(const wstring& id, Level *level) { shared_ptr<Entity> entity; - AUTO_VAR(it, idCreateMap->find(id)); + auto it = idCreateMap->find(id); if(it != idCreateMap->end() ) { entityCreateFn create = it->second; @@ -169,7 +169,7 @@ shared_ptr<Entity> EntityIO::loadStatic(CompoundTag *tag, Level *level) tag->remove(L"Type"); } - AUTO_VAR(it, idCreateMap->find(tag->getString(L"id"))); + auto it = idCreateMap->find(tag->getString(L"id")); if(it != idCreateMap->end() ) { entityCreateFn create = it->second; @@ -197,7 +197,7 @@ shared_ptr<Entity> EntityIO::newById(int id, Level *level) { shared_ptr<Entity> entity; - AUTO_VAR(it, numCreateMap->find(id)); + auto it = numCreateMap->find(id); if(it != numCreateMap->end() ) { entityCreateFn create = it->second; @@ -222,10 +222,10 @@ shared_ptr<Entity> EntityIO::newByEnumType(eINSTANCEOF eType, Level *level) { shared_ptr<Entity> entity; - unordered_map<eINSTANCEOF, int, eINSTANCEOFKeyHash, eINSTANCEOFKeyEq>::iterator it = classNumMap->find( eType ); + auto it = classNumMap->find( eType ); if( it != classNumMap->end() ) { - AUTO_VAR(it2, numCreateMap->find(it->second)); + auto it2 = numCreateMap->find(it->second); if(it2 != numCreateMap->end() ) { entityCreateFn create = it2->second; @@ -257,7 +257,7 @@ wstring EntityIO::getEncodeId(shared_ptr<Entity> entity) int EntityIO::getId(const wstring &encodeId) { - AUTO_VAR(it, idNumMap->find(encodeId)); + auto it = idNumMap->find(encodeId); if (it == idNumMap->end()) { // defaults to pig... @@ -274,7 +274,7 @@ wstring EntityIO::getEncodeId(int entityIoValue) //return classIdMap.get(class1); //} - AUTO_VAR(it, numClassMap->find(entityIoValue)); + auto it = numClassMap->find(entityIoValue); if(it != numClassMap->end() ) { unordered_map<eINSTANCEOF, wstring, eINSTANCEOFKeyHash, eINSTANCEOFKeyEq>::iterator classIdIt = classIdMap->find( it->second ); @@ -291,7 +291,7 @@ int EntityIO::getNameId(int entityIoValue) { int id = -1; - AUTO_VAR(it, idsSpawnableInCreative.find(entityIoValue)); + auto it = idsSpawnableInCreative.find(entityIoValue); if(it != idsSpawnableInCreative.end()) { id = it->second->nameId; @@ -302,7 +302,7 @@ int EntityIO::getNameId(int entityIoValue) eINSTANCEOF EntityIO::getType(const wstring &idString) { - AUTO_VAR(it, numClassMap->find(getId(idString))); + auto it = numClassMap->find(getId(idString)); if(it != numClassMap->end() ) { return it->second; @@ -312,7 +312,7 @@ eINSTANCEOF EntityIO::getType(const wstring &idString) eINSTANCEOF EntityIO::getClass(int id) { - AUTO_VAR(it, numClassMap->find(id)); + auto it = numClassMap->find(id); if(it != numClassMap->end() ) { return it->second; diff --git a/Minecraft.World/ExplodePacket.cpp b/Minecraft.World/ExplodePacket.cpp index aec5b261..30d09e46 100644 --- a/Minecraft.World/ExplodePacket.cpp +++ b/Minecraft.World/ExplodePacket.cpp @@ -27,16 +27,12 @@ ExplodePacket::ExplodePacket(double x, double y, double z, float r, unordered_se this->r = r; m_bKnockbackOnly = knockBackOnly; - if(toBlow != NULL) + if(toBlow != nullptr) { this->toBlow.assign(toBlow->begin(),toBlow->end()); - //for( AUTO_VAR(it, toBlow->begin()); it != toBlow->end(); it++ ) - //{ - // this->toBlow.push_back(*it); - //} } - if (knockback != NULL) + if (knockback != nullptr) { knockbackX = (float) knockback->x; knockbackY = (float) knockback->y; @@ -89,13 +85,8 @@ void ExplodePacket::write(DataOutputStream *dos) //throws IOException int yp = (int)y; int zp = (int)z; - //(Myset::const_iterator it = c1.begin(); - //it != c1.end(); ++it) - - for( AUTO_VAR(it, toBlow.begin()); it != toBlow.end(); it++ ) + for ( const TilePos& tp : toBlow ) { - TilePos tp = *it; - int xx = tp.x-xp; int yy = tp.y-yp; int zz = tp.z-zp; diff --git a/Minecraft.World/Explosion.cpp b/Minecraft.World/Explosion.cpp index 028ad673..ab305a02 100644 --- a/Minecraft.World/Explosion.cpp +++ b/Minecraft.World/Explosion.cpp @@ -29,9 +29,9 @@ Explosion::Explosion(Level *level, shared_ptr<Entity> source, double x, double y Explosion::~Explosion() { delete random; - for(AUTO_VAR(it, hitPlayers.begin()); it != hitPlayers.end(); ++it) + for( auto& it : hitPlayers ) { - delete it->second; + delete it.second; } } @@ -105,17 +105,14 @@ void Explosion::explode() vector<shared_ptr<Entity> > entities(levelEntities->begin(), levelEntities->end() ); Vec3 *center = Vec3::newTemp(x, y, z); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) + for ( auto& e : entities ) { - shared_ptr<Entity> e = *it; //entities->at(i); - // 4J Stu - If the entity is not in a block that would be blown up, then they should not be damaged // Fix for #46606 - TU5: Content: Gameplay: The player can be damaged and killed by explosions behind obsidian walls bool canDamage = false; - for(AUTO_VAR(it2, toBlow.begin()); it2 != toBlow.end(); ++it2) + for ( auto& it2 : toBlow ) { - if(e->bb->intersects(it2->x,it2->y,it2->z,it2->x + 1,it2->y + 1,it2->z + 1)) + if(e->bb->intersects(it2.x,it2.y,it2.z,it2.x + 1,it2.y + 1,it2.z + 1)) { canDamage = true; break; @@ -192,7 +189,7 @@ void Explosion::finalizeExplosion(bool generateParticles, vector<TilePos> *toBlo if( fraction == 0 ) fraction = 1; size_t j = toBlowArray->size() - 1; //for (size_t j = toBlowArray->size() - 1; j >= 0; j--) - for(AUTO_VAR(it,toBlowArray->rbegin()); it != toBlowArray->rend(); ++it) + for (auto it = toBlowArray->rbegin(); it != toBlowArray->rend(); ++it) { TilePos *tp = &(*it); //&toBlowArray->at(j); int xt = tp->x; @@ -249,8 +246,7 @@ void Explosion::finalizeExplosion(bool generateParticles, vector<TilePos> *toBlo if (fire) { - //for (size_t j = toBlowArray->size() - 1; j >= 0; j--) - for(AUTO_VAR(it,toBlowArray->rbegin()); it != toBlowArray->rend(); ++it) + for (auto it = toBlowArray->rbegin(); it != toBlowArray->rend(); ++it) { TilePos *tp = &(*it); //&toBlowArray->at(j); int xt = tp->x; @@ -276,7 +272,7 @@ Explosion::playerVec3Map *Explosion::getHitPlayers() Vec3 *Explosion::getHitPlayerKnockback( shared_ptr<Player> player ) { - AUTO_VAR(it, hitPlayers.find(player)); + auto it = hitPlayers.find(player); if(it == hitPlayers.end() ) return Vec3::newTemp(0.0,0.0,0.0); diff --git a/Minecraft.World/FallingTile.cpp b/Minecraft.World/FallingTile.cpp index 28248014..c0eb7d22 100644 --- a/Minecraft.World/FallingTile.cpp +++ b/Minecraft.World/FallingTile.cpp @@ -145,13 +145,15 @@ void FallingTile::tick() CompoundTag *swap = new CompoundTag(); tileEntity->save(swap); vector<Tag *> *allTags = tileData->getAllTags(); - for(AUTO_VAR(it, allTags->begin()); it != allTags->end(); ++it) + if ( allTags ) { - Tag *tag = *it; - if (tag->getName().compare(L"x") == 0 || tag->getName().compare(L"y") == 0 || tag->getName().compare(L"z") == 0) continue; - swap->put(tag->getName(), tag->copy()); + for ( Tag* tag : *allTags ) + { + if (tag->getName().compare(L"x") == 0 || tag->getName().compare(L"y") == 0 || tag->getName().compare(L"z") == 0) continue; + swap->put(tag->getName(), tag->copy()); + } + delete allTags; } - delete allTags; tileEntity->load(swap); tileEntity->setChanged(); } @@ -181,12 +183,14 @@ void FallingTile::causeFallDamage(float distance) // 4J: Copy vector since it might be modified when we hurt the entities (invalidating our iterator) vector<shared_ptr<Entity> > *entities = new vector<shared_ptr<Entity> >(*level->getEntities(shared_from_this(), bb)); DamageSource *source = tile == Tile::anvil_Id ? DamageSource::anvil : DamageSource::fallingBlock; - //for (Entity entity : entities) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + if ( source ) { - (*it)->hurt(source, min(Mth::floor(dmg * fallDamageAmount), fallDamageMax)); + for (auto& it : *entities) + { + it->hurt(source, static_cast<float>(std::min<int>(Mth::floor(dmg * fallDamageAmount), fallDamageMax))); + } + delete entities; } - delete entities; if (tile == Tile::anvil_Id && random->nextFloat() < 0.05f + (dmg * 0.05)) { diff --git a/Minecraft.World/File.cpp b/Minecraft.World/File.cpp index 21bc3021..82e593dc 100644 --- a/Minecraft.World/File.cpp +++ b/Minecraft.World/File.cpp @@ -152,17 +152,16 @@ bool File::mkdirs() const std::vector<std::wstring> path = stringSplit( m_abstractPathName, pathSeparator ); std::wstring pathToHere = L""; - AUTO_VAR(itEnd, path.end()); - for( AUTO_VAR(it, path.begin()); it != itEnd; it++ ) + for( auto& it : path ) { // If this member of the vector is the root then just skip to the next - if( pathRoot.compare( *it ) == 0 ) + if( pathRoot.compare(it) == 0 ) { - pathToHere = *it; + pathToHere = it; continue; } - pathToHere = pathToHere + pathSeparator + *it; + pathToHere = pathToHere + pathSeparator + it; // if not exists #ifdef _UNICODE diff --git a/Minecraft.World/FileHeader.cpp b/Minecraft.World/FileHeader.cpp index 35f7b02d..0a47e043 100644 --- a/Minecraft.World/FileHeader.cpp +++ b/Minecraft.World/FileHeader.cpp @@ -53,7 +53,7 @@ void FileHeader::RemoveFile( FileEntry *file ) AdjustStartOffsets(file, file->getFileSize(), true); - AUTO_VAR(it, find(fileTable.begin(), fileTable.end(),file)); + auto it = find(fileTable.begin(), fileTable.end(), file); if( it < fileTable.end() ) { diff --git a/Minecraft.World/Fireball.cpp b/Minecraft.World/Fireball.cpp index 1d9fbdda..2a538b06 100644 --- a/Minecraft.World/Fireball.cpp +++ b/Minecraft.World/Fireball.cpp @@ -200,11 +200,9 @@ void Fireball::tick() shared_ptr<Entity> hitEntity = nullptr; vector<shared_ptr<Entity> > *objects = level->getEntities(shared_from_this(), bb->expand(xd, yd, zd)->grow(1, 1, 1)); double nearest = 0; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) + for ( auto& e : *objects ) { - shared_ptr<Entity> e = *it; //objects->at(i); - if (!e->isPickable() || (e->is(owner) )) continue; //4J Stu - Never collide with the owner (Enderdragon) // && flightTime < 25)) continue; + if ( e == nullptr || !e->isPickable() || (e->is(owner) )) continue; //4J Stu - Never collide with the owner (Enderdragon) // && flightTime < 25)) continue; float rr = 0.3f; AABB *bb = e->bb->grow(rr, rr, rr); diff --git a/Minecraft.World/FireworksItem.cpp b/Minecraft.World/FireworksItem.cpp index 045ea130..f81b4588 100644 --- a/Minecraft.World/FireworksItem.cpp +++ b/Minecraft.World/FireworksItem.cpp @@ -52,7 +52,7 @@ void FireworksItem::appendHoverText(shared_ptr<ItemInstance> itemInstance, share } if (fireTag->contains(TAG_FLIGHT)) { - lines->push_back(wstring(app.GetString(IDS_ITEM_FIREWORKS_FLIGHT)) + L" " + _toString<int>((fireTag->getByte(TAG_FLIGHT)))); + lines->push_back(wstring(app.GetString(IDS_ITEM_FIREWORKS_FLIGHT)) + L" " + std::to_wstring((fireTag->getByte(TAG_FLIGHT)))); } ListTag<CompoundTag> *explosions = (ListTag<CompoundTag> *) fireTag->getList(TAG_EXPLOSIONS); diff --git a/Minecraft.World/FishingHook.cpp b/Minecraft.World/FishingHook.cpp index 3e627af2..e38a64b6 100644 --- a/Minecraft.World/FishingHook.cpp +++ b/Minecraft.World/FishingHook.cpp @@ -233,8 +233,7 @@ void FishingHook::tick() shared_ptr<Entity> hitEntity = nullptr; vector<shared_ptr<Entity> > *objects = level->getEntities(shared_from_this(), bb->expand(xd, yd, zd)->grow(1, 1, 1)); double nearest = 0; - AUTO_VAR(itEnd, objects->end()); - for (AUTO_VAR(it, objects->begin()); it != itEnd; it++) + for (auto it = objects->begin(); it != objects->end(); it++) { shared_ptr<Entity> e = *it; // objects->at(i); if (!e->isPickable() || (e == owner && flightTime < 5)) continue; diff --git a/Minecraft.World/FlatGeneratorInfo.cpp b/Minecraft.World/FlatGeneratorInfo.cpp index 9df19693..dfd4cb66 100644 --- a/Minecraft.World/FlatGeneratorInfo.cpp +++ b/Minecraft.World/FlatGeneratorInfo.cpp @@ -20,9 +20,9 @@ FlatGeneratorInfo::FlatGeneratorInfo() FlatGeneratorInfo::~FlatGeneratorInfo() { - for(AUTO_VAR(it, layers.begin()); it != layers.end(); ++it) + for(auto& layer : layers) { - delete *it; + delete layer; } } @@ -50,9 +50,8 @@ void FlatGeneratorInfo::updateLayers() { int y = 0; - for(AUTO_VAR(it, layers.begin()); it != layers.end(); ++it) + for(auto& layer : layers) { - FlatLayerInfo *layer = *it; layer->setStart(y); y += layer->getHeight(); } @@ -113,7 +112,7 @@ wstring FlatGeneratorInfo::toString() #endif } -FlatLayerInfo *FlatGeneratorInfo::getLayerFromString(const wstring &input, int yOffset) +FlatLayerInfo *FlatGeneratorInfo::getLayerFromString(const wstring &input, int yOffset) { return NULL; #if 0 @@ -159,9 +158,9 @@ vector<FlatLayerInfo *> *FlatGeneratorInfo::getLayersFromString(const wstring &i int yOffset = 0; - for(AUTO_VAR(it, depths.begin()); it != depths.end(); ++it) + for(auto& depth : depths) { - FlatLayerInfo *layer = getLayerFromString(*it, yOffset); + FlatLayerInfo *layer = getLayerFromString(depth, yOffset); if (layer == NULL) return NULL; result->push_back(layer); yOffset += layer->getHeight(); @@ -203,8 +202,8 @@ FlatGeneratorInfo *FlatGeneratorInfo::fromValue(const wstring &input) { std::vector<std::wstring> structures = stringSplit(parts[index++], L','); - for(AUTO_VAR(it, structures.begin()); it != structures.end(); ++it) - { + for (auto it = structures.begin(); it != structures.end(); ++it) + { std::vector<std::wstring> separated = stringSplit(parts[index++], L"\\("); unordered_map<wstring, wstring> structureOptions; diff --git a/Minecraft.World/FlatLayerInfo.cpp b/Minecraft.World/FlatLayerInfo.cpp index 4a4d79dd..331717e2 100644 --- a/Minecraft.World/FlatLayerInfo.cpp +++ b/Minecraft.World/FlatLayerInfo.cpp @@ -63,15 +63,15 @@ void FlatLayerInfo::setStart(int start) wstring FlatLayerInfo::toString() { - wstring result = _toString<int>(id); + wstring result = std::to_wstring(id); if (height > 1) { - result = _toString<int>(height) + L"x" + result; + result = std::to_wstring(height) + L"x" + result; } if (data > 0) { - result += L":" + _toString<int>(data); + result += L":" + std::to_wstring(data); } return result; diff --git a/Minecraft.World/FollowParentGoal.cpp b/Minecraft.World/FollowParentGoal.cpp index 61c5614a..8983590a 100644 --- a/Minecraft.World/FollowParentGoal.cpp +++ b/Minecraft.World/FollowParentGoal.cpp @@ -22,9 +22,9 @@ bool FollowParentGoal::canUse() shared_ptr<Animal> closest = nullptr; double closestDistSqr = Double::MAX_VALUE; - for(AUTO_VAR(it, parents->begin()); it != parents->end(); ++it) + for(auto& it : *parents) { - shared_ptr<Animal> parent = dynamic_pointer_cast<Animal>(*it); + shared_ptr<Animal> parent = dynamic_pointer_cast<Animal>(it); if (parent->getAge() < 0) continue; double distSqr = animal->distanceToSqr(parent); if (distSqr > closestDistSqr) continue; diff --git a/Minecraft.World/FurnaceMenu.cpp b/Minecraft.World/FurnaceMenu.cpp index 2a6ebc63..f67d6388 100644 --- a/Minecraft.World/FurnaceMenu.cpp +++ b/Minecraft.World/FurnaceMenu.cpp @@ -44,12 +44,10 @@ void FurnaceMenu::addSlotListener(ContainerListener *listener) void FurnaceMenu::broadcastChanges() { AbstractContainerMenu::broadcastChanges(); - - AUTO_VAR(itEnd, containerListeners.end()); - for (AUTO_VAR(it, containerListeners.begin()); it != itEnd; it++) + + for (auto& listener : containerListeners) { - ContainerListener *listener = *it; //containerListeners->at(i); - if (tc != furnace->tickCount) + if (tc != furnace->tickCount) { listener->setContainerData(this, 0, furnace->tickCount); } @@ -57,7 +55,7 @@ void FurnaceMenu::broadcastChanges() { listener->setContainerData(this, 1, furnace->litTime); } - if (ld != furnace->litDuration) + if (ld != furnace->litDuration) { listener->setContainerData(this, 2, furnace->litDuration); } diff --git a/Minecraft.World/FurnaceRecipes.cpp b/Minecraft.World/FurnaceRecipes.cpp index af59884c..bed4e1b6 100644 --- a/Minecraft.World/FurnaceRecipes.cpp +++ b/Minecraft.World/FurnaceRecipes.cpp @@ -10,12 +10,12 @@ void FurnaceRecipes::staticCtor() FurnaceRecipes::instance = new FurnaceRecipes(); } -FurnaceRecipes *FurnaceRecipes::getInstance() +FurnaceRecipes *FurnaceRecipes::getInstance() { return instance; } -FurnaceRecipes::FurnaceRecipes() +FurnaceRecipes::FurnaceRecipes() { addFurnaceRecipy(Tile::ironOre_Id, new ItemInstance(Item::ironIngot), .7f); addFurnaceRecipy(Tile::goldOre_Id, new ItemInstance(Item::goldIngot), 1); @@ -33,7 +33,7 @@ FurnaceRecipes::FurnaceRecipes() addFurnaceRecipy(Tile::emeraldOre_Id, new ItemInstance(Item::emerald), 1); addFurnaceRecipy(Item::potato_Id, new ItemInstance(Item::potatoBaked), .35f); addFurnaceRecipy(Tile::netherRack_Id, new ItemInstance(Item::netherbrick), .1f); - + // special silk touch related recipes: addFurnaceRecipy(Tile::coalOre_Id, new ItemInstance(Item::coal), .1f); addFurnaceRecipy(Tile::redStoneOre_Id, new ItemInstance(Item::redStone), .7f); @@ -43,38 +43,38 @@ FurnaceRecipes::FurnaceRecipes() } -void FurnaceRecipes::addFurnaceRecipy(int itemId, ItemInstance *result, float value) +void FurnaceRecipes::addFurnaceRecipy(int itemId, ItemInstance *result, float value) { //recipies->put(itemId, result); recipies[itemId]=result; recipeValue[result->id] = value; } -bool FurnaceRecipes::isFurnaceItem(int itemId) +bool FurnaceRecipes::isFurnaceItem(int itemId) { - AUTO_VAR(it, recipies.find(itemId)); - return it != recipies.end(); + auto it = recipies.find(itemId); + return it != recipies.end(); } -ItemInstance *FurnaceRecipes::getResult(int itemId) +ItemInstance *FurnaceRecipes::getResult(int itemId) { - AUTO_VAR(it, recipies.find(itemId)); - if(it != recipies.end()) + auto it = recipies.find(itemId); + if(it != recipies.end()) { return it->second; } return NULL; } -unordered_map<int, ItemInstance *> *FurnaceRecipes::getRecipies() +unordered_map<int, ItemInstance *> *FurnaceRecipes::getRecipies() { return &recipies; } float FurnaceRecipes::getRecipeValue(int itemId) { - AUTO_VAR(it, recipeValue.find(itemId)); - if (it != recipeValue.end()) + auto it = recipeValue.find(itemId); + if (it != recipeValue.end()) { return it->second; } diff --git a/Minecraft.World/GameRules.cpp b/Minecraft.World/GameRules.cpp index 0e594520..d1d034e2 100644 --- a/Minecraft.World/GameRules.cpp +++ b/Minecraft.World/GameRules.cpp @@ -14,27 +14,6 @@ const int GameRules::RULE_DOTILEDROPS = 5; const int GameRules::RULE_NATURAL_REGENERATION = 7; const int GameRules::RULE_DAYLIGHT = 8; -GameRules::GameRules() -{ - /*registerRule(RULE_DOFIRETICK, L"1"); - registerRule(RULE_MOBGRIEFING, L"1"); - registerRule(RULE_KEEPINVENTORY, L"0"); - registerRule(RULE_DOMOBSPAWNING, L"1"); - registerRule(RULE_DOMOBLOOT, L"1"); - registerRule(RULE_DOTILEDROPS, L"1"); - registerRule(RULE_COMMANDBLOCKOUTPUT, L"1"); - registerRule(RULE_NATURAL_REGENERATION, L"1"); - registerRule(RULE_DAYLIGHT, L"1");*/ -} - -GameRules::~GameRules() -{ - /*for(AUTO_VAR(it,rules.begin()); it != rules.end(); ++it) - { - delete it->second; - }*/ -} - bool GameRules::getBoolean(const int rule) { switch(rule) @@ -60,134 +39,3 @@ bool GameRules::getBoolean(const int rule) return false; } } - -/* -void GameRules::registerRule(const wstring &name, const wstring &startValue) -{ - rules[name] = new GameRule(startValue); -} - -void GameRules::set(const wstring &ruleName, const wstring &newValue) -{ - AUTO_VAR(it, rules.find(ruleName)); - if(it != rules.end() ) - { - GameRule *gameRule = it->second; - gameRule->set(newValue); - } - else - { - registerRule(ruleName, newValue); - } -} - -wstring GameRules::get(const wstring &ruleName) -{ - AUTO_VAR(it, rules.find(ruleName)); - if(it != rules.end() ) - { - GameRule *gameRule = it->second; - return gameRule->get(); - } - return L""; -} - -int GameRules::getInt(const wstring &ruleName) -{ - AUTO_VAR(it, rules.find(ruleName)); - if(it != rules.end() ) - { - GameRule *gameRule = it->second; - return gameRule->getInt(); - } - return 0; -} - -double GameRules::getDouble(const wstring &ruleName) -{ - AUTO_VAR(it, rules.find(ruleName)); - if(it != rules.end() ) - { - GameRule *gameRule = it->second; - return gameRule->getDouble(); - } - return 0; -} - -CompoundTag *GameRules::createTag() -{ - CompoundTag *result = new CompoundTag(L"GameRules"); - - for(AUTO_VAR(it,rules.begin()); it != rules.end(); ++it) - { - GameRule *gameRule = it->second; - result->putString(it->first, gameRule->get()); - } - - return result; -} - -void GameRules::loadFromTag(CompoundTag *tag) -{ - vector<Tag *> *allTags = tag->getAllTags(); - for (AUTO_VAR(it, allTags->begin()); it != allTags->end(); ++it) - { - Tag *ruleTag = *it; - wstring ruleName = ruleTag->getName(); - wstring value = tag->getString(ruleTag->getName()); - - set(ruleName, value); - } - delete allTags; -} - -// Need to delete returned vector. -vector<wstring> *GameRules::getRuleNames() -{ - vector<wstring> *out = new vector<wstring>(); - for (AUTO_VAR(it, rules.begin()); it != rules.end(); it++) out->push_back(it->first); - return out; -} - -bool GameRules::contains(const wstring &rule) -{ - AUTO_VAR(it, rules.find(rule)); - return it != rules.end(); -} - -GameRules::GameRule::GameRule(const wstring &startValue) -{ - value = L""; - booleanValue = false; - intValue = 0; - doubleValue = 0.0; - set(startValue); -} - -void GameRules::GameRule::set(const wstring &newValue) -{ - value = newValue; - booleanValue = _fromString<bool>(newValue); - intValue = _fromString<int>(newValue); - doubleValue = _fromString<double>(newValue); -} - -wstring GameRules::GameRule::get() -{ - return value; -} - -bool GameRules::GameRule::getBoolean() -{ - return booleanValue; -} - -int GameRules::GameRule::getInt() -{ - return intValue; -} - -double GameRules::GameRule::getDouble() -{ - return doubleValue; -}*/
\ No newline at end of file diff --git a/Minecraft.World/GameRules.h b/Minecraft.World/GameRules.h index 35eddc6c..179b499b 100644 --- a/Minecraft.World/GameRules.h +++ b/Minecraft.World/GameRules.h @@ -34,23 +34,9 @@ public: static const int RULE_NATURAL_REGENERATION; static const int RULE_DAYLIGHT; -private: - unordered_map<wstring, GameRule *> rules; - public: - GameRules(); - ~GameRules(); + GameRules() = default; + ~GameRules() = default; bool getBoolean(const int rule); - - // 4J: Removed unused functions - /*void set(const wstring &ruleName, const wstring &newValue); - void registerRule(const wstring &name, const wstring &startValue); - wstring get(const wstring &ruleName); - int getInt(const wstring &ruleName); - double getDouble(const wstring &ruleName); - CompoundTag *createTag(); - void loadFromTag(CompoundTag *tag); - vector<wstring> *getRuleNames(); - bool contains(const wstring &rule);*/ };
\ No newline at end of file diff --git a/Minecraft.World/GoalSelector.cpp b/Minecraft.World/GoalSelector.cpp index 3e3d99b5..49139f52 100644 --- a/Minecraft.World/GoalSelector.cpp +++ b/Minecraft.World/GoalSelector.cpp @@ -18,10 +18,10 @@ GoalSelector::GoalSelector() GoalSelector::~GoalSelector() { - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) + for(auto& goal : goals) { - if((*it)->canDeletePointer) delete (*it)->goal; - delete (*it); + if(goal->canDeletePointer) delete goal->goal; + delete goal; } } @@ -32,15 +32,15 @@ void GoalSelector::addGoal(int prio, Goal *goal, bool canDeletePointer /*= true* void GoalSelector::removeGoal(Goal *toRemove) { - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ) - { + for (auto it = goals.begin(); it != goals.end();) + { InternalGoal *ig = *it; Goal *goal = ig->goal; if (goal == toRemove) { - AUTO_VAR(it2, find(usingGoals.begin(), usingGoals.end(), ig) ); - if (it2 != usingGoals.end()) + auto it2 = find(usingGoals.begin(), usingGoals.end(), ig); + if (it2 != usingGoals.end()) { goal->stop(); usingGoals.erase(it2); @@ -63,14 +63,11 @@ void GoalSelector::tick() if(tickCount++ % newGoalRate == 0) { - //for (InternalGoal ig : goals) - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) + for(auto& ig : goals) { - InternalGoal *ig = *it; - //bool isUsing = usingGoals.contains(ig); - AUTO_VAR(usingIt, find(usingGoals.begin(), usingGoals.end(), ig)); + auto usingIt = find(usingGoals.begin(), usingGoals.end(), ig); - //if (isUsing) + //if (isUsing) if(usingIt != usingGoals.end()) { if (!canUseInSystem(ig) || !canContinueToUse(ig)) @@ -90,8 +87,8 @@ void GoalSelector::tick() } else { - for(AUTO_VAR(it, usingGoals.begin() ); it != usingGoals.end(); ) - { + for (auto it = usingGoals.begin(); it != usingGoals.end();) + { InternalGoal *ig = *it; if (!ig->goal->canContinueToUse()) { @@ -106,21 +103,14 @@ void GoalSelector::tick() } - //bool debug = false; - //if (debug && toStart.size() > 0) System.out.println("Starting: "); - //for (InternalGoal ig : toStart) - for(AUTO_VAR(it, toStart.begin()); it != toStart.end(); ++it) + for(auto & ig : toStart) { - //if (debug) System.out.println(ig.goal.toString() + ", "); - (*it)->goal->start(); + ig->goal->start(); } - //if (debug && usingGoals.size() > 0) System.out.println("Running: "); - //for (InternalGoal ig : usingGoals) - for(AUTO_VAR(it, usingGoals.begin()); it != usingGoals.end(); ++it) + for(auto& ig : usingGoals) { - //if (debug) System.out.println(ig.goal.toString()); - (*it)->goal->tick(); + ig->goal->tick(); } } @@ -137,14 +127,13 @@ bool GoalSelector::canContinueToUse(InternalGoal *ig) bool GoalSelector::canUseInSystem(GoalSelector::InternalGoal *goal) { //for (InternalGoal ig : goals) - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) + for(auto& ig : goals) { - InternalGoal *ig = *it; if (ig == goal) continue; - AUTO_VAR(usingIt, find(usingGoals.begin(), usingGoals.end(), ig)); + auto usingIt = find(usingGoals.begin(), usingGoals.end(), ig); - if (goal->prio >= ig->prio) + if (goal->prio >= ig->prio) { if (usingIt != usingGoals.end() && !canCoExist(goal, ig)) return false; } @@ -166,9 +155,8 @@ void GoalSelector::setNewGoalRate(int newGoalRate) void GoalSelector::setLevel(Level *level) { - for(AUTO_VAR(it, goals.begin()); it != goals.end(); ++it) + for(auto& ig : goals) { - InternalGoal *ig = *it; ig->goal->setLevel(level); } }
\ No newline at end of file diff --git a/Minecraft.World/HangingEntity.cpp b/Minecraft.World/HangingEntity.cpp index 8ba3e1fc..26261710 100644 --- a/Minecraft.World/HangingEntity.cpp +++ b/Minecraft.World/HangingEntity.cpp @@ -10,7 +10,7 @@ void HangingEntity::_init(Level *level) -{ +{ checkInterval = 0; dir = 0; xTile = yTile = zTile = 0; @@ -32,7 +32,7 @@ HangingEntity::HangingEntity(Level *level, int xTile, int yTile, int zTile, int this->zTile = zTile; } -void HangingEntity::setDir(int dir) +void HangingEntity::setDir(int dir) { this->dir = dir; yRotO = yRot = (float)(dir * 90); @@ -41,12 +41,12 @@ void HangingEntity::setDir(int dir) float h = (float)getHeight(); float d = (float)getWidth(); - if (dir == Direction::NORTH || dir == Direction::SOUTH) + if (dir == Direction::NORTH || dir == Direction::SOUTH) { d = 0.5f; yRot = yRotO = (float)(Direction::DIRECTION_OPPOSITE[dir] * 90); - } - else + } + else { w = 0.5f; } @@ -86,14 +86,14 @@ void HangingEntity::setDir(int dir) bb->set(min(x0,x1), min(y0,y1), min(z0,z1), max(x0,x1), max(y0,y1), max(z0,z1)); } -float HangingEntity::offs(int w) +float HangingEntity::offs(int w) { if (w == 32) return 0.5f; if (w == 64) return 0.5f; return 0.0f; } -void HangingEntity::tick() +void HangingEntity::tick() { xo = x; yo = y; @@ -101,7 +101,7 @@ void HangingEntity::tick() if (checkInterval++ == 20 * 5 && !level->isClientSide) { checkInterval = 0; - if (!removed && !survives()) + if (!removed && !survives()) { remove(); dropItem(nullptr); @@ -109,13 +109,13 @@ void HangingEntity::tick() } } -bool HangingEntity::survives() +bool HangingEntity::survives() { - if (level->getCubes(shared_from_this(), bb)->size()!=0)//isEmpty()) + if (level->getCubes(shared_from_this(), bb)->size()!=0)//isEmpty()) { return false; - } - else + } + else { int ws = max(1, getWidth() / 16); int hs = max(1, getHeight() / 16); @@ -131,18 +131,18 @@ bool HangingEntity::survives() for (int ss = 0; ss < ws; ss++) { - for (int yy = 0; yy < hs; yy++) + for (int yy = 0; yy < hs; yy++) { Material *m; - if (dir == Direction::NORTH || dir == Direction::SOUTH) + if (dir == Direction::NORTH || dir == Direction::SOUTH) { m = level->getMaterial(xt + ss, yt + yy, zTile); - } - else + } + else { m = level->getMaterial(xTile, yt + yy, zt + ss); } - if (!m->isSolid()) + if (!m->isSolid()) { return false; } @@ -152,11 +152,9 @@ bool HangingEntity::survives() if (entities != NULL && entities->size() > 0) { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = (*it); - if( e->instanceof(eTYPE_HANGING_ENTITY) ) + if( e && e->instanceof(eTYPE_HANGING_ENTITY) ) { return false; } @@ -167,12 +165,12 @@ bool HangingEntity::survives() return true; } -bool HangingEntity::isPickable() +bool HangingEntity::isPickable() { return true; } -bool HangingEntity::skipAttackInteraction(shared_ptr<Entity> source) +bool HangingEntity::skipAttackInteraction(shared_ptr<Entity> source) { if(source->GetType()==eTYPE_PLAYER) { @@ -181,10 +179,10 @@ bool HangingEntity::skipAttackInteraction(shared_ptr<Entity> source) return false; } -bool HangingEntity::hurt(DamageSource *source, float damage) +bool HangingEntity::hurt(DamageSource *source, float damage) { if (isInvulnerable()) return false; - if (!removed && !level->isClientSide) + if (!removed && !level->isClientSide) { if (dynamic_cast<EntityDamageSource *>(source) != NULL) { @@ -206,7 +204,7 @@ bool HangingEntity::hurt(DamageSource *source, float damage) player = dynamic_pointer_cast<Player>( e ); } - if (player != NULL && player->abilities.instabuild) + if (player != NULL && player->abilities.instabuild) { return true; } @@ -217,25 +215,25 @@ bool HangingEntity::hurt(DamageSource *source, float damage) } // 4J - added noEntityCubes parameter -void HangingEntity::move(double xa, double ya, double za, bool noEntityCubes) +void HangingEntity::move(double xa, double ya, double za, bool noEntityCubes) { - if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) + if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) { remove(); dropItem(nullptr); } } -void HangingEntity::push(double xa, double ya, double za) +void HangingEntity::push(double xa, double ya, double za) { - if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) + if (!level->isClientSide && !removed && (xa * xa + ya * ya + za * za) > 0) { remove(); dropItem(nullptr); } } -void HangingEntity::addAdditonalSaveData(CompoundTag *tag) +void HangingEntity::addAdditonalSaveData(CompoundTag *tag) { tag->putByte(L"Direction", (byte) dir); tag->putInt(L"TileX", xTile); @@ -243,7 +241,7 @@ void HangingEntity::addAdditonalSaveData(CompoundTag *tag) tag->putInt(L"TileZ", zTile); // Back compat - switch (dir) + switch (dir) { case Direction::NORTH: tag->putByte(L"Dir", (byte) 0); @@ -260,15 +258,15 @@ void HangingEntity::addAdditonalSaveData(CompoundTag *tag) } } -void HangingEntity::readAdditionalSaveData(CompoundTag *tag) +void HangingEntity::readAdditionalSaveData(CompoundTag *tag) { - if (tag->contains(L"Direction")) + if (tag->contains(L"Direction")) { dir = tag->getByte(L"Direction"); - } - else + } + else { - switch (tag->getByte(L"Dir")) + switch (tag->getByte(L"Dir")) { case 0: dir = Direction::NORTH; diff --git a/Minecraft.World/Hasher.cpp b/Minecraft.World/Hasher.cpp index 954ff1e4..86030e21 100644 --- a/Minecraft.World/Hasher.cpp +++ b/Minecraft.World/Hasher.cpp @@ -19,7 +19,7 @@ wstring Hasher::getHash(wstring &name) //return new BigInteger(1, m.digest()).toString(16); // TODO 4J Stu - Will this hash us with the same distribution as the MD5? - return _toString(std::hash<wstring>{}( s ) ); + return std::to_wstring(std::hash<wstring>{}( s ) ); //} //catch (NoSuchAlgorithmException e) //{ diff --git a/Minecraft.World/HealthCriteria.cpp b/Minecraft.World/HealthCriteria.cpp index 52db9f11..33520621 100644 --- a/Minecraft.World/HealthCriteria.cpp +++ b/Minecraft.World/HealthCriteria.cpp @@ -10,9 +10,8 @@ int HealthCriteria::getScoreModifier(vector<shared_ptr<Player> > *players) { float health = 0; - for (AUTO_VAR(it,players->begin()); it != players->end(); ++it) + for (auto& player : *players) { - shared_ptr<Player> player = *it; health += player->getHealth() + player->getAbsorptionAmount(); } diff --git a/Minecraft.World/HurtByTargetGoal.cpp b/Minecraft.World/HurtByTargetGoal.cpp index 32bcd3c7..076e5b6a 100644 --- a/Minecraft.World/HurtByTargetGoal.cpp +++ b/Minecraft.World/HurtByTargetGoal.cpp @@ -26,9 +26,9 @@ void HurtByTargetGoal::start() { double within = getFollowDistance(); vector<shared_ptr<Entity> > *nearby = mob->level->getEntitiesOfClass(typeid(*mob), AABB::newTemp(mob->x, mob->y, mob->z, mob->x + 1, mob->y + 1, mob->z + 1)->grow(within, 4, within)); - for(AUTO_VAR(it, nearby->begin()); it != nearby->end(); ++it) + for(auto& it : *nearby) { - shared_ptr<PathfinderMob> other = dynamic_pointer_cast<PathfinderMob>(*it); + shared_ptr<PathfinderMob> other = dynamic_pointer_cast<PathfinderMob>(it); if (this->mob->shared_from_this() == other) continue; if (other->getTarget() != NULL) continue; if (other->isAlliedTo(mob->getLastHurtByMob())) continue; // don't target allies diff --git a/Minecraft.World/ItemEntity.cpp b/Minecraft.World/ItemEntity.cpp index e6bdffa5..66d271f7 100644 --- a/Minecraft.World/ItemEntity.cpp +++ b/Minecraft.World/ItemEntity.cpp @@ -72,7 +72,7 @@ void ItemEntity::defineSynchedData() void ItemEntity::tick() { Entity::tick(); - + if (throwTime > 0) throwTime--; xo = x; yo = y; @@ -80,7 +80,7 @@ void ItemEntity::tick() yd -= 0.04f; noPhysics = checkInTile(x, (bb->y0 + bb->y1) / 2, z); - + // 4J - added parameter here so that these don't care about colliding with other entities move(xd, yd, zd, true); @@ -133,11 +133,11 @@ void ItemEntity::tick() } void ItemEntity::mergeWithNeighbours() -{ +{ vector<shared_ptr<Entity> > *neighbours = level->getEntitiesOfClass(typeid(*this), bb->grow(0.5, 0, 0.5)); - for(AUTO_VAR(it, neighbours->begin()); it != neighbours->end(); ++it) + for(auto& neighbour : *neighbours) { - shared_ptr<ItemEntity> entity = dynamic_pointer_cast<ItemEntity>(*it); + shared_ptr<ItemEntity> entity = dynamic_pointer_cast<ItemEntity>(neighbour); merge(entity); } delete neighbours; @@ -189,7 +189,7 @@ bool ItemEntity::hurt(DamageSource *source, float damage) // 4J - added next line: found whilst debugging an issue with item entities getting into a bad state when being created by a cactus, since entities insides cactuses get hurt // and therefore depending on the timing of things they could get removed from the client when they weren't supposed to be. Are there really any cases were we would want // an itemEntity to be locally hurt? - if (level->isClientSide ) return false; + if (level->isClientSide ) return false; if (isInvulnerable()) return false; if (getItem() != NULL && getItem()->id == Item::netherStar_Id && source->isExplosion()) return false; @@ -253,7 +253,7 @@ void ItemEntity::playerTouch(shared_ptr<Player> player) } #endif } - if (item->id == Item::blazeRod_Id) + if (item->id == Item::blazeRod_Id) player->awardStat(GenericStats::blazeRod(), GenericStats::param_blazeRod()); playSound(eSoundType_RANDOM_POP, 0.2f, ((random->nextFloat() - random->nextFloat()) * 0.7f + 1.0f) * 2.0f); diff --git a/Minecraft.World/ItemInstance.cpp b/Minecraft.World/ItemInstance.cpp index 32367b12..4dcde7aa 100644 --- a/Minecraft.World/ItemInstance.cpp +++ b/Minecraft.World/ItemInstance.cpp @@ -588,7 +588,7 @@ vector<HtmlString> *ItemInstance::getHoverText(shared_ptr<Player> player, bool a /*if (!hasCustomHoverName() && id == Item::map_Id) { - title.text += L" #" + _toString(auxValue); + title.text += L" #" + std::to_wstring(auxValue); }*/ lines->push_back(title); @@ -652,20 +652,20 @@ vector<HtmlString> *ItemInstance::getHoverText(shared_ptr<Player> player, bool a if (!modifiers->empty()) { // New line - lines->push_back(HtmlString(L"")); + lines->emplace_back(L""); // Modifier descriptions - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& modifier : *modifiers) { // 4J: Moved modifier string building to AttributeModifier - lines->push_back(it->second->getHoverText(it->first)); + lines->push_back(modifier.second->getHoverText(modifier.first)); } } // Delete modifiers map - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& it : *modifiers) { - AttributeModifier *modifier = it->second; + AttributeModifier *modifier = it.second; delete modifier; } delete modifiers; @@ -674,7 +674,7 @@ vector<HtmlString> *ItemInstance::getHoverText(shared_ptr<Player> player, bool a { if (isDamaged()) { - wstring damageStr = L"Durability: LOCALISE " + _toString<int>((getMaxDamage()) - getDamageValue()) + L" / " + _toString<int>(getMaxDamage()); + wstring damageStr = L"Durability: LOCALISE " + std::to_wstring((getMaxDamage()) - getDamageValue()) + L" / " + std::to_wstring(getMaxDamage()); lines->push_back(HtmlString(damageStr)); } } diff --git a/Minecraft.World/LeashFenceKnotEntity.cpp b/Minecraft.World/LeashFenceKnotEntity.cpp index 21f98a6a..55947d04 100644 --- a/Minecraft.World/LeashFenceKnotEntity.cpp +++ b/Minecraft.World/LeashFenceKnotEntity.cpp @@ -79,9 +79,9 @@ bool LeashFenceKnotEntity::interact(shared_ptr<Player> player) vector<shared_ptr<Entity> > *mobs = level->getEntitiesOfClass(typeid(Mob), AABB::newTemp(x - range, y - range, z - range, x + range, y + range, z + range)); if (mobs != NULL) { - for(AUTO_VAR(it, mobs->begin()); it != mobs->end(); ++it) + for(auto& it : *mobs) { - shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>( *it ); + shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>( it ); if (mob->isLeashed() && mob->getLeashHolder() == player) { mob->setLeashedTo(shared_from_this(), true); @@ -103,9 +103,9 @@ bool LeashFenceKnotEntity::interact(shared_ptr<Player> player) vector<shared_ptr<Entity> > *mobs = level->getEntitiesOfClass(typeid(Mob), AABB::newTemp(x - range, y - range, z - range, x + range, y + range, z + range)); if (mobs != NULL) { - for(AUTO_VAR(it, mobs->begin()); it != mobs->end(); ++it) + for(auto& it : *mobs) { - shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>( *it ); + shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>( it ); if (mob->isLeashed() && mob->getLeashHolder() == shared_from_this()) { mob->dropLeash(true, false); @@ -142,9 +142,9 @@ shared_ptr<LeashFenceKnotEntity> LeashFenceKnotEntity::findKnotAt(Level *level, vector<shared_ptr<Entity> > *knots = level->getEntitiesOfClass(typeid(LeashFenceKnotEntity), AABB::newTemp(x - 1.0, y - 1.0, z - 1.0, x + 1.0, y + 1.0, z + 1.0)); if (knots != NULL) { - for(AUTO_VAR(it, knots->begin()); it != knots->end(); ++it) - { - shared_ptr<LeashFenceKnotEntity> knot = dynamic_pointer_cast<LeashFenceKnotEntity>( *it ); + for (auto& it : *knots ) + { + shared_ptr<LeashFenceKnotEntity> knot = dynamic_pointer_cast<LeashFenceKnotEntity>( it ); if (knot->xTile == x && knot->yTile == y && knot->zTile == z) { delete knots; diff --git a/Minecraft.World/LeashItem.cpp b/Minecraft.World/LeashItem.cpp index d8d7b3fc..ddb7878b 100644 --- a/Minecraft.World/LeashItem.cpp +++ b/Minecraft.World/LeashItem.cpp @@ -38,9 +38,9 @@ bool LeashItem::bindPlayerMobs(shared_ptr<Player> player, Level *level, int x, i vector<shared_ptr<Entity> > *mobs = level->getEntitiesOfClass(typeid(Mob), AABB::newTemp(x - range, y - range, z - range, x + range, y + range, z + range)); if (mobs != NULL) { - for(AUTO_VAR(it,mobs->begin()); it != mobs->end(); ++it) + for(auto& it : *mobs) { - shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(*it); + shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(it); if (mob->isLeashed() && mob->getLeashHolder() == player) { if (activeKnot == NULL) @@ -64,9 +64,9 @@ bool LeashItem::bindPlayerMobsTest(shared_ptr<Player> player, Level *level, int if (mobs != NULL) { - for(AUTO_VAR(it,mobs->begin()); it != mobs->end(); ++it) + for(auto& it : *mobs) { - shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(*it); + shared_ptr<Mob> mob = dynamic_pointer_cast<Mob>(it); if (mob->isLeashed() && mob->getLeashHolder() == player) return true; } } diff --git a/Minecraft.World/Level.cpp b/Minecraft.World/Level.cpp index f9c383ed..b977ad7d 100644 --- a/Minecraft.World/Level.cpp +++ b/Minecraft.World/Level.cpp @@ -691,7 +691,7 @@ void Level::_init(shared_ptr<LevelStorage>levelStorage, const wstring& levelName //{ // dimension = Dimension::getNew(levelData->getDimension()); //} - else + else { dimension = Dimension::getNew(0); } @@ -740,7 +740,7 @@ Level::~Level() DeleteCriticalSection(&m_checkLightCS); // 4J-PB - savedDataStorage is shared between overworld and nether levels in the server, so it will already have been deleted on the first level delete - if(savedDataStorage!=NULL) delete savedDataStorage; + if(savedDataStorage!=NULL) delete savedDataStorage; DeleteCriticalSection(&m_entitiesCS); DeleteCriticalSection(&m_tileEntityListCS); @@ -934,7 +934,7 @@ bool Level::setTileAndData(int x, int y, int z, int tile, int data, int updateFl int olddata = c->getData( x & 15, y, z & 15); #endif result = c->setTileAndData(x & 15, y, z & 15, tile, data); - if( updateFlags != Tile::UPDATE_INVISIBLE_NO_LIGHT) + if( updateFlags != Tile::UPDATE_INVISIBLE_NO_LIGHT) { #ifndef _CONTENT_PACKAGE PIXBeginNamedEvent(0,"Checking light %d %d %d",x,y,z); @@ -1019,7 +1019,7 @@ bool Level::setData(int x, int y, int z, int data, int updateFlags, bool forceUp /** * Sets a tile to air without dropping resources or showing any animation. -* +* * @param x * @param y * @param z @@ -1033,7 +1033,7 @@ bool Level::removeTile(int x, int y, int z) /** * Sets a tile to air and plays a destruction animation, with option to also * drop resources. -* +* * @param x * @param y * @param z @@ -1063,10 +1063,9 @@ bool Level::setTileAndUpdate(int x, int y, int z, int tile) void Level::sendTileUpdated(int x, int y, int z) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->tileChanged(x, y, z); + listener->tileChanged(x, y, z); } } @@ -1105,20 +1104,18 @@ void Level::lightColumnChanged(int x, int z, int y0, int y1) void Level::setTileDirty(int x, int y, int z) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->setTilesDirty(x, y, z, x, y, z, this); + listener->setTilesDirty(x, y, z, x, y, z, this); } } void Level::setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->setTilesDirty(x0, y0, z0, x1, y1, z1, this); + listener->setTilesDirty(x0, y0, z0, x1, y1, z1, this); } } @@ -1351,7 +1348,7 @@ int Level::getBrightness(LightLayer::variety layer, int x, int y, int z) // the level chunk once void Level::getNeighbourBrightnesses(int *brightnesses, LightLayer::variety layer, int x, int y, int z) { - if( ( ( ( x & 15 ) == 0 ) || ( ( x & 15 ) == 15 ) ) || + if( ( ( ( x & 15 ) == 0 ) || ( ( x & 15 ) == 15 ) ) || ( ( ( z & 15 ) == 0 ) || ( ( z & 15 ) == 15 ) ) || ( ( y <= 0 ) || ( y >= 127 ) ) ) { @@ -1443,20 +1440,18 @@ void Level::setBrightness(LightLayer::variety layer, int x, int y, int z, int br } else { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->tileLightChanged(x, y, z); + listener->tileLightChanged(x, y, z); } } } void Level::setTileBrightnessChanged(int x, int y, int z) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->tileLightChanged(x, y, z); + listener->tileLightChanged(x, y, z); } } @@ -1637,19 +1632,18 @@ HitResult *Level::clip(Vec3 *a, Vec3 *b, bool liquid, bool solidOnly) void Level::playEntitySound(shared_ptr<Entity> entity, int iSound, float volume, float pitch) { if(entity == NULL) return; - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { // 4J-PB - if the entity is a local player, don't play the sound if(entity->GetType() == eTYPE_SERVERPLAYER) { //app.DebugPrintf("ENTITY is serverplayer\n"); - (*it)->playSound(iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); + listener->playSound(iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); } else { - (*it)->playSound(iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); + listener->playSound(iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); } } } @@ -1657,20 +1651,18 @@ void Level::playEntitySound(shared_ptr<Entity> entity, int iSound, float volume, void Level::playPlayerSound(shared_ptr<Player> entity, int iSound, float volume, float pitch) { if (entity == NULL) return; - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->playSoundExceptPlayer(entity, iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); + listener->playSoundExceptPlayer(entity, iSound, entity->x, entity->y - entity->heightOffset, entity->z, volume, pitch); } } //void Level::playSound(double x, double y, double z, const wstring& name, float volume, float pitch) void Level::playSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->playSound(iSound, x, y, z, volume, pitch, fClipSoundDist); + listener->playSound(iSound, x, y, z, volume, pitch, fClipSoundDist); } } @@ -1680,10 +1672,9 @@ void Level::playLocalSound(double x, double y, double z, int iSound, float volum void Level::playStreamingMusic(const wstring& name, int x, int y, int z) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->playStreamingMusic(name, x, y, z); + listener->playStreamingMusic(name, x, y, z); } } @@ -1692,22 +1683,11 @@ void Level::playMusic(double x, double y, double z, const wstring& string, float { } -// 4J removed - -/* -void Level::addParticle(const wstring& id, double x, double y, double z, double xd, double yd, double zd) -{ -AUTO_VAR(itEnd, listeners.end()); -for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) -(*it)->addParticle(id, x, y, z, xd, yd, zd); -} -*/ - // 4J-PB added void Level::addParticle(ePARTICLE_TYPE id, double x, double y, double z, double xd, double yd, double zd) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) - (*it)->addParticle(id, x, y, z, xd, yd, zd); + for (auto& listener : listeners) + listener->addParticle(id, x, y, z, xd, yd, zd); } bool Level::addGlobalEntity(shared_ptr<Entity> e) @@ -1768,48 +1748,45 @@ bool Level::addEntity(shared_ptr<Entity> e) void Level::entityAdded(shared_ptr<Entity> e) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->entityAdded(e); + listener->entityAdded(e); } } void Level::entityRemoved(shared_ptr<Entity> e) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->entityRemoved(e); + listener->entityRemoved(e); } } // 4J added void Level::playerRemoved(shared_ptr<Entity> e) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->playerRemoved(e); + listener->playerRemoved(e); } } void Level::removeEntity(shared_ptr<Entity> e) { - if (e->rider.lock() != NULL) + if (e->rider.lock()) { e->rider.lock()->ride(nullptr); } - if (e->riding != NULL) + if (e->riding) { e->ride(nullptr); } e->remove(); if (e->instanceof(eTYPE_PLAYER)) { - vector<shared_ptr<Player> >::iterator it = players.begin(); - vector<shared_ptr<Player> >::iterator itEnd = players.end(); + auto it = players.begin(); + auto itEnd = players.end(); while( it != itEnd && *it != dynamic_pointer_cast<Player>(e) ) it++; @@ -1958,16 +1935,15 @@ AABBList *Level::getCubes(shared_ptr<Entity> source, AABB *box, bool noEntities/ double r = 0.25; vector<shared_ptr<Entity> > *ee = getEntities(source, box->grow(r, r, r)); - vector<shared_ptr<Entity> >::iterator itEnd = ee->end(); - for (AUTO_VAR(it, ee->begin()); it != itEnd; it++) + for (auto& it : *ee) { - AABB *collideBox = (*it)->getCollideBox(); + AABB *collideBox = it->getCollideBox(); if (collideBox != NULL && collideBox->intersects(box)) { boxes.push_back(collideBox); } - collideBox = source->getCollideAgainstBox(*it); + collideBox = source->getCollideAgainstBox(it); if (collideBox != NULL && collideBox->intersects(box)) { boxes.push_back(collideBox); @@ -2277,12 +2253,12 @@ void Level::tickEntities() EnterCriticalSection(&m_entitiesCS); - for( AUTO_VAR(it, entities.begin()); it != entities.end(); ) - { + for (auto it = entities.begin(); it != entities.end();) + { bool found = false; - for( AUTO_VAR(it2, entitiesToRemove.begin()); it2 != entitiesToRemove.end(); it2++ ) + for(auto& it2 : entitiesToRemove) { - if( (*it) == (*it2) ) + if( (*it) == it2 ) { found = true; break; @@ -2299,10 +2275,8 @@ void Level::tickEntities() } LeaveCriticalSection(&m_entitiesCS); - AUTO_VAR(itETREnd, entitiesToRemove.end()); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != itETREnd; it++) + for (auto& e : entitiesToRemove) { - shared_ptr<Entity> e = *it;//entitiesToRemove.at(j); int xc = e->xChunk; int zc = e->zChunk; if (e->inChunk && hasChunk(xc, zc)) @@ -2311,12 +2285,11 @@ void Level::tickEntities() } } - itETREnd = entitiesToRemove.end(); - for (AUTO_VAR(it, entitiesToRemove.begin()); it != itETREnd; it++) + for (auto& it : entitiesToRemove) { - entityRemoved(*it); + entityRemoved(it); } - // + // entitiesToRemove.clear(); //for (int i = 0; i < entities.size(); i++) @@ -2348,7 +2321,7 @@ void Level::tickEntities() { #ifndef _FINAL_BUILD if ( !( app.DebugSettingsOn() && app.GetMobsDontTickEnabled() && e->instanceof(eTYPE_MOB) && !e->instanceof(eTYPE_PLAYER)) ) -#endif +#endif { tick(e); } @@ -2367,8 +2340,8 @@ void Level::tickEntities() // 4J Find the entity again before deleting, as things might have moved in the entity array eg // from the explosion created by tnt - AUTO_VAR(it, find(entities.begin(), entities.end(), e)); - if( it != entities.end() ) + auto it = find(entities.begin(), entities.end(), e); + if( it != entities.end() ) { entities.erase(it); } @@ -2385,8 +2358,8 @@ void Level::tickEntities() EnterCriticalSection(&m_tileEntityListCS); updatingTileEntities = true; - for (AUTO_VAR(it, tileEntityList.begin()); it != tileEntityList.end();) - { + for (auto it = tileEntityList.begin(); it != tileEntityList.end();) + { shared_ptr<TileEntity> te = *it;//tilevector<shared_ptr<Entity> >.at(i); if( !te->isRemoved() && te->hasLevel() ) { @@ -2421,15 +2394,15 @@ void Level::tickEntities() // 4J-PB - Stuart - check this is correct here if (!tileEntitiesToUnload.empty()) - { + { //tileEntityList.removeAll(tileEntitiesToUnload); - for( AUTO_VAR(it, tileEntityList.begin()); it != tileEntityList.end(); ) - { + for (auto it = tileEntityList.begin(); it != tileEntityList.end();) + { bool found = false; - for( AUTO_VAR(it2, tileEntitiesToUnload.begin()); it2 != tileEntitiesToUnload.end(); it2++ ) + for(auto& it2 : tileEntitiesToUnload) { - if( (*it) == (*it2) ) + if( (*it) == it2 ) { found = true; break; @@ -2453,10 +2426,9 @@ void Level::tickEntities() if( !pendingTileEntities.empty() ) { - for( AUTO_VAR(it, pendingTileEntities.begin()); it != pendingTileEntities.end(); it++ ) + for(auto& e : pendingTileEntities) { - shared_ptr<TileEntity> e = *it; - if( !e->isRemoved() ) + if( e && !e->isRemoved() ) { if( find(tileEntityList.begin(),tileEntityList.end(),e) == tileEntityList.end() ) { @@ -2481,16 +2453,16 @@ void Level::addAllPendingTileEntities(vector< shared_ptr<TileEntity> >& entities EnterCriticalSection(&m_tileEntityListCS); if( updatingTileEntities ) { - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) + for(auto& it : entities) { - pendingTileEntities.push_back(*it); + pendingTileEntities.push_back(it); } } else { - for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) + for(auto& it : entities) { - tileEntityList.push_back(*it); + tileEntityList.push_back(it); } } LeaveCriticalSection(&m_tileEntityListCS); @@ -2602,11 +2574,9 @@ bool Level::isUnobstructed(AABB *aabb) bool Level::isUnobstructed(AABB *aabb, shared_ptr<Entity> ignore) { vector<shared_ptr<Entity> > *ents = getEntities(nullptr, aabb); - AUTO_VAR(itEnd, ents->end()); - for (AUTO_VAR(it, ents->begin()); it != itEnd; it++) + for (auto& e : *ents) { - shared_ptr<Entity> e = *it; - if (!e->removed && e->blocksBuilding && e != ignore) return false; + if (e && !e->removed && e->blocksBuilding && e != ignore) return false; } return true; } @@ -2841,7 +2811,7 @@ shared_ptr<Explosion> Level::explode(shared_ptr<Entity> source, double x, double shared_ptr<Explosion> Level::explode(shared_ptr<Entity> source, double x, double y, double z, float r, bool fire, bool destroyBlocks) { shared_ptr<Explosion> explosion = shared_ptr<Explosion>( new Explosion(this, source, x, y, z, r) ); - explosion->fire = fire; + explosion->fire = fire; explosion->destroyBlocks = destroyBlocks; explosion->explode(); explosion->finalizeExplosion(true); @@ -2950,11 +2920,9 @@ shared_ptr<TileEntity> Level::getTileEntity(int x, int y, int z) if (tileEntity == NULL) { EnterCriticalSection(&m_tileEntityListCS); - for( AUTO_VAR(it, pendingTileEntities.begin()); it != pendingTileEntities.end(); it++ ) + for(auto& e : pendingTileEntities) { - shared_ptr<TileEntity> e = *it; - - if (!e->isRemoved() && e->x == x && e->y == y && e->z == z) + if ( e && !e->isRemoved() && e->x == x && e->y == y && e->z == z) { tileEntity = e; break; @@ -2978,8 +2946,8 @@ void Level::setTileEntity(int x, int y, int z, shared_ptr<TileEntity> tileEntity tileEntity->z = z; // avoid adding duplicates - for( AUTO_VAR(it, pendingTileEntities.begin()); it != pendingTileEntities.end();) - { + for (auto it = pendingTileEntities.begin(); it != pendingTileEntities.end();) + { shared_ptr<TileEntity> next = *it; if (next->x == x && next->y == y && next->z == z) { @@ -3012,8 +2980,8 @@ void Level::removeTileEntity(int x, int y, int z) if (te != NULL && updatingTileEntities) { te->setRemoved(); - AUTO_VAR(it, find(pendingTileEntities.begin(), pendingTileEntities.end(), te )); - if( it != pendingTileEntities.end() ) + auto it = find(pendingTileEntities.begin(), pendingTileEntities.end(), te); + if( it != pendingTileEntities.end() ) { pendingTileEntities.erase(it); } @@ -3022,13 +2990,13 @@ void Level::removeTileEntity(int x, int y, int z) { if (te != NULL) { - AUTO_VAR(it, find(pendingTileEntities.begin(), pendingTileEntities.end(), te )); - if( it != pendingTileEntities.end() ) + auto it = find(pendingTileEntities.begin(), pendingTileEntities.end(), te); + if( it != pendingTileEntities.end() ) { pendingTileEntities.erase(it); } - AUTO_VAR(it2, find(tileEntityList.begin(), tileEntityList.end(), te)); - if( it2 != tileEntityList.end() ) + auto it2 = find(tileEntityList.begin(), tileEntityList.end(), te); + if( it2 != tileEntityList.end() ) { tileEntityList.erase(it2); } @@ -3126,7 +3094,7 @@ bool Level::isTopSolidBlocking(Tile *tile, int data) if (tile == NULL) return false; if (tile->material->isSolidBlocking() && tile->isCubeShaped()) return true; - if (dynamic_cast<StairTile *>(tile) != NULL) + if (dynamic_cast<StairTile *>(tile) != NULL) { return (data & StairTile::UPSIDEDOWN_BIT) == StairTile::UPSIDEDOWN_BIT; } @@ -3273,11 +3241,9 @@ void Level::toggleDownfall() void Level::buildAndPrepareChunksToPoll() { -#if 0 - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) +#if 0 + for (auto& player : players) { - shared_ptr<Player> player = *it; int xx = Mth::floor(player->x / 16); int zz = Mth::floor(player->z / 16); @@ -3295,7 +3261,7 @@ void Level::buildAndPrepareChunksToPoll() int playerCount = (int)players.size(); int *xx = new int[playerCount]; int *zz = new int[playerCount]; - for (int i = 0; i < playerCount; i++) + for (size_t i = 0; i < playerCount; i++) { shared_ptr<Player> player = players[i]; xx[i] = Mth::floor(player->x / 16); @@ -3534,7 +3500,7 @@ void Level::checkLight(LightLayer::variety layer, int xc, int yc, int zc, bool f { int centerCurrent = getBrightnessCached(cache, layer, xc, yc, zc); int centerExpected = getExpectedLight(cache, xc, yc, zc, layer, false); - + if( centerExpected != centerCurrent && cache ) { initCacheComplete(cache, xc, yc, zc); @@ -3802,9 +3768,8 @@ shared_ptr<Entity> Level::getClosestEntityOfClass(const type_info& baseClass, AA shared_ptr<Entity> closest = nullptr; double closestDistSqr = Double::MAX_VALUE; //for (Entity entity : entities) - for(AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + for(auto& entity : *entities) { - shared_ptr<Entity> entity = *it; if (entity == source) continue; double distSqr = source->distanceToSqr(entity); if (distSqr > closestDistSqr) continue; @@ -3837,10 +3802,8 @@ unsigned int Level::countInstanceOf(BaseObject::Class *clas) { unsigned int count = 0; EnterCriticalSection(&m_entitiesCS); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) + for (auto& e : entities) { - shared_ptr<Entity> e = *it;//entities.at(i); if (clas->isAssignableFrom(e->getClass())) count++; } LeaveCriticalSection(&m_entitiesCS); @@ -3857,10 +3820,8 @@ unsigned int Level::countInstanceOf(eINSTANCEOF clas, bool singleType, unsigned if( protectedCount ) *protectedCount = 0; if( couldWanderCount ) *couldWanderCount = 0; EnterCriticalSection(&m_entitiesCS); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) + for (auto& e : entities) { - shared_ptr<Entity> e = *it;//entities.at(i); if( singleType ) { if (e->GetType() == clas) @@ -3892,11 +3853,8 @@ unsigned int Level::countInstanceOfInRange(eINSTANCEOF clas, bool singleType, in { unsigned int count = 0; EnterCriticalSection(&m_entitiesCS); - AUTO_VAR(itEnd, entities.end()); - for (AUTO_VAR(it, entities.begin()); it != itEnd; it++) + for (auto& e : entities) { - shared_ptr<Entity> e = *it;//entities.at(i); - float sd = e->distanceTo(x,y,z); if (sd * sd > range * range) { @@ -3925,14 +3883,13 @@ void Level::addEntities(vector<shared_ptr<Entity> > *list) //entities.addAll(list); EnterCriticalSection(&m_entitiesCS); entities.insert(entities.end(), list->begin(), list->end()); - AUTO_VAR(itEnd, list->end()); bool deleteDragons = false; - for (AUTO_VAR(it, list->begin()); it != itEnd; it++) + for (auto& it : *list) { - entityAdded(*it); + entityAdded(it); // 4J Stu - Special change to remove duplicate enderdragons that a previous bug might have produced - if( (*it)->GetType() == eTYPE_ENDERDRAGON) + if( it->GetType() == eTYPE_ENDERDRAGON) { deleteDragons = true; } @@ -3941,14 +3898,14 @@ void Level::addEntities(vector<shared_ptr<Entity> > *list) if(deleteDragons) { deleteDragons = false; - for(AUTO_VAR(it, entities.begin()); it != entities.end(); ++it) + for(auto& it : entities) { // 4J Stu - Special change to remove duplicate enderdragons that a previous bug might have produced - if( (*it)->GetType() == eTYPE_ENDERDRAGON) + if( it->GetType() == eTYPE_ENDERDRAGON) { if(deleteDragons) { - (*it)->remove(); + it->remove(); } else { @@ -4118,10 +4075,8 @@ shared_ptr<Player> Level::getNearestPlayer(double x, double y, double z, double MemSect(21); double best = -1; shared_ptr<Player> result = nullptr; - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& p : players) { - shared_ptr<Player> p = *it;//players.at(i); double dist = p->distanceToSqr(x, y, z); // Allow specifying shorter distances in the vertical @@ -4142,10 +4097,8 @@ shared_ptr<Player> Level::getNearestPlayer(double x, double z, double maxDist) { double best = -1; shared_ptr<Player> result = nullptr; - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& p : players) { - shared_ptr<Player> p = *it; double dist = p->distanceToSqr(x, p->y, z); if ((maxDist < 0 || dist < maxDist * maxDist) && (best == -1 || dist < best)) { @@ -4166,11 +4119,8 @@ shared_ptr<Player> Level::getNearestAttackablePlayer(double x, double y, double double best = -1; shared_ptr<Player> result = nullptr; - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& p : players) { - shared_ptr<Player> p = *it; - // 4J Stu - Added privilege check if (p->abilities.invulnerable || !p->isAlive() || p->hasInvisiblePrivilege() ) { @@ -4207,28 +4157,26 @@ shared_ptr<Player> Level::getNearestAttackablePlayer(double x, double y, double shared_ptr<Player> Level::getPlayerByName(const wstring& name) { - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& player : players) { - if (name.compare( (*it)->getName()) == 0) + if (name.compare( player->getName()) == 0) { - return *it; //players.at(i); + return player; } } - return shared_ptr<Player>(); + return {}; } shared_ptr<Player> Level::getPlayerByUUID(const wstring& name) { - AUTO_VAR(itEnd, players.end()); - for (AUTO_VAR(it, players.begin()); it != itEnd; it++) + for (auto& player : players) { - if (name.compare( (*it)->getUUID() ) == 0) + if (name.compare( player->getUUID() ) == 0) { - return *it; //players.at(i); + return player; } } - return shared_ptr<Player>(); + return {}; } // 4J Stu - Removed in 1.2.3 ? @@ -4355,10 +4303,9 @@ void Level::setGameTime(__int64 time) // Apply stat to each player. if ( timeDiff > 0 && levelData->getGameTime() != -1 ) { - AUTO_VAR(itEnd, players.end()); - for (vector<shared_ptr<Player> >::iterator it = players.begin(); it != itEnd; it++) + for (auto& player : players) { - (*it)->awardStat( GenericStats::timePlayed(), GenericStats::param_time(timeDiff) ); + player->awardStat( GenericStats::timePlayed(), GenericStats::param_time(timeDiff) ); } } } @@ -4538,12 +4485,11 @@ int Level::getAuxValueForMap(PlayerUID xuid, int dimension, int centreXC, int ce return savedDataStorage->getAuxValueForMap(xuid, dimension, centreXC, centreZC, scale); } -void Level::globalLevelEvent(int type, int sourceX, int sourceY, int sourceZ, int data) +void Level::globalLevelEvent(int type, int sourceX, int sourceY, int sourceZ, int data) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->globalLevelEvent(type, sourceX, sourceY, sourceZ, data); + listener->globalLevelEvent(type, sourceX, sourceY, sourceZ, data); } } @@ -4555,10 +4501,9 @@ void Level::levelEvent(int type, int x, int y, int z, int data) void Level::levelEvent(shared_ptr<Player> source, int type, int x, int y, int z, int data) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->levelEvent(source, type, x, y, z, data); + listener->levelEvent(source, type, x, y, z, data); } } @@ -4594,9 +4539,9 @@ bool Level::isAllEmpty() return false; } -double Level::getHorizonHeight() +double Level::getHorizonHeight() { - if (levelData->getGenerator() == LevelType::lvl_flat) + if (levelData->getGenerator() == LevelType::lvl_flat) { return 0.0; } @@ -4605,10 +4550,9 @@ double Level::getHorizonHeight() void Level::destroyTileProgress(int id, int x, int y, int z, int progress) { - AUTO_VAR(itEnd, listeners.end()); - for (AUTO_VAR(it, listeners.begin()); it != itEnd; it++) + for (auto& listener : listeners) { - (*it)->destroyTileProgress(id, x, y, z, progress); + listener->destroyTileProgress(id, x, y, z, progress); } } diff --git a/Minecraft.World/LevelChunk.cpp b/Minecraft.World/LevelChunk.cpp index 920fdfc1..d4be5ac2 100644 --- a/Minecraft.World/LevelChunk.cpp +++ b/Minecraft.World/LevelChunk.cpp @@ -54,7 +54,7 @@ void LevelChunk::init(Level *level, int x, int z) biomes = byteArray(16 * 16); for(int i = 0; i < 16 * 16; i++ ) { - biomes[i] = 0xff; + biomes[i] = 0xff; } #ifdef _ENTITIES_RW_SECTION EnterCriticalRWSection(&m_csEntities, true); @@ -109,12 +109,12 @@ void LevelChunk::init(Level *level, int x, int z) // Optimisation brought forward from 1.8.2, change from int to unsigned char & this special value changed from -999 to 255 for(int i = 0; i < 16 * 16; i++ ) { - rainHeights[i] = 255; + rainHeights[i] = 255; } // 4J - lighting change brought forward from 1.8.2, introduced an array of bools called gapsToRecheck, which are now a single bit in array of nybble flags in this version for(int i = 0; i < 8 * 16; i++ ) { - columnFlags[i] = 0; + columnFlags[i] = 0; } // 4J added - to flag if any emissive tile has been added to this chunk (will be cleared when lighting has been successfully completed for this chunk). Defaulting to true @@ -128,7 +128,7 @@ void LevelChunk::init(Level *level, int x, int z) } // This ctor is used for loading a save into -LevelChunk::LevelChunk(Level *level, int x, int z) : ENTITY_BLOCKS_LENGTH( Level::maxBuildHeight/16 ) +LevelChunk::LevelChunk(Level *level, int x, int z) { init(level, x, z); lowerBlocks = new CompressedTileStorage(); @@ -160,7 +160,7 @@ LevelChunk::LevelChunk(Level *level, int x, int z) : ENTITY_BLOCKS_LENGTH( Level // 4J - note that since we now compress the block storage, the parameter blocks is used as a source of data, but doesn't get used As the source data so needs // to be deleted after calling this ctor. -LevelChunk::LevelChunk(Level *level, byteArray blocks, int x, int z) : ENTITY_BLOCKS_LENGTH( Level::maxBuildHeight/16 ) +LevelChunk::LevelChunk(Level *level, byteArray blocks, int x, int z) { init(level, x, z); @@ -189,7 +189,7 @@ LevelChunk::LevelChunk(Level *level, byteArray blocks, int x, int z) : ENTITY_BL // skyLight = new DataLayer(blocks.length, level->depthBits); // blockLight = new DataLayer(blocks.length, level->depthBits); - if(Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) + if(Level::maxBuildHeight > Level::COMPRESSED_CHUNK_SECTION_HEIGHT) { if(blocks.length > Level::COMPRESSED_CHUNK_SECTION_TILES) upperBlocks = new CompressedTileStorage(blocks,Level::COMPRESSED_CHUNK_SECTION_TILES); else upperBlocks = new CompressedTileStorage(true); @@ -213,7 +213,7 @@ LevelChunk::LevelChunk(Level *level, byteArray blocks, int x, int z) : ENTITY_BL // 4J - this ctor added to be able to make a levelchunk that shares its underlying block data between the server chunk cache & the multiplayer chunk cache. // The original version this is shared from owns all the data that is shared into this copy, so it isn't deleted in the dtor. -LevelChunk::LevelChunk(Level *level, int x, int z, LevelChunk *lc) : ENTITY_BLOCKS_LENGTH( Level::maxBuildHeight/16 ) +LevelChunk::LevelChunk(Level *level, int x, int z, LevelChunk *lc) { init(level, x, z); @@ -705,7 +705,7 @@ void LevelChunk::recheckGaps(bool bForce) // 4J added - otherwise we can end up doing a very broken kind of lighting since for an empty chunk, the heightmap is all zero, but it // still has an x and z of 0 which means that the level->getHeightmap references in here find a real chunk near the origin, and then attempt // to light massive gaps between the height of 0 and whatever heights are in those. - if( isEmpty() ) return; + if( isEmpty() ) return; // 4J added int minXZ = - (level->dimension->getXZSize() * 16 ) / 2; @@ -773,7 +773,7 @@ void LevelChunk::lightGap(int x, int z, int source) { lightGap(x, z, source, height + 1); } - else if (height < source) + else if (height < source) { lightGap(x, z, height, source + 1); } @@ -900,7 +900,7 @@ void LevelChunk::recalcHeight(int x, int yStart, int z) /** * The purpose of this method is to allow the EmptyLevelChunk to be all air * but still block light. See EmptyLevelChunk.java -* +* * @param x * @param y * @param z @@ -1240,7 +1240,7 @@ void LevelChunk::removeEntity(shared_ptr<Entity> e, int yc) #endif // 4J - was entityBlocks[yc]->remove(e); - AUTO_VAR(it, find(entityBlocks[yc]->begin(),entityBlocks[yc]->end(),e)); + auto it = find(entityBlocks[yc]->begin(), entityBlocks[yc]->end(), e); if( it != entityBlocks[yc]->end() ) { entityBlocks[yc]->erase(it); @@ -1250,7 +1250,7 @@ void LevelChunk::removeEntity(shared_ptr<Entity> e, int yc) // MGH - have to sort this C++11 code static bool bShowMsg = true; if(bShowMsg) - { + { app.DebugPrintf("Need to add C++11 shrink_to_fit for PS3\n"); bShowMsg = false; } @@ -1292,7 +1292,7 @@ shared_ptr<TileEntity> LevelChunk::getTileEntity(int x, int y, int z) //shared_ptr<TileEntity> tileEntity = tileEntities[pos]; EnterCriticalSection(&m_csTileEntities); shared_ptr<TileEntity> tileEntity = nullptr; - AUTO_VAR(it, tileEntities.find(pos)); + auto it = tileEntities.find(pos); if (it == tileEntities.end()) { @@ -1320,8 +1320,8 @@ shared_ptr<TileEntity> LevelChunk::getTileEntity(int x, int y, int z) // 4J Stu - It should have been inserted by now, but check to be sure EnterCriticalSection(&m_csTileEntities); - AUTO_VAR(newIt, tileEntities.find(pos)); - if (newIt != tileEntities.end()) + auto newIt = tileEntities.find(pos); + if (newIt != tileEntities.end()) { tileEntity = newIt->second; } @@ -1371,8 +1371,8 @@ void LevelChunk::setTileEntity(int x, int y, int z, shared_ptr<TileEntity> tileE app.DebugPrintf("Attempted to place a tile entity where there was no entity tile!\n"); return; } - AUTO_VAR(it, tileEntities.find(pos) ); - if(it != tileEntities.end()) it->second->setRemoved(); + auto it = tileEntities.find(pos); + if(it != tileEntities.end()) it->second->setRemoved(); tileEntity->clearRemoved(); @@ -1393,8 +1393,8 @@ void LevelChunk::removeTileEntity(int x, int y, int z) // removeThis.setRemoved(); // } EnterCriticalSection(&m_csTileEntities); - AUTO_VAR(it, tileEntities.find(pos)); - if( it != tileEntities.end() ) + auto it = tileEntities.find(pos); + if( it != tileEntities.end() ) { shared_ptr<TileEntity> te = tileEntities[pos]; tileEntities.erase(pos); @@ -1456,9 +1456,9 @@ void LevelChunk::load() vector< shared_ptr<TileEntity> > values; EnterCriticalSection(&m_csTileEntities); - for( AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); it++ ) + for(auto& it : tileEntities) { - values.push_back(it->second); + values.push_back(it.second); } LeaveCriticalSection(&m_csTileEntities); level->addAllPendingTileEntities(values); @@ -1492,10 +1492,10 @@ void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter if( unloadTileEntities ) { EnterCriticalSection(&m_csTileEntities); - for( AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); it++ ) + for(auto& it : tileEntities) { // 4J-PB -m 1.7.3 was it->second->setRemoved(); - level->markForRemoval(it->second); + level->markForRemoval(it.second); } LeaveCriticalSection(&m_csTileEntities); } @@ -1531,16 +1531,13 @@ void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter EnterCriticalSection(&m_csEntities); for (int i = 0; i < ENTITY_BLOCKS_LENGTH; i++) { - AUTO_VAR(itEnd, entityBlocks[i]->end()); - for( vector<shared_ptr<Entity> >::iterator it = entityBlocks[i]->begin(); it != itEnd; it++ ) + for(auto& e : *entityBlocks[i]) { - shared_ptr<Entity> e = *it; CompoundTag *teTag = new CompoundTag(); if (e->save(teTag)) { entityTags->add(teTag); } - } // Clear out this list @@ -1554,13 +1551,10 @@ void LevelChunk::unload(bool unloadTileEntities) // 4J - added parameter PIXBeginNamedEvent(0,"Saving tile entities"); ListTag<CompoundTag> *tileEntityTags = new ListTag<CompoundTag>(); - AUTO_VAR(itEnd,tileEntities.end()); - for( unordered_map<TilePos, shared_ptr<TileEntity>, TilePosKeyHash, TilePosKeyEq>::iterator it = tileEntities.begin(); - it != itEnd; it++) + for(auto& it : tileEntities) { - shared_ptr<TileEntity> te = it->second; CompoundTag *teTag = new CompoundTag(); - te->save(teTag); + it.second->save(teTag); tileEntityTags->add(teTag); } // Clear out the tileEntities list @@ -1632,20 +1626,18 @@ void LevelChunk::getEntities(shared_ptr<Entity> except, AABB *bb, vector<shared_ { vector<shared_ptr<Entity> > *entities = entityBlocks[yc]; - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = *it; //entities->at(i); - if (e != except && e->bb->intersects(bb) && (selector == NULL || selector->matches(e))) + if ( e && e != except && e->bb->intersects(bb) && (selector == NULL || selector->matches(e))) { es.push_back(e); vector<shared_ptr<Entity> > *subs = e->getSubEntities(); if (subs != NULL) { - for (int j = 0; j < subs->size(); j++) + for (const auto& sub : *subs) { - e = subs->at(j); - if (e != except && e->bb->intersects(bb) && (selector == NULL || selector->matches(e))) + e = sub; + if ( e && e != except && e->bb->intersects(bb) && (selector == NULL || selector->matches(e))) { es.push_back(e); } @@ -1689,11 +1681,8 @@ void LevelChunk::getEntitiesOfClass(const type_info& ec, AABB *bb, vector<shared { vector<shared_ptr<Entity> > *entities = entityBlocks[yc]; - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = *it; //entities->at(i); - bool isAssignableFrom = false; // Some special cases where the base class is a general type that our class may be derived from, otherwise do a direct comparison of type_info if ( ec==typeid(Player) ) isAssignableFrom = e->instanceof(eTYPE_PLAYER); @@ -1929,9 +1918,9 @@ int LevelChunk::setBlocksAndData(byteArray data, int x0, int y0, int z0, int x1, } */ - for(AUTO_VAR(it, tileEntities.begin()); it != tileEntities.end(); ++it) + for(auto& it : tileEntities) { - it->second->clearCache(); + it.second->clearCache(); } // recalcHeightmap(); @@ -2216,7 +2205,7 @@ void LevelChunk::setSkyLightDataAllBright() void LevelChunk::compressLighting() { // The lighting data is now generally not shared between host & local client, but is for a while at the start of level creation (until the point where the chunk data would be transferred by network - // data for remote clients). We'll therefore either be compressing a shared copy here or one of the server or client copies depending on + // data for remote clients). We'll therefore either be compressing a shared copy here or one of the server or client copies depending on lowerSkyLight->compress(); upperSkyLight->compress(); lowerBlockLight->compress(); @@ -2532,7 +2521,7 @@ void LevelChunk::reorderBlocksAndDataToXZY(int y0, int xs, int ys, int zs, byteA //setBlocksAndData(*data, x0, y0, z0, x1, y1, z1, p); //// If it is a full chunk, we'll need to rearrange into the order the rest of the game expects - //if( xs == 16 && ys == 128 && zs == 16 && ( ( x & 15 ) == 0 ) && ( y == 0 ) && ( ( z & 15 ) == 0 ) ) + //if( xs == 16 && ys == 128 && zs == 16 && ( ( x & 15 ) == 0 ) && ( y == 0 ) && ( ( z & 15 ) == 0 ) ) //{ // byteArray newBuffer = byteArray(81920); // for( int x = 0; x < 16; x++ ) diff --git a/Minecraft.World/LevelChunk.h b/Minecraft.World/LevelChunk.h index bc45016b..661fbdac 100644 --- a/Minecraft.World/LevelChunk.h +++ b/Minecraft.World/LevelChunk.h @@ -29,9 +29,8 @@ class LevelChunk public: byteArray biomes; // 4J Stu - Made public - // 4J Stu - No longer static in 1.8.2 - const int ENTITY_BLOCKS_LENGTH; - static const int BLOCKS_LENGTH = Level::CHUNK_TILE_COUNT; // 4J added + static constexpr int ENTITY_BLOCKS_LENGTH = Level::maxBuildHeight/16; + static constexpr int BLOCKS_LENGTH = Level::CHUNK_TILE_COUNT; // 4J added static bool touchedSky; diff --git a/Minecraft.World/LightningBolt.cpp b/Minecraft.World/LightningBolt.cpp index 7f32c8ec..a109d96b 100644 --- a/Minecraft.World/LightningBolt.cpp +++ b/Minecraft.World/LightningBolt.cpp @@ -9,7 +9,7 @@ #include "net.minecraft.world.level.dimension.h" -LightningBolt::LightningBolt(Level *level, double x, double y, double z) : +LightningBolt::LightningBolt(Level *level, double x, double y, double z) : life( 0 ), seed( 0 ), flashes( 0 ), @@ -103,10 +103,8 @@ void LightningBolt::tick() { double r = 3; vector<shared_ptr<Entity> > *entities = level->getEntities(shared_from_this(), AABB::newTemp(x - r, y - r, z - r, x + r, y + 6 + r, z + r)); - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = (*it); //entities->at(i); e->thunderHit(this); } } diff --git a/Minecraft.World/ListTag.h b/Minecraft.World/ListTag.h index c80c0f39..69e51aee 100644 --- a/Minecraft.World/ListTag.h +++ b/Minecraft.World/ListTag.h @@ -20,9 +20,8 @@ public: dos->writeByte(type); dos->writeInt((int)list.size()); - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) - (*it)->write(dos); + for ( auto& it : list ) + it->write(dos); } void load(DataInput *dis, int tagDepth) @@ -52,7 +51,7 @@ public: wstring toString() { static wchar_t buf[64]; - swprintf(buf,64,L"%d entries of type %ls",list.size(),Tag::getTagName(type)); + swprintf(buf,64,L"%zu entries of type %ls",list.size(),Tag::getTagName(type)); return wstring( buf ); } @@ -65,9 +64,8 @@ public: char *newPrefix = new char[ strlen(prefix) + 4 ]; strcpy( newPrefix, prefix); strcat( newPrefix, " "); - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) - (*it)->print(newPrefix, out); + for ( auto& it : list ) + it->print(newPrefix, out); delete[] newPrefix; out << prefix << "}" << endl; } @@ -95,10 +93,9 @@ public: virtual ~ListTag() { - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) + for ( auto& it : list ) { - delete *it; + delete it; } } @@ -106,10 +103,9 @@ public: { ListTag<T> *res = new ListTag<T>(getName()); res->type = type; - AUTO_VAR(itEnd, list.end()); - for (AUTO_VAR(it, list.begin()); it != itEnd; it++) + for ( auto& it : list ) { - T *copy = (T *) (*it)->copy(); + T *copy = (T *) it->copy(); res->list.push_back(copy); } return res; @@ -126,14 +122,13 @@ public: if(list.size() == o->list.size()) { equal = true; - AUTO_VAR(itEnd, list.end()); // 4J Stu - Pretty inefficient method, but I think we can live with it give how often it will happen, and the small sizes of the data sets - for (AUTO_VAR(it, list.begin()); it != itEnd; ++it) + for ( auto& it : list ) { bool thisMatches = false; - for(AUTO_VAR(it2, o->list.begin()); it2 != o->list.end(); ++it2) + for( auto it2 : o->list ) { - if((*it)->equals(*it2)) + if(it->equals(it2)) { thisMatches = true; break; diff --git a/Minecraft.World/LivingEntity.cpp b/Minecraft.World/LivingEntity.cpp index 5f8a3dd1..ef5658c3 100644 --- a/Minecraft.World/LivingEntity.cpp +++ b/Minecraft.World/LivingEntity.cpp @@ -118,9 +118,9 @@ LivingEntity::LivingEntity( Level* level) : Entity(level) LivingEntity::~LivingEntity() { - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) + for(auto& it : activeEffects) { - delete it->second; + delete it.second; } delete attributes; @@ -129,7 +129,7 @@ LivingEntity::~LivingEntity() if(lastEquipment.data != NULL) delete [] lastEquipment.data; } -void LivingEntity::defineSynchedData() +void LivingEntity::defineSynchedData() { entityData->define(DATA_EFFECT_COLOR_ID, 0); entityData->define(DATA_EFFECT_AMBIENCE_ID, (byte) 0); @@ -186,12 +186,12 @@ bool LivingEntity::isWaterMob() return false; } -void LivingEntity::baseTick() +void LivingEntity::baseTick() { oAttackAnim = attackAnim; Entity::baseTick(); - if (isAlive() && isInWall()) + if (isAlive() && isInWall()) { hurt(DamageSource::inWall, 1); } @@ -202,7 +202,7 @@ void LivingEntity::baseTick() if (isAlive() && isUnderLiquid(Material::water)) { - if(!isWaterMob() && !hasEffect(MobEffect::waterBreathing->id) && !isInvulnerable) + if(!isWaterMob() && !hasEffect(MobEffect::waterBreathing->id) && !isInvulnerable) { setAirSupply(decreaseAirSupply(getAirSupply())); if (getAirSupply() == -20) @@ -227,8 +227,8 @@ void LivingEntity::baseTick() { ride(nullptr); } - } - else + } + else { setAirSupply(TOTAL_AIR_SUPPLY); } @@ -238,7 +238,7 @@ void LivingEntity::baseTick() if (attackTime > 0) attackTime--; if (hurtTime > 0) hurtTime--; if (invulnerableTime > 0) invulnerableTime--; - if (getHealth() <= 0) + if (getHealth() <= 0) { tickDeath(); } @@ -281,9 +281,9 @@ bool LivingEntity::isBaby() } void LivingEntity::tickDeath() -{ +{ deathTime++; - if (deathTime == 20) + if (deathTime == 20) { // 4J Stu - Added level->isClientSide check from 1.2 to fix XP orbs being created client side if(!level->isClientSide && (lastHurtByPlayerTime > 0 || isAlwaysExperienceDropper()) ) @@ -301,7 +301,7 @@ void LivingEntity::tickDeath() } remove(); - for (int i = 0; i < 20; i++) + for (int i = 0; i < 20; i++) { double xa = random->nextGaussian() * 0.02; double ya = random->nextGaussian() * 0.02; @@ -422,16 +422,16 @@ void LivingEntity::addAdditonalSaveData(CompoundTag *entityTag) { ListTag<CompoundTag> *listTag = new ListTag<CompoundTag>(); - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) + for(auto & it : activeEffects) { - MobEffectInstance *effect = it->second; + MobEffectInstance *effect = it.second; listTag->add(effect->save(new CompoundTag())); } entityTag->put(L"ActiveEffects", listTag); } } -void LivingEntity::readAdditionalSaveData(CompoundTag *tag) +void LivingEntity::readAdditionalSaveData(CompoundTag *tag) { setAbsorptionAmount(tag->getFloat(L"AbsorptionAmount")); @@ -481,8 +481,8 @@ void LivingEntity::readAdditionalSaveData(CompoundTag *tag) void LivingEntity::tickEffects() { bool removed = false; - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end();) - { + for (auto it = activeEffects.begin(); it != activeEffects.end();) + { MobEffectInstance *effect = it->second; removed = false; if (!effect->tick(dynamic_pointer_cast<LivingEntity>(shared_from_this()))) @@ -520,9 +520,9 @@ void LivingEntity::tickEffects() else { vector<MobEffectInstance *> values; - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end();++it) + for(auto& it : activeEffects) { - values.push_back(it->second); + values.push_back(it.second); } int colorValue = PotionBrewing::getColorValue(&values); entityData->set(DATA_EFFECT_AMBIENCE_ID, PotionBrewing::areAllEffectsAmbient(&values) ? (byte) 1 : (byte) 0); @@ -570,16 +570,12 @@ void LivingEntity::tickEffects() void LivingEntity::removeAllEffects() { - //Iterator<Integer> effectIdIterator = activeEffects.keySet().iterator(); - //while (effectIdIterator.hasNext()) - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ) - { - //Integer effectId = effectIdIterator.next(); + for (auto it = activeEffects.begin(); it != activeEffects.end();) + { MobEffectInstance *effect = it->second;//activeEffects.get(effectId); if (!level->isClientSide) { - //effectIdIterator.remove(); it = activeEffects.erase(it); onEffectRemoved(effect); delete effect; @@ -595,9 +591,9 @@ vector<MobEffectInstance *> *LivingEntity::getActiveEffects() { vector<MobEffectInstance *> *active = new vector<MobEffectInstance *>(); - for(AUTO_VAR(it, activeEffects.begin()); it != activeEffects.end(); ++it) + for(auto& it : activeEffects) { - active->push_back(it->second); + active->push_back(it.second); } return active; @@ -617,8 +613,8 @@ MobEffectInstance *LivingEntity::getEffect(MobEffect *effect) { MobEffectInstance *effectInst = NULL; - AUTO_VAR(it, activeEffects.find(effect->id)); - if(it != activeEffects.end() ) effectInst = it->second; + auto it = activeEffects.find(effect->id); + if(it != activeEffects.end() ) effectInst = it->second; return effectInst; } @@ -685,8 +681,8 @@ bool LivingEntity::isInvertedHealAndHarm() void LivingEntity::removeEffectNoUpdate(int effectId) { - AUTO_VAR(it, activeEffects.find(effectId)); - if (it != activeEffects.end()) + auto it = activeEffects.find(effectId); + if (it != activeEffects.end()) { MobEffectInstance *effect = it->second; if(effect != NULL) @@ -699,8 +695,8 @@ void LivingEntity::removeEffectNoUpdate(int effectId) void LivingEntity::removeEffect(int effectId) { - AUTO_VAR(it, activeEffects.find(effectId)); - if (it != activeEffects.end()) + auto it = activeEffects.find(effectId); + if (it != activeEffects.end()) { MobEffectInstance *effect = it->second; if(effect != NULL) @@ -734,7 +730,7 @@ void LivingEntity::onEffectRemoved(MobEffectInstance *effect) if (!level->isClientSide) MobEffect::effects[effect->getId()]->removeAttributeModifiers(dynamic_pointer_cast<LivingEntity>(shared_from_this()), getAttributes(), effect->getAmplifier()); } -void LivingEntity::heal(float heal) +void LivingEntity::heal(float heal) { float health = getHealth(); if (health > 0) @@ -753,7 +749,7 @@ void LivingEntity::setHealth(float health) entityData->set(DATA_HEALTH_ID, Mth::clamp(health, 0.0f, getMaxHealth())); } -bool LivingEntity::hurt(DamageSource *source, float dmg) +bool LivingEntity::hurt(DamageSource *source, float dmg) { if (isInvulnerable()) return false; @@ -786,14 +782,14 @@ bool LivingEntity::hurt(DamageSource *source, float dmg) walkAnimSpeed = 1.5f; bool sound = true; - if (invulnerableTime > invulnerableDuration / 2.0f) + if (invulnerableTime > invulnerableDuration / 2.0f) { if (dmg <= lastHurt) return false; if(!level->isClientSide) actuallyHurt(source, dmg - lastHurt); lastHurt = dmg; sound = false; - } - else + } + else { lastHurt = dmg; lastHealth = getHealth(); @@ -837,31 +833,31 @@ bool LivingEntity::hurt(DamageSource *source, float dmg) { level->broadcastEntityEvent(shared_from_this(), EntityEvent::HURT); if (source != DamageSource::drown) markHurt(); - if (sourceEntity != NULL) + if (sourceEntity != NULL) { double xd = sourceEntity->x - x; double zd = sourceEntity->z - z; - while (xd * xd + zd * zd < 0.0001) + while (xd * xd + zd * zd < 0.0001) { xd = (Math::random() - Math::random()) * 0.01; zd = (Math::random() - Math::random()) * 0.01; } hurtDir = (float) (atan2(zd, xd) * 180 / PI) - yRot; knockback(sourceEntity, dmg, xd, zd); - } - else + } + else { hurtDir = (float) (int) ((Math::random() * 2) * 180); // 4J This cast is the same as Java } } MemSect(31); - if (getHealth() <= 0) + if (getHealth() <= 0) { if (sound) playSound(getDeathSound(), getSoundVolume(), getVoicePitch()); die(source); - } - else + } + else { if (sound) playSound(getHurtSound(), getSoundVolume(), getVoicePitch()); } @@ -888,7 +884,7 @@ void LivingEntity::breakItem(shared_ptr<ItemInstance> itemInstance) } } -void LivingEntity::die(DamageSource *source) +void LivingEntity::die(DamageSource *source) { shared_ptr<Entity> sourceEntity = source->getEntity(); shared_ptr<LivingEntity> killer = getKillCredit(); @@ -898,11 +894,11 @@ void LivingEntity::die(DamageSource *source) dead = true; - if (!level->isClientSide) + if (!level->isClientSide) { int playerBonus = 0; - shared_ptr<Player> player = nullptr; + shared_ptr<Player> player = nullptr; if ( (sourceEntity != NULL) && sourceEntity->instanceof(eTYPE_PLAYER) ) { player = dynamic_pointer_cast<Player>(sourceEntity); @@ -937,7 +933,7 @@ void LivingEntity::dropEquipment(bool byPlayer, int playerBonusLevel) { } -void LivingEntity::knockback(shared_ptr<Entity> source, float dmg, double xd, double zd) +void LivingEntity::knockback(shared_ptr<Entity> source, float dmg, double xd, double zd) { if (random->nextDouble() < getAttribute(SharedMonsterAttributes::KNOCKBACK_RESISTANCE)->getValue()) { @@ -959,12 +955,12 @@ void LivingEntity::knockback(shared_ptr<Entity> source, float dmg, double xd, do if (yd > 0.4f) yd = 0.4f; } -int LivingEntity::getHurtSound() +int LivingEntity::getHurtSound() { return eSoundType_DAMAGE_HURT; } -int LivingEntity::getDeathSound() +int LivingEntity::getDeathSound() { return eSoundType_DAMAGE_HURT; } @@ -972,7 +968,7 @@ int LivingEntity::getDeathSound() /** * Drop extra rare loot. Only occurs roughly 5% of the time, rareRootLevel * is set to 1 (otherwise 0) 1% of the time. -* +* * @param rareLootLevel */ void LivingEntity::dropRareDeathLoot(int rareLootLevel) @@ -980,11 +976,11 @@ void LivingEntity::dropRareDeathLoot(int rareLootLevel) } -void LivingEntity::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) +void LivingEntity::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { } -bool LivingEntity::onLadder() +bool LivingEntity::onLadder() { int xt = Mth::floor(x); int yt = Mth::floor(bb->y0); @@ -995,24 +991,24 @@ bool LivingEntity::onLadder() return (iTile== Tile::ladder_Id) || (iTile== Tile::vine_Id); } -bool LivingEntity::isShootable() +bool LivingEntity::isShootable() { return true; } -bool LivingEntity::isAlive() +bool LivingEntity::isAlive() { return !removed && getHealth() > 0; } -void LivingEntity::causeFallDamage(float distance) +void LivingEntity::causeFallDamage(float distance) { Entity::causeFallDamage(distance); MobEffectInstance *jumpBoost = getEffect(MobEffect::jump); float padding = jumpBoost != NULL ? jumpBoost->getAmplifier() + 1 : 0; int dmg = (int) ceil(distance - 3 - padding); - if (dmg > 0) + if (dmg > 0) { // 4J - new sounds here brought forward from 1.2.3 if (dmg > 4) @@ -1026,7 +1022,7 @@ void LivingEntity::causeFallDamage(float distance) hurt(DamageSource::fall, dmg); int t = level->getTile( Mth::floor(x), Mth::floor(y - 0.2f - this->heightOffset), Mth::floor(z)); - if (t > 0) + if (t > 0) { const Tile::SoundType *soundType = Tile::tiles[t]->soundType; MemSect(31); @@ -1036,7 +1032,7 @@ void LivingEntity::causeFallDamage(float distance) } } -void LivingEntity::animateHurt() +void LivingEntity::animateHurt() { hurtTime = hurtDuration = 10; hurtDir = 0; @@ -1044,7 +1040,7 @@ void LivingEntity::animateHurt() /** * Fetches the mob's armor value, from 0 (no armor) to 20 (full armor) -* +* * @return */ int LivingEntity::getArmorValue() @@ -1111,7 +1107,7 @@ float LivingEntity::getDamageAfterMagicAbsorb(DamageSource *damageSource, float return damage; } -void LivingEntity::actuallyHurt(DamageSource *source, float dmg) +void LivingEntity::actuallyHurt(DamageSource *source, float dmg) { if (isInvulnerable()) return; dmg = getDamageAfterArmorAbsorb(source, dmg); @@ -1183,9 +1179,9 @@ void LivingEntity::swing() } } -void LivingEntity::handleEntityEvent(byte id) +void LivingEntity::handleEntityEvent(byte id) { - if (id == EntityEvent::HURT) + if (id == EntityEvent::HURT) { walkAnimSpeed = 1.5f; @@ -1197,32 +1193,32 @@ void LivingEntity::handleEntityEvent(byte id) // 4J-PB -added because villagers have no sounds int iHurtSound=getHurtSound(); if(iHurtSound!=-1) - { + { playSound(iHurtSound, getSoundVolume(), (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); } MemSect(0); hurt(DamageSource::genericSource, 0); - } - else if (id == EntityEvent::DEATH) + } + else if (id == EntityEvent::DEATH) { MemSect(31); // 4J-PB -added because villagers have no sounds int iDeathSound=getDeathSound(); if(iDeathSound!=-1) - { + { playSound(iDeathSound, getSoundVolume(), (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f); } MemSect(0); setHealth(0); die(DamageSource::genericSource); - } - else + } + else { Entity::handleEntityEvent(id); } } -void LivingEntity::outOfWorld() +void LivingEntity::outOfWorld() { hurt(DamageSource::outOfWorld, 4); } @@ -1282,7 +1278,7 @@ void LivingEntity::setSprinting(bool value) } } -float LivingEntity::getSoundVolume() +float LivingEntity::getSoundVolume() { return 1; } @@ -1297,12 +1293,12 @@ float LivingEntity::getVoicePitch() return (random->nextFloat() - random->nextFloat()) * 0.2f + 1.0f; } -bool LivingEntity::isImmobile() +bool LivingEntity::isImmobile() { return getHealth() <= 0; } -void LivingEntity::teleportTo(double x, double y, double z) +void LivingEntity::teleportTo(double x, double y, double z) { moveTo(x, y, z, yRot, xRot); } @@ -1352,12 +1348,12 @@ bool LivingEntity::shouldShowName() return false; } -Icon *LivingEntity::getItemInHandIcon(shared_ptr<ItemInstance> item, int layer) +Icon *LivingEntity::getItemInHandIcon(shared_ptr<ItemInstance> item, int layer) { return item->getIcon(); } -void LivingEntity::jumpFromGround() +void LivingEntity::jumpFromGround() { yd = 0.42f; if (hasEffect(MobEffect::jump)) @@ -1374,7 +1370,7 @@ void LivingEntity::jumpFromGround() this->hasImpulse = true; } -void LivingEntity::travel(float xa, float ya) +void LivingEntity::travel(float xa, float ya) { #ifdef __PSVITA__ // AP - dynamic_pointer_cast is a non-trivial call @@ -1386,7 +1382,7 @@ void LivingEntity::travel(float xa, float ya) #else shared_ptr<Player> thisPlayer = dynamic_pointer_cast<Player>(shared_from_this()); #endif - if (isInWater() && !(thisPlayer && thisPlayer->abilities.flying) ) + if (isInWater() && !(thisPlayer && thisPlayer->abilities.flying) ) { double yo = y; moveRelative(xa, ya, useNewAi() ? 0.04f : 0.02f); @@ -1397,12 +1393,12 @@ void LivingEntity::travel(float xa, float ya) zd *= 0.80f; yd -= 0.02; - if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) + if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) { yd = 0.3f; } - } - else if (isInLava() && !(thisPlayer && thisPlayer->abilities.flying) ) + } + else if (isInLava() && !(thisPlayer && thisPlayer->abilities.flying) ) { double yo = y; moveRelative(xa, ya, 0.02f); @@ -1412,19 +1408,19 @@ void LivingEntity::travel(float xa, float ya) zd *= 0.50f; yd -= 0.02; - if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) + if (horizontalCollision && isFree(xd, yd + 0.6f - y + yo, zd)) { yd = 0.3f; } - } - else + } + else { float friction = 0.91f; - if (onGround) + if (onGround) { friction = 0.6f * 0.91f; int t = level->getTile(Mth::floor(x), Mth::floor(bb->y0) - 1, Mth::floor(z)); - if (t > 0) + if (t > 0) { friction = Tile::tiles[t]->friction * 0.91f; } @@ -1445,16 +1441,16 @@ void LivingEntity::travel(float xa, float ya) moveRelative(xa, ya, speed); friction = 0.91f; - if (onGround) + if (onGround) { friction = 0.6f * 0.91f; int t = level->getTile( Mth::floor(x), Mth::floor(bb->y0) - 1, Mth::floor(z)); - if (t > 0) + if (t > 0) { friction = Tile::tiles[t]->friction * 0.91f; } } - if (onLadder()) + if (onLadder()) { float max = 0.15f; if (xd < -max) xd = -max; @@ -1469,7 +1465,7 @@ void LivingEntity::travel(float xa, float ya) move(xd, yd, zd); - if (horizontalCollision && onLadder()) + if (horizontalCollision && onLadder()) { yd = 0.2; } @@ -1570,12 +1566,12 @@ bool LivingEntity::doHurtTarget(shared_ptr<Entity> target) return false; } -bool LivingEntity::isSleeping() +bool LivingEntity::isSleeping() { return false; } -void LivingEntity::tick() +void LivingEntity::tick() { Entity::tick(); @@ -1622,17 +1618,17 @@ void LivingEntity::tick() float walkSpeed = 0; oRun = run; float tRun = 0; - if (sideDist > 0.05f * 0.05f) + if (sideDist > 0.05f * 0.05f) { tRun = 1; walkSpeed = sqrt(sideDist) * 3; yBodyRotT = ((float) atan2(zd, xd) * 180 / (float) PI - 90); } - if (attackAnim > 0) + if (attackAnim > 0) { yBodyRotT = yRot; } - if (!onGround) + if (!onGround) { tRun = 0; } @@ -1686,10 +1682,10 @@ float LivingEntity::tickHeadTurn(float yBodyRotT, float walkSpeed) return walkSpeed; } -void LivingEntity::aiStep() +void LivingEntity::aiStep() { if (noJumpDelay > 0) noJumpDelay--; - if (lSteps > 0) + if (lSteps > 0) { double xt = x + (lx - x) / lSteps; double yt = y + (ly - y) / lSteps; @@ -1716,10 +1712,8 @@ void LivingEntity::aiStep() if (collisions->size() > 0) { double yTop = 0; - AUTO_VAR(itEnd, collisions->end()); - for (AUTO_VAR(it, collisions->begin()); it != itEnd; it++) + for (const auto& ab : *collisions) { - AABB *ab = *it; //collisions->at(i); if (ab->y1 > yTop) yTop = ab->y1; } @@ -1740,14 +1734,14 @@ void LivingEntity::aiStep() if (abs(yd) < MIN_MOVEMENT_DISTANCE) yd = 0; if (abs(zd) < MIN_MOVEMENT_DISTANCE) zd = 0; - if (isImmobile()) + if (isImmobile()) { jumping = false; xxa = 0; yya = 0; yRotA = 0; - } - else + } + else { MemSect(25); if (isEffectiveAi()) @@ -1765,13 +1759,13 @@ void LivingEntity::aiStep() MemSect(0); } - if (jumping) + if (jumping) { - if (isInWater() || isInLava() ) + if (isInWater() || isInLava() ) { yd += 0.04f; } - else if (onGround) + else if (onGround) { if (noJumpDelay == 0) { @@ -1806,13 +1800,12 @@ void LivingEntity::pushEntities() { vector<shared_ptr<Entity> > *entities = level->getEntities(shared_from_this(), this->bb->grow(0.2f, 0, 0.2f)); - if (entities != NULL && !entities->empty()) + if (entities != NULL && !entities->empty()) { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = *it; //entities->at(i); - if (e->isPushable()) e->push(shared_from_this()); + if ( e && e->isPushable()) + e->push(shared_from_this()); } } } @@ -1822,7 +1815,7 @@ void LivingEntity::doPush(shared_ptr<Entity> e) e->push(shared_from_this()); } -void LivingEntity::rideTick() +void LivingEntity::rideTick() { Entity::rideTick(); oRun = run; @@ -1830,7 +1823,7 @@ void LivingEntity::rideTick() fallDistance = 0; } -void LivingEntity::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) +void LivingEntity::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) { heightOffset = 0; lx = x; @@ -1846,7 +1839,7 @@ void LivingEntity::serverAiMobStep() { } -void LivingEntity::serverAiStep() +void LivingEntity::serverAiStep() { noActionTime++; } @@ -1876,7 +1869,7 @@ void LivingEntity::take(shared_ptr<Entity> e, int orgCount) } } -bool LivingEntity::canSee(shared_ptr<Entity> target) +bool LivingEntity::canSee(shared_ptr<Entity> target) { HitResult *hres = level->clip(Vec3::newTemp(x, y + getHeadHeight(), z), Vec3::newTemp(target->x, target->y + target->getHeadHeight(), target->z)); bool retVal = (hres == NULL); @@ -1884,14 +1877,14 @@ bool LivingEntity::canSee(shared_ptr<Entity> target) return retVal; } -Vec3 *LivingEntity::getLookAngle() +Vec3 *LivingEntity::getLookAngle() { return getViewVector(1); } -Vec3 *LivingEntity::getViewVector(float a) +Vec3 *LivingEntity::getViewVector(float a) { - if (a == 1) + if (a == 1) { float yCos = Mth::cos(-yRot * Mth::RAD_TO_GRAD - PI); float ySin = Mth::sin(-yRot * Mth::RAD_TO_GRAD - PI); @@ -1911,16 +1904,16 @@ Vec3 *LivingEntity::getViewVector(float a) return Vec3::newTemp(ySin * xCos, xSin, yCos * xCos); } -float LivingEntity::getAttackAnim(float a) +float LivingEntity::getAttackAnim(float a) { float diff = attackAnim - oAttackAnim; if (diff < 0) diff += 1; return oAttackAnim + diff * a; } -Vec3 *LivingEntity::getPos(float a) +Vec3 *LivingEntity::getPos(float a) { - if (a == 1) + if (a == 1) { return Vec3::newTemp(x, y, z); } @@ -1931,7 +1924,7 @@ Vec3 *LivingEntity::getPos(float a) return Vec3::newTemp(x, y, z); } -HitResult *LivingEntity::pick(double range, float a) +HitResult *LivingEntity::pick(double range, float a) { Vec3 *from = getPos(a); Vec3 *b = getViewVector(a); @@ -1944,17 +1937,17 @@ bool LivingEntity::isEffectiveAi() return !level->isClientSide; } -bool LivingEntity::isPickable() +bool LivingEntity::isPickable() { return !removed; } -bool LivingEntity::isPushable() +bool LivingEntity::isPushable() { return !removed; } -float LivingEntity::getHeadHeight() +float LivingEntity::getHeadHeight() { return bbHeight * 0.85f; } diff --git a/Minecraft.World/MapItem.cpp b/Minecraft.World/MapItem.cpp index a5143257..03529c1a 100644 --- a/Minecraft.World/MapItem.cpp +++ b/Minecraft.World/MapItem.cpp @@ -20,18 +20,18 @@ MapItem::MapItem(int id) : ComplexItem(id) } shared_ptr<MapItemSavedData> MapItem::getSavedData(short idNum, Level *level) -{ - std::wstring id = wstring( L"map_" ) + _toString(idNum); +{ + std::wstring id = wstring( L"map_" ) + std::to_wstring(idNum); shared_ptr<MapItemSavedData> mapItemSavedData = dynamic_pointer_cast<MapItemSavedData>(level->getSavedData(typeid(MapItemSavedData), id)); - if (mapItemSavedData == NULL) + if (mapItemSavedData == NULL) { // 4J Stu - This call comes from ClientConnection, but i don't see why we should be trying to work out // the id again when it's passed as a param. In any case that won't work with the new map setup //int aux = level->getFreeAuxValueFor(L"map"); int aux = idNum; - id = wstring( L"map_" ) + _toString(aux); + id = wstring( L"map_" ) + std::to_wstring(aux); mapItemSavedData = shared_ptr<MapItemSavedData>( new MapItemSavedData(id) ); level->setSavedData(id, (shared_ptr<SavedData> ) mapItemSavedData); @@ -43,7 +43,7 @@ shared_ptr<MapItemSavedData> MapItem::getSavedData(short idNum, Level *level) shared_ptr<MapItemSavedData> MapItem::getSavedData(shared_ptr<ItemInstance> itemInstance, Level *level) { MemSect(31); - std::wstring id = wstring( L"map_" ) + _toString(itemInstance->getAuxValue() ); + std::wstring id = wstring( L"map_" ) + std::to_wstring(itemInstance->getAuxValue() ); MemSect(0); shared_ptr<MapItemSavedData> mapItemSavedData = dynamic_pointer_cast<MapItemSavedData>( level->getSavedData(typeid(MapItemSavedData), id ) ); @@ -54,7 +54,7 @@ shared_ptr<MapItemSavedData> MapItem::getSavedData(shared_ptr<ItemInstance> item // In any case that won't work with the new map setup //itemInstance->setAuxValue(level->getFreeAuxValueFor(L"map")); - id = wstring( L"map_" ) + _toString(itemInstance->getAuxValue() ); + id = wstring( L"map_" ) + std::to_wstring(itemInstance->getAuxValue() ); mapItemSavedData = shared_ptr<MapItemSavedData>( new MapItemSavedData(id) ); newData = true; @@ -75,7 +75,7 @@ shared_ptr<MapItemSavedData> MapItem::getSavedData(shared_ptr<ItemInstance> item mapItemSavedData->z = Math::round(level->getLevelData()->getZSpawn() / scale) * scale; #endif mapItemSavedData->dimension = (byte) level->dimension->id; - + mapItemSavedData->setDirty(); level->setSavedData(id, (shared_ptr<SavedData> ) mapItemSavedData); @@ -86,7 +86,7 @@ shared_ptr<MapItemSavedData> MapItem::getSavedData(shared_ptr<ItemInstance> item void MapItem::update(Level *level, shared_ptr<Entity> player, shared_ptr<MapItemSavedData> data) { - if ( (level->dimension->id != data->dimension) || !player->instanceof(eTYPE_PLAYER) ) + if ( (level->dimension->id != data->dimension) || !player->instanceof(eTYPE_PLAYER) ) { // Wrong dimension, abort return; @@ -148,8 +148,8 @@ void MapItem::update(Level *level, shared_ptr<Entity> player, shared_ptr<MapItem if (((ss >> 20) & 1) == 0) count[Tile::dirt_Id] += 10; else count[Tile::stone_Id] += 10; hh = 100; - } - else + } + else { for (int xs = 0; xs < scale; xs++) { @@ -157,7 +157,7 @@ void MapItem::update(Level *level, shared_ptr<Entity> player, shared_ptr<MapItem { int yy = lc->getHeightmap(xs + xso, zs + zso) + 1; int t = 0; - if (yy > 1) + if (yy > 1) { bool ok = false; do @@ -215,7 +215,7 @@ void MapItem::update(Level *level, shared_ptr<Entity> player, shared_ptr<MapItem if (diff < -0.6) br = 0; int col = 0; - if (tBest > 0) + if (tBest > 0) { MaterialColor *mc = Tile::tiles[tBest]->material->color; if (mc == MaterialColor::water) @@ -245,7 +245,7 @@ void MapItem::update(Level *level, shared_ptr<Entity> player, shared_ptr<MapItem data->colors[x + z * w] = newColor; } } - if (yd0 <= yd1) + if (yd0 <= yd1) { data->setDirty(x, yd0, yd1); } @@ -257,7 +257,7 @@ void MapItem::inventoryTick(shared_ptr<ItemInstance> itemInstance, Level *level, if (level->isClientSide) return; shared_ptr<MapItemSavedData> data = getSavedData(itemInstance, level); - if ( owner->instanceof(eTYPE_PLAYER) ) + if ( owner->instanceof(eTYPE_PLAYER) ) { shared_ptr<Player> player = dynamic_pointer_cast<Player>(owner); @@ -276,7 +276,7 @@ void MapItem::inventoryTick(shared_ptr<ItemInstance> itemInstance, Level *level, ownersData->tickCarriedBy(player, itemInstance ); ownersData->mergeInMapData(data); player->inventoryMenu->broadcastChanges(); - + data = ownersData; } else @@ -285,13 +285,13 @@ void MapItem::inventoryTick(shared_ptr<ItemInstance> itemInstance, Level *level, } } - if (selected) + if (selected) { update(level, owner, data); } } -shared_ptr<Packet> MapItem::getUpdatePacket(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player) +shared_ptr<Packet> MapItem::getUpdatePacket(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player) { charArray data = MapItem::getSavedData(itemInstance, level)->getUpdatePacket(itemInstance, level, player); @@ -302,7 +302,7 @@ shared_ptr<Packet> MapItem::getUpdatePacket(shared_ptr<ItemInstance> itemInstanc return retval; } -void MapItem::onCraftedBy(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player) +void MapItem::onCraftedBy(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player) { wchar_t buf[64]; @@ -318,7 +318,7 @@ void MapItem::onCraftedBy(shared_ptr<ItemInstance> itemInstance, Level *level, s #endif itemInstance->setAuxValue(level->getAuxValueForMap(player->getXuid(), player->dimension, centreXC, centreZC, mapScale)); - + swprintf(buf,64,L"map_%d", itemInstance->getAuxValue()); std::wstring id = wstring(buf); @@ -330,7 +330,7 @@ void MapItem::onCraftedBy(shared_ptr<ItemInstance> itemInstance, Level *level, s data = shared_ptr<MapItemSavedData>( new MapItemSavedData(id) ); } level->setSavedData(id, (shared_ptr<SavedData> ) data); - + data->scale = mapScale; // 4J-PB - for Xbox maps, we'll centre them on the origin of the world, since we can fit the whole world in our map data->x = centreXC; diff --git a/Minecraft.World/MapItemSavedData.cpp b/Minecraft.World/MapItemSavedData.cpp index 981bab3e..c06c3fac 100644 --- a/Minecraft.World/MapItemSavedData.cpp +++ b/Minecraft.World/MapItemSavedData.cpp @@ -64,7 +64,7 @@ charArray MapItemSavedData::HoldingPlayer::nextUpdatePacket(shared_ptr<ItemInsta if (--sendPosTick < 0) { sendPosTick = 4; - + unsigned int playerDecorationsSize = (int)parent->decorations.size(); unsigned int nonPlayerDecorationsSize = (int)parent->nonPlayerDecorations.size(); charArray data = charArray( (playerDecorationsSize + nonPlayerDecorationsSize ) * DEC_PACKET_BYTES + 1); @@ -79,7 +79,7 @@ charArray MapItemSavedData::HoldingPlayer::nextUpdatePacket(shared_ptr<ItemInsta data[i * DEC_PACKET_BYTES + 1] = (char) ((md->img << 4) | (md->rot & 0xF)); #endif data[i * DEC_PACKET_BYTES + 2] = md->x; - data[i * DEC_PACKET_BYTES + 3] = md->y; + data[i * DEC_PACKET_BYTES + 3] = md->y; data[i * DEC_PACKET_BYTES + 4] = md->entityId & 0xFF; data[i * DEC_PACKET_BYTES + 5] = (md->entityId>>8) & 0xFF; data[i * DEC_PACKET_BYTES + 6] = (md->entityId>>16) & 0xFF; @@ -87,9 +87,9 @@ charArray MapItemSavedData::HoldingPlayer::nextUpdatePacket(shared_ptr<ItemInsta data[i * DEC_PACKET_BYTES + 7] |= md->visible ? 0x80 : 0x0; } unsigned int dataIndex = playerDecorationsSize; - for(AUTO_VAR(it, parent->nonPlayerDecorations.begin()); it != parent->nonPlayerDecorations.end(); ++it) + for(auto it : parent->nonPlayerDecorations) { - MapDecoration *md = it->second; + MapDecoration *md = it.second; #ifdef _LARGE_WORLDS data[dataIndex * DEC_PACKET_BYTES + 1] = (char) (md->img); data[dataIndex * DEC_PACKET_BYTES + 8] = (char) (md->rot & 0xF); @@ -97,7 +97,7 @@ charArray MapItemSavedData::HoldingPlayer::nextUpdatePacket(shared_ptr<ItemInsta data[dataIndex * DEC_PACKET_BYTES + 1] = (char) ((md->img << 4) | (md->rot & 0xF)); #endif data[dataIndex * DEC_PACKET_BYTES + 2] = md->x; - data[dataIndex * DEC_PACKET_BYTES + 3] = md->y; + data[dataIndex * DEC_PACKET_BYTES + 3] = md->y; data[dataIndex * DEC_PACKET_BYTES + 4] = md->entityId & 0xFF; data[dataIndex * DEC_PACKET_BYTES + 5] = (md->entityId>>8) & 0xFF; data[dataIndex * DEC_PACKET_BYTES + 6] = (md->entityId>>16) & 0xFF; @@ -246,21 +246,21 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI delete decorations[i]; } decorations.clear(); - + // 4J Stu - Put this block back in if you want to display entity positions on a map (see below) #if 0 nonPlayerDecorations.clear(); #endif bool addedPlayers = false; - for (AUTO_VAR(it, carriedBy.begin()); it != carriedBy.end(); ) - { + for (auto it = carriedBy.begin(); it != carriedBy.end();) + { shared_ptr<HoldingPlayer> hp = *it; // 4J Stu - Players in the same dimension as an item frame with a map need to be sent this data, so don't remove them if (hp->player->removed ) //|| (!hp->player->inventory->contains(item) && !item->isFramed() )) { - AUTO_VAR(it2, carriedByPlayers.find( (shared_ptr<Player> ) hp->player )); - if( it2 != carriedByPlayers.end() ) + auto it2 = carriedByPlayers.find(shared_ptr<Player>(hp->player)); + if( it2 != carriedByPlayers.end() ) { carriedByPlayers.erase( it2 ); } @@ -275,9 +275,8 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI { bool atLeastOnePlayerInTheEnd = false; PlayerList *players = MinecraftServer::getInstance()->getPlayerList(); - for(AUTO_VAR(it3, players->players.begin()); it3 != players->players.end(); ++it3) + for( const auto& serverPlayer : players->players) { - shared_ptr<ServerPlayer> serverPlayer = *it3; if(serverPlayer->dimension == 1) { atLeastOnePlayerInTheEnd = true; @@ -285,8 +284,8 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI } } - AUTO_VAR(currentPortalDecoration, nonPlayerDecorations.find( END_PORTAL_DECORATION_KEY )); - if( currentPortalDecoration == nonPlayerDecorations.end() && atLeastOnePlayerInTheEnd) + auto currentPortalDecoration = nonPlayerDecorations.find(END_PORTAL_DECORATION_KEY); + if( currentPortalDecoration == nonPlayerDecorations.end() && atLeastOnePlayerInTheEnd) { float origX = 0.0f; float origZ = 0.0f; @@ -330,7 +329,7 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI if (item->isFramed()) { //addDecoration(1, player.level, "frame-" + item.getFrame().entityId, item.getFrame().xTile, item.getFrame().zTile, item.getFrame().dir * 90); - + if( nonPlayerDecorations.find( item->getFrame()->entityId ) == nonPlayerDecorations.end() ) { float xd = (float) ( item->getFrame()->xTile - x ) / (1 << scale); @@ -361,10 +360,8 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI // 4J Stu - Put this block back in if you want to display entity positions on a map (see above as well) #if 0 - for(AUTO_VAR(it,playerLevel->entities.begin()); it != playerLevel->entities.end(); ++it) + for(auto& ent : playerLevel->entities) { - shared_ptr<Entity> ent = *it; - if((ent->GetType() & eTYPE_ENEMY) == 0) continue; float xd = (float) ( ent->x - x ) / (1 << scale); @@ -400,9 +397,8 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI addedPlayers = true; PlayerList *players = MinecraftServer::getInstance()->getPlayerList(); - for(AUTO_VAR(it3, players->players.begin()); it3 != players->players.end(); ++it3) + for(auto& decorationPlayer : players->players) { - shared_ptr<ServerPlayer> decorationPlayer = *it3; if(decorationPlayer!=NULL && decorationPlayer->dimension == this->dimension) { float xd = (float) (decorationPlayer->x - x) / (1 << scale); @@ -481,8 +477,8 @@ void MapItemSavedData::tickCarriedBy(shared_ptr<Player> player, shared_ptr<ItemI charArray MapItemSavedData::getUpdatePacket(shared_ptr<ItemInstance> itemInstance, Level *level, shared_ptr<Player> player) { - AUTO_VAR(it, carriedByPlayers.find(player)); - if (it == carriedByPlayers.end() ) return charArray(); + auto it = carriedByPlayers.find(player); + if (it == carriedByPlayers.end() ) return charArray(); shared_ptr<HoldingPlayer> hp = it->second; return hp->nextUpdatePacket(itemInstance); @@ -492,10 +488,8 @@ void MapItemSavedData::setDirty(int x, int y0, int y1) { SavedData::setDirty(); - AUTO_VAR(itEnd, carriedBy.end()); - for (AUTO_VAR(it, carriedBy.begin()); it != itEnd; it++) + for (auto& hp : carriedBy) { - shared_ptr<HoldingPlayer> hp = *it; //carriedBy.at(i); if (hp->rowsDirtyMin[x] < 0 || hp->rowsDirtyMin[x] > y0) hp->rowsDirtyMin[x] = y0; if (hp->rowsDirtyMax[x] < 0 || hp->rowsDirtyMax[x] < y1) hp->rowsDirtyMax[x] = y1; } @@ -547,9 +541,9 @@ void MapItemSavedData::handleComplexItemData(charArray &data) shared_ptr<MapItemSavedData::HoldingPlayer> MapItemSavedData::getHoldingPlayer(shared_ptr<Player> player) { shared_ptr<HoldingPlayer> hp = nullptr; - AUTO_VAR(it,carriedByPlayers.find(player)); + auto it = carriedByPlayers.find(player); - if (it == carriedByPlayers.end()) + if (it == carriedByPlayers.end()) { hp = shared_ptr<HoldingPlayer>( new HoldingPlayer(player, this) ); carriedByPlayers[player] = hp; @@ -587,7 +581,7 @@ void MapItemSavedData::mergeInMapData(shared_ptr<MapItemSavedData> dataToAdd) colors[x + z * w] = newColor; } } - if (yd0 <= yd1) + if (yd0 <= yd1) { setDirty(x, yd0, yd1); } @@ -598,7 +592,7 @@ void MapItemSavedData::removeItemFrameDecoration(shared_ptr<ItemInstance> item) { if ( !item ) return; - + std::shared_ptr<ItemFrame> frame = item->getFrame(); if ( !frame ) return; diff --git a/Minecraft.World/McRegionChunkStorage.cpp b/Minecraft.World/McRegionChunkStorage.cpp index d02125a6..344ff6c7 100644 --- a/Minecraft.World/McRegionChunkStorage.cpp +++ b/Minecraft.World/McRegionChunkStorage.cpp @@ -32,7 +32,7 @@ McRegionChunkStorage::McRegionChunkStorage(ConsoleSaveFile *saveFile, const wstr m_saveFile->createFile(ConsoleSavePath(L"r.-1.0.mcr")); } - + #ifdef SPLIT_SAVES ConsoleSavePath currentFile = ConsoleSavePath( m_prefix + wstring( L"entities.dat" ) ); @@ -64,9 +64,9 @@ McRegionChunkStorage::McRegionChunkStorage(ConsoleSaveFile *saveFile, const wstr McRegionChunkStorage::~McRegionChunkStorage() { - for(AUTO_VAR(it,m_entityData.begin()); it != m_entityData.end(); ++it) + for(auto& it : m_entityData) { - delete it->second.data; + delete it.second.data; } } @@ -80,8 +80,8 @@ LevelChunk *McRegionChunkStorage::load(Level *level, int x, int z) { __int64 index = ((__int64)(x) << 32) | (((__int64)(z))&0x00000000FFFFFFFF); - AUTO_VAR(it, m_entityData.find(index)); - if(it != m_entityData.end()) + auto it = m_entityData.find(index); + if(it != m_entityData.end()) { delete it->second.data; m_entityData.erase(it); @@ -262,8 +262,8 @@ void McRegionChunkStorage::saveEntities(Level *level, LevelChunk *levelChunk) } else { - AUTO_VAR(it, m_entityData.find(index)); - if(it != m_entityData.end()) + auto it = m_entityData.find(index); + if(it != m_entityData.end()) { m_entityData.erase(it); } @@ -277,9 +277,9 @@ void McRegionChunkStorage::loadEntities(Level *level, LevelChunk *levelChunk) { #ifdef SPLIT_SAVES __int64 index = ((__int64)(levelChunk->x) << 32) | (((__int64)(levelChunk->z))&0x00000000FFFFFFFF); - - AUTO_VAR(it, m_entityData.find(index)); - if(it != m_entityData.end()) + + auto it = m_entityData.find(index); + if(it != m_entityData.end()) { ByteArrayInputStream bais(it->second); DataInputStream dis(&bais); @@ -308,10 +308,10 @@ void McRegionChunkStorage::flush() PIXBeginNamedEvent(0,"Writing to stream"); dos.writeInt(m_entityData.size()); - for(AUTO_VAR(it,m_entityData.begin()); it != m_entityData.end(); ++it) + for(auto& it : m_entityData) { - dos.writeLong(it->first); - dos.write(it->second,0,it->second.length); + dos.writeLong(it.first); + dos.write(it.second,0,it.second.length); } bos.flush(); PIXEndNamedEvent(); diff --git a/Minecraft.World/McRegionLevelStorage.cpp b/Minecraft.World/McRegionLevelStorage.cpp index 687ee048..daf6a7ef 100644 --- a/Minecraft.World/McRegionLevelStorage.cpp +++ b/Minecraft.World/McRegionLevelStorage.cpp @@ -20,13 +20,13 @@ McRegionLevelStorage::~McRegionLevelStorage() RegionFileCache::clear(); } -ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) +ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) { //File folder = getFolder(); if (dynamic_cast<HellDimension *>(dimension) != NULL) { - + if(app.GetResetNether()) { #ifdef SPLIT_SAVES @@ -34,19 +34,19 @@ ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) if(netherFiles!=NULL) { DWORD bytesWritten = 0; - for(AUTO_VAR(it, netherFiles->begin()); it != netherFiles->end(); ++it) + for(auto& netherFile : *netherFiles) { - m_saveFile->zeroFile(*it, (*it)->getFileSize(), &bytesWritten); + m_saveFile->zeroFile(netherFile, netherFile->getFileSize(), &bytesWritten); } delete netherFiles; } #else vector<FileEntry *> *netherFiles = m_saveFile->getFilesWithPrefix(LevelStorage::NETHER_FOLDER); if(netherFiles!=NULL) - { - for(AUTO_VAR(it, netherFiles->begin()); it != netherFiles->end(); ++it) + { + for(auto& netherFile : *netherFiles) { - m_saveFile->deleteFile(*it); + m_saveFile->deleteFile(netherFile); } delete netherFiles; } @@ -56,13 +56,13 @@ ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) return new McRegionChunkStorage(m_saveFile, LevelStorage::NETHER_FOLDER); } - + if (dynamic_cast<TheEndDimension *>(dimension)) { //File dir2 = new File(folder, LevelStorage.ENDER_FOLDER); //dir2.mkdirs(); //return new ThreadedMcRegionChunkStorage(dir2); - + // 4J-PB - save version 0 at this point means it's a create new world int iSaveVersion=m_saveFile->getSaveVersion(); @@ -75,10 +75,10 @@ ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) // 4J-PB - There will be no End in early saves if(endFiles!=NULL) - { - for(AUTO_VAR(it, endFiles->begin()); it != endFiles->end(); ++it) + { + for(auto& endFile : *endFiles) { - m_saveFile->deleteFile(*it); + m_saveFile->deleteFile(endFile); } delete endFiles; } @@ -89,7 +89,7 @@ ChunkStorage *McRegionLevelStorage::createChunkStorage(Dimension *dimension) return new McRegionChunkStorage(m_saveFile, L""); } -void McRegionLevelStorage::saveLevelData(LevelData *levelData, vector<shared_ptr<Player> > *players) +void McRegionLevelStorage::saveLevelData(LevelData *levelData, vector<shared_ptr<Player> > *players) { levelData->setVersion(MCREGION_VERSION_ID); MemSect(38); @@ -97,7 +97,7 @@ void McRegionLevelStorage::saveLevelData(LevelData *levelData, vector<shared_ptr MemSect(0); } -void McRegionLevelStorage::closeAll() +void McRegionLevelStorage::closeAll() { RegionFileCache::clear(); }
\ No newline at end of file diff --git a/Minecraft.World/McRegionLevelStorageSource.cpp b/Minecraft.World/McRegionLevelStorageSource.cpp index 0652ad84..60904fde 100644 --- a/Minecraft.World/McRegionLevelStorageSource.cpp +++ b/Minecraft.World/McRegionLevelStorageSource.cpp @@ -39,12 +39,11 @@ vector<LevelSummary *> *McRegionLevelStorageSource::getLevelList() #if 0 vector<File *> *subFolders = baseDir.listFiles(); File *file; - AUTO_VAR(itEnd, subFolders->end()); - for (AUTO_VAR(it, subFolders->begin()); it != itEnd; it++) + for (auto& subFolder : *subFolders) { - file = *it; //subFolders->at(i); + file = subFolder; //subFolders->at(i); - if (file->isDirectory()) + if (file->isDirectory()) { continue; } @@ -74,13 +73,13 @@ void McRegionLevelStorageSource::clearAll() { } -shared_ptr<LevelStorage> McRegionLevelStorageSource::selectLevel(ConsoleSaveFile *saveFile, const wstring& levelId, bool createPlayerDir) +shared_ptr<LevelStorage> McRegionLevelStorageSource::selectLevel(ConsoleSaveFile *saveFile, const wstring& levelId, bool createPlayerDir) { // return new LevelStorageProfilerDecorator(new McRegionLevelStorage(baseDir, levelId, createPlayerDir)); return shared_ptr<LevelStorage>(new McRegionLevelStorage(saveFile, baseDir, levelId, createPlayerDir)); } -bool McRegionLevelStorageSource::isConvertible(ConsoleSaveFile *saveFile, const wstring& levelId) +bool McRegionLevelStorageSource::isConvertible(ConsoleSaveFile *saveFile, const wstring& levelId) { // check if there is old file format level data LevelData *levelData = getDataTagFor(saveFile, levelId); @@ -145,7 +144,7 @@ bool McRegionLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const w } int totalCount = normalRegions->size() + netherRegions->size() + enderRegions.size() + normalBaseFolders->size() + netherBaseFolders->size() + enderBaseFolders.size(); - + // System.out.println("Total conversion count is " + totalCount); 4J Jev, TODO // convert normal world @@ -173,16 +172,15 @@ bool McRegionLevelStorageSource::convertLevel(ConsoleSaveFile *saveFile, const w #if 0 // 4J - not required anymore -void McRegionLevelStorageSource::addRegions(File &baseFolder, vector<ChunkFile *> *dest, vector<File *> *firstLevelFolders) +void McRegionLevelStorageSource::addRegions(File &baseFolder, vector<ChunkFile *> *dest, vector<File *> *firstLevelFolders) { FolderFilter folderFilter; ChunkFilter chunkFilter; File *folder1; vector<File *> *folderLevel1 = baseFolder.listFiles((FileFilter *) &folderFilter); - AUTO_VAR(itEnd, folderLevel1->end()); - for (AUTO_VAR(it, folderLevel1->begin()); it != itEnd; it++) - { + for (auto it = folderLevel1->begin(); it != folderLevel1->end(); it++) + { folder1 = *it; //folderLevel1->at(i1); // keep this for the clean-up process later on @@ -190,17 +188,17 @@ void McRegionLevelStorageSource::addRegions(File &baseFolder, vector<ChunkFile * File *folder2; vector<File *> *folderLevel2 = folder1->listFiles(&folderFilter); - AUTO_VAR(itEnd2, folderLevel2->end()); - for (AUTO_VAR(it2, folderLevel2->begin()); it2 != itEnd; it2++) + auto itEnd2 = folderLevel2->end(); + for ( auto it2 = folderLevel2->begin(); it2 != itEnd2; it2++) { folder2 = *it2; //folderLevel2->at(i2); vector<File *> *chunkFiles = folder2->listFiles((FileFilter *) &chunkFilter); File *chunk; - AUTO_VAR(itEndFile, chunkFiles->end()); - for (AUTO_VAR(itFile, chunkFiles->begin()); itFile != itEndFile; itFile++) - { + auto itEndFile = chunkFiles->end(); + for (auto itFile = chunkFiles->begin(); itFile != itEndFile; itFile++) + { chunk = *itFile; //chunkFiles->at(i3); dest->push_back(new ChunkFile(chunk)); @@ -210,7 +208,7 @@ void McRegionLevelStorageSource::addRegions(File &baseFolder, vector<ChunkFile * } #endif -void McRegionLevelStorageSource::convertRegions(File &baseFolder, vector<ChunkFile *> *chunkFiles, int currentCount, int totalCount, ProgressListener *progress) +void McRegionLevelStorageSource::convertRegions(File &baseFolder, vector<ChunkFile *> *chunkFiles, int currentCount, int totalCount, ProgressListener *progress) { assert( false ); @@ -222,10 +220,9 @@ void McRegionLevelStorageSource::convertRegions(File &baseFolder, vector<ChunkFi byteArray buffer = byteArray(4096); ChunkFile *chunkFile; - AUTO_VAR(itEnd, chunkFiles->end()); - for (AUTO_VAR(it, chunkFiles->begin()); it != itEnd; it++) + for (auto& it : *chunkFiles) { - chunkFile = *it; //chunkFiles->at(i1); + chunkFile = it; //chunkFiles->at(i1); // Matcher matcher = ChunkFilter.chunkFilePattern.matcher(chunkFile.getName()); // if (!matcher.matches()) { @@ -238,7 +235,7 @@ void McRegionLevelStorageSource::convertRegions(File &baseFolder, vector<ChunkFi int z = chunkFile->getZ(); RegionFile *region = RegionFileCache::getRegionFile(baseFolder, x, z); - if (!region->hasChunk(x & 31, z & 31)) + if (!region->hasChunk(x & 31, z & 31)) { FileInputStream fis = new BufferedInputStream(FileInputStream(*chunkFile->getFile())); DataInputStream istream = DataInputStream(&fis); // 4J - was new GZIPInputStream as well @@ -271,12 +268,8 @@ void McRegionLevelStorageSource::convertRegions(File &baseFolder, vector<ChunkFi void McRegionLevelStorageSource::eraseFolders(vector<File *> *folders, int currentCount, int totalCount, ProgressListener *progress) { - File *folder; - AUTO_VAR(itEnd, folders->end()); - for (AUTO_VAR(it, folders->begin()); it != itEnd; it++) + for (File *folder : *folders) { - folder = *it; //folders->at(i); - vector<File *> *files = folder->listFiles(); deleteRecursive(files); folder->_delete(); @@ -289,7 +282,7 @@ void McRegionLevelStorageSource::eraseFolders(vector<File *> *folders, int curre #if 0 // 4J - not required anymore -bool McRegionLevelStorageSource::FolderFilter::accept(File *file) +bool McRegionLevelStorageSource::FolderFilter::accept(File *file) { if (file->isDirectory()) { @@ -300,23 +293,23 @@ bool McRegionLevelStorageSource::FolderFilter::accept(File *file) } -bool McRegionLevelStorageSource::ChunkFilter::accept(File *dir, const wstring& name) +bool McRegionLevelStorageSource::ChunkFilter::accept(File *dir, const wstring& name) { Matcher matcher( chunkFilePattern, name ); return matcher.matches(); } -McRegionLevelStorageSource::ChunkFile::ChunkFile(File *file) +McRegionLevelStorageSource::ChunkFile::ChunkFile(File *file) { this->file = file; Matcher matcher( ChunkFilter::chunkFilePattern, file->getName() ); - if (matcher.matches()) + if (matcher.matches()) { x = Integer::parseInt(matcher.group(1), 36); z = Integer::parseInt(matcher.group(2), 36); - } + } else { x = 0; @@ -348,17 +341,17 @@ bool McRegionLevelStorageSource::ChunkFile::operator<( ChunkFile *b ) return compareTo( b ) < 0; } -File *McRegionLevelStorageSource::ChunkFile::getFile() +File *McRegionLevelStorageSource::ChunkFile::getFile() { return (File *) file; } -int McRegionLevelStorageSource::ChunkFile::getX() +int McRegionLevelStorageSource::ChunkFile::getX() { return x; } -int McRegionLevelStorageSource::ChunkFile::getZ() +int McRegionLevelStorageSource::ChunkFile::getZ() { return z; } diff --git a/Minecraft.World/MerchantRecipeList.cpp b/Minecraft.World/MerchantRecipeList.cpp index bd7a126c..c994081f 100644 --- a/Minecraft.World/MerchantRecipeList.cpp +++ b/Minecraft.World/MerchantRecipeList.cpp @@ -13,9 +13,9 @@ MerchantRecipeList::MerchantRecipeList(CompoundTag *tag) MerchantRecipeList::~MerchantRecipeList() { - for(AUTO_VAR(it, m_recipes.begin()); it != m_recipes.end(); ++it) + for(auto& it : m_recipes) { - delete (*it); + delete it; } } diff --git a/Minecraft.World/MineShaftFeature.cpp b/Minecraft.World/MineShaftFeature.cpp index 78178de0..d32af346 100644 --- a/Minecraft.World/MineShaftFeature.cpp +++ b/Minecraft.World/MineShaftFeature.cpp @@ -19,11 +19,11 @@ MineShaftFeature::MineShaftFeature(unordered_map<wstring, wstring> options) { chance = 0.01; - for(AUTO_VAR(it,options.begin()); it != options.end(); ++it) + for(auto& option : options) { - if (it->first.compare(OPTION_CHANCE) == 0) + if (option.first.compare(OPTION_CHANCE) == 0) { - chance = Mth::getDouble(it->second, chance); + chance = Mth::getDouble(option.second, chance); } } } diff --git a/Minecraft.World/MineShaftPieces.cpp b/Minecraft.World/MineShaftPieces.cpp index 844514dc..3fda1bfc 100644 --- a/Minecraft.World/MineShaftPieces.cpp +++ b/Minecraft.World/MineShaftPieces.cpp @@ -103,9 +103,9 @@ MineShaftPieces::MineShaftRoom::MineShaftRoom(int genDepth, Random *random, int MineShaftPieces::MineShaftRoom::~MineShaftRoom() { - for(AUTO_VAR(it, childEntranceBoxes.begin()); it != childEntranceBoxes.end(); ++it) + for(auto& it : childEntranceBoxes) { - delete (*it); + delete it; } } @@ -204,9 +204,8 @@ bool MineShaftPieces::MineShaftRoom::postProcess(Level *level, Random *random, B // room air generateBox(level, chunkBB, boundingBox->x0, boundingBox->y0 + 1, boundingBox->z0, boundingBox->x1, min(boundingBox->y0 + 3, boundingBox->y1), boundingBox->z1, 0, 0, false); - for(AUTO_VAR(it, childEntranceBoxes.begin()); it != childEntranceBoxes.end(); ++it) + for(auto& entranceBox : childEntranceBoxes) { - BoundingBox *entranceBox = *it; generateBox(level, chunkBB, entranceBox->x0, entranceBox->y1 - (DEFAULT_SHAFT_HEIGHT - 1), entranceBox->z0, entranceBox->x1, entranceBox->y1, entranceBox->z1, 0, 0, false); } generateUpperHalfSphere(level, chunkBB, boundingBox->x0, boundingBox->y0 + 4, boundingBox->z0, boundingBox->x1, boundingBox->y1, boundingBox->z1, 0, false); @@ -217,9 +216,8 @@ bool MineShaftPieces::MineShaftRoom::postProcess(Level *level, Random *random, B void MineShaftPieces::MineShaftRoom::addAdditonalSaveData(CompoundTag *tag) { ListTag<IntArrayTag> *entrances = new ListTag<IntArrayTag>(L"Entrances"); - for (AUTO_VAR(it,childEntranceBoxes.begin()); it != childEntranceBoxes.end(); ++it) + for (auto& bb : childEntranceBoxes) { - BoundingBox *bb =*it; entrances->add(bb->createTag(L"")); } tag->put(L"Entrances", entrances); @@ -523,12 +521,12 @@ bool MineShaftPieces::MineShaftCorridor::postProcess(Level *level, Random *rando } // prevent air floating - for (int x = x0; x <= x1; x++) + for (int x = x0; x <= x1; x++) { - for (int z = 0; z <= length; z++) + for (int z = 0; z <= length; z++) { int block = getBlock(level, x, -1, z, chunkBB); - if (block == 0) + if (block == 0) { placeBlock(level, Tile::wood_Id, 0, x, -1, z, chunkBB); } @@ -687,12 +685,12 @@ bool MineShaftPieces::MineShaftCrossing::postProcess(Level *level, Random *rando // prevent air floating // note: use world coordinates because the corridor hasn't defined // orientation - for (int x = boundingBox->x0; x <= boundingBox->x1; x++) + for (int x = boundingBox->x0; x <= boundingBox->x1; x++) { - for (int z = boundingBox->z0; z <= boundingBox->z1; z++) + for (int z = boundingBox->z0; z <= boundingBox->z1; z++) { int block = getBlock(level, x, boundingBox->y0 - 1, z, chunkBB); - if (block == 0) + if (block == 0) { placeBlock(level, Tile::wood_Id, 0, x, boundingBox->y0 - 1, z, chunkBB); } diff --git a/Minecraft.World/Minecart.cpp b/Minecraft.World/Minecart.cpp index 48787f55..4e1419cc 100644 --- a/Minecraft.World/Minecart.cpp +++ b/Minecraft.World/Minecart.cpp @@ -346,11 +346,9 @@ void Minecart::tick() vector<shared_ptr<Entity> > *entities = level->getEntities(shared_from_this(), bb->grow(0.2f, 0, 0.2f)); if (entities != NULL && !entities->empty()) { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = (*it); //entities->at(i); - if (e != rider.lock() && e->isPushable() && e->instanceof(eTYPE_MINECART)) + if ( e && e != rider.lock() && e->isPushable() && e->instanceof(eTYPE_MINECART)) { shared_ptr<Minecart> cart = dynamic_pointer_cast<Minecart>(e); cart->m_bHasPushedCartThisTick = false; @@ -455,7 +453,7 @@ void Minecart::moveAlongTrack(int xt, int yt, int zt, double maxSpeed, double sl xd = pow * xD / dd; zd = pow * zD / dd; - + if ( rider.lock() != NULL && rider.lock()->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr<LivingEntity> living = dynamic_pointer_cast<LivingEntity>(rider.lock()); diff --git a/Minecraft.World/Minecraft.World.vcxproj b/Minecraft.World/Minecraft.World.vcxproj index 7ab7c4ce..c9191573 100644 --- a/Minecraft.World/Minecraft.World.vcxproj +++ b/Minecraft.World/Minecraft.World.vcxproj @@ -707,6 +707,9 @@ <IncludePath>$(ProjectDir)\x64headers;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -735,6 +738,9 @@ <IncludePath>$(ProjectDir)\x64headers;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -753,6 +759,9 @@ <IncludePath>$(ProjectDir)\x64headers;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ContentPackage_Vita|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -834,6 +843,9 @@ <IncludePath>$(ProjectDir)\x64header;$(DXSDK_DIR)include;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ContentPackage|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -852,6 +864,9 @@ <IncludePath>$(ProjectDir)\x64header;$(DXSDK_DIR)include;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='CONTENTPACKAGE_SYMBOLS|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -870,6 +885,9 @@ <IncludePath>$(ProjectDir)\x64header;$(DXSDK_DIR)include;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Platform)_$(Configuration)\</OutDir> <IntDir>$(Platform)_$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseForArt|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -888,6 +906,9 @@ <IncludePath>$(ProjectDir)\x64header;$(DXSDK_DIR)include;$(IncludePath)</IncludePath> <OutDir>$(ProjectDir)\$(Configuration)\</OutDir> <IntDir>$(ProjectDir)\$(Configuration)\</IntDir> + <RunCodeAnalysis>false</RunCodeAnalysis> + <EnableMicrosoftCodeAnalysis>false</EnableMicrosoftCodeAnalysis> + <EnableClangTidyCodeAnalysis>false</EnableClangTidyCodeAnalysis> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ContentPackage_NO_TU|ARM64EC'"> <OutputFile>$(OutDir)$(ProjectName).lib</OutputFile> @@ -4958,4 +4979,4 @@ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> -</Project> +</Project>
\ No newline at end of file diff --git a/Minecraft.World/Mob.cpp b/Minecraft.World/Mob.cpp index cac25ddb..342400b4 100644 --- a/Minecraft.World/Mob.cpp +++ b/Minecraft.World/Mob.cpp @@ -152,38 +152,38 @@ void Mob::ate() { } -void Mob::defineSynchedData() +void Mob::defineSynchedData() { LivingEntity::defineSynchedData(); entityData->define(DATA_CUSTOM_NAME_VISIBLE, (byte) 0); entityData->define(DATA_CUSTOM_NAME, L""); } -int Mob::getAmbientSoundInterval() +int Mob::getAmbientSoundInterval() { return 20 * 4; } -void Mob::playAmbientSound() +void Mob::playAmbientSound() { MemSect(31); int ambient = getAmbientSound(); - if (ambient != -1) + if (ambient != -1) { playSound(ambient, getSoundVolume(), getVoicePitch()); } MemSect(0); } -void Mob::baseTick() +void Mob::baseTick() { LivingEntity::baseTick(); - if (isAlive() && random->nextInt(1000) < ambientSoundTime++) + if (isAlive() && random->nextInt(1000) < ambientSoundTime++) { ambientSoundTime = -getAmbientSoundInterval(); - playAmbientSound(); + playAmbientSound(); } } @@ -209,9 +209,9 @@ int Mob::getExperienceReward(shared_ptr<Player> killedBy) return xpReward; } } -void Mob::spawnAnim() +void Mob::spawnAnim() { - for (int i = 0; i < 20; i++) + for (int i = 0; i < 20; i++) { double xa = random->nextGaussian() * 0.02; double ya = random->nextGaussian() * 0.02; @@ -222,7 +222,7 @@ void Mob::spawnAnim() } } -void Mob::tick() +void Mob::tick() { LivingEntity::tick(); @@ -245,7 +245,7 @@ float Mob::tickHeadTurn(float yBodyRotT, float walkSpeed) } } -int Mob::getAmbientSound() +int Mob::getAmbientSound() { return -1; } @@ -255,10 +255,10 @@ int Mob::getDeathLoot() return 0; } -void Mob::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) +void Mob::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) { int loot = getDeathLoot(); - if (loot > 0) + if (loot > 0) { int count = random->nextInt(3); if (playerBonusLevel > 0) @@ -270,7 +270,7 @@ void Mob::dropDeathLoot(bool wasKilledByPlayer, int playerBonusLevel) } } -void Mob::addAdditonalSaveData(CompoundTag *entityTag) +void Mob::addAdditonalSaveData(CompoundTag *entityTag) { LivingEntity::addAdditonalSaveData(entityTag); entityTag->putBoolean(L"CanPickUpLoot", canPickUpLoot()); @@ -288,7 +288,7 @@ void Mob::addAdditonalSaveData(CompoundTag *entityTag) ListTag<FloatTag> *dropChanceList = new ListTag<FloatTag>(); for (int i = 0; i < dropChances.length; i++) { - dropChanceList->add(new FloatTag( _toString(i), dropChances[i])); + dropChanceList->add(new FloatTag( std::to_wstring(i), dropChances[i])); } entityTag->put(L"DropChances", dropChanceList); entityTag->putString(L"CustomName", getCustomName()); @@ -316,7 +316,7 @@ void Mob::addAdditonalSaveData(CompoundTag *entityTag) } } -void Mob::readAdditionalSaveData(CompoundTag *tag) +void Mob::readAdditionalSaveData(CompoundTag *tag) { LivingEntity::readAdditionalSaveData(tag); @@ -362,16 +362,16 @@ void Mob::setSpeed(float speed) setYya(speed); } -void Mob::aiStep() +void Mob::aiStep() { LivingEntity::aiStep(); if (!level->isClientSide && canPickUpLoot() && !dead && level->getGameRules()->getBoolean(GameRules::RULE_MOBGRIEFING)) { vector<shared_ptr<Entity> > *entities = level->getEntitiesOfClass(typeid(ItemEntity), bb->grow(1, 0, 1)); - for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + for (auto& it : *entities) { - shared_ptr<ItemEntity> entity = dynamic_pointer_cast<ItemEntity>(*it); + shared_ptr<ItemEntity> entity = dynamic_pointer_cast<ItemEntity>(it); if (entity->removed || entity->getItem() == NULL) continue; shared_ptr<ItemInstance> item = entity->getItem(); int slot = getEquipmentSlotForItem(item); @@ -457,12 +457,12 @@ bool Mob::useNewAi() return false; } -bool Mob::removeWhenFarAway() +bool Mob::removeWhenFarAway() { return true; } -void Mob::checkDespawn() +void Mob::checkDespawn() { if (persistenceRequired) { @@ -470,23 +470,23 @@ void Mob::checkDespawn() return; } shared_ptr<Entity> player = level->getNearestPlayer(shared_from_this(), -1); - if (player != NULL) + if (player != NULL) { double xd = player->x - x; double yd = player->y - y; double zd = player->z - z; double sd = xd * xd + yd * yd + zd * zd; - if (removeWhenFarAway() && sd > 128 * 128) + if (removeWhenFarAway() && sd > 128 * 128) { remove(); } - if (noActionTime > 20 * 30 && random->nextInt(800) == 0 && sd > 32 * 32 && removeWhenFarAway()) + if (noActionTime > 20 * 30 && random->nextInt(800) == 0 && sd > 32 * 32 && removeWhenFarAway()) { remove(); } - else if (sd < 32 * 32) + else if (sd < 32 * 32) { noActionTime = 0; } @@ -502,7 +502,7 @@ void Mob::newServerAiStep() checkDespawn(); PIXEndNamedEvent(); PIXBeginNamedEvent(0,"Tick sensing"); - sensing->tick(); + sensing->tick(); PIXEndNamedEvent(); PIXBeginNamedEvent(0,"Tick target selector"); targetSelector.tick(); @@ -534,7 +534,7 @@ void Mob::newServerAiStep() PIXEndNamedEvent(); } -void Mob::serverAiStep() +void Mob::serverAiStep() { LivingEntity::serverAiStep(); @@ -544,15 +544,15 @@ void Mob::serverAiStep() checkDespawn(); float lookDistance = 8; - if (random->nextFloat() < 0.02f) + if (random->nextFloat() < 0.02f) { shared_ptr<Player> player = level->getNearestPlayer(shared_from_this(), lookDistance); - if (player != NULL) + if (player != NULL) { lookingAt = player; lookTime = 10 + random->nextInt(20); - } - else + } + else { yRotA = (random->nextFloat() - 0.5f) * 20; } @@ -561,14 +561,14 @@ void Mob::serverAiStep() if (lookingAt != NULL) { lookAt(lookingAt, 10.0f, (float) getMaxHeadXRot()); - if (lookTime-- <= 0 || lookingAt->removed || lookingAt->distanceToSqr(shared_from_this()) > lookDistance * lookDistance) + if (lookTime-- <= 0 || lookingAt->removed || lookingAt->distanceToSqr(shared_from_this()) > lookDistance * lookDistance) { lookingAt = nullptr; } - } - else + } + else { - if (random->nextFloat() < 0.05f) + if (random->nextFloat() < 0.05f) { yRotA = (random->nextFloat() - 0.5f) * 20; } @@ -581,24 +581,24 @@ void Mob::serverAiStep() if (inWater || inLava) jumping = random->nextFloat() < 0.8f; } -int Mob::getMaxHeadXRot() +int Mob::getMaxHeadXRot() { return 40; } -void Mob::lookAt(shared_ptr<Entity> e, float yMax, float xMax) +void Mob::lookAt(shared_ptr<Entity> e, float yMax, float xMax) { double xd = e->x - x; double yd; double zd = e->z - z; - + if ( e->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr<LivingEntity> mob = dynamic_pointer_cast<LivingEntity>(e); yd = (mob->y + mob->getHeadHeight()) - (y + getHeadHeight()); - } - else + } + else { yd = (e->bb->y0 + e->bb->y1) / 2 - (y + getHeadHeight()); } @@ -611,31 +611,31 @@ void Mob::lookAt(shared_ptr<Entity> e, float yMax, float xMax) yRot = rotlerp(yRot, yRotD, yMax); } -bool Mob::isLookingAtAnEntity() +bool Mob::isLookingAtAnEntity() { return lookingAt != NULL; } -shared_ptr<Entity> Mob::getLookingAt() +shared_ptr<Entity> Mob::getLookingAt() { return lookingAt; } -float Mob::rotlerp(float a, float b, float max) +float Mob::rotlerp(float a, float b, float max) { float diff = Mth::wrapDegrees(b - a); - if (diff > max) + if (diff > max) { diff = max; } - if (diff < -max) + if (diff < -max) { diff = -max; } return a + diff; } -bool Mob::canSpawn() +bool Mob::canSpawn() { // 4J - altered to use special containsAnyLiquid variant return level->isUnobstructed(bb) && level->getCubes(shared_from_this(), bb)->empty() && !level->containsAnyLiquid_NoLoad(bb); @@ -651,7 +651,7 @@ float Mob::getHeadSizeScale() return 1.0f; } -int Mob::getMaxSpawnClusterSize() +int Mob::getMaxSpawnClusterSize() { return 4; } @@ -815,7 +815,7 @@ void Mob::populateDefaultEquipmentEnchantments() /** * Added this method so mobs can handle their own spawn settings instead of * hacking MobSpawner.java -* +* * @param groupData * TODO * @return TODO @@ -918,7 +918,7 @@ bool Mob::interact(shared_ptr<Player> player) if (canBeLeashed()) { shared_ptr<TamableAnimal> tamableAnimal = nullptr; - if ( shared_from_this()->instanceof(eTYPE_TAMABLE_ANIMAL) + if ( shared_from_this()->instanceof(eTYPE_TAMABLE_ANIMAL) && (tamableAnimal = dynamic_pointer_cast<TamableAnimal>(shared_from_this()))->isTame() ) // 4J-JEV: excuse the assignment operator in here, don't want to dyn-cast if it's avoidable. { if (player->getUUID().compare(tamableAnimal->getOwnerUUID()) == 0) @@ -1007,7 +1007,7 @@ void Mob::setLeashedTo(shared_ptr<Entity> holder, bool synch) { _isLeashed = true; leashHolder = holder; - + ServerLevel *serverLevel = dynamic_cast<ServerLevel *>(level); if (!level->isClientSide && synch && serverLevel) { @@ -1024,9 +1024,9 @@ void Mob::restoreLeashFromSave() { wstring leashUuid = leashInfoTag->getString(L"UUID"); vector<shared_ptr<Entity> > *livingEnts = level->getEntitiesOfClass(typeid(LivingEntity), bb->grow(10, 10, 10)); - for(AUTO_VAR(it, livingEnts->begin()); it != livingEnts->end(); ++it) + for(auto& livingEnt : *livingEnts) { - shared_ptr<LivingEntity> le = dynamic_pointer_cast<LivingEntity>(*it); + shared_ptr<LivingEntity> le = dynamic_pointer_cast<LivingEntity>(livingEnt); if (le->getUUID().compare(leashUuid) == 0) { leashHolder = le; diff --git a/Minecraft.World/MobEffect.cpp b/Minecraft.World/MobEffect.cpp index 61aee91f..92f8c9d0 100644 --- a/Minecraft.World/MobEffect.cpp +++ b/Minecraft.World/MobEffect.cpp @@ -15,26 +15,26 @@ MobEffect *MobEffect::voidEffect; MobEffect *MobEffect::movementSpeed; MobEffect *MobEffect::movementSlowdown; MobEffect *MobEffect::digSpeed; -MobEffect *MobEffect::digSlowdown; -MobEffect *MobEffect::damageBoost; -MobEffect *MobEffect::heal; -MobEffect *MobEffect::harm; +MobEffect *MobEffect::digSlowdown; +MobEffect *MobEffect::damageBoost; +MobEffect *MobEffect::heal; +MobEffect *MobEffect::harm; MobEffect *MobEffect::jump; MobEffect *MobEffect::confusion; -MobEffect *MobEffect::regeneration; +MobEffect *MobEffect::regeneration; MobEffect *MobEffect::damageResistance; -MobEffect *MobEffect::fireResistance; -MobEffect *MobEffect::waterBreathing; -MobEffect *MobEffect::invisibility; -MobEffect *MobEffect::blindness; -MobEffect *MobEffect::nightVision; -MobEffect *MobEffect::hunger; -MobEffect *MobEffect::weakness; -MobEffect *MobEffect::poison; -MobEffect *MobEffect::wither; -MobEffect *MobEffect::healthBoost; -MobEffect *MobEffect::absorption; -MobEffect *MobEffect::saturation; +MobEffect *MobEffect::fireResistance; +MobEffect *MobEffect::waterBreathing; +MobEffect *MobEffect::invisibility; +MobEffect *MobEffect::blindness; +MobEffect *MobEffect::nightVision; +MobEffect *MobEffect::hunger; +MobEffect *MobEffect::weakness; +MobEffect *MobEffect::poison; +MobEffect *MobEffect::wither; +MobEffect *MobEffect::healthBoost; +MobEffect *MobEffect::absorption; +MobEffect *MobEffect::saturation; MobEffect *MobEffect::reserved_24; MobEffect *MobEffect::reserved_25; MobEffect *MobEffect::reserved_26; @@ -121,7 +121,7 @@ int MobEffect::getId() * This method should perform periodic updates on the player. Mainly used * for regeneration effects and the like. Other effects, such as blindness, * are in effect for the whole duration of the effect. -* +* * @param mob * @param amplification */ @@ -201,7 +201,7 @@ bool MobEffect::isInstantenous() * This parameter says if the applyEffect method should be called depending * on the remaining duration ticker. For instance, the regeneration will be * activated every 8 ticks, healing one point of health. -* +* * @param remainingDuration * @param amplification * Effect amplification, starts at 0 (weakest) @@ -355,26 +355,26 @@ unordered_map<Attribute *, AttributeModifier *> *MobEffect::getAttributeModifier void MobEffect::removeAttributeModifiers(shared_ptr<LivingEntity> entity, BaseAttributeMap *attributes, int amplifier) { - for (AUTO_VAR(it, attributeModifiers.begin()); it != attributeModifiers.end(); ++it) + for (auto& it : attributeModifiers) { - AttributeInstance *attribute = attributes->getInstance(it->first); + AttributeInstance *attribute = attributes->getInstance(it.first); if (attribute != NULL) { - attribute->removeModifier(it->second); + attribute->removeModifier(it.second); } } } void MobEffect::addAttributeModifiers(shared_ptr<LivingEntity> entity, BaseAttributeMap *attributes, int amplifier) { - for (AUTO_VAR(it, attributeModifiers.begin()); it != attributeModifiers.end(); ++it) + for (auto& it : attributeModifiers) { - AttributeInstance *attribute = attributes->getInstance(it->first); + AttributeInstance *attribute = attributes->getInstance(it.first); if (attribute != NULL) { - AttributeModifier *original = it->second; + AttributeModifier *original = it.second; attribute->removeModifier(original); attribute->addModifier(new AttributeModifier(original->getId(), getAttributeModifierValue(amplifier, original), original->getOperation())); } diff --git a/Minecraft.World/MobSpawner.cpp b/Minecraft.World/MobSpawner.cpp index 8cd60e92..e593a59f 100644 --- a/Minecraft.World/MobSpawner.cpp +++ b/Minecraft.World/MobSpawner.cpp @@ -100,12 +100,10 @@ const int MobSpawner::tick(ServerLevel *level, bool spawnEnemies, bool spawnFrie } MemSect(20); chunksToPoll.clear(); - + #if 0 - AUTO_VAR(itEnd, level->players.end()); - for (AUTO_VAR(it, level->players.begin()); it != itEnd; it++) + for (auto& player : level->players) { - shared_ptr<Player> player = *it; //level->players.at(i); int xx = Mth::floor(player->x / 16); int zz = Mth::floor(player->z / 16); @@ -164,20 +162,20 @@ const int MobSpawner::tick(ServerLevel *level, bool spawnEnemies, bool spawnFrie #ifdef __PSVITA__ ChunkPos cp = ChunkPos( ( xx[i] - r ) + l , ( zz[i] - r )); if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); - cp = ChunkPos( ( xx[i] + r ), ( zz[i] - r ) + l ); + cp = ChunkPos( ( xx[i] + r ), ( zz[i] - r ) + l ); if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); - cp = ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r )); + cp = ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r )); if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); - cp = ChunkPos( ( xx[i] - r ), ( zz[i] + r ) - l); + cp = ChunkPos( ( xx[i] - r ), ( zz[i] + r ) - l); if( chunksToPoll.find( cp ) ) chunksToPoll.insert(cp, true); #else ChunkPos cp = ChunkPos( ( xx[i] - r ) + l , ( zz[i] - r )); if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair<ChunkPos,bool>(cp, true)); - cp = ChunkPos( ( xx[i] + r ), ( zz[i] - r ) + l ); + cp = ChunkPos( ( xx[i] + r ), ( zz[i] - r ) + l ); if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair<ChunkPos,bool>(cp, true)); - cp = ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r )); + cp = ChunkPos( ( xx[i] + r ) - l , ( zz[i] + r )); if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair<ChunkPos,bool>(cp, true)); - cp = ChunkPos( ( xx[i] - r ), ( zz[i] + r ) - l); + cp = ChunkPos( ( xx[i] - r ), ( zz[i] + r ) - l); if( chunksToPoll.find( cp ) == chunksToPoll.end() ) chunksToPoll.insert(std::pair<ChunkPos,bool>(cp, true)); #endif @@ -224,16 +222,15 @@ const int MobSpawner::tick(ServerLevel *level, bool spawnEnemies, bool spawnFrie { SCustomMapNode *it = chunksToPoll.get(i); #else - AUTO_VAR(itEndCTP, chunksToPoll.end()); - for (AUTO_VAR(it, chunksToPoll.begin()); it != itEndCTP; it++) + for (auto& it : chunksToPoll) { #endif - if( it->second ) + if( it.second ) { // don't add mobs to edge chunks, to prevent adding mobs "outside" of the active playground continue; } - ChunkPos *cp = (ChunkPos *) (&it->first); + ChunkPos *cp = (ChunkPos *) (&it.first); // 4J - don't let this actually create/load a chunk that isn't here already - we'll let the normal updateDirtyChunks etc. processes do that, so it can happen on another thread if( !level->hasChunk(cp->x,cp->z) ) continue; @@ -399,7 +396,7 @@ bool MobSpawner::isSpawnPositionOk(MobCategory *category, Level *level, int x, i // 4J - changed to spawn water things only in deep water int yo = 0; int liquidCount = 0; - + while( ( y - yo ) >= 0 && ( yo < 5 ) ) { if( level->getMaterial(x, y - yo, z)->isLiquid() ) liquidCount++; diff --git a/Minecraft.World/ModifiableAttributeInstance.cpp b/Minecraft.World/ModifiableAttributeInstance.cpp index 50aa6504..3108df4d 100644 --- a/Minecraft.World/ModifiableAttributeInstance.cpp +++ b/Minecraft.World/ModifiableAttributeInstance.cpp @@ -15,12 +15,12 @@ ModifiableAttributeInstance::ModifiableAttributeInstance(BaseAttributeMap *attri ModifiableAttributeInstance::~ModifiableAttributeInstance() { - for (int i = 0; i < AttributeModifier::TOTAL_OPERATIONS; i++) + for (auto& modifier : modifiers) { - for (AUTO_VAR(it, modifiers[i].begin()); it != modifiers[i].end(); ++it) + for (auto it : modifier) { // Delete all modifiers - delete *it; + delete it; } } } @@ -51,14 +51,12 @@ unordered_set<AttributeModifier *> *ModifiableAttributeInstance::getModifiers(in // Returns a pointer to a new vector of all modifiers void ModifiableAttributeInstance::getModifiers(unordered_set<AttributeModifier *>& result) { - for (int i = 0; i < AttributeModifier::TOTAL_OPERATIONS; i++) + for (auto& modifier : modifiers) { - unordered_set<AttributeModifier *> *opModifiers = &modifiers[i]; - - for (AUTO_VAR(it, opModifiers->begin()); it != opModifiers->end(); ++it) + for (auto& opModifier : modifier) { - result.insert(*it); - } + result.insert(opModifier); + } } } @@ -66,20 +64,20 @@ AttributeModifier *ModifiableAttributeInstance::getModifier(eMODIFIER_ID id) { AttributeModifier *modifier = NULL; - AUTO_VAR(it, modifierById.find(id)); - if(it != modifierById.end()) + auto it = modifierById.find(id); + if(it != modifierById.end()) { modifier = it->second; } - return modifier; + return modifier; } void ModifiableAttributeInstance::addModifiers(unordered_set<AttributeModifier *> *modifiers) { - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& modifier : *modifiers) { - addModifier(*it); + addModifier(modifier); } } @@ -87,7 +85,7 @@ void ModifiableAttributeInstance::addModifiers(unordered_set<AttributeModifier * void ModifiableAttributeInstance::addModifier(AttributeModifier *modifier) { // Can't add modifiers with the same ID (unless the modifier is anonymous) - if (modifier->getId() != eModifierId_ANONYMOUS && getModifier(modifier->getId()) != NULL) + if (modifier->getId() != eModifierId_ANONYMOUS && getModifier(modifier->getId()) != NULL) { assert(0); // throw new IllegalArgumentException("Modifier is already applied on this attribute!"); @@ -108,13 +106,13 @@ void ModifiableAttributeInstance::setDirty() void ModifiableAttributeInstance::removeModifier(AttributeModifier *modifier) { - for (int i = 0; i < AttributeModifier::TOTAL_OPERATIONS; i++) + for (auto& mod : modifiers) { - for (AUTO_VAR(it, modifiers[i].begin()); it != modifiers[i].end(); ++it) - { - if (modifier->equals(*it)) + for (auto& it : mod ) + { + if (modifier->equals(it)) { - modifiers[i].erase(it); + mod.erase(it); break; } } @@ -136,9 +134,9 @@ void ModifiableAttributeInstance::removeModifiers() unordered_set<AttributeModifier *> removingModifiers; getModifiers(removingModifiers); - for (AUTO_VAR(it, removingModifiers.begin()); it != removingModifiers.end(); ++it) + for (auto& it : removingModifiers) { - removeModifier(*it); + removeModifier(it); } } @@ -159,25 +157,22 @@ double ModifiableAttributeInstance::calculateValue() unordered_set<AttributeModifier *> *modifiers; modifiers = getModifiers(AttributeModifier::OPERATION_ADDITION); - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& modifier : *modifiers) { - AttributeModifier *modifier = *it; base += modifier->getAmount(); } double result = base; modifiers = getModifiers(AttributeModifier::OPERATION_MULTIPLY_BASE); - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& modifier : *modifiers) { - AttributeModifier *modifier = *it; result += base * modifier->getAmount(); } - + modifiers = getModifiers(AttributeModifier::OPERATION_MULTIPLY_TOTAL); - for (AUTO_VAR(it, modifiers->begin()); it != modifiers->end(); ++it) + for (auto& modifier : *modifiers) { - AttributeModifier *modifier = *it; result *= 1 + modifier->getAmount(); } diff --git a/Minecraft.World/MonsterPlacerItem.cpp b/Minecraft.World/MonsterPlacerItem.cpp index a2970033..e5a84122 100644 --- a/Minecraft.World/MonsterPlacerItem.cpp +++ b/Minecraft.World/MonsterPlacerItem.cpp @@ -29,7 +29,7 @@ wstring MonsterPlacerItem::getHoverName(shared_ptr<ItemInstance> itemInstance) //elementName += " " + I18n.get("entity." + encodeId + ".name"); } else - { + { elementName = replaceAll(elementName,L"{*CREATURE*}",L""); } @@ -38,8 +38,8 @@ wstring MonsterPlacerItem::getHoverName(shared_ptr<ItemInstance> itemInstance) int MonsterPlacerItem::getColor(shared_ptr<ItemInstance> item, int spriteLayer) { - AUTO_VAR(it, EntityIO::idsSpawnableInCreative.find(item->getAuxValue())); - if (it != EntityIO::idsSpawnableInCreative.end()) + auto it = EntityIO::idsSpawnableInCreative.find(item->getAuxValue()); + if (it != EntityIO::idsSpawnableInCreative.end()) { EntityIO::SpawnableMobInfo *spawnableMobInfo = it->second; if (spriteLayer == 0) { @@ -193,7 +193,7 @@ bool MonsterPlacerItem::useOn(shared_ptr<ItemInstance> itemInstance, shared_ptr< x += Facing::STEP_X[face]; y += Facing::STEP_Y[face]; z += Facing::STEP_Z[face]; - + double yOff = 0; // 4J-PB - missing parentheses added if (face == Facing::UP && (tile == Tile::fence_Id || tile == Tile::netherFence_Id)) @@ -211,11 +211,11 @@ bool MonsterPlacerItem::useOn(shared_ptr<ItemInstance> itemInstance, shared_ptr< } if (spawned) - { + { if (!player->abilities.instabuild) { itemInstance->count--; - } + } } else { diff --git a/Minecraft.World/MoveThroughVillageGoal.cpp b/Minecraft.World/MoveThroughVillageGoal.cpp index d4cdde94..f112c109 100644 --- a/Minecraft.World/MoveThroughVillageGoal.cpp +++ b/Minecraft.World/MoveThroughVillageGoal.cpp @@ -87,10 +87,8 @@ shared_ptr<DoorInfo> MoveThroughVillageGoal::getNextDoorInfo(shared_ptr<Village> shared_ptr<DoorInfo> closest = nullptr; int closestDistSqr = Integer::MAX_VALUE; vector<shared_ptr<DoorInfo> > *doorInfos = village->getDoorInfos(); - //for (DoorInfo di : doorInfos) - for(AUTO_VAR(it, doorInfos->begin()); it != doorInfos->end(); ++it) + for(auto& di : *doorInfos) { - shared_ptr<DoorInfo> di = *it; int distSqr = di->distanceToSqr(Mth::floor(mob->x), Mth::floor(mob->y), Mth::floor(mob->z)); if (distSqr < closestDistSqr) { @@ -104,11 +102,10 @@ shared_ptr<DoorInfo> MoveThroughVillageGoal::getNextDoorInfo(shared_ptr<Village> bool MoveThroughVillageGoal::hasVisited(shared_ptr<DoorInfo>di) { - //for (DoorInfo di2 : visited) - for(AUTO_VAR(it, visited.begin()); it != visited.end(); ) - { + for (auto it = visited.begin(); it != visited.end();) + { shared_ptr<DoorInfo> di2 = (*it).lock(); - if( di2 == NULL ) + if( di2 ) { it = visited.erase(it); } diff --git a/Minecraft.World/NbtSlotFile.cpp b/Minecraft.World/NbtSlotFile.cpp index 81880cfb..8bae14c6 100644 --- a/Minecraft.World/NbtSlotFile.cpp +++ b/Minecraft.World/NbtSlotFile.cpp @@ -89,11 +89,8 @@ vector<CompoundTag *> *NbtSlotFile::readAll(int slot) vector<int> *fileSlots = fileSlotMap[slot]; int skipped = 0; - AUTO_VAR(itEnd, fileSlots->end()); - for (AUTO_VAR(it, fileSlots->begin()); it != itEnd; it++) + for (int c : *fileSlots) { - int c = *it; //fileSlots->at(i); - int pos = 0; int continuesAt = -1; int expectedSlot = slot + 1; @@ -115,8 +112,6 @@ vector<CompoundTag *> *NbtSlotFile::readAll(int slot) goto fileSlotLoop; // 4J - used to be continue fileSlotLoop, with for loop labelled as fileSlotLoop } -// if (oldSlot != expectedSlot) throw new IOException("Wrong slot! Got " + oldSlot + ", expected " + expectedSlot); // 4J - TODO - ReadFile(raf,READ_BUFFER.data + pos,size,&numberOfBytesRead,NULL); if (continuesAt >= 0) @@ -144,12 +139,12 @@ int NbtSlotFile::getFreeSlot() // fileSlot = toReplace->back(); // toReplace->pop_back(); // } else - + if (freeFileSlots.size() > 0) { fileSlot = freeFileSlots.back(); freeFileSlots.pop_back(); - } + } else { fileSlot = totalFileSlots++; @@ -164,11 +159,9 @@ void NbtSlotFile::replaceSlot(int slot, vector<CompoundTag *> *tags) DWORD numberOfBytesWritten; toReplace = fileSlotMap[slot]; fileSlotMap[slot] = new vector<int>(); - - AUTO_VAR(itEndTags, tags->end()); - for (AUTO_VAR(it, tags->begin()); it != itEndTags; it++) + + for (auto tag : *tags) { - CompoundTag *tag = *it; //tags->at(i); byteArray compressed = NbtIo::compress(tag); if (compressed.length > largest) { @@ -227,12 +220,9 @@ void NbtSlotFile::replaceSlot(int slot, vector<CompoundTag *> *tags) } delete[] compressed.data; } - - AUTO_VAR(itEndToRep, toReplace->end()); - for (AUTO_VAR(it, toReplace->begin()); it != itEndToRep; it++) - { - int c = *it; //toReplace->at(i); + for (int c : *toReplace) + { freeFileSlots.push_back(c); seekSlotHeader(c); diff --git a/Minecraft.World/NetherBridgeFeature.cpp b/Minecraft.World/NetherBridgeFeature.cpp index 2cf883c4..d661d3b7 100644 --- a/Minecraft.World/NetherBridgeFeature.cpp +++ b/Minecraft.World/NetherBridgeFeature.cpp @@ -13,7 +13,7 @@ NetherBridgeFeature::NetherBridgeFeature() : StructureFeature() bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_BLAZE, 10, 2, 3)); bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_PIGZOMBIE, 5, 4, 4)); bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_SKELETON, 10, 4, 4)); - bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_LAVASLIME, 3, 4, 4)); + bridgeEnemies.push_back(new Biome::MobSpawnerData(eTYPE_LAVASLIME, 3, 4, 4)); isSpotSelected=false; netherFortressPos = NULL; @@ -38,7 +38,7 @@ bool NetherBridgeFeature::isFeatureChunk(int x, int z, bool bIsSuperflat) { // 4J Stu - New implementation to force a nether fortress if (!isSpotSelected) - { + { // Set the random random->setSeed(level->getSeed()); random->nextInt(); @@ -119,8 +119,8 @@ NetherBridgeFeature::NetherBridgeStart::NetherBridgeStart(Level *level, Random * while (!pendingChildren->empty()) { int pos = random->nextInt((int)pendingChildren->size()); - AUTO_VAR(it, pendingChildren->begin() + pos); - StructurePiece *structurePiece = *it; + auto it = pendingChildren->begin() + pos; + StructurePiece *structurePiece = *it; pendingChildren->erase(it); structurePiece->addChildren(start, &pieces, random); } diff --git a/Minecraft.World/NetherBridgePieces.cpp b/Minecraft.World/NetherBridgePieces.cpp index ff158fba..35baa71a 100644 --- a/Minecraft.World/NetherBridgePieces.cpp +++ b/Minecraft.World/NetherBridgePieces.cpp @@ -65,7 +65,7 @@ NetherBridgePieces::PieceWeight *NetherBridgePieces::bridgePieceWeights[NetherBr new PieceWeight(EPieceClass_StairsRoom, 10, 3), }; -NetherBridgePieces::PieceWeight *NetherBridgePieces::castlePieceWeights[NetherBridgePieces::CASTLE_PIECEWEIGHTS_COUNT] = +NetherBridgePieces::PieceWeight *NetherBridgePieces::castlePieceWeights[NetherBridgePieces::CASTLE_PIECEWEIGHTS_COUNT] = { new PieceWeight(EPieceClass_CastleStalkRoom, 30, 2), // 4J Stu - Increased weight to ensure that we have these (was 5), required for Nether Wart, and therefore required for brewing new PieceWeight(EPieceClass_CastleSmallCorridorPiece, 25, 0, true), @@ -171,10 +171,8 @@ int NetherBridgePieces::NetherBridgePiece::updatePieceWeight(list<PieceWeight *> { bool hasAnyPieces = false; int totalWeight = 0; - for( AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); it++ ) + for(auto& piece : *currentPieces) { - PieceWeight *piece = *it; - if (piece->maxPlaceCount > 0 && piece->placeCount < piece->maxPlaceCount) { hasAnyPieces = true; @@ -195,9 +193,8 @@ NetherBridgePieces::NetherBridgePiece *NetherBridgePieces::NetherBridgePiece::ge numAttempts++; int weightSelection = random->nextInt(totalWeight); - for( AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); it++ ) - { - PieceWeight *piece = *it; + for ( PieceWeight *piece : *currentPieces ) + { weightSelection -= piece->weight; if (weightSelection < 0) { @@ -378,7 +375,7 @@ NetherBridgePieces::BridgeStraight *NetherBridgePieces::BridgeStraight::createPi { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -444,7 +441,7 @@ NetherBridgePieces::BridgeEndFiller *NetherBridgePieces::BridgeEndFiller::create { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -552,7 +549,7 @@ NetherBridgePieces::BridgeCrossing *NetherBridgePieces::BridgeCrossing::createPi { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -8, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -671,7 +668,7 @@ NetherBridgePieces::RoomCrossing *NetherBridgePieces::RoomCrossing::createPiece( { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -741,7 +738,7 @@ NetherBridgePieces::StairsRoom *NetherBridgePieces::StairsRoom::createPiece(list { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -815,7 +812,7 @@ NetherBridgePieces::MonsterThrone *NetherBridgePieces::MonsterThrone::createPiec { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -2, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -911,7 +908,7 @@ NetherBridgePieces::CastleEntrance *NetherBridgePieces::CastleEntrance::createPi { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -5, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1041,7 +1038,7 @@ NetherBridgePieces::CastleStalkRoom *NetherBridgePieces::CastleStalkRoom::create { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -5, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1207,7 +1204,7 @@ NetherBridgePieces::CastleSmallCorridorPiece *NetherBridgePieces::CastleSmallCor BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1271,7 +1268,7 @@ NetherBridgePieces::CastleSmallCorridorCrossingPiece *NetherBridgePieces::Castle { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1347,7 +1344,7 @@ NetherBridgePieces::CastleSmallCorridorRightTurnPiece *NetherBridgePieces::Castl { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1439,7 +1436,7 @@ NetherBridgePieces::CastleSmallCorridorLeftTurnPiece *NetherBridgePieces::Castle { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1515,7 +1512,7 @@ NetherBridgePieces::CastleCorridorStairsPiece *NetherBridgePieces::CastleCorrido { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -7, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1597,7 +1594,7 @@ NetherBridgePieces::CastleCorridorTBalconyPiece *NetherBridgePieces::CastleCorri { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -3, 0, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((NetherBridgePieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) diff --git a/Minecraft.World/NetherWartTile.cpp b/Minecraft.World/NetherWartTile.cpp index 1faa57ca..add3eccf 100644 --- a/Minecraft.World/NetherWartTile.cpp +++ b/Minecraft.World/NetherWartTile.cpp @@ -107,6 +107,6 @@ void NetherWartTile::registerIcons(IconRegister *iconRegister) { for (int i = 0; i < NETHER_STALK_TEXTURE_COUNT; i++) { - icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + _toString<int>(i) ); + icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + std::to_wstring(i) ); } } diff --git a/Minecraft.World/Node.cpp b/Minecraft.World/Node.cpp index 5f501a84..7059c045 100644 --- a/Minecraft.World/Node.cpp +++ b/Minecraft.World/Node.cpp @@ -28,12 +28,12 @@ hash(createHash(x, y, z)) //hash = createHash(x, y, z); } -int Node::createHash(const int x, const int y, const int z) +int Node::createHash(const int x, const int y, const int z) { return (y & 0xff) | ((x & 0x7fff) << 8) | ((z & 0x7fff) << 24) | ((x < 0) ? 0x0080000000 : 0) | ((z < 0) ? 0x0000008000 : 0); } -float Node::distanceTo(Node *to) +float Node::distanceTo(Node *to) { float xd = (float) ( to->x - x ); float yd = (float) ( to->y - y ); @@ -49,27 +49,27 @@ float Node::distanceToSqr(Node *to) return xd * xd + yd * yd + zd * zd; } -bool Node::equals(Node *o) +bool Node::equals(Node *o) { //4J Jev, never used anything other than a node. - //if (dynamic_cast<Node *>((Node *) o) != NULL) + //if (dynamic_cast<Node *>((Node *) o) != NULL) //{ return hash == o->hash && x == o->x && y == o->y && z == o->z; //} //return false; } -int Node::hashCode() +int Node::hashCode() { return hash; } -bool Node::inOpenSet() +bool Node::inOpenSet() { return heapIdx >= 0; } -wstring Node::toString() +wstring Node::toString() { - return _toString<int>(x) + L", " + _toString<int>(y) + L", " + _toString<int>(z); + return std::to_wstring(x) + L", " + std::to_wstring(y) + L", " + std::to_wstring(z); }
\ No newline at end of file diff --git a/Minecraft.World/NotGateTile.cpp b/Minecraft.World/NotGateTile.cpp index 464e0ca5..3aa9aee1 100644 --- a/Minecraft.World/NotGateTile.cpp +++ b/Minecraft.World/NotGateTile.cpp @@ -28,10 +28,9 @@ bool NotGateTile::isToggledTooFrequently(Level *level, int x, int y, int z, bool if (add) recentToggles[level]->push_back(Toggle(x, y, z, level->getGameTime())); int count = 0; - AUTO_VAR(itEnd, recentToggles[level]->end()); - for (AUTO_VAR(it, recentToggles[level]->begin()); it != itEnd; it++) + for (const auto& it : *recentToggles[level]) { - if (it->x == x && it->y == y && it->z == z) + if (it.x == x && it.y == y && it.z == z) { count++; if (count >= MAX_RECENT_TOGGLES) @@ -122,7 +121,7 @@ void NotGateTile::tick(Level *level, int x, int y, int z, Random *random) } } - if (on) + if (on) { if (neighborSignal) { @@ -153,7 +152,7 @@ void NotGateTile::tick(Level *level, int x, int y, int z, Random *random) level->setTileAndData(x, y, z, Tile::redstoneTorch_on_Id, level->getData(x, y, z), Tile::UPDATE_ALL); } else - { + { app.DebugPrintf("Torch at (%d,%d,%d) has toggled too many times\n",x,y,z); } } @@ -236,9 +235,9 @@ void NotGateTile::levelTimeChanged(Level *level, __int64 delta, __int64 newTime) if (toggles != NULL) { - for (AUTO_VAR(it,toggles->begin()); it != toggles->end(); ++it) + for (auto& toggle : *toggles) { - (*it).when += delta; + toggle.when += delta; } } } diff --git a/Minecraft.World/OldChunkStorage.cpp b/Minecraft.World/OldChunkStorage.cpp index 31f4394f..24263d0d 100644 --- a/Minecraft.World/OldChunkStorage.cpp +++ b/Minecraft.World/OldChunkStorage.cpp @@ -103,7 +103,7 @@ File OldChunkStorage::getFile(int x, int z) file = File( file, wstring( name ) ); if ( !file.exists() ) { - if (!create) + if (!create) { return File(L""); } @@ -163,7 +163,7 @@ void OldChunkStorage::save(Level *level, LevelChunk *levelChunk) { LevelData *levelData = level->getLevelData(); levelData->setSizeOnDisk( levelData->getSizeOnDisk() - file.length() ); - } + } // 4J - removed try/catch // try { @@ -202,7 +202,7 @@ bool OldChunkStorage::saveEntities(LevelChunk *lc, Level *level, CompoundTag *ta lc->lastSaveHadEntities = false; ListTag<CompoundTag> *entityTags = new ListTag<CompoundTag>(); - + #ifdef _ENTITIES_RW_SECTION EnterCriticalRWSection(&lc->m_csEntities, true); #else @@ -210,17 +210,14 @@ bool OldChunkStorage::saveEntities(LevelChunk *lc, Level *level, CompoundTag *ta #endif for (int i = 0; i < lc->ENTITY_BLOCKS_LENGTH; i++) { - AUTO_VAR(itEnd, lc->entityBlocks[i]->end()); - for( vector<shared_ptr<Entity> >::iterator it = lc->entityBlocks[i]->begin(); it != itEnd; it++ ) + for( auto& e : *lc->entityBlocks[i] ) { - shared_ptr<Entity> e = *it; lc->lastSaveHadEntities = true; CompoundTag *teTag = new CompoundTag(); - if (e->save(teTag)) + if ( e && e->save(teTag)) { entityTags->add(teTag); } - } } #ifdef _ENTITIES_RW_SECTION @@ -264,15 +261,13 @@ void OldChunkStorage::save(LevelChunk *lc, Level *level, DataOutputStream *dos) #ifndef SPLIT_SAVES saveEntities(lc, level, tag); #endif - + PIXBeginNamedEvent(0,"Saving tile entities"); ListTag<CompoundTag> *tileEntityTags = new ListTag<CompoundTag>(); - AUTO_VAR(itEnd, lc->tileEntities.end()); - for( unordered_map<TilePos, shared_ptr<TileEntity>, TilePosKeyHash, TilePosKeyEq>::iterator it = lc->tileEntities.begin(); - it != itEnd; it++) + for(auto& it : lc->tileEntities) { - shared_ptr<TileEntity> te = it->second; + shared_ptr<TileEntity> te = it.second; CompoundTag *teTag = new CompoundTag(); te->save(teTag); tileEntityTags->add(teTag); @@ -358,11 +353,9 @@ void OldChunkStorage::save(LevelChunk *lc, Level *level, CompoundTag *tag) PIXBeginNamedEvent(0,"Saving tile entities"); ListTag<CompoundTag> *tileEntityTags = new ListTag<CompoundTag>(); - AUTO_VAR(itEnd, lc->tileEntities.end()); - for( unordered_map<TilePos, shared_ptr<TileEntity>, TilePosKeyHash, TilePosKeyEq>::iterator it = lc->tileEntities.begin(); - it != itEnd; it++) + for(auto& it : lc->tileEntities) { - shared_ptr<TileEntity> te = it->second; + shared_ptr<TileEntity> te = it.second; CompoundTag *teTag = new CompoundTag(); te->save(teTag); tileEntityTags->add(teTag); @@ -451,7 +444,7 @@ LevelChunk *OldChunkStorage::load(Level *level, DataInputStream *dis) dis->readFully(levelChunk->heightmap); - levelChunk->terrainPopulated = dis->readShort(); + levelChunk->terrainPopulated = dis->readShort(); // If all neighbours have been post-processed, then we should have done the post-post-processing now. Check that this is set as if it isn't then we won't be able // to send network data for chunks, and we won't ever try and set it again as all the directional flags are now already set - should only be an issue for old maps // before this flag was added. @@ -537,13 +530,13 @@ LevelChunk *OldChunkStorage::load(Level *level, CompoundTag *tag) if( tag->get(L"TerrainPopulated") ) { // Java bool type or byte bitfield - levelChunk->terrainPopulated = tag->getByte(L"TerrainPopulated"); + levelChunk->terrainPopulated = tag->getByte(L"TerrainPopulated"); if( levelChunk->terrainPopulated >= 1 ) levelChunk->terrainPopulated = LevelChunk::sTerrainPopulatedAllNeighbours | LevelChunk::sTerrainPostPostProcessed; // Convert from old bool type to new bitfield } else { // New style short - levelChunk->terrainPopulated = tag->getShort(L"TerrainPopulatedFlags"); + levelChunk->terrainPopulated = tag->getShort(L"TerrainPopulatedFlags"); // If all neighbours have been post-processed, then we should have done the post-post-processing now. Check that this is set as if it isn't then we won't be able // to send network data for chunks, and we won't ever try and set it again as all the directional flags are now already set - should only be an issue for old maps // before this flag was added. diff --git a/Minecraft.World/Packet.cpp b/Minecraft.World/Packet.cpp index f1630db5..a37cb2ad 100644 --- a/Minecraft.World/Packet.cpp +++ b/Minecraft.World/Packet.cpp @@ -30,7 +30,7 @@ void Packet::staticCtor() map(8, true, false, true, true, typeid(SetHealthPacket), SetHealthPacket::create); map(9, true, true, true, false, typeid(RespawnPacket), RespawnPacket::create); - map(10, true, true, true, false, typeid(MovePlayerPacket), MovePlayerPacket::create); + map(10, true, true, true, false, typeid(MovePlayerPacket), MovePlayerPacket::create); map(11, true, true, true, true, typeid(MovePlayerPacket::Pos), MovePlayerPacket::Pos::create); map(12, true, true, true, true, typeid(MovePlayerPacket::Rot), MovePlayerPacket::Rot::create); map(13, true, true, true, true, typeid(MovePlayerPacket::PosRot), MovePlayerPacket::PosRot::create); @@ -182,7 +182,7 @@ int Packet::renderPos = 0; void Packet::map(int id, bool receiveOnClient, bool receiveOnServer, bool sendToAnyClient, bool renderStats, const type_info& clazz, packetCreateFn createFn) { #if 0 - if (idToClassMap.count(id) > 0) throw new IllegalArgumentException(wstring(L"Duplicate packet id:") + _toString<int>(id)); + if (idToClassMap.count(id) > 0) throw new IllegalArgumentException(wstring(L"Duplicate packet id:") + std::to_wstring(id)); if (classToIdMap.count(clazz) > 0) throw new IllegalArgumentException(L"Duplicate packet class:"); // TODO + clazz); #endif @@ -228,7 +228,7 @@ void Packet::recordOutgoingPacket(shared_ptr<Packet> packet, int playerIndex) idx = 100; } #endif - AUTO_VAR(it, outgoingStatistics.find(idx)); + auto it = outgoingStatistics.find(idx); if( it == outgoingStatistics.end() ) { @@ -248,8 +248,8 @@ void Packet::updatePacketStatsPIX() { #ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - - for( AUTO_VAR(it, outgoingStatistics.begin()); it != outgoingStatistics.end(); it++ ) + + for( auto it = outgoingStatistics.begin(); it != outgoingStatistics.end(); it++ ) { Packet::PacketStatistics *stat = it->second; __int64 count = stat->getRunningCount(); @@ -265,7 +265,7 @@ void Packet::updatePacketStatsPIX() #endif } -shared_ptr<Packet> Packet::getPacket(int id) +shared_ptr<Packet> Packet::getPacket(int id) { // 4J: Removed try/catch return idToCreateMap[id](); @@ -332,16 +332,16 @@ shared_ptr<Packet> Packet::readPacket(DataInputStream *dis, bool isServer) // th //app.DebugPrintf("Bad packet id %d\n", id); __debugbreak(); assert(false); - // throw new IOException(wstring(L"Bad packet id ") + _toString<int>(id)); + // throw new IOException(wstring(L"Bad packet id ") + std::to_wstring(id)); } packet = getPacket(id); - if (packet == NULL) assert(false);//throw new IOException(wstring(L"Bad packet id ") + _toString<int>(id)); - + if (packet == NULL) assert(false);//throw new IOException(wstring(L"Bad packet id ") + std::to_wstring(id)); + //app.DebugPrintf("%s reading packet %d\n", isServer ? "Server" : "Client", packet->getId()); packet->read(dis); // } - // catch (EOFException e) + // catch (EOFException e) // { // // reached end of stream // OutputDebugString("Reached end of stream"); @@ -352,7 +352,7 @@ shared_ptr<Packet> Packet::readPacket(DataInputStream *dis, bool isServer) // th // 4J Stu - This changes a bit in 1.0.1, but we don't really use it so stick with what we have #ifndef _CONTENT_PACKAGE #if PACKET_ENABLE_STAT_TRACKING - AUTO_VAR(it, statistics.find(id)); + auto it = statistics.find(id); if( it == statistics.end() ) { @@ -380,7 +380,7 @@ void Packet::writePacket(shared_ptr<Packet> packet, DataOutputStream *dos) // th void Packet::writeUtf(const wstring& value, DataOutputStream *dos) // throws IOException TODO 4J JEV, should this declare a throws? { #if 0 - if (value.length() > Short::MAX_VALUE) + if (value.length() > Short::MAX_VALUE) { throw new IOException(L"String too big"); } @@ -408,7 +408,7 @@ wstring Packet::readUtf(DataInputStream *dis, int maxLength) // throws IOExcepti } wstring builder = L""; - for (int i = 0; i < stringLength; i++) + for (int i = 0; i < stringLength; i++) { wchar_t rc = dis->readChar(); builder.push_back( rc ); @@ -432,7 +432,7 @@ void Packet::PacketStatistics::addPacket(int bytes) count++; } -int Packet::PacketStatistics::getCount() +int Packet::PacketStatistics::getCount() { return count; } @@ -446,7 +446,7 @@ double Packet::PacketStatistics::getAverageSize() return (double) totalSize / count; } -int Packet::PacketStatistics::getTotalSize() +int Packet::PacketStatistics::getTotalSize() { return totalSize; } diff --git a/Minecraft.World/PathFinder.cpp b/Minecraft.World/PathFinder.cpp index 029cf582..2e11648f 100644 --- a/Minecraft.World/PathFinder.cpp +++ b/Minecraft.World/PathFinder.cpp @@ -26,14 +26,13 @@ PathFinder::~PathFinder() // references to the same things, so just need to destroy their containers delete [] neighbors->data; delete neighbors; - AUTO_VAR(itEnd, nodes.end()); - for( AUTO_VAR(it, nodes.begin()); it != itEnd; it++ ) + for(auto& node : nodes) { - delete it->second; + delete node.second; } } -Path *PathFinder::findPath(Entity *from, Entity *to, float maxDist) +Path *PathFinder::findPath(Entity *from, Entity *to, float maxDist) { return findPath(from, to->x, to->bb->y0, to->z, maxDist); } @@ -187,9 +186,9 @@ Node *PathFinder::getNode(Entity *entity, int x, int y, int z, Node *size, int j /*final*/ Node *PathFinder::getNode(int x, int y, int z) { int i = Node::createHash(x, y, z); - Node *node; - AUTO_VAR(it, nodes.find(i)); - if ( it == nodes.end() ) + Node *node = nullptr; + auto it = nodes.find(i); + if ( it == nodes.end() ) { MemSect(54); node = new Node(x, y, z); @@ -279,7 +278,7 @@ Path *PathFinder::reconstruct_path(Node *from, Node *to) NodeArray nodes = NodeArray(count); n = to; nodes.data[--count] = n; - while (n->cameFrom != NULL) + while (n->cameFrom != NULL) { n = n->cameFrom; nodes.data[--count] = n; diff --git a/Minecraft.World/PigZombie.cpp b/Minecraft.World/PigZombie.cpp index 7a736c9a..c284c323 100644 --- a/Minecraft.World/PigZombie.cpp +++ b/Minecraft.World/PigZombie.cpp @@ -70,7 +70,7 @@ void PigZombie::tick() Zombie::tick(); } -bool PigZombie::canSpawn() +bool PigZombie::canSpawn() { return level->difficulty > Difficulty::PEACEFUL && level->isUnobstructed(bb) && level->getCubes(shared_from_this(), bb)->empty() && !level->containsAnyLiquid(bb); } @@ -107,11 +107,9 @@ bool PigZombie::hurt(DamageSource *source, float dmg) shared_ptr<Entity> sourceEntity = source->getEntity(); if ( sourceEntity != NULL && sourceEntity->instanceof(eTYPE_PLAYER) ) { - vector<shared_ptr<Entity> > *nearby = level->getEntities( shared_from_this(), bb->grow(32, 32, 32)); - AUTO_VAR(itEnd, nearby->end()); - for (AUTO_VAR(it, nearby->begin()); it != itEnd; it++) + vector<shared_ptr<Entity> > *nearby = level->getEntities( shared_from_this(), bb->grow(32, 32, 32)); + for (auto& e : *nearby) { - shared_ptr<Entity> e = *it; //nearby->at(i); if ( e->instanceof(eTYPE_PIGZOMBIE) ) { shared_ptr<PigZombie> pigZombie = dynamic_pointer_cast<PigZombie>(e); diff --git a/Minecraft.World/PistonPieceEntity.cpp b/Minecraft.World/PistonPieceEntity.cpp index 0d0a86d0..a915c2ff 100644 --- a/Minecraft.World/PistonPieceEntity.cpp +++ b/Minecraft.World/PistonPieceEntity.cpp @@ -123,14 +123,14 @@ void PistonPieceEntity::moveCollidedEntities(float progress, float amount) if (!entities->empty()) { vector< shared_ptr<Entity> > collisionHolder; - for( AUTO_VAR(it, entities->begin()); it != entities->end(); it++ ) + for(auto& it : *entities) { - collisionHolder.push_back(*it); + collisionHolder.push_back(it); } - for( AUTO_VAR(it, collisionHolder.begin()); it != collisionHolder.end(); it++ ) + for(auto& it : collisionHolder) { - (*it)->move(amount * Facing::STEP_X[facing], + it->move(amount * Facing::STEP_X[facing], amount * Facing::STEP_Y[facing], amount * Facing::STEP_Z[facing]); } diff --git a/Minecraft.World/PlayGoal.cpp b/Minecraft.World/PlayGoal.cpp index a3760862..72ee69d4 100644 --- a/Minecraft.World/PlayGoal.cpp +++ b/Minecraft.World/PlayGoal.cpp @@ -27,10 +27,8 @@ bool PlayGoal::canUse() vector<shared_ptr<Entity> > *children = mob->level->getEntitiesOfClass(typeid(Villager), mob->bb->grow(6, 3, 6)); double closestDistSqr = Double::MAX_VALUE; - //for (Entity c : children) - for(AUTO_VAR(it, children->begin()); it != children->end(); ++it) + for(auto& c : *children) { - shared_ptr<Entity> c = *it; if (c.get() == mob) continue; shared_ptr<Villager> friendV = dynamic_pointer_cast<Villager>(c); if (friendV->isChasing()) continue; diff --git a/Minecraft.World/Player.cpp b/Minecraft.World/Player.cpp index e0fa26ad..bd6b68a8 100644 --- a/Minecraft.World/Player.cpp +++ b/Minecraft.World/Player.cpp @@ -2,7 +2,7 @@ // All the instanceof s from Java have been converted to dynamic_cast in this file // Once all the classes are finished it may be that we do not need to use dynamic_cast -// for every test and a simple virtual function should suffice. We probably only need +// for every test and a simple virtual function should suffice. We probably only need // dynamic_cast to find one of the classes that an object derives from, and not to find // the derived class itself (which should own the virtual GetType function) @@ -348,7 +348,7 @@ void Player::tick() zCloak += zca * 0.25; yCloak += yca * 0.25; - if (riding == NULL) + if (riding == NULL) { if( minecartAchievementPos != NULL ) { @@ -458,7 +458,7 @@ void Player::tick() // minecart. For some reason some of the torches come off so it will also need some fixing along the way. static bool madeTrack = false; if( !madeTrack ) - { + { this->drop( shared_ptr<ItemInstance>( new ItemInstance( Item::minecart, 1 ) ) ); this->drop( shared_ptr<ItemInstance>( new ItemInstance( Tile::goldenRail, 10 ) ) ); this->drop( shared_ptr<ItemInstance>( new ItemInstance( Tile::lever, 10 ) ) ); @@ -631,8 +631,8 @@ void Player::ride(shared_ptr<Entity> e) LivingEntity::ride(e); } -void Player::setPlayerDefaultSkin(EDefaultSkins skin) -{ +void Player::setPlayerDefaultSkin(EDefaultSkins skin) +{ #ifndef _CONTENT_PACKAGE wprintf(L"Setting default skin to %d for player %ls\n", skin, name.c_str() ); #endif @@ -651,8 +651,8 @@ void Player::setCustomSkin(DWORD skinId) setAnimOverrideBitmask(getSkinAnimOverrideBitmask(skinId)); if( !GET_IS_DLC_SKIN_FROM_BITMASK(skinId) ) - { - // GET_UGC_SKIN_ID_FROM_BITMASK will always be zero - this was for a possible custom skin editor skin + { + // GET_UGC_SKIN_ID_FROM_BITMASK will always be zero - this was for a possible custom skin editor skin DWORD ugcSkinIndex = GET_UGC_SKIN_ID_FROM_BITMASK(skinId); DWORD defaultSkinIndex = GET_DEFAULT_SKIN_ID_FROM_BITMASK(skinId); if( ugcSkinIndex == 0 && defaultSkinIndex > 0 ) @@ -722,7 +722,7 @@ unsigned int Player::getSkinAnimOverrideBitmask(DWORD skinId) { unsigned long bitmask = 0L; if( GET_IS_DLC_SKIN_FROM_BITMASK(skinId) ) - { + { // Temp check for anim override switch( GET_DLC_SKIN_ID_FROM_BITMASK(skinId) ) { @@ -785,7 +785,7 @@ void Player::setCustomCape(DWORD capeId) else { MOJANG_DATA *pMojangData=app.GetMojangDataForXuid(getOnlineXuid()); - if(pMojangData) + if(pMojangData) { // Cape if(pMojangData->wchCape) @@ -822,7 +822,7 @@ void Player::setCustomCape(DWORD capeId) DWORD Player::getCapeIdFromPath(const wstring &cape) { - bool dlcCape = false; + bool dlcCape = false; unsigned int capeId = 0; if(cape.size() >= 14) @@ -886,7 +886,7 @@ void Player::ChangePlayerSkin() this->customTextureUrl=L""; } else - { + { if(m_uiPlayerCurrentSkin>0) { // change this players custom texture url @@ -900,7 +900,7 @@ void Player::prepareCustomTextures() { MOJANG_DATA *pMojangData=app.GetMojangDataForXuid(getOnlineXuid()); - if(pMojangData) + if(pMojangData) { // Skin if(pMojangData->wchSkin) @@ -1054,11 +1054,9 @@ void Player::aiStep() vector<shared_ptr<Entity> > *entities = level->getEntities(shared_from_this(), pickupArea); if (entities != NULL) { - AUTO_VAR(itEnd, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEnd; it++) + for (auto& e : *entities) { - shared_ptr<Entity> e = *it; //entities->at(i); - if (!e->removed) + if ( e && !e->removed) { touch(e); } @@ -1135,11 +1133,14 @@ void Player::awardKillScore(shared_ptr<Entity> victim, int awardPoints) if(objectives) { - for (AUTO_VAR(it,objectives->begin()); it != objectives->end(); ++it) + for (auto& objective : *objectives) { - Objective *objective = *it; - Score *score = getScoreboard()->getPlayerScore(getAName(), objective); - score->increment(); + if ( objective ) + { + Score *score = getScoreboard()->getPlayerScore(getAName(), objective); + if ( score ) + score->increment(); + } } } } @@ -1546,7 +1547,7 @@ bool Player::interact(shared_ptr<Entity> entity) } if ( (item != NULL) && entity->instanceof(eTYPE_LIVINGENTITY) ) - { + { // 4J - PC Comments // Hack to prevent item stacks from decrementing if the player has // the ability to instabuild @@ -1597,7 +1598,7 @@ void Player::attack(shared_ptr<Entity> entity) int knockback = 0; float magicBoost = 0; - + if ( entity->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr<Player> thisPlayer = dynamic_pointer_cast<Player>(shared_from_this()); @@ -1657,7 +1658,7 @@ void Player::attack(shared_ptr<Entity> entity) } setLastHurtMob(entity); - + if ( entity->instanceof(eTYPE_LIVINGENTITY) ) { shared_ptr<LivingEntity> mob = dynamic_pointer_cast<LivingEntity>(entity); @@ -1800,11 +1801,11 @@ Player::BedSleepingResult Player::startSleepInBed(int x, int y, int z, bool bTes } // This causes a message to be displayed, so we do want to show the tooltip in test mode - if (!bTestUse && level->isDay()) + if (!bTestUse && level->isDay()) { // may not sleep during day return NOT_POSSIBLE_NOW; - } + } } if(bTestUse) @@ -1889,7 +1890,7 @@ void Player::setBedOffset(int bedDirection) /** -* +* * @param forcefulWakeUp * If the player has been forced to wake up. When this happens, * the client will skip the wake-up animation. For example, when @@ -2193,7 +2194,7 @@ void Player::checkMovementStatistiscs(double dx, double dy, double dz) void Player::checkRidingStatistiscs(double dx, double dy, double dz) -{ +{ if (riding != NULL) { int distance = (int) Math::round(sqrt(dx * dx + dy * dy + dz * dz) * 100.0f); @@ -2215,7 +2216,7 @@ void Player::checkRidingStatistiscs(double dx, double dy, double dz) minecartAchievementPos = new Pos(Mth::floor(x), Mth::floor(y), Mth::floor(z)); } // 4J-PB - changed this because our world isn't big enough to go 1000m - else + else { // 4-JEV, changed slightly to add extra parameters for event on durango. int dist = minecartAchievementPos->dist(Mth::floor(x), Mth::floor(y), Mth::floor(z)); @@ -2242,7 +2243,7 @@ void Player::checkRidingStatistiscs(double dx, double dy, double dz) awardStat(GenericStats::onARail(), GenericStats::param_onARail(dist)); m_bAwardedOnARail=true; } -#endif +#endif } } @@ -2304,13 +2305,13 @@ void Player::killed(shared_ptr<LivingEntity> mob) case eTYPE_SKELETON: if( mob->isRiding() && mob->riding->GetType() == eTYPE_SPIDER ) awardStat(GenericStats::killsSpiderJockey(), GenericStats::param_noArgs()); - else + else awardStat(GenericStats::killsSkeleton(), GenericStats::param_noArgs()); break; case eTYPE_SPIDER: if( mob->rider.lock() != NULL && mob->rider.lock()->GetType() == eTYPE_SKELETON ) awardStat(GenericStats::killsSpiderJockey(), GenericStats::param_noArgs()); - else + else awardStat(GenericStats::killsSpider(), GenericStats::param_noArgs()); break; case eTYPE_ZOMBIE: @@ -2432,7 +2433,7 @@ int Player::getXpNeededForNextLevel() /** * This method adds on to the player's exhaustion, which may decrease the * player's food level. -* +* * @param amount * Amount of exhaustion to add, between 0 and 20 (setting it to * 20 will guarantee that at least 1, and at most 4, food points @@ -2769,7 +2770,7 @@ void Player::setPlayerGamePrivilege(unsigned int &uiGamePrivileges, EPlayerGameP } } else if (privilege < ePlayerGamePrivilege_MAX ) - { + { if(value!=0) { uiGamePrivileges|=(1<<privilege); @@ -3073,7 +3074,7 @@ void Player::enableAllPlayerPrivileges(unsigned int &uigamePrivileges, bool enab } void Player::enableAllPlayerPrivileges(bool enable) -{ +{ Player::enableAllPlayerPrivileges(m_uiGamePrivileges,enable); } @@ -3082,8 +3083,8 @@ bool Player::canCreateParticles() return !hasInvisiblePrivilege(); } -vector<ModelPart *> *Player::GetAdditionalModelParts() -{ +vector<ModelPart *> *Player::GetAdditionalModelParts() +{ if(m_ppAdditionalModelParts==NULL && !m_bCheckedForModelParts) { bool hasCustomTexture = !customTextureUrl.empty(); @@ -3127,8 +3128,8 @@ vector<ModelPart *> *Player::GetAdditionalModelParts() return m_ppAdditionalModelParts; } -void Player::SetAdditionalModelParts(vector<ModelPart *> *ppAdditionalModelParts) -{ +void Player::SetAdditionalModelParts(vector<ModelPart *> *ppAdditionalModelParts) +{ m_ppAdditionalModelParts=ppAdditionalModelParts; } @@ -3139,7 +3140,7 @@ Player::ePlayerNameValidState Player::GetPlayerNameValidState(void) return m_ePlayerNameValidState; } -void Player::SetPlayerNameValidState(bool bState) +void Player::SetPlayerNameValidState(bool bState) { if(bState) { diff --git a/Minecraft.World/PortalForcer.cpp b/Minecraft.World/PortalForcer.cpp index 8880399e..b3850807 100644 --- a/Minecraft.World/PortalForcer.cpp +++ b/Minecraft.World/PortalForcer.cpp @@ -19,9 +19,9 @@ PortalForcer::PortalForcer(ServerLevel *level) PortalForcer::~PortalForcer() { - for(AUTO_VAR(it,cachedPortals.begin()); it != cachedPortals.end(); ++it) + for(auto& it : cachedPortals) { - delete it->second; + delete it.second; } } @@ -96,8 +96,8 @@ bool PortalForcer::findPortal(shared_ptr<Entity> e, double xOriginal, double yOr long hash = ChunkPos::hashCode(xc, zc); bool updateCache = true; - AUTO_VAR(it, cachedPortals.find(hash)); - if (it != cachedPortals.end()) + auto it = cachedPortals.find(hash); + if (it != cachedPortals.end()) { PortalPosition *pos = it->second; @@ -271,7 +271,7 @@ bool PortalForcer::createPortal(shared_ptr<Entity> e) int XZSIZE = level->dimension->getXZSize() * 16; // XZSize is chunks, convert to blocks int XZOFFSET = (XZSIZE / 2) - 4; // Subtract 4 to stay away from the edges // TODO Make the 4 a constant in HellRandomLevelSource - // Move the positions that we want to check away from the edge of the world + // Move the positions that we want to check away from the edge of the world if( (xc - r) < -XZOFFSET ) { app.DebugPrintf("Adjusting portal creation x due to being too close to the edge\n"); @@ -339,7 +339,7 @@ bool PortalForcer::createPortal(shared_ptr<Entity> e) int yt = y + h; int zt = z + (s - 1) * za - b * xa; - // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock + // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock if( ( xt < -XZOFFSET ) || ( xt >= XZOFFSET ) || ( zt < -XZOFFSET ) || ( zt >= XZOFFSET ) ) { app.DebugPrintf("Skipping possible portal location as at least one block is too close to the edge\n"); @@ -399,7 +399,7 @@ next_first: continue; int yt = y + h; int zt = z + (s - 1) * za; - // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock + // 4J Stu - Changes to stop Portals being created at the border of the nether inside the bedrock if( ( xt < -XZOFFSET ) || ( xt >= XZOFFSET ) || ( zt < -XZOFFSET ) || ( zt >= XZOFFSET ) ) { app.DebugPrintf("Skipping possible portal location as at least one block is too close to the edge\n"); @@ -508,8 +508,8 @@ void PortalForcer::tick(__int64 time) { __int64 cutoff = time - SharedConstants::TICKS_PER_SECOND * 30; - for(AUTO_VAR(it,cachedPortalKeys.begin()); it != cachedPortalKeys.end();) - { + for (auto it = cachedPortalKeys.begin(); it != cachedPortalKeys.end();) + { __int64 key = *it; PortalPosition *pos = cachedPortals[key]; diff --git a/Minecraft.World/PotatoTile.cpp b/Minecraft.World/PotatoTile.cpp index 64a696ec..872622ba 100644 --- a/Minecraft.World/PotatoTile.cpp +++ b/Minecraft.World/PotatoTile.cpp @@ -55,6 +55,6 @@ void PotatoTile::registerIcons(IconRegister *iconRegister) { for (int i = 0; i < 4; i++) { - icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + _toString<int>(i) ); + icons[i] = iconRegister->registerIcon(getIconName() + L"_stage_" + std::to_wstring(i) ); } }
\ No newline at end of file diff --git a/Minecraft.World/PotionBrewing.cpp b/Minecraft.World/PotionBrewing.cpp index 5c454fd4..8e27a601 100644 --- a/Minecraft.World/PotionBrewing.cpp +++ b/Minecraft.World/PotionBrewing.cpp @@ -197,9 +197,8 @@ int PotionBrewing::getColorValue(vector<MobEffectInstance *> *effects) float count = 0; //for (MobEffectInstance effect : effects){ - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - MobEffectInstance *effect = *it; int potionColor = colourTable->getColor( MobEffect::effects[effect->getId()]->getColor() ); for (int potency = 0; potency <= effect->getAmplifier(); potency++) @@ -220,9 +219,8 @@ int PotionBrewing::getColorValue(vector<MobEffectInstance *> *effects) bool PotionBrewing::areAllEffectsAmbient(vector<MobEffectInstance *> *effects) { - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - MobEffectInstance *effect = *it; if (!effect->isAmbient()) return false; } @@ -233,8 +231,8 @@ int PotionBrewing::getColorValue(int brew, bool includeDisabledEffects) { if (!includeDisabledEffects) { - AUTO_VAR(colIt, cachedColors.find(brew)); - if (colIt != cachedColors.end()) + auto colIt = cachedColors.find(brew); + if (colIt != cachedColors.end()) { return colIt->second;//cachedColors.get(brew); } @@ -242,9 +240,8 @@ int PotionBrewing::getColorValue(int brew, bool includeDisabledEffects) int color = getColorValue(effects); if(effects != NULL) { - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - MobEffectInstance *effect = *it; delete effect; } delete effects; @@ -566,8 +563,8 @@ vector<MobEffectInstance *> *PotionBrewing::getEffects(int brew, bool includeDis continue; } //wstring durationString = potionEffectDuration.get(effect->getId()); - AUTO_VAR(effIt, potionEffectDuration.find(effect->getId())); - if ( effIt == potionEffectDuration.end() ) + auto effIt = potionEffectDuration.find(effect->getId()); + if ( effIt == potionEffectDuration.end() ) { continue; } @@ -577,9 +574,9 @@ vector<MobEffectInstance *> *PotionBrewing::getEffects(int brew, bool includeDis if (duration > 0) { int amplifier = 0; - AUTO_VAR(ampIt, potionEffectAmplifier.find(effect->getId())); - if (ampIt != potionEffectAmplifier.end()) - { + auto ampIt = potionEffectAmplifier.find(effect->getId()); + if (ampIt != potionEffectAmplifier.end()) + { wstring amplifierString = ampIt->second; amplifier = parseEffectFormulaValue(amplifierString, 0, (int)amplifierString.length(), brew); if (amplifier < 0) diff --git a/Minecraft.World/PotionItem.cpp b/Minecraft.World/PotionItem.cpp index e302b8f9..fd8937bf 100644 --- a/Minecraft.World/PotionItem.cpp +++ b/Minecraft.World/PotionItem.cpp @@ -36,8 +36,8 @@ vector<MobEffectInstance *> *PotionItem::getMobEffects(shared_ptr<ItemInstance> if (!potion->hasTag() || !potion->getTag()->contains(L"CustomPotionEffects")) { vector<MobEffectInstance *> *effects = NULL; - AUTO_VAR(it, cachedMobEffects.find(potion->getAuxValue())); - if(it != cachedMobEffects.end()) effects = it->second; + auto it = cachedMobEffects.find(potion->getAuxValue()); + if(it != cachedMobEffects.end()) effects = it->second; if (effects == NULL) { effects = PotionBrewing::getEffects(potion->getAuxValue(), false); @@ -65,8 +65,8 @@ vector<MobEffectInstance *> *PotionItem::getMobEffects(shared_ptr<ItemInstance> vector<MobEffectInstance *> *PotionItem::getMobEffects(int auxValue) { vector<MobEffectInstance *> *effects = NULL; - AUTO_VAR(it, cachedMobEffects.find(auxValue)); - if(it != cachedMobEffects.end()) effects = it->second; + auto it = cachedMobEffects.find(auxValue); + if(it != cachedMobEffects.end()) effects = it->second; if (effects == NULL) { effects = PotionBrewing::getEffects(auxValue, false); @@ -84,10 +84,9 @@ shared_ptr<ItemInstance> PotionItem::useTimeDepleted(shared_ptr<ItemInstance> in vector<MobEffectInstance *> *effects = getMobEffects(instance); if (effects != NULL) { - //for (MobEffectInstance effect : effects) - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - player->addEffect(new MobEffectInstance(*it)); + player->addEffect(new MobEffectInstance(effect)); } } } @@ -188,10 +187,8 @@ bool PotionItem::hasInstantenousEffects(int itemAuxValue) { return false; } - //for (MobEffectInstance effect : mobEffects) { - for(AUTO_VAR(it, mobEffects->begin()); it != mobEffects->end(); ++it) + for(auto& effect : *mobEffects) { - MobEffectInstance *effect = *it; if (MobEffect::effects[effect->getId()]->isInstantenous()) { return true; @@ -224,7 +221,7 @@ wstring PotionItem::getHoverName(shared_ptr<ItemInstance> itemInstance) //String postfixString = effects.get(0).getDescriptionId(); //postfixString += ".postfix"; //return elementName + " " + I18n.get(postfixString).trim(); - + elementName = replaceAll(elementName,L"{*prefix*}",L""); elementName = replaceAll(elementName,L"{*postfix*}",app.GetString(effects->at(0)->getPostfixDescriptionId())); } @@ -232,7 +229,7 @@ wstring PotionItem::getHoverName(shared_ptr<ItemInstance> itemInstance) { //String appearanceName = PotionBrewing.getAppearanceName(itemInstance.getAuxValue()); //return I18n.get(appearanceName).trim() + " " + elementName; - + elementName = replaceAll(elementName,L"{*prefix*}",app.GetString( PotionBrewing::getAppearanceName(itemInstance->getAuxValue()))); elementName = replaceAll(elementName,L"{*postfix*}",L""); } @@ -250,9 +247,8 @@ void PotionItem::appendHoverText(shared_ptr<ItemInstance> itemInstance, shared_p if (effects != NULL && !effects->empty()) { //for (MobEffectInstance effect : effects) - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - MobEffectInstance *effect = *it; wstring effectString = app.GetString( effect->getDescriptionId() ); MobEffect *mobEffect = MobEffect::effects[effect->getId()]; @@ -260,12 +256,12 @@ void PotionItem::appendHoverText(shared_ptr<ItemInstance> itemInstance, shared_p if (effectModifiers != NULL && effectModifiers->size() > 0) { - for(AUTO_VAR(it, effectModifiers->begin()); it != effectModifiers->end(); ++it) + for(auto& it : *effectModifiers) { // 4J - anonymous modifiers added here are destroyed shortly? - AttributeModifier *original = it->second; + AttributeModifier *original = it.second; AttributeModifier *modifier = new AttributeModifier(mobEffect->getAttributeModifierValue(effect->getAmplifier(), original), original->getOperation()); - modifiers.insert( std::pair<eATTRIBUTE_ID, AttributeModifier*>( it->first->getId(), modifier) ); + modifiers.insert( std::pair<eATTRIBUTE_ID, AttributeModifier*>( it.first->getId(), modifier) ); } } @@ -318,20 +314,20 @@ void PotionItem::appendHoverText(shared_ptr<ItemInstance> itemInstance, shared_p { wstring effectString = app.GetString(IDS_POTION_EMPTY); //I18n.get("potion.empty").trim(); - lines->push_back(HtmlString(effectString, eHTMLColor_7)); //"§7" + lines->push_back(HtmlString(effectString, eHTMLColor_7)); //"�7" } if (!modifiers.empty()) { // Add new line - lines->push_back(HtmlString(L"")); - lines->push_back(HtmlString(app.GetString(IDS_POTION_EFFECTS_WHENDRANK), eHTMLColor_5)); + lines->emplace_back(L""); + lines->emplace_back(app.GetString(IDS_POTION_EFFECTS_WHENDRANK), eHTMLColor_5); // Add modifier descriptions - for (AUTO_VAR(it, modifiers.begin()); it != modifiers.end(); ++it) + for (auto& modifier : modifiers) { // 4J: Moved modifier string building to AttributeModifier - lines->push_back(it->second->getHoverText(it->first)); + lines->push_back(modifier.second->getHoverText(modifier.first)); } } } @@ -392,18 +388,17 @@ vector<pair<int, int> > *PotionItem::getUniquePotionValues() // 4J Stu - Based on implementation of Java List.hashCode() at http://docs.oracle.com/javase/6/docs/api/java/util/List.html#hashCode() // and adding deleting to clear up as we go int effectsHashCode = 1; - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - MobEffectInstance *mei = *it; - effectsHashCode = 31*effectsHashCode + (mei==NULL ? 0 : mei->hashCode()); - delete (*it); + effectsHashCode = 31*effectsHashCode + (effect ? 0 : effect->hashCode()); + delete effect; } bool toAdd = true; - for(AUTO_VAR(it, s_uniquePotionValues.begin()); it != s_uniquePotionValues.end(); ++it) + for(auto& it : s_uniquePotionValues) { // Some potions hash the same (identical effects) but are throwable so account for that - if(it->first == effectsHashCode && !(!isThrowable(it->second) && isThrowable(brew)) ) + if(it.first == effectsHashCode && !(!isThrowable(it.second) && isThrowable(brew)) ) { toAdd = false; break; diff --git a/Minecraft.World/PressurePlateTile.cpp b/Minecraft.World/PressurePlateTile.cpp index 6a30819d..beed308a 100644 --- a/Minecraft.World/PressurePlateTile.cpp +++ b/Minecraft.World/PressurePlateTile.cpp @@ -32,9 +32,8 @@ int PressurePlateTile::getSignalStrength(Level *level, int x, int y, int z) if (entities != NULL && !entities->empty()) { - for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) - { - shared_ptr<Entity> e = *it; + for (auto& e : *entities) + { if (!e->isIgnoringTileTriggers()) { if (sensitivity != everything) delete entities; diff --git a/Minecraft.World/RandomScatteredLargeFeature.cpp b/Minecraft.World/RandomScatteredLargeFeature.cpp index 2a2290e3..bd0b70bb 100644 --- a/Minecraft.World/RandomScatteredLargeFeature.cpp +++ b/Minecraft.World/RandomScatteredLargeFeature.cpp @@ -34,11 +34,11 @@ RandomScatteredLargeFeature::RandomScatteredLargeFeature(unordered_map<wstring, { _init(); - for(AUTO_VAR(it, options.begin()); it != options.end(); ++it) + for(auto& option : options) { - if (it->first.compare(OPTION_SPACING) == 0) + if (option.first.compare(OPTION_SPACING) == 0) { - spacing = Mth::getInt(it->second, spacing, minSeparation + 1); + spacing = Mth::getInt(option.second, spacing, minSeparation + 1); } } } @@ -75,9 +75,8 @@ bool RandomScatteredLargeFeature::isFeatureChunk(int x, int z, bool bIsSuperflat if (forcePlacement || (x == xCenterFeatureChunk && z == zCenterFeatureChunk)) { Biome *biome = level->getBiomeSource()->getBiome(x * 16 + 8, z * 16 + 8); - for (AUTO_VAR(it,allowedBiomes.begin()); it != allowedBiomes.end(); ++it) + for ( const auto& a : allowedBiomes) { - Biome *a = *it; if (biome == a) { return true; @@ -129,8 +128,8 @@ bool RandomScatteredLargeFeature::isSwamphut(int cellX, int cellY, int cellZ) return false; } StructurePiece *first = NULL; - AUTO_VAR(it, structureAt->pieces.begin()); - if(it != structureAt->pieces.end() ) first = *it; + auto it = structureAt->pieces.begin(); + if(it != structureAt->pieces.end() ) first = *it; return dynamic_cast<ScatteredFeaturePieces::SwamplandHut *>(first) != NULL; } diff --git a/Minecraft.World/Recipes.cpp b/Minecraft.World/Recipes.cpp index dbb1dbde..8dcbafdf 100644 --- a/Minecraft.World/Recipes.cpp +++ b/Minecraft.World/Recipes.cpp @@ -30,7 +30,7 @@ void Recipes::_init() recipies = new RecipyList(); } -Recipes::Recipes() +Recipes::Recipes() { int iCount=0; _init(); @@ -40,7 +40,7 @@ Recipes::Recipes() pFoodRecipies = new FoodRecipies; pOreRecipies = new OreRecipies; pStructureRecipies = new StructureRecipies; - pToolRecipies = new ToolRecipies; + pToolRecipies = new ToolRecipies; pWeaponRecipies = new WeaponRecipies; // 4J Stu - These just don't work with our crafting menu @@ -64,8 +64,8 @@ Recipes::Recipes() L"#", // L'#', new ItemInstance(Tile::treeTrunk, 1, TreeTile::BIRCH_TRUNK), - L'S'); - + L'S'); + addShapedRecipy(new ItemInstance(Tile::wood, 4, TreeTile::DARK_TRUNK), // L"sczg", L"#", // @@ -89,7 +89,7 @@ Recipes::Recipes() L'S'); pToolRecipies->addRecipes(this); - pFoodRecipies->addRecipes(this); + pFoodRecipies->addRecipes(this); pStructureRecipies->addRecipes(this); @@ -136,8 +136,8 @@ Recipes::Recipes() L"#W#", // L'#', Item::stick, L'W', Tile::wood, - L'S'); - + L'S'); + addShapedRecipy(new ItemInstance(Tile::fence, 2), // L"sscig", L"###", // @@ -145,7 +145,7 @@ Recipes::Recipes() L'#', Item::stick, L'S'); - + addShapedRecipy(new ItemInstance(Tile::netherFence, 6), // L"ssctg", L"###", // @@ -293,10 +293,10 @@ Recipes::Recipes() L'#', Tile::quartzBlock, L'S'); - pArmorRecipes->addRecipes(this); + pArmorRecipes->addRecipes(this); //iCount=getRecipies()->size(); - pClothDyeRecipes->addRecipes(this); + pClothDyeRecipes->addRecipes(this); addShapedRecipy(new ItemInstance(Tile::snow, 1), // @@ -360,14 +360,14 @@ Recipes::Recipes() L"###", // L'#', Tile::stone, - L'S'); + L'S'); addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::COBBLESTONE_SLAB), // L"sctg", L"###", // L'#', Tile::cobblestone, L'S'); - + addShapedRecipy(new ItemInstance(Tile::stoneSlabHalf, 6, StoneSlabTile::BRICK_SLAB), // L"sctg", L"###", // @@ -580,7 +580,7 @@ Recipes::Recipes() L"# X", // L" #X", // - L'X', Item::string,// + L'X', Item::string,// L'#', Item::stick, L'T'); @@ -590,8 +590,8 @@ Recipes::Recipes() L"#", // L"Y", // - L'Y', Item::feather,// - L'X', Item::flint,// + L'Y', Item::feather,// + L'X', Item::flint,// L'#', Item::stick, L'T'); @@ -751,7 +751,7 @@ Recipes::Recipes() L"~~ ", // L"~O ", // L" ~", // - + L'~', Item::string, L'O', Item::slimeBall, L'T'); @@ -773,7 +773,7 @@ Recipes::Recipes() L'#', Item::paper, L'X', Item::compass, L'T'); - + addShapedRecipy(new ItemInstance(Tile::button, 1), // L"sctg", L"#", // @@ -922,7 +922,7 @@ Recipes::Recipes() L'#', Item::stick, L'X', Item::leather, L'D'); - pOreRecipies->addRecipes(this); + pOreRecipies->addRecipes(this); addShapedRecipy(new ItemInstance(Item::goldIngot), // L"ssscig", @@ -996,17 +996,17 @@ Recipes::Recipes() // Sort so the largest recipes get checked first! /* 4J-PB - TODO - Collections.sort(recipies, new Comparator<Recipy>() + Collections.sort(recipies, new Comparator<Recipy>() { - public: int compare(Recipy r0, Recipy r1) + public: int compare(Recipy r0, Recipy r1) { // shapeless recipes are put in the back of the list - if (r0 instanceof ShapelessRecipy && r1 instanceof ShapedRecipy) + if (r0 instanceof ShapelessRecipy && r1 instanceof ShapedRecipy) { return 1; } - if (r1 instanceof ShapelessRecipy && r0 instanceof ShapedRecipy) + if (r1 instanceof ShapelessRecipy && r0 instanceof ShapedRecipy) { return -1; } @@ -1059,7 +1059,7 @@ ShapedRecipy *Recipes::addShapedRecipy(ItemInstance *result, ...) wchTypes = va_arg(vl,wchar_t *); - for(int i = 0; wchTypes[i] != L'\0'; ++i ) + for(int i = 0; wchTypes[i] != L'\0'; ++i ) { if(wchTypes[i+1]==L'\0' && wchTypes[i]!=L'g') { @@ -1153,15 +1153,15 @@ ShapedRecipy *Recipes::addShapedRecipy(ItemInstance *result, ...) ids = new ItemInstance *[width * height]; - for (int j = 0; j < width * height; j++) + for (int j = 0; j < width * height; j++) { wchar_t ch = map[j]; myMap::iterator it=mappings->find(ch); - if (it != mappings->end()) + if (it != mappings->end()) { ids[j] =it->second; - } - else + } + else { ids[j] = NULL; } @@ -1175,7 +1175,7 @@ ShapedRecipy *Recipes::addShapedRecipy(ItemInstance *result, ...) return recipe; } -void Recipes::addShapelessRecipy(ItemInstance *result,... ) +void Recipes::addShapelessRecipy(ItemInstance *result,... ) { va_list vl; wchar_t *szTypes; @@ -1194,7 +1194,7 @@ void Recipes::addShapelessRecipy(ItemInstance *result,... ) // t - Tile * szTypes = va_arg(vl,wchar_t *); - for(int i = 0; szTypes[i] != L'\0'; ++i ) + for(int i = 0; szTypes[i] != L'\0'; ++i ) { switch(szTypes[i]) { @@ -1245,10 +1245,10 @@ void Recipes::addShapelessRecipy(ItemInstance *result,... ) break; } } - recipies->push_back(new ShapelessRecipy(result, ingredients, group)); + recipies->push_back(new ShapelessRecipy(result, ingredients, group)); } -shared_ptr<ItemInstance> Recipes::getItemFor(shared_ptr<CraftingContainer> craftSlots, Level *level, Recipy *recipesClass /*= NULL*/) +shared_ptr<ItemInstance> Recipes::getItemFor(shared_ptr<CraftingContainer> craftSlots, Level *level, Recipy *recipesClass /*= NULL*/) { int count = 0; shared_ptr<ItemInstance> first = nullptr; @@ -1281,23 +1281,21 @@ shared_ptr<ItemInstance> Recipes::getItemFor(shared_ptr<CraftingContainer> craft } else { - AUTO_VAR(itEnd, recipies->end()); - for (AUTO_VAR(it, recipies->begin()); it != itEnd; it++) + for (auto& r : *recipies) { - Recipy *r = *it; //recipies->at(i); if (r->matches(craftSlots, level)) return r->assemble(craftSlots); } } return nullptr; } -vector <Recipy *> *Recipes::getRecipies() +vector <Recipy *> *Recipes::getRecipies() { return recipies; } // 4J-PB - added to deal with Xb0x 'crafting' -shared_ptr<ItemInstance> Recipes::getItemForRecipe(Recipy *r) +shared_ptr<ItemInstance> Recipes::getItemForRecipe(Recipy *r) { return r->assemble(nullptr); } @@ -1312,11 +1310,8 @@ void Recipes::buildRecipeIngredientsArray(void) m_pRecipeIngredientsRequired= new Recipy::INGREDIENTS_REQUIRED [iRecipeC]; int iCount=0; - AUTO_VAR(itEndRec, recipies->end()); - for (AUTO_VAR(it, recipies->begin()); it != itEndRec; it++) + for (auto& recipe : *recipies) { - Recipy *recipe = *it; - //wprintf(L"RECIPE - [%d] is %w\n",iCount,recipe->getResultItem()->getItem()->getName()); recipe->requires(&m_pRecipeIngredientsRequired[iCount++]); } diff --git a/Minecraft.World/RecordingItem.cpp b/Minecraft.World/RecordingItem.cpp index 3b501899..455323c2 100644 --- a/Minecraft.World/RecordingItem.cpp +++ b/Minecraft.World/RecordingItem.cpp @@ -66,8 +66,8 @@ void RecordingItem::registerIcons(IconRegister *iconRegister) RecordingItem *RecordingItem::getByName(const wstring &name) { - AUTO_VAR(it,BY_NAME.find(name)); - if(it != BY_NAME.end()) + auto it = BY_NAME.find(name); + if(it != BY_NAME.end()) { return it->second; } diff --git a/Minecraft.World/RedStoneDustTile.cpp b/Minecraft.World/RedStoneDustTile.cpp index 0107b667..a4577bd3 100644 --- a/Minecraft.World/RedStoneDustTile.cpp +++ b/Minecraft.World/RedStoneDustTile.cpp @@ -84,10 +84,8 @@ void RedStoneDustTile::updatePowerStrength(Level *level, int x, int y, int z) vector<TilePos> updates = vector<TilePos>(toUpdate.begin(), toUpdate.end()); toUpdate.clear(); - AUTO_VAR(itEnd, updates.end()); - for(AUTO_VAR(it, updates.begin()); it != itEnd; it++) + for(auto& tp : updates) { - TilePos tp = *it; level->updateNeighborsAt(tp.x, tp.y, tp.z, id); } } @@ -399,7 +397,7 @@ void RedStoneDustTile::registerIcons(IconRegister *iconRegister) icon = iconCross; } -Icon *RedStoneDustTile::getTexture(const wstring &name) +Icon *RedStoneDustTile::getTexture(const wstring &name) { #ifdef __PSVITA__ // AP - alpha cut out is expensive on vita. Set the Alpha Cut out flag diff --git a/Minecraft.World/RegionFileCache.cpp b/Minecraft.World/RegionFileCache.cpp index 23c87118..2bb370a8 100644 --- a/Minecraft.World/RegionFileCache.cpp +++ b/Minecraft.World/RegionFileCache.cpp @@ -25,22 +25,22 @@ RegionFile *RegionFileCache::_getRegionFile(ConsoleSaveFile *saveFile, const wst //File regionDir(basePath, L"region"); - //File file(regionDir, wstring(L"r.") + _toString(chunkX>>5) + L"." + _toString(chunkZ>>5) + L".mcr" ); + //File file(regionDir, wstring(L"r.") + std::to_wstring(chunkX>>5) + L"." + std::to_wstring(chunkZ>>5) + L".mcr" ); MemSect(31); File file; if(useSplitSaves(saveFile->getSavePlatform())) { - file = File( prefix + wstring(L"r.") + _toString(chunkX>>4) + L"." + _toString(chunkZ>>4) + L".mcr" ); + file = File( prefix + wstring(L"r.") + std::to_wstring(chunkX>>4) + L"." + std::to_wstring(chunkZ>>4) + L".mcr" ); } else { - file = File( prefix + wstring(L"r.") + _toString(chunkX>>5) + L"." + _toString(chunkZ>>5) + L".mcr" ); + file = File( prefix + wstring(L"r.") + std::to_wstring(chunkX>>5) + L"." + std::to_wstring(chunkZ>>5) + L".mcr" ); } MemSect(0); RegionFile *ref = NULL; - AUTO_VAR(it, cache.find(file)); - if( it != cache.end() ) + auto it = cache.find(file); + if( it != cache.end() ) ref = it->second; // 4J Jev, put back in. @@ -69,20 +69,14 @@ RegionFile *RegionFileCache::_getRegionFile(ConsoleSaveFile *saveFile, const wst void RegionFileCache::_clear() // 4J - TODO was synchronized { - AUTO_VAR(itEnd, cache.end()); - for( AUTO_VAR(it, cache.begin()); it != itEnd; it++ ) + for(auto& it : cache) { - // 4J - removed try/catch -// try { - RegionFile *regionFile = it->second; + RegionFile *regionFile = it.second; if (regionFile != NULL) { regionFile->close(); } delete regionFile; -// } catch (IOException e) { -// e.printStackTrace(); -// } } cache.clear(); } diff --git a/Minecraft.World/RepairMenu.cpp b/Minecraft.World/RepairMenu.cpp index d246b73f..a4c48edf 100644 --- a/Minecraft.World/RepairMenu.cpp +++ b/Minecraft.World/RepairMenu.cpp @@ -134,22 +134,22 @@ void RepairMenu::createResult() unordered_map<int, int> *additionalEnchantments = EnchantmentHelper::getEnchantments(addition); - for(AUTO_VAR(it, additionalEnchantments->begin()); it != additionalEnchantments->end(); ++it) + for(auto& it : *additionalEnchantments) { - int id = it->first; + int id = it.first; Enchantment *enchantment = Enchantment::enchantments[id]; - AUTO_VAR(localIt, enchantments->find(id)); - int current = localIt != enchantments->end() ? localIt->second : 0; - int level = it->second; + auto localIt = enchantments->find(id); + int current = localIt != enchantments->end() ? localIt->second : 0; + int level = it.second; level = (current == level) ? level += 1 : max(level, current); int extra = level - current; bool compatible = enchantment->canEnchant(input); if (player->abilities.instabuild) compatible = true; - for(AUTO_VAR(it2, enchantments->begin()); it2 != enchantments->end(); ++it2) + for(auto& it2 : *enchantments) { - int other = it2->first; + int other = it2.first; if (other != id && !enchantment->isCompatibleWith(Enchantment::enchantments[other])) { compatible = false; @@ -219,11 +219,11 @@ void RepairMenu::createResult() } int count = 0; - for(AUTO_VAR(it, enchantments->begin()); it != enchantments->end(); ++it) + for(auto& it : *enchantments) { - int id = it->first; + int id = it.first; Enchantment *enchantment = Enchantment::enchantments[id]; - int level = it->second; + int level = it.second; int fee = 0; count++; diff --git a/Minecraft.World/SavedDataStorage.cpp b/Minecraft.World/SavedDataStorage.cpp index 3dbd6400..422b66dc 100644 --- a/Minecraft.World/SavedDataStorage.cpp +++ b/Minecraft.World/SavedDataStorage.cpp @@ -8,7 +8,7 @@ #include "ConsoleSaveFileIO.h" -SavedDataStorage::SavedDataStorage(LevelStorage *levelStorage) +SavedDataStorage::SavedDataStorage(LevelStorage *levelStorage) { /* cache = new unordered_map<wstring, shared_ptr<SavedData> >; @@ -22,15 +22,15 @@ SavedDataStorage::SavedDataStorage(LevelStorage *levelStorage) shared_ptr<SavedData> SavedDataStorage::get(const type_info& clazz, const wstring& id) { - AUTO_VAR(it, cache.find( id )); - if (it != cache.end()) return (*it).second; + auto it = cache.find(id); + if (it != cache.end()) return (*it).second; shared_ptr<SavedData> data = nullptr; if (levelStorage != NULL) { //File file = levelStorage->getDataFile(id); ConsoleSavePath file = levelStorage->getDataFile(id); - if (!file.getName().empty() && levelStorage->getSaveFile()->doesFileExist( file ) ) + if (!file.getName().empty() && levelStorage->getSaveFile()->doesFileExist( file ) ) { // mob = dynamic_pointer_cast<Mob>(Mob::_class->newInstance( level )); //data = clazz.getConstructor(String.class).newInstance(id); @@ -69,18 +69,18 @@ shared_ptr<SavedData> SavedDataStorage::get(const type_info& clazz, const wstrin return data; } -void SavedDataStorage::set(const wstring& id, shared_ptr<SavedData> data) +void SavedDataStorage::set(const wstring& id, shared_ptr<SavedData> data) { if (data == NULL) { // TODO 4J Stu - throw new RuntimeException("Can't set null data"); assert( false ); } - AUTO_VAR(it, cache.find(id)); - if ( it != cache.end() ) + auto it = cache.find(id); + if ( it != cache.end() ) { - AUTO_VAR(it2, find( savedDatas.begin(), savedDatas.end(), it->second )); - if( it2 != savedDatas.end() ) + auto it2 = find(savedDatas.begin(), savedDatas.end(), it->second); + if( it2 != savedDatas.end() ) { savedDatas.erase( it2 ); } @@ -92,10 +92,8 @@ void SavedDataStorage::set(const wstring& id, shared_ptr<SavedData> data) void SavedDataStorage::save() { - AUTO_VAR(itEnd, savedDatas.end()); - for (AUTO_VAR(it, savedDatas.begin()); it != itEnd; it++) + for (auto& data : savedDatas) { - shared_ptr<SavedData> data = *it; //savedDatas->at(i); if (data->isDirty()) { save(data); @@ -139,16 +137,12 @@ void SavedDataStorage::loadAuxValues() CompoundTag *tags = NbtIo::read(&dis); dis.close(); - Tag *tag; vector<Tag *> *allTags = tags->getAllTags(); - AUTO_VAR(itEnd, allTags->end()); - for (AUTO_VAR(it, allTags->begin()); it != itEnd; it++) + for ( Tag *tag : *allTags ) { - tag = *it; //tags->getAllTags()->at(i); - - if (dynamic_cast<ShortTag *>(tag) != NULL) + if (dynamic_cast<ShortTag *>(tag)) { - ShortTag *sTag = (ShortTag *) tag; + ShortTag *sTag = static_cast<ShortTag *>(tag); wstring id = sTag->getName(); short val = sTag->data; usedAuxIds.insert( uaiMapType::value_type( id, val ) ); @@ -160,7 +154,7 @@ void SavedDataStorage::loadAuxValues() int SavedDataStorage::getFreeAuxValueFor(const wstring& id) { - AUTO_VAR(it, usedAuxIds.find( id )); + auto it = usedAuxIds.find(id); short val = 0; if ( it != usedAuxIds.end() ) { @@ -177,11 +171,10 @@ int SavedDataStorage::getFreeAuxValueFor(const wstring& id) CompoundTag *tag = new CompoundTag(); // TODO 4J Stu - This was iterating over the keySet in Java, so potentially we are looking at more items? - AUTO_VAR(itEndAuxIds, usedAuxIds.end()); - for(uaiMapType::iterator it2 = usedAuxIds.begin(); it2 != itEndAuxIds; it2++) + for(auto& it : usedAuxIds) { - short value = it2->second; - tag->putShort( (wchar_t *) it2->first.c_str(), value); + short value = it.second; + tag->putShort(it.first.c_str(), value); } ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream(levelStorage->getSaveFile(), file); diff --git a/Minecraft.World/Sensing.cpp b/Minecraft.World/Sensing.cpp index d451f483..ae7d90c6 100644 --- a/Minecraft.World/Sensing.cpp +++ b/Minecraft.World/Sensing.cpp @@ -17,13 +17,13 @@ bool Sensing::canSee(shared_ptr<Entity> target) { //if ( find(seen.begin(), seen.end(), target) != seen.end() ) return true; //if ( find(unseen.begin(), unseen.end(), target) != unseen.end()) return false; - for(AUTO_VAR(it, seen.begin()); it != seen.end(); ++it) + for(auto& it : seen) { - if(target == (*it).lock()) return true; + if(target == it.lock()) return true; } - for(AUTO_VAR(it, unseen.begin()); it != unseen.end(); ++it) + for(auto & it : unseen) { - if(target == (*it).lock()) return false; + if(target == it.lock()) return false; } //util.Timer.push("canSee"); diff --git a/Minecraft.World/ServersideAttributeMap.cpp b/Minecraft.World/ServersideAttributeMap.cpp index ec75aa22..901854cc 100644 --- a/Minecraft.World/ServersideAttributeMap.cpp +++ b/Minecraft.World/ServersideAttributeMap.cpp @@ -14,12 +14,12 @@ AttributeInstance *ServersideAttributeMap::getInstance(Attribute *attribute) AttributeInstance *ServersideAttributeMap::getInstance(eATTRIBUTE_ID id) { AttributeInstance *result = BaseAttributeMap::getInstance(id); - + // 4J: Removed legacy name // If we didn't find it, search by legacy name /*if (result == NULL) { - AUTO_VAR(it, attributesByLegacy.find(name)); + auto it = attributesByLegacy.find(name); if(it != attributesByLegacy.end()) { result = it->second; @@ -31,15 +31,15 @@ AttributeInstance *ServersideAttributeMap::getInstance(eATTRIBUTE_ID id) AttributeInstance *ServersideAttributeMap::registerAttribute(Attribute *attribute) { - AUTO_VAR(it,attributesById.find(attribute->getId())); - if (it != attributesById.end()) + auto it = attributesById.find(attribute->getId()); + if (it != attributesById.end()) { return it->second; } AttributeInstance *instance = new ModifiableAttributeInstance(this, attribute); attributesById.insert(std::pair<eATTRIBUTE_ID, AttributeInstance *>(attribute->getId(), instance)); - + // 4J: Removed legacy name // If this is a ranged attribute also add to legacy name map /*RangedAttribute *rangedAttribute = dynamic_cast<RangedAttribute*>(attribute); diff --git a/Minecraft.World/SetPlayerTeamPacket.cpp b/Minecraft.World/SetPlayerTeamPacket.cpp index 8c605784..fe36bfff 100644 --- a/Minecraft.World/SetPlayerTeamPacket.cpp +++ b/Minecraft.World/SetPlayerTeamPacket.cpp @@ -96,9 +96,9 @@ void SetPlayerTeamPacket::write(DataOutputStream *dos) { dos->writeShort(players.size()); - for (AUTO_VAR(it,players.begin()); it != players.end(); ++it) + for (auto& player : players) { - writeUtf(*it, dos); + writeUtf(player, dos); } } } diff --git a/Minecraft.World/ShapelessRecipy.cpp b/Minecraft.World/ShapelessRecipy.cpp index 67ed0381..44bf6a54 100644 --- a/Minecraft.World/ShapelessRecipy.cpp +++ b/Minecraft.World/ShapelessRecipy.cpp @@ -39,18 +39,17 @@ bool ShapelessRecipy::matches(shared_ptr<CraftingContainer> craftSlots, Level *l { shared_ptr<ItemInstance> item = craftSlots->getItem(x, y); - if (item != NULL) + if (item) { bool found = false; - AUTO_VAR(citEnd, ingredients->end()); - for (AUTO_VAR(cit, ingredients->begin()); cit != citEnd; ++cit) + auto citEnd = ingredients->end(); + for ( ItemInstance *ingredient : *ingredients ) { - ItemInstance *ingredient = *cit; if (item->id == ingredient->id && (ingredient->getAuxValue() == Recipes::ANY_AUX_VALUE || item->getAuxValue() == ingredient->getAuxValue())) { found = true; - AUTO_VAR( it, find(tempList.begin(), tempList.end(), ingredient ) ); + auto it = find(tempList.begin(), tempList.end(), ingredient); if(it != tempList.end() ) tempList.erase(it); break; } @@ -86,9 +85,8 @@ bool ShapelessRecipy::requires(int iRecipe) //printf("ShapelessRecipy %d\n",iRecipe); - AUTO_VAR(citEnd, ingredients->end()); int iCount=0; - for (vector<ItemInstance *>::iterator ingredient = ingredients->begin(); ingredient != citEnd; ingredient++) + for ( auto ingredient = ingredients->begin(); ingredient != ingredients->end(); ingredient++) { //printf("\tIngredient %d is %d\n",iCount++,(*ingredient)->id); //if (item->id == (*ingredient)->id && ((*ingredient)->getAuxValue() == Recipes::ANY_AUX_VALUE || item->getAuxValue() == (*ingredient)->getAuxValue())) @@ -119,15 +117,11 @@ void ShapelessRecipy::requires(INGREDIENTS_REQUIRED *pIngReq) memset(TempIngReq.iIngAuxValA,Recipes::ANY_AUX_VALUE,sizeof(int)*9); ZeroMemory(TempIngReq.uiGridA,sizeof(unsigned int)*9); - AUTO_VAR(citEnd, ingredients->end()); - - for (vector<ItemInstance *>::const_iterator ingredient = ingredients->begin(); ingredient != citEnd; ingredient++) + for ( ItemInstance *expected : *ingredients ) { - ItemInstance *expected = *ingredient; - - if (expected!=NULL) + if ( expected ) { - int iAuxVal = (*ingredient)->getAuxValue(); + int iAuxVal = expected->getAuxValue(); TempIngReq.uiGridA[iCount++]=expected->id | iAuxVal<<24; // 4J-PB - put the ingredients in boxes 1,2,4,5 so we can see them in a 2x2 crafting screen if(iCount==2) iCount=3; diff --git a/Minecraft.World/SharedMonsterAttributes.cpp b/Minecraft.World/SharedMonsterAttributes.cpp index f434f1e7..3ff84197 100644 --- a/Minecraft.World/SharedMonsterAttributes.cpp +++ b/Minecraft.World/SharedMonsterAttributes.cpp @@ -15,9 +15,8 @@ ListTag<CompoundTag> *SharedMonsterAttributes::saveAttributes(BaseAttributeMap * vector<AttributeInstance *> atts; attributes->getAttributes(atts); - for (AUTO_VAR(it, atts.begin()); it != atts.end(); ++it) + for (auto& attribute : atts) { - AttributeInstance *attribute = *it; list->add(saveAttribute(attribute)); } @@ -39,9 +38,8 @@ CompoundTag *SharedMonsterAttributes::saveAttribute(AttributeInstance *instance) { ListTag<CompoundTag> *list = new ListTag<CompoundTag>(); - for (AUTO_VAR(it,modifiers.begin()); it != modifiers.end(); ++it) + for (auto& modifier : modifiers) { - AttributeModifier* modifier = *it; if (modifier->isSerializable()) { list->add(saveAttributeModifier(modifier)); diff --git a/Minecraft.World/SpawnEggItem.cpp b/Minecraft.World/SpawnEggItem.cpp index ab082bfb..9c059126 100644 --- a/Minecraft.World/SpawnEggItem.cpp +++ b/Minecraft.World/SpawnEggItem.cpp @@ -30,7 +30,7 @@ wstring SpawnEggItem::getHoverName(shared_ptr<ItemInstance> itemInstance) //elementName += " " + I18n.get("entity." + encodeId + ".name"); } else - { + { elementName = replaceAll(elementName,L"{*CREATURE*}",L""); } @@ -39,8 +39,8 @@ wstring SpawnEggItem::getHoverName(shared_ptr<ItemInstance> itemInstance) int SpawnEggItem::getColor(shared_ptr<ItemInstance> item, int spriteLayer) { - AUTO_VAR(it, EntityIO::idsSpawnableInCreative.find(item->getAuxValue())); - if (it != EntityIO::idsSpawnableInCreative.end()) + auto it = EntityIO ::idsSpawnableInCreative.find(item->getAuxValue()); + if (it != EntityIO::idsSpawnableInCreative.end()) { EntityIO::SpawnableMobInfo *spawnableMobInfo = it->second; if (spriteLayer == 0) { @@ -228,7 +228,7 @@ bool SpawnEggItem::useOn(shared_ptr<ItemInstance> itemInstance, shared_ptr<Playe } if (result != NULL) - { + { // 4J-JEV: SetCustomName is a method for Mob not LivingEntity; so change instanceof to check for Mobs. if ( result->instanceof(eTYPE_MOB) && itemInstance->hasCustomHoverName() ) { @@ -237,7 +237,7 @@ bool SpawnEggItem::useOn(shared_ptr<ItemInstance> itemInstance, shared_ptr<Playe if ( !player->abilities.instabuild ) { itemInstance->count--; - } + } } else { diff --git a/Minecraft.World/Stat.cpp b/Minecraft.World/Stat.cpp index 868ff3bd..97a655c7 100644 --- a/Minecraft.World/Stat.cpp +++ b/Minecraft.World/Stat.cpp @@ -76,21 +76,21 @@ wstring Stat::TimeFormatter::format(int value) if (years > 0.5) { return decimalFormat->format(years) + L" y"; - } - else if (days > 0.5) + } + else if (days > 0.5) { return decimalFormat->format(days) + L" d"; } else if (hours > 0.5) { return decimalFormat->format(hours) + L" h"; - } - else if (minutes > 0.5) + } + else if (minutes > 0.5) { return decimalFormat->format(minutes) + L" m"; } - return _toString<double>(seconds) + L" s"; + return std::to_wstring(seconds) + L" s"; } wstring Stat::DefaultFormat::format(int value) @@ -103,13 +103,13 @@ wstring Stat::DistanceFormatter::format(int cm) double meters = cm / 100.0; double kilometers = meters / 1000.0; - if (kilometers > 0.5) + if (kilometers > 0.5) { return decimalFormat->format(kilometers) + L" km"; - } else if (meters > 0.5) + } else if (meters > 0.5) { return decimalFormat->format(meters) + L" m"; } - return _toString<int>(cm) + L" cm"; + return std::to_wstring(cm) + L" cm"; } diff --git a/Minecraft.World/Stats.cpp b/Minecraft.World/Stats.cpp index 89da587b..c8a615ff 100644 --- a/Minecraft.World/Stats.cpp +++ b/Minecraft.World/Stats.cpp @@ -216,7 +216,7 @@ void Stats::buildBlockStats() bool Stats::itemStatsLoaded = false; -void Stats::buildItemStats() +void Stats::buildItemStats() { itemStatsLoaded = true; buildCraftableStats(); @@ -239,7 +239,7 @@ void Stats::buildCraftableStats() craftableStatsLoaded = true; //Collected stats - + itemsCollected = StatArray(32000); ItemStat* newStat = new ItemStat(ITEMS_COLLECTED_OFFSET + 0, L"collectItem.egg", Item::egg->id); @@ -248,12 +248,12 @@ void Stats::buildCraftableStats() newStat->postConstruct(); // 4J Stu - The following stats were added as it was too easy to cheat the leaderboards by dropping and picking up these items - // They are now changed to mining the block which involves a tiny bit more effort + // They are now changed to mining the block which involves a tiny bit more effort newStat = new ItemStat(BLOCKS_MINED_OFFSET + 18, L"mineBlock.wheat", Tile::wheat_Id); blocksMinedStats->push_back(newStat); blocksMined[Tile::wheat_Id] = newStat; newStat->postConstruct(); - + newStat = new ItemStat(BLOCKS_MINED_OFFSET + 19, L"mineBlock.mushroom1", Tile::mushroom_brown_Id); blocksMinedStats->push_back(newStat); blocksMined[Tile::mushroom_brown_Id] = newStat; @@ -522,7 +522,7 @@ void Stats::buildAdditionalStats() rainbowCollection = StatArray(16); for (unsigned int i = 0; i < 16; i++) { - generalStat = new GeneralStat(offset++, L"rainbowCollection." + _toString<unsigned int>(i)); + generalStat = new GeneralStat(offset++, L"rainbowCollection." + std::to_wstring(i)); generalStats->push_back(generalStat); rainbowCollection[i] = generalStat; generalStat->postConstruct(); @@ -531,7 +531,7 @@ void Stats::buildAdditionalStats() biomesVisisted = StatArray(23); for (unsigned int i = 0; i < 23; i++) { - generalStat = new GeneralStat(offset++, L"biomesVisited." + _toString<unsigned int>(i)); + generalStat = new GeneralStat(offset++, L"biomesVisited." + std::to_wstring(i)); generalStats->push_back(generalStat); biomesVisisted[i] = generalStat; generalStat->postConstruct(); @@ -548,10 +548,10 @@ void Stats::buildAdditionalStats() itemStat->postConstruct(); } #endif - + } -Stat *Stats::get(int key) +Stat *Stats::get(int key) { return statsById->at(key); } diff --git a/Minecraft.World/StringHelpers.h b/Minecraft.World/StringHelpers.h index 1b364118..dee676ba 100644 --- a/Minecraft.World/StringHelpers.h +++ b/Minecraft.World/StringHelpers.h @@ -6,19 +6,7 @@ wstring trimString(const wstring& a); wstring replaceAll(const wstring& in, const wstring& replace, const wstring& with); bool equalsIgnoreCase(const wstring& a, const wstring& b); -// 4J-PB - for use in the ::toString -template <class T> std::wstring _toString(T t) -{ - std::wostringstream oss; - oss << std::dec << t; - return oss.str(); -} -template <class T> std::wstring _toHexString(T t) -{ - std::wostringstream oss; - oss << std::hex << t; - return oss.str(); -} + template <class T> T _fromString(const std::wstring& s) { std::wistringstream stream (s); diff --git a/Minecraft.World/StrongholdFeature.cpp b/Minecraft.World/StrongholdFeature.cpp index 3aed0195..fa85dc42 100644 --- a/Minecraft.World/StrongholdFeature.cpp +++ b/Minecraft.World/StrongholdFeature.cpp @@ -53,21 +53,21 @@ StrongholdFeature::StrongholdFeature(unordered_map<wstring, wstring> options) { _init(); - for (AUTO_VAR(it, options.begin()); it != options.end(); ++it) + for (auto& option : options) { - if (it->first.compare(OPTION_DISTANCE) == 0) + if (option.first.compare(OPTION_DISTANCE) == 0) { - distance = Mth::getDouble(it->second, distance, 1); + distance = Mth::getDouble(option.second, distance, 1); } - else if (it->first.compare(OPTION_COUNT) == 0) + else if (option.first.compare(OPTION_COUNT) == 0) { // 4J-JEV: Removed, we only have the one stronghold. //strongholdPos = new ChunkPos[ Mth::getInt(it->second, strongholdPos_length, 1) ]; assert(false); } - else if (it->first.compare(OPTION_SPREAD) == 0) + else if (option.first.compare(OPTION_SPREAD) == 0) { - spread = Mth::getInt(it->second, spread, 1); + spread = Mth::getInt(option.second, spread, 1); } } } @@ -174,7 +174,7 @@ bool StrongholdFeature::isFeatureChunk(int x, int z,bool bIsSuperflat) #ifdef _LARGE_WORLDS angle = random.nextDouble() * PI * 2.0 * circle / (double) spread; #endif - } + } while(!hasFoundValidPos && findAttempts < MAX_STRONGHOLD_ATTEMPTS); if(!hasFoundValidPos) @@ -255,8 +255,8 @@ StrongholdFeature::StrongholdStart::StrongholdStart(Level *level, Random *random while (!pendingChildren->empty()) { int pos = random->nextInt((int)pendingChildren->size()); - AUTO_VAR(it, pendingChildren->begin() + pos); - StructurePiece *structurePiece = *it; + auto it = pendingChildren->begin() + pos; + StructurePiece *structurePiece = *it; pendingChildren->erase(it); structurePiece->addChildren(startRoom, &pieces, random); } diff --git a/Minecraft.World/StrongholdPieces.cpp b/Minecraft.World/StrongholdPieces.cpp index d736fb0e..383be42c 100644 --- a/Minecraft.World/StrongholdPieces.cpp +++ b/Minecraft.World/StrongholdPieces.cpp @@ -52,9 +52,9 @@ bool StrongholdPieces::PieceWeight::isValid() void StrongholdPieces::resetPieces() { - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) + for(auto& it : currentPieces) { - delete (*it); + delete it; } currentPieces.clear(); @@ -77,9 +77,8 @@ bool StrongholdPieces::updatePieceWeight() { bool hasAnyPieces = false; totalWeight = 0; - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) + for(auto& piece : currentPieces) { - PieceWeight *piece = *it; if (piece->maxPlaceCount > 0 && piece->placeCount < piece->maxPlaceCount) { hasAnyPieces = true; @@ -166,9 +165,8 @@ StrongholdPieces::StrongholdPiece *StrongholdPieces::generatePieceFromSmallDoor( numAttempts++; int weightSelection = random->nextInt(totalWeight); - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) - { - PieceWeight *piece = *it; + for ( PieceWeight *piece : currentPieces ) + { weightSelection -= piece->weight; if (weightSelection < 0) { @@ -215,10 +213,8 @@ StructurePiece *StrongholdPieces::generateAndAddPiece(StartPiece *startPiece, li // Force attempt at spawning a portal room if(startPiece->m_level->getOriginalSaveVersion() >= SAVE_FILE_VERSION_MOVED_STRONGHOLD && !startPiece->m_level->getLevelData()->getHasStrongholdEndPortal()) { - for( AUTO_VAR(it, currentPieces.begin()); it != currentPieces.end(); it++ ) - { - PieceWeight *piece = *it; - + for ( PieceWeight *piece : currentPieces ) + { if(piece->pieceClass != EPieceClass_PortalRoom) continue; #ifndef _CONTENT_PACKAGE @@ -254,7 +250,7 @@ StructurePiece *StrongholdPieces::generateAndAddPiece(StartPiece *startPiece, li return newPiece; } -StrongholdPieces::StrongholdPiece::StrongholdPiece() +StrongholdPieces::StrongholdPiece::StrongholdPiece() { entryDoor = OPENING; // for reflection @@ -267,7 +263,7 @@ StrongholdPieces::StrongholdPiece::StrongholdPiece(int genDepth) : StructurePiec void StrongholdPieces::StrongholdPiece::addAdditonalSaveData(CompoundTag *tag) { - tag->putString(L"EntryDoor", _toString<int>(entryDoor)); + tag->putString(L"EntryDoor", std::to_wstring(entryDoor)); } void StrongholdPieces::StrongholdPiece::readAdditonalSaveData(CompoundTag *tag) @@ -565,7 +561,7 @@ StrongholdPieces::StairsDown *StrongholdPieces::StairsDown::createPiece(list<Str { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 4 - height, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -676,7 +672,7 @@ StrongholdPieces::Straight *StrongholdPieces::Straight::createPiece(list<Structu { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -719,7 +715,7 @@ bool StrongholdPieces::Straight::postProcess(Level *level, Random *random, Bound return true; } -WeighedTreasure *StrongholdPieces::ChestCorridor::treasureItems[TREASURE_ITEMS_COUNT] = +WeighedTreasure *StrongholdPieces::ChestCorridor::treasureItems[TREASURE_ITEMS_COUNT] = { new WeighedTreasure(Item::enderPearl_Id, 0, 1, 1, 10), new WeighedTreasure(Item::diamond_Id, 0, 1, 3, 3), @@ -776,7 +772,7 @@ StrongholdPieces::ChestCorridor *StrongholdPieces::ChestCorridor::createPiece(li { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -848,7 +844,7 @@ StrongholdPieces::StraightStairsDown *StrongholdPieces::StraightStairsDown::crea { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, 4 - height, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -920,7 +916,7 @@ StrongholdPieces::LeftTurn *StrongholdPieces::LeftTurn::createPiece(list<Structu { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1010,7 +1006,7 @@ StrongholdPieces::RoomCrossing::RoomCrossing(int genDepth, Random *random, Bound { entryDoor = randomSmallDoor(random); orientation = direction; - boundingBox = stairsBox; + boundingBox = stairsBox; } void StrongholdPieces::RoomCrossing::addAdditonalSaveData(CompoundTag *tag) @@ -1036,7 +1032,7 @@ StrongholdPieces::RoomCrossing *StrongholdPieces::RoomCrossing::createPiece(list { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1048,7 +1044,7 @@ StrongholdPieces::RoomCrossing *StrongholdPieces::RoomCrossing::createPiece(list return new RoomCrossing(genDepth, random, box, direction); } -WeighedTreasure *StrongholdPieces::RoomCrossing::smallTreasureItems[SMALL_TREASURE_ITEMS_COUNT] = +WeighedTreasure *StrongholdPieces::RoomCrossing::smallTreasureItems[SMALL_TREASURE_ITEMS_COUNT] = { new WeighedTreasure(Item::ironIngot_Id, 0, 1, 5, 10), new WeighedTreasure(Item::goldIngot_Id, 0, 1, 3, 5), @@ -1188,7 +1184,7 @@ StrongholdPieces::PrisonHall *StrongholdPieces::PrisonHall::createPiece(list<Str { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -1, -1, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1267,7 +1263,7 @@ StrongholdPieces::Library *StrongholdPieces::Library::createPiece(list<Structure // attempt to make a tall library first BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, tallHeight, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1286,7 +1282,7 @@ StrongholdPieces::Library *StrongholdPieces::Library::createPiece(list<Structure return new Library(genDepth, random, box, direction); } -WeighedTreasure *StrongholdPieces::Library::libraryTreasureItems[LIBRARY_TREASURE_ITEMS_COUNT] = +WeighedTreasure *StrongholdPieces::Library::libraryTreasureItems[LIBRARY_TREASURE_ITEMS_COUNT] = { new WeighedTreasure(Item::book_Id, 0, 1, 3, 20), new WeighedTreasure(Item::paper_Id, 0, 2, 7, 20), @@ -1467,7 +1463,7 @@ void StrongholdPieces::FiveCrossing::addChildren(StructurePiece *startPiece, lis { zOffA = depth - 3 - zOffA; zOffB = depth - 3 - zOffB; - } + } generateSmallDoorChildForward((StartPiece *) startPiece, pieces, random, 5, 1); if (leftLow) generateSmallDoorChildLeft((StartPiece *) startPiece, pieces, random, zOffA, 1); @@ -1480,7 +1476,7 @@ StrongholdPieces::FiveCrossing *StrongholdPieces::FiveCrossing::createPiece(list { BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -3, 0, width, height, depth, direction); - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1576,7 +1572,7 @@ StrongholdPieces::PortalRoom *StrongholdPieces::PortalRoom::createPiece(list<Str BoundingBox *box = BoundingBox::orientBox(footX, footY, footZ, -4, -1, 0, width, height, depth, direction); // 4J Added so that we can check that Portals stay within the bounds of the world (which they ALWAYS should anyway) - StartPiece *startPiece = NULL; + StartPiece *startPiece = NULL; if(pieces != NULL) startPiece = ((StrongholdPieces::StartPiece *) pieces->front()); if (!isOkBox(box, startPiece) || StructurePiece::findCollisionPiece(pieces, box) != NULL) @@ -1684,7 +1680,7 @@ bool StrongholdPieces::PortalRoom::postProcess(Level *level, Random *random, Bou if (chunkBB->isInside(x, y, z)) { // 4J Stu - The mob spawner location is close enough for the map icon display, and this ensures that we only need to set the position once - app.AddTerrainFeaturePosition(eTerrainFeature_StrongholdEndPortal,x,z); + app.AddTerrainFeaturePosition(eTerrainFeature_StrongholdEndPortal,x,z); level->getLevelData()->setXStrongholdEndPortal(x); level->getLevelData()->setZStrongholdEndPortal(z); level->getLevelData()->setHasStrongholdEndPortal(); diff --git a/Minecraft.World/StructureFeature.cpp b/Minecraft.World/StructureFeature.cpp index 41ee5c81..dfb214a5 100644 --- a/Minecraft.World/StructureFeature.cpp +++ b/Minecraft.World/StructureFeature.cpp @@ -16,9 +16,9 @@ StructureFeature::StructureFeature() StructureFeature::~StructureFeature() { - for( AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); it++ ) + for(auto& it : cachedStructures) { - delete it->second; + delete it.second; } } @@ -58,9 +58,9 @@ bool StructureFeature::postProcess(Level *level, Random *random, int chunkX, int int cz = (chunkZ << 4); // + 8; bool intersection = false; - for( AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); it++ ) + for(auto& it : cachedStructures) { - StructureStart *structureStart = it->second; + StructureStart *structureStart = it.second; if (structureStart->isValid()) { @@ -84,15 +84,15 @@ bool StructureFeature::isIntersection(int cellX, int cellZ) { restoreSavedData(level); - for( AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); it++ ) + for(auto & it : cachedStructures) { - StructureStart *structureStart = it->second; + StructureStart *structureStart = it.second; if (structureStart->isValid()) { if (structureStart->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) { - AUTO_VAR(it2, structureStart->getPieces()->begin()); - while( it2 != structureStart->getPieces()->end() ) + auto it2 = structureStart->getPieces()->begin(); + while( it2 != structureStart->getPieces()->end() ) { StructurePiece *next = *it2++; if (next->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) @@ -106,7 +106,7 @@ bool StructureFeature::isIntersection(int cellX, int cellZ) return false; } -bool StructureFeature::isInsideFeature(int cellX, int cellY, int cellZ) +bool StructureFeature::isInsideFeature(int cellX, int cellY, int cellZ) { restoreSavedData(level); return getStructureAt(cellX, cellY, cellZ) != NULL; @@ -114,14 +114,13 @@ bool StructureFeature::isInsideFeature(int cellX, int cellY, int cellZ) StructureStart *StructureFeature::getStructureAt(int cellX, int cellY, int cellZ) { - //for (StructureStart structureStart : cachedStructures.values()) - for(AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); ++it) + for(auto& it : cachedStructures) { - StructureStart *pStructureStart = it->second; + StructureStart *pStructureStart = it.second; - if (pStructureStart->isValid()) + if (pStructureStart->isValid()) { - if (pStructureStart->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) + if (pStructureStart->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)) { /* Iterator<StructurePiece> it = structureStart.getPieces().iterator(); @@ -133,9 +132,8 @@ StructureStart *StructureFeature::getStructureAt(int cellX, int cellY, int cellZ */ list<StructurePiece *> *pieces=pStructureStart->getPieces(); - for ( AUTO_VAR(it2, pieces->begin()); it2 != pieces->end(); it2++ ) + for (auto& piece : *pieces) { - StructurePiece* piece = *it2; if ( piece->getBoundingBox()->isInside(cellX, cellY, cellZ) ) { return pStructureStart; @@ -151,9 +149,9 @@ bool StructureFeature::isInsideBoundingFeature(int cellX, int cellY, int cellZ) { restoreSavedData(level); - for(AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); ++it) + for(auto& it : cachedStructures) { - StructureStart *structureStart = it->second; + StructureStart *structureStart = it.second; if (structureStart->isValid()) { return (structureStart->getBoundingBox()->intersects(cellX, cellZ, cellX, cellZ)); @@ -162,7 +160,7 @@ bool StructureFeature::isInsideBoundingFeature(int cellX, int cellY, int cellZ) return false; } -TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, int cellY, int cellZ) +TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, int cellY, int cellZ) { // this is a hack that will "force" the feature to generate positions // even if the player hasn't generated new chunks yet @@ -182,11 +180,11 @@ TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, i double minDistance = DBL_MAX; TilePos *selected = NULL; - for(AUTO_VAR(it, cachedStructures.begin()); it != cachedStructures.end(); ++it) + for(auto& it : cachedStructures) { - StructureStart *pStructureStart = it->second; + StructureStart *pStructureStart = it.second; - if (pStructureStart->isValid()) + if (pStructureStart->isValid()) { //StructurePiece *pStructurePiece = pStructureStart->getPieces().get(0); @@ -198,37 +196,37 @@ TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, i int dz = locatorPosition->z - cellZ; double dist = dx * dx + dy * dy + dz * dz; - if (dist < minDistance) + if (dist < minDistance) { minDistance = dist; selected = locatorPosition; } } } - if (selected != NULL) + if (selected != NULL) { return selected; - } - else + } + else { vector<TilePos> *guesstimatedFeaturePositions = getGuesstimatedFeaturePositions(); - if (guesstimatedFeaturePositions != NULL) + if (guesstimatedFeaturePositions != NULL) { TilePos *pSelectedPos = new TilePos(0,0,0); - for(AUTO_VAR(it, guesstimatedFeaturePositions->begin()); it != guesstimatedFeaturePositions->end(); ++it) + for(const auto& it : *guesstimatedFeaturePositions) { - int dx = (*it).x - cellX; - int dy = (*it).y - cellY; - int dz = (*it).z - cellZ; + int dx = it.x - cellX; + int dy = it.y - cellY; + int dz = it.z - cellZ; double dist = dx * dx + dy * dy + dz * dz; - if (dist < minDistance) + if (dist < minDistance) { minDistance = dist; - pSelectedPos->x = (*it).x; - pSelectedPos->y = (*it).y; - pSelectedPos->z = (*it).z; + pSelectedPos->x = it.x; + pSelectedPos->y = it.y; + pSelectedPos->z = it.z; } } delete guesstimatedFeaturePositions; @@ -238,7 +236,7 @@ TilePos *StructureFeature::getNearestGeneratedFeature(Level *level, int cellX, i return NULL; } -vector<TilePos> *StructureFeature::getGuesstimatedFeaturePositions() +vector<TilePos> *StructureFeature::getGuesstimatedFeaturePositions() { return NULL; } @@ -260,10 +258,9 @@ void StructureFeature::restoreSavedData(Level *level) CompoundTag *fullTag = savedData->getFullTag(); vector<Tag *> *allTags = fullTag->getAllTags(); - for (AUTO_VAR(it,allTags->begin()); it != allTags->end(); ++it) + for ( Tag *featureTag : *allTags ) { - Tag *featureTag = *it; - if (featureTag->getId() == Tag::TAG_Compound) + if ( featureTag && featureTag->getId() == Tag::TAG_Compound) { CompoundTag *ct = (CompoundTag *) featureTag; diff --git a/Minecraft.World/StructureFeatureIO.cpp b/Minecraft.World/StructureFeatureIO.cpp index d910cf3d..3e73b028 100644 --- a/Minecraft.World/StructureFeatureIO.cpp +++ b/Minecraft.World/StructureFeatureIO.cpp @@ -37,8 +37,8 @@ void StructureFeatureIO::staticCtor() wstring StructureFeatureIO::getEncodeId(StructureStart *start) { - AUTO_VAR(it, startClassIdMap.find( start->GetType() ) ); - if(it != startClassIdMap.end()) + auto it = startClassIdMap.find(start->GetType()); + if(it != startClassIdMap.end()) { return it->second; } @@ -50,8 +50,8 @@ wstring StructureFeatureIO::getEncodeId(StructureStart *start) wstring StructureFeatureIO::getEncodeId(StructurePiece *piece) { - AUTO_VAR(it, pieceClassIdMap.find( piece->GetType() ) ); - if(it != pieceClassIdMap.end()) + auto it = pieceClassIdMap.find(piece->GetType()); + if(it != pieceClassIdMap.end()) { return it->second; } @@ -65,8 +65,8 @@ StructureStart *StructureFeatureIO::loadStaticStart(CompoundTag *tag, Level *lev { StructureStart *start = NULL; - AUTO_VAR(it, startIdClassMap.find( tag->getString(L"id") ) ); - if(it != startIdClassMap.end()) + auto it = startIdClassMap.find(tag->getString(L"id")); + if(it != startIdClassMap.end()) { start = (it->second)(); } @@ -86,8 +86,8 @@ StructurePiece *StructureFeatureIO::loadStaticPiece(CompoundTag *tag, Level *lev { StructurePiece *piece = NULL; - AUTO_VAR(it, pieceIdClassMap.find( tag->getString(L"id") ) ); - if(it != pieceIdClassMap.end()) + auto it = pieceIdClassMap.find(tag->getString(L"id")); + if(it != pieceIdClassMap.end()) { piece = (it->second)(); } diff --git a/Minecraft.World/StructureFeatureSavedData.cpp b/Minecraft.World/StructureFeatureSavedData.cpp index 6c2aa412..6d580d02 100644 --- a/Minecraft.World/StructureFeatureSavedData.cpp +++ b/Minecraft.World/StructureFeatureSavedData.cpp @@ -38,7 +38,7 @@ void StructureFeatureSavedData::putFeatureTag(CompoundTag *tag, int chunkX, int wstring StructureFeatureSavedData::createFeatureTagId(int chunkX, int chunkZ) { - return L"[" + _toString<int>(chunkX) + L"," + _toString<int>(chunkZ) + L"]"; + return L"[" + std::to_wstring(chunkX) + L"," + std::to_wstring(chunkZ) + L"]"; } CompoundTag *StructureFeatureSavedData::getFullTag() diff --git a/Minecraft.World/StructurePiece.cpp b/Minecraft.World/StructurePiece.cpp index cd483a6e..85a19ab4 100644 --- a/Minecraft.World/StructurePiece.cpp +++ b/Minecraft.World/StructurePiece.cpp @@ -14,7 +14,7 @@ #include "DoorItem.h" /** -* +* * A structure piece is a construction or room, located somewhere in the world * with a given orientatino (out of Direction.java). Structure pieces have a * bounding box that says where the piece is located and its bounds, and the @@ -113,10 +113,9 @@ bool StructurePiece::isInChunk( ChunkPos* pos ) StructurePiece* StructurePiece::findCollisionPiece( list< StructurePiece* > *pieces, BoundingBox* box ) { - for ( AUTO_VAR(it, pieces->begin()); it != pieces->end(); it++ ) + for (auto& piece : *pieces) { - StructurePiece* piece = *it; - if ( piece->getBoundingBox() != NULL && piece->getBoundingBox()->intersects( box ) ) + if ( piece && piece->getBoundingBox() && piece->getBoundingBox()->intersects( box ) ) { return piece; } @@ -125,7 +124,7 @@ StructurePiece* StructurePiece::findCollisionPiece( list< StructurePiece* > *pie } // 4J-PB - Added from 1.2.3 -TilePos *StructurePiece::getLocatorPosition() +TilePos *StructurePiece::getLocatorPosition() { return new TilePos(boundingBox->getXCenter(), boundingBox->getYCenter(), boundingBox->getZCenter()); } @@ -559,7 +558,7 @@ void StructurePiece::placeBlock( Level* level, int block, int data, int x, int y * The purpose of this method is to wrap the getTile call on Level, in order * to prevent the level from generating chunks that shouldn't be loaded yet. * Returns 0 if the call is out of bounds. -* +* * @param level * @param x * @param y diff --git a/Minecraft.World/StructureStart.cpp b/Minecraft.World/StructureStart.cpp index 9e5ba0a8..3f22b4a7 100644 --- a/Minecraft.World/StructureStart.cpp +++ b/Minecraft.World/StructureStart.cpp @@ -21,9 +21,9 @@ StructureStart::StructureStart(int x, int z) StructureStart::~StructureStart() { - for(AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) + for(auto& piece : pieces) { - delete (*it); + delete piece; } delete boundingBox; } @@ -40,9 +40,9 @@ list<StructurePiece *> *StructureStart::getPieces() void StructureStart::postProcess(Level *level, Random *random, BoundingBox *chunkBB) { - AUTO_VAR(it, pieces.begin()); + auto it = pieces.begin(); - while( it != pieces.end() ) + while( it != pieces.end() ) { if( (*it)->getBoundingBox()->intersects(chunkBB) && !(*it)->postProcess(level, random, chunkBB)) { @@ -61,9 +61,8 @@ void StructureStart::calculateBoundingBox() { boundingBox = BoundingBox::getUnknownBox(); - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) + for(auto& piece : pieces) { - StructurePiece *piece = *it; boundingBox->expand(piece->getBoundingBox()); } } @@ -78,9 +77,8 @@ CompoundTag *StructureStart::createTag(int chunkX, int chunkZ) tag->put(L"BB", boundingBox->createTag(L"BB")); ListTag<CompoundTag> *childrenTags = new ListTag<CompoundTag>(L"Children"); - for(AUTO_VAR(it, pieces.begin()); it != pieces.end(); ++it) + for(auto& piece : pieces) { - StructurePiece *piece = *it; childrenTags->add(piece->createTag()); } tag->put(L"Children", childrenTags); @@ -133,9 +131,8 @@ void StructureStart::moveBelowSeaLevel(Level *level, Random *random, int offset) // move all bounding boxes int dy = y1Pos - boundingBox->y1; boundingBox->move(0, dy, 0); - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) + for(auto& piece : pieces) { - StructurePiece *piece = *it; piece->getBoundingBox()->move(0, dy, 0); } } @@ -157,9 +154,8 @@ void StructureStart::moveInsideHeights(Level *level, Random *random, int lowestA // move all bounding boxes int dy = y0Pos - boundingBox->y0; boundingBox->move(0, dy, 0); - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) + for(auto& piece : pieces) { - StructurePiece *piece = *it; piece->getBoundingBox()->move(0, dy, 0); } } diff --git a/Minecraft.World/SynchedEntityData.cpp b/Minecraft.World/SynchedEntityData.cpp index e6bb9ec7..655fa0c3 100644 --- a/Minecraft.World/SynchedEntityData.cpp +++ b/Minecraft.World/SynchedEntityData.cpp @@ -85,11 +85,11 @@ void SynchedEntityData::checkId(int id) #if 0 if (id > MAX_ID_VALUE) { - throw new IllegalArgumentException(L"Data value id is too big with " + _toString<int>(id) + L"! (Max is " + _toString<int>(MAX_ID_VALUE) + L")"); + throw new IllegalArgumentException(L"Data value id is too big with " + std::to_wstring(id) + L"! (Max is " + std::to_wstring(MAX_ID_VALUE) + L")"); } if (itemsById.find(id) != itemsById.end()) { - throw new IllegalArgumentException(L"Duplicate id value for " + _toString<int>(id) + L"!"); + throw new IllegalArgumentException(L"Duplicate id value for " + std::to_wstring(id) + L"!"); } #endif } @@ -223,12 +223,10 @@ bool SynchedEntityData::isDirty() void SynchedEntityData::pack(vector<shared_ptr<DataItem> > *items, DataOutputStream *output) // TODO throws IOException { - if (items != NULL) + if (items) { - AUTO_VAR(itEnd, items->end()); - for (AUTO_VAR(it, items->begin()); it != itEnd; it++) + for (auto& dataItem : *items) { - shared_ptr<DataItem> dataItem = *it; writeDataItem(output, dataItem); } } @@ -311,7 +309,7 @@ void SynchedEntityData::writeDataItem(DataOutputStream *output, shared_ptr<DataI { case TYPE_BYTE: output->writeByte( dataItem->getValue_byte()); - break; + break; case TYPE_INT: output->writeInt( dataItem->getValue_int()); break; @@ -324,13 +322,13 @@ void SynchedEntityData::writeDataItem(DataOutputStream *output, shared_ptr<DataI case TYPE_STRING: Packet::writeUtf(dataItem->getValue_wstring(), output); break; - case TYPE_ITEMINSTANCE: + case TYPE_ITEMINSTANCE: { shared_ptr<ItemInstance> instance = (shared_ptr<ItemInstance> )dataItem->getValue_itemInstance(); Packet::writeItem(instance, output); } break; - + default: assert(false); // 4J - not implemented break; @@ -387,7 +385,7 @@ vector<shared_ptr<SynchedEntityData::DataItem> > *SynchedEntityData::unpack(Data case TYPE_STRING: item = shared_ptr<DataItem>( new DataItem(itemType, itemId, Packet::readUtf(input, MAX_STRING_DATA_LENGTH)) ); break; - case TYPE_ITEMINSTANCE: + case TYPE_ITEMINSTANCE: { item = shared_ptr<DataItem>(new DataItem(itemType, itemId, Packet::readItem(input))); } @@ -408,17 +406,14 @@ vector<shared_ptr<SynchedEntityData::DataItem> > *SynchedEntityData::unpack(Data /** * Assigns values from a list of data items. -* +* * @param items */ void SynchedEntityData::assignValues(vector<shared_ptr<DataItem> > *items) { - AUTO_VAR(itEnd, items->end()); - for (AUTO_VAR(it, items->begin()); it != itEnd; it++) + for (auto& item : *items) { - shared_ptr<DataItem> item = *it; - shared_ptr<DataItem> itemFromId = itemsById[item->getId()]; if( itemFromId != NULL ) { @@ -479,7 +474,7 @@ int SynchedEntityData::getSizeInBytes() { case TYPE_BYTE: size += 1; - break; + break; case TYPE_SHORT: size += 2; break; diff --git a/Minecraft.World/TakeFlowerGoal.cpp b/Minecraft.World/TakeFlowerGoal.cpp index feb87093..48db34d3 100644 --- a/Minecraft.World/TakeFlowerGoal.cpp +++ b/Minecraft.World/TakeFlowerGoal.cpp @@ -24,24 +24,31 @@ bool TakeFlowerGoal::canUse() if (!villager->level->isDay()) return false; vector<shared_ptr<Entity> > *golems = villager->level->getEntitiesOfClass(typeid(VillagerGolem), villager->bb->grow(6, 2, 6)); - if (golems->size() == 0) + if ( golems == nullptr ) + return false; + + if ( golems->size() == 0) { delete golems; return false; } - //for (Entity e : golems) - for(AUTO_VAR(it,golems->begin()); it != golems->end(); ++it) - { - shared_ptr<VillagerGolem> vg = dynamic_pointer_cast<VillagerGolem>(*it); - if (vg->getOfferFlowerTick() > 0) + for (auto entity : *golems ) + { + if ( entity == nullptr ) + continue; + + // safe to call std::static_pointer_cast because of getEntitiesOfClass(typeid(VillagerGolem), ...) makes sure we do not have entities of any other type. + auto vg = std::static_pointer_cast<VillagerGolem>(entity); + if ( vg && vg->getOfferFlowerTick() > 0) { - golem = weak_ptr<VillagerGolem>(vg); - break; + golem = vg; + delete golems; + return true; } } delete golems; - return golem.lock() != NULL; + return false; } bool TakeFlowerGoal::canContinueToUse() diff --git a/Minecraft.World/TextureAndGeometryPacket.cpp b/Minecraft.World/TextureAndGeometryPacket.cpp index 70f2f516..d28fc862 100644 --- a/Minecraft.World/TextureAndGeometryPacket.cpp +++ b/Minecraft.World/TextureAndGeometryPacket.cpp @@ -6,7 +6,7 @@ -TextureAndGeometryPacket::TextureAndGeometryPacket() +TextureAndGeometryPacket::TextureAndGeometryPacket() { this->textureName = L""; this->dwTextureBytes = 0; @@ -16,21 +16,21 @@ TextureAndGeometryPacket::TextureAndGeometryPacket() uiAnimOverrideBitmask=0; } -TextureAndGeometryPacket::~TextureAndGeometryPacket() +TextureAndGeometryPacket::~TextureAndGeometryPacket() { // can't free these - they're used elsewhere // if(this->BoxDataA!=NULL) // { // delete [] this->BoxDataA; // } -// +// // if(this->pbData!=NULL) // { // delete [] this->pbData; // } } -TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes) +TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes) { this->textureName = textureName; @@ -47,7 +47,7 @@ TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, P this->uiAnimOverrideBitmask=0; } -TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes, DLCSkinFile *pDLCSkinFile) +TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes, DLCSkinFile *pDLCSkinFile) { this->textureName = textureName; @@ -68,11 +68,10 @@ TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, P vector<SKIN_BOX *> *pSkinBoxes=pDLCSkinFile->getAdditionalBoxes(); int iCount=0; - for(AUTO_VAR(it, pSkinBoxes->begin());it != pSkinBoxes->end(); ++it) + for(auto& pSkinBox : *pSkinBoxes) { - SKIN_BOX *pSkinBox=*it; this->BoxDataA[iCount++]=*pSkinBox; - } + } } else { @@ -80,7 +79,7 @@ TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, P } } -TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes,vector<SKIN_BOX *> *pvSkinBoxes, unsigned int uiAnimOverrideBitmask) +TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, PBYTE pbData, DWORD dwBytes,vector<SKIN_BOX *> *pvSkinBoxes, unsigned int uiAnimOverrideBitmask) { this->textureName = textureName; @@ -105,16 +104,15 @@ TextureAndGeometryPacket::TextureAndGeometryPacket(const wstring &textureName, P this->BoxDataA= new SKIN_BOX [this->dwBoxC]; int iCount=0; - for(AUTO_VAR(it, pvSkinBoxes->begin());it != pvSkinBoxes->end(); ++it) + for(auto& pSkinBox : *pvSkinBoxes) { - SKIN_BOX *pSkinBox=*it; this->BoxDataA[iCount++]=*pSkinBox; - } + } } } -void TextureAndGeometryPacket::handle(PacketListener *listener) +void TextureAndGeometryPacket::handle(PacketListener *listener) { listener->handleTextureAndGeometry(shared_from_this()); } @@ -157,7 +155,7 @@ void TextureAndGeometryPacket::read(DataInputStream *dis) //throws IOException } } -void TextureAndGeometryPacket::write(DataOutputStream *dos) //throws IOException +void TextureAndGeometryPacket::write(DataOutputStream *dos) //throws IOException { dos->writeUTF(textureName); dos->writeInt(dwSkinID); @@ -183,7 +181,7 @@ void TextureAndGeometryPacket::write(DataOutputStream *dos) //throws IOException } } -int TextureAndGeometryPacket::getEstimatedSize() +int TextureAndGeometryPacket::getEstimatedSize() { return 4096+ +sizeof(int) + sizeof(float)*8*4; } diff --git a/Minecraft.World/ThrownPotion.cpp b/Minecraft.World/ThrownPotion.cpp index f99a0ecb..69c096a2 100644 --- a/Minecraft.World/ThrownPotion.cpp +++ b/Minecraft.World/ThrownPotion.cpp @@ -14,7 +14,7 @@ const double ThrownPotion::SPLASH_RANGE = 4.0; const double ThrownPotion::SPLASH_RANGE_SQ = ThrownPotion::SPLASH_RANGE * ThrownPotion::SPLASH_RANGE; void ThrownPotion::_init() -{ +{ // 4J Stu - This function call had to be moved here from the Entity ctor to ensure that // the derived version of the function is called this->defineSynchedData(); @@ -95,11 +95,9 @@ void ThrownPotion::onHit(HitResult *res) if (entitiesOfClass != NULL && !entitiesOfClass->empty()) { - //for (Entity e : entitiesOfClass) - for(AUTO_VAR(it, entitiesOfClass->begin()); it != entitiesOfClass->end(); ++it) + for(auto & it : *entitiesOfClass) { - //shared_ptr<Entity> e = *it; - shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( *it ); + shared_ptr<LivingEntity> e = dynamic_pointer_cast<LivingEntity>( it ); double dist = distanceToSqr(e); if (dist < SPLASH_RANGE_SQ) { @@ -110,9 +108,8 @@ void ThrownPotion::onHit(HitResult *res) } //for (MobEffectInstance effect : mobEffects) - for(AUTO_VAR(itMEI, mobEffects->begin()); itMEI != mobEffects->end(); ++itMEI) + for(auto& effect : *mobEffects) { - MobEffectInstance *effect = *itMEI; int id = effect->getId(); if (MobEffect::effects[id]->isInstantenous()) { diff --git a/Minecraft.World/Tile.cpp b/Minecraft.World/Tile.cpp index df4e407e..a07fdfe4 100644 --- a/Minecraft.World/Tile.cpp +++ b/Minecraft.World/Tile.cpp @@ -17,14 +17,14 @@ #include "net.minecraft.h" #include "Tile.h" -wstring Tile::TILE_DESCRIPTION_PREFIX = L"Tile."; +wstring Tile::TILE_DESCRIPTION_PREFIX = L"Tile."; const float Tile::INDESTRUCTIBLE_DESTROY_TIME = -1.0f; Tile::SoundType *Tile::SOUND_NORMAL = NULL; Tile::SoundType *Tile::SOUND_WOOD = NULL; Tile::SoundType *Tile::SOUND_GRAVEL = NULL; -Tile::SoundType *Tile::SOUND_GRASS = NULL; +Tile::SoundType *Tile::SOUND_GRASS = NULL; Tile::SoundType *Tile::SOUND_STONE = NULL; Tile::SoundType *Tile::SOUND_METAL = NULL; Tile::SoundType *Tile::SOUND_GLASS = NULL; @@ -204,7 +204,7 @@ ComparatorTile *Tile::comparator_off = NULL; ComparatorTile *Tile::comparator_on = NULL; DaylightDetectorTile *Tile::daylightDetector = NULL; -Tile *Tile::redstoneBlock = NULL; +Tile *Tile::redstoneBlock = NULL; Tile *Tile::netherQuartz = NULL; HopperTile *Tile::hopper = NULL; @@ -427,7 +427,7 @@ void Tile::staticCtor() Tile::comparator_on = (ComparatorTile *) (new ComparatorTile(150, true)) ->setDestroyTime(0.0f)->setLightEmission(10 / 16.0f)->setSoundType(SOUND_WOOD)->setIconName(L"comparator_on")->setDescriptionId(IDS_TILE_COMPARATOR)->setUseDescriptionId(IDS_DESC_COMPARATOR); Tile::daylightDetector = (DaylightDetectorTile *) (new DaylightDetectorTile(151))->setDestroyTime(0.2f)->setSoundType(SOUND_WOOD)->setIconName(L"daylight_detector")->setDescriptionId(IDS_TILE_DAYLIGHT_DETECTOR)->setUseDescriptionId(IDS_DESC_DAYLIGHT_DETECTOR); - Tile::redstoneBlock = (new PoweredMetalTile(152)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, Item::eMaterial_redstone)->setDestroyTime(5.0f)->setExplodeable(10)->setSoundType(SOUND_METAL)->setIconName(L"redstone_block")->setDescriptionId(IDS_TILE_REDSTONE_BLOCK)->setUseDescriptionId(IDS_DESC_REDSTONE_BLOCK); + Tile::redstoneBlock = (new PoweredMetalTile(152)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_block, Item::eMaterial_redstone)->setDestroyTime(5.0f)->setExplodeable(10)->setSoundType(SOUND_METAL)->setIconName(L"redstone_block")->setDescriptionId(IDS_TILE_REDSTONE_BLOCK)->setUseDescriptionId(IDS_DESC_REDSTONE_BLOCK); Tile::netherQuartz = (new OreTile(153)) ->setDestroyTime(3.0f)->setExplodeable(5)->setSoundType(SOUND_STONE)->setIconName(L"quartz_ore")->setDescriptionId(IDS_TILE_NETHER_QUARTZ)->setUseDescriptionId(IDS_DESC_NETHER_QUARTZ_ORE); Tile::hopper = (HopperTile *)(new HopperTile(154)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_redstoneContainer, Item::eMaterial_undefined)->setDestroyTime(3.0f)->setExplodeable(8)->setSoundType(SOUND_WOOD)->setIconName(L"hopper")->setDescriptionId(IDS_TILE_HOPPER)->setUseDescriptionId(IDS_DESC_HOPPER); Tile::quartzBlock = (new QuartzBlockTile(155)) ->setBaseItemTypeAndMaterial(Item::eBaseItemType_structblock, Item::eMaterial_quartz)->setSoundType(SOUND_STONE)->setDestroyTime(0.8f)->setIconName(L"quartz_block")->setDescriptionId(IDS_TILE_QUARTZ_BLOCK)->setUseDescriptionId(IDS_DESC_QUARTZ_BLOCK); @@ -819,7 +819,7 @@ AABB *Tile::getTileAABB(Level *level, int x, int y, int z) return AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + tls->yy1, z + tls->zz1); } -void Tile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, shared_ptr<Entity> source) +void Tile::addAABBs(Level *level, int x, int y, int z, AABB *box, AABBList *boxes, shared_ptr<Entity> source) { AABB *aabb = getAABB(level, x, y, z); if (aabb != NULL && box->intersects(aabb)) boxes->push_back(aabb); @@ -1413,7 +1413,7 @@ Tile *Tile::setIconName(const wstring &iconName) wstring Tile::getIconName() { - return iconName.empty() ? L"MISSING_ICON_TILE_" + _toString<int>(id) + L"_" + _toString<int>(descriptionId) : iconName; + return iconName.empty() ? L"MISSING_ICON_TILE_" + std::to_wstring(id) + L"_" + std::to_wstring(descriptionId) : iconName; } void Tile::registerIcons(IconRegister *iconRegister) @@ -1527,26 +1527,26 @@ Tile::SoundType::SoundType(eMATERIALSOUND_TYPE eMaterialSound, float volume, flo } float Tile::SoundType::getVolume() const -{ - return volume; +{ + return volume; } float Tile::SoundType::getPitch() const -{ - return pitch; +{ + return pitch; } //wstring getBreakSound() const { return breakSound; } //wstring getStepSound() const { return stepSound; } int Tile::SoundType::getBreakSound() const -{ - return iBreakSound; +{ + return iBreakSound; } int Tile::SoundType::getStepSound() const -{ - return iStepSound; +{ + return iStepSound; } int Tile::SoundType::getPlaceSound() const -{ - return iPlaceSound; +{ + return iPlaceSound; } diff --git a/Minecraft.World/TileEntity.cpp b/Minecraft.World/TileEntity.cpp index ded0c665..1eb9cab2 100644 --- a/Minecraft.World/TileEntity.cpp +++ b/Minecraft.World/TileEntity.cpp @@ -78,8 +78,8 @@ void TileEntity::load(CompoundTag *tag) void TileEntity::save(CompoundTag *tag) { - AUTO_VAR(it, classIdMap.find( this->GetType() )); - if ( it == classIdMap.end() ) + auto it = classIdMap.find(this->GetType()); + if ( it == classIdMap.end() ) { // TODO 4J Stu - Some sort of exception handling //throw new RuntimeException(this->getClass() + " is missing a mapping! This is a bug!"); @@ -98,17 +98,9 @@ void TileEntity::tick() shared_ptr<TileEntity> TileEntity::loadStatic(CompoundTag *tag) { shared_ptr<TileEntity> entity = nullptr; - - //try - //{ - AUTO_VAR(it, idCreateMap.find(tag->getString(L"id"))); - if (it != idCreateMap.end() ) entity = shared_ptr<TileEntity>(it->second()); - //} - //catch (Exception e) - //{ - // TODO 4J Stu - Exception handling? - // e->printStackTrace(); - //} + auto it = idCreateMap.find(tag->getString(L"id")); + if (it != idCreateMap.end()) + entity = shared_ptr<TileEntity>(it->second()); if (entity != NULL) { entity->load(tag); diff --git a/Minecraft.World/TripWireTile.cpp b/Minecraft.World/TripWireTile.cpp index 2fd7da6c..b8ae9f33 100644 --- a/Minecraft.World/TripWireTile.cpp +++ b/Minecraft.World/TripWireTile.cpp @@ -13,7 +13,7 @@ TripWireTile::TripWireTile(int id) : Tile(id, Material::decoration, isSolidRende int TripWireTile::getTickDelay(Level *level) { - // 4J: Increased (x2); quick update caused problems with shared + // 4J: Increased (x2); quick update caused problems with shared // data between client and server. return 20; // 10; } @@ -164,15 +164,14 @@ void TripWireTile::checkPressed(Level *level, int x, int y, int z) int data = level->getData(x, y, z); bool wasPressed = (data & MASK_POWERED) == MASK_POWERED; bool shouldBePressed = false; - + ThreadStorage *tls = (ThreadStorage *)TlsGetValue(Tile::tlsIdxShape); vector<shared_ptr<Entity> > *entities = level->getEntities(nullptr, AABB::newTemp(x + tls->xx0, y + tls->yy0, z + tls->zz0, x + tls->xx1, y + tls->yy1, z + tls->zz1)); if (!entities->empty()) { - for (AUTO_VAR(it, entities->begin()); it != entities->end(); ++it) + for (auto& e : *entities) { - shared_ptr<Entity> e = *it; - if (!e->isIgnoringTileTriggers()) + if ( e && !e->isIgnoringTileTriggers()) { shouldBePressed = true; break; diff --git a/Minecraft.World/UpdateAttributesPacket.cpp b/Minecraft.World/UpdateAttributesPacket.cpp index 45c20575..e80ebe4e 100644 --- a/Minecraft.World/UpdateAttributesPacket.cpp +++ b/Minecraft.World/UpdateAttributesPacket.cpp @@ -13,9 +13,8 @@ UpdateAttributesPacket::UpdateAttributesPacket(int entityId, unordered_set<Attri { this->entityId = entityId; - for (AUTO_VAR(it,values->begin()); it != values->end(); ++it) + for (AttributeInstance *value : *values) { - AttributeInstance *value = *it; unordered_set<AttributeModifier*> mods; value->getModifiers(mods); attributes.insert(new AttributeSnapshot(value->getAttribute()->getId(), value->getBaseValue(), &mods)); @@ -25,9 +24,9 @@ UpdateAttributesPacket::UpdateAttributesPacket(int entityId, unordered_set<Attri UpdateAttributesPacket::~UpdateAttributesPacket() { // Delete modifiers - these are always copies, either on construction or on read - for(AUTO_VAR(it,attributes.begin()); it != attributes.end(); ++it) - { - delete (*it); + for(auto& attribute : attributes) + { + delete attribute; } } @@ -54,9 +53,9 @@ void UpdateAttributesPacket::read(DataInputStream *dis) attributes.insert(new AttributeSnapshot(id, base, &modifiers)); // modifiers is copied in AttributeSnapshot ctor so delete contents - for(AUTO_VAR(it, modifiers.begin()); it != modifiers.end(); ++it) + for(auto& modifier : modifiers) { - delete *it; + delete modifier; } } } @@ -66,19 +65,16 @@ void UpdateAttributesPacket::write(DataOutputStream *dos) dos->writeInt(entityId); dos->writeInt(attributes.size()); - for(AUTO_VAR(it, attributes.begin()); it != attributes.end(); ++it) + for(auto& attribute : attributes) { - AttributeSnapshot *attribute = (*it); - unordered_set<AttributeModifier *> *modifiers = attribute->getModifiers(); dos->writeShort(attribute->getId()); dos->writeDouble(attribute->getBase()); dos->writeShort(modifiers->size()); - for (AUTO_VAR(it2, modifiers->begin()); it2 != modifiers->end(); ++it2) + for (auto& modifier : *modifiers) { - AttributeModifier *modifier = (*it2); dos->writeInt(modifier->getId()); dos->writeDouble(modifier->getAmount()); dos->writeByte(modifier->getOperation()); @@ -111,17 +107,17 @@ UpdateAttributesPacket::AttributeSnapshot::AttributeSnapshot(eATTRIBUTE_ID id, d this->id = id; this->base = base; - for(AUTO_VAR(it,modifiers->begin()); it != modifiers->end(); ++it) + for(auto& modifier : *modifiers) { - this->modifiers.insert( new AttributeModifier((*it)->getId(), (*it)->getAmount(), (*it)->getOperation())); + this->modifiers.insert( new AttributeModifier(modifier->getId(), modifier->getAmount(), modifier->getOperation())); } } UpdateAttributesPacket::AttributeSnapshot::~AttributeSnapshot() { - for(AUTO_VAR(it, modifiers.begin()); it != modifiers.end(); ++it) + for(auto& modifier : modifiers) { - delete (*it); + delete modifier; } } diff --git a/Minecraft.World/Village.cpp b/Minecraft.World/Village.cpp index 507bc717..a72319fe 100644 --- a/Minecraft.World/Village.cpp +++ b/Minecraft.World/Village.cpp @@ -46,9 +46,9 @@ Village::~Village() { delete accCenter; delete center; - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) + for(auto& aggressor : aggressors) { - delete *it; + delete aggressor; } } @@ -181,9 +181,8 @@ shared_ptr<DoorInfo> Village::getClosestDoorInfo(int x, int y, int z) shared_ptr<DoorInfo> closest = nullptr; int closestDistSqr = Integer::MAX_VALUE; //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) + for(auto& dm : doorInfos) { - shared_ptr<DoorInfo> dm = *it; int distSqr = dm->distanceToSqr(x, y, z); if (distSqr < closestDistSqr) { @@ -199,10 +198,8 @@ shared_ptr<DoorInfo>Village::getBestDoorInfo(int x, int y, int z) shared_ptr<DoorInfo> closest = nullptr; int closestDist = Integer::MAX_VALUE; //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) + for(auto& dm : doorInfos) { - shared_ptr<DoorInfo>dm = *it; - int distSqr = dm->distanceToSqr(x, y, z); if (distSqr > 16 * 16) distSqr *= 1000; else distSqr = dm->getBookingsCount(); @@ -221,14 +218,13 @@ bool Village::hasDoorInfo(int x, int y, int z) return getDoorInfo(x, y, z) != NULL; } -shared_ptr<DoorInfo>Village::getDoorInfo(int x, int y, int z) +shared_ptr<DoorInfo> Village::getDoorInfo(int x, int y, int z) { if (center->distSqr(x, y, z) > radius * radius) return nullptr; - //for (DoorInfo di : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) + for( auto& di : doorInfos) { - shared_ptr<DoorInfo> di = *it; - if (di->x == x && di->z == z && abs(di->y - y) <= 1) return di; + if (di->x == x && di->z == z && abs(di->y - y) <= 1) + return di; } return nullptr; } @@ -250,10 +246,8 @@ bool Village::canRemove() void Village::addAggressor(shared_ptr<LivingEntity> mob) { - //for (Aggressor a : aggressors) - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) + for(auto& a : aggressors) { - Aggressor *a = *it; if (a->mob == mob) { a->timeStamp = _tick; @@ -267,10 +261,8 @@ shared_ptr<LivingEntity> Village::getClosestAggressor(shared_ptr<LivingEntity> f { double closestSqr = Double::MAX_VALUE; Aggressor *closest = NULL; - //for (int i = 0; i < aggressors.size(); ++i) - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end(); ++it) + for(auto& a : aggressors) { - Aggressor *a = *it; //aggressors.get(i); double distSqr = a->mob->distanceToSqr(from); if (distSqr > closestSqr) continue; closest = a; @@ -284,10 +276,9 @@ shared_ptr<Player> Village::getClosestBadStandingPlayer(shared_ptr<LivingEntity> double closestSqr = Double::MAX_VALUE; shared_ptr<Player> closest = nullptr; - //for (String player : playerStanding.keySet()) - for(AUTO_VAR(it,playerStanding.begin()); it != playerStanding.end(); ++it) + for(auto& it : playerStanding) { - wstring player = it->first; + wstring player = it.first; if (isVeryBadStanding(player)) { shared_ptr<Player> mob = level->getPlayerByName(player); @@ -306,9 +297,8 @@ shared_ptr<Player> Village::getClosestBadStandingPlayer(shared_ptr<LivingEntity> void Village::updateAggressors() { - //for (Iterator<Aggressor> it = aggressors.iterator(); it.hasNext();) - for(AUTO_VAR(it, aggressors.begin()); it != aggressors.end();) - { + for (auto it = aggressors.begin(); it != aggressors.end();) + { Aggressor *a = *it; //it.next(); if (!a->mob->isAlive() || abs(_tick - a->timeStamp) > 300) { @@ -328,8 +318,8 @@ void Village::updateDoors() bool removed = false; bool resetBookings = level->random->nextInt(50) == 0; //for (Iterator<DoorInfo> it = doorInfos.iterator(); it.hasNext();) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end();) - { + for (auto it = doorInfos.begin(); it != doorInfos.end();) + { shared_ptr<DoorInfo> dm = *it; //it.next(); if (resetBookings) dm->resetBookingCount(); if (!isDoor(dm->x, dm->y, dm->z) || abs(_tick - dm->timeStamp) > 1200) @@ -371,10 +361,9 @@ void Village::calcInfo() center->set(accCenter->x / s, accCenter->y / s, accCenter->z / s); int maxRadiusSqr = 0; //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it, doorInfos.begin()); it != doorInfos.end(); ++it) + for(auto& dm : doorInfos) { - shared_ptr<DoorInfo> dm = *it; - maxRadiusSqr = max(dm->distanceToSqr(center->x, center->y, center->z), maxRadiusSqr); + maxRadiusSqr = std::max<int>(dm->distanceToSqr(center->x, center->y, center->z), maxRadiusSqr); } int doorDist= Villages::MaxDoorDist; // Take into local int for PS4 as max takes a reference to the const int there and then needs the value to exist for the linker radius = max(doorDist, (int) sqrt((float)maxRadiusSqr) + 1); @@ -382,8 +371,8 @@ void Village::calcInfo() int Village::getStanding(const wstring &playerName) { - AUTO_VAR(it,playerStanding.find(playerName)); - if (it != playerStanding.end()) + auto it = playerStanding.find(playerName); + if (it != playerStanding.end()) { return it->second; } @@ -462,9 +451,8 @@ void Village::addAdditonalSaveData(CompoundTag *tag) ListTag<CompoundTag> *doorTags = new ListTag<CompoundTag>(L"Doors"); //for (DoorInfo dm : doorInfos) - for(AUTO_VAR(it,doorInfos.begin()); it != doorInfos.end(); ++it) + for(auto& dm : doorInfos) { - shared_ptr<DoorInfo> dm = *it; CompoundTag *doorTag = new CompoundTag(L"Door"); doorTag->putInt(L"X", dm->x); doorTag->putInt(L"Y", dm->y); @@ -478,12 +466,12 @@ void Village::addAdditonalSaveData(CompoundTag *tag) ListTag<CompoundTag> *playerTags = new ListTag<CompoundTag>(L"Players"); //for (String player : playerStanding.keySet()) - for(AUTO_VAR(it, playerStanding.begin()); it != playerStanding.end(); ++it) + for(auto& it : playerStanding) { - wstring player = it->first; + wstring player = it.first; CompoundTag *playerTag = new CompoundTag(player); playerTag->putString(L"Name", player); - playerTag->putInt(L"S", it->second); + playerTag->putInt(L"S", it.second); playerTags->add(playerTag); } tag->put(L"Players", playerTags); @@ -504,9 +492,8 @@ bool Village::isBreedTimerOk() void Village::rewardAllPlayers(int amount) { - //for (String player : playerStanding.keySet()) - for(AUTO_VAR(it, playerStanding.begin()); it != playerStanding.end(); ++it) + for(auto& it : playerStanding) { - modifyStanding(it->first, amount); + modifyStanding(it.first, amount); } }
\ No newline at end of file diff --git a/Minecraft.World/VillageFeature.cpp b/Minecraft.World/VillageFeature.cpp index 82974c7b..5249256c 100644 --- a/Minecraft.World/VillageFeature.cpp +++ b/Minecraft.World/VillageFeature.cpp @@ -34,15 +34,15 @@ VillageFeature::VillageFeature(unordered_map<wstring, wstring> options, int iXZS { _init(iXZSize); - for (AUTO_VAR(it,options.begin()); it != options.end(); ++it) + for (auto& option : options) { - if (it->first.compare(OPTION_SIZE_MODIFIER) == 0) + if (option.first.compare(OPTION_SIZE_MODIFIER) == 0) { - villageSizeModifier = Mth::getInt(it->second, villageSizeModifier, 0); + villageSizeModifier = Mth::getInt(option.second, villageSizeModifier, 0); } - else if (it->first.compare(OPTION_SPACING) == 0) + else if (option.first.compare(OPTION_SPACING) == 0) { - townSpacing = Mth::getInt(it->second, townSpacing, minTownSeparation + 1); + townSpacing = Mth::getInt(option.second, townSpacing, minTownSeparation + 1); } } } @@ -60,7 +60,7 @@ bool VillageFeature::isFeatureChunk(int x, int z,bool bIsSuperflat) #ifdef _LARGE_WORLDS && level->dimension->getXZSize() < 128 #endif - ) + ) { townSpacing= 16;// 4J change 32; } @@ -135,16 +135,16 @@ VillageFeature::VillageStart::VillageStart(Level *level, Random *random, int chu if (pendingRoads->empty()) { int pos = random->nextInt((int)pendingHouses->size()); - AUTO_VAR(it, pendingHouses->begin() + pos); - StructurePiece *structurePiece = *it; + auto it = pendingHouses->begin() + pos; + StructurePiece *structurePiece = *it; pendingHouses->erase(it); structurePiece->addChildren(startRoom, &pieces, random); } else { int pos = random->nextInt((int)pendingRoads->size()); - AUTO_VAR(it, pendingRoads->begin() + pos); - StructurePiece *structurePiece = *it; + auto it = pendingRoads->begin() + pos; + StructurePiece *structurePiece = *it; pendingRoads->erase(it); structurePiece->addChildren(startRoom, &pieces, random); } @@ -152,13 +152,12 @@ VillageFeature::VillageStart::VillageStart(Level *level, Random *random, int chu calculateBoundingBox(); - int count = 0; - for( AUTO_VAR(it, pieces.begin()); it != pieces.end(); it++ ) + size_t count = 0; + for(auto& piece : pieces) { - StructurePiece *piece = *it; - if (dynamic_cast<VillagePieces::VillageRoadPiece *>(piece) == NULL) + if ( piece && dynamic_cast<VillagePieces::VillageRoadPiece *>(piece) ) { - count++; + ++count; } } valid = count > 2; diff --git a/Minecraft.World/VillagePieces.cpp b/Minecraft.World/VillagePieces.cpp index 0a08d4fb..1737d6e0 100644 --- a/Minecraft.World/VillagePieces.cpp +++ b/Minecraft.World/VillagePieces.cpp @@ -66,8 +66,8 @@ list<VillagePieces::PieceWeight *> *VillagePieces::createPieceSet(Random *random newPieces->push_back(new PieceWeight(VillagePieces::EPieceClass_TwoRoomHouse, 8, Mth::nextInt(random, 0 + villageSize, 3 + villageSize * 2))); // silly way of filtering "infinite" buildings - AUTO_VAR(it, newPieces->begin()); - while( it != newPieces->end() ) + auto it = newPieces->begin(); + while( it != newPieces->end() ) { if( (*it)->maxPlaceCount == 0 ) { @@ -87,9 +87,8 @@ int VillagePieces::updatePieceWeight(list<PieceWeight *> *currentPieces) { bool hasAnyPieces = false; int totalWeight = 0; - for( AUTO_VAR(it, currentPieces->begin()); it != currentPieces->end(); it++ ) + for(auto& piece : *currentPieces) { - PieceWeight *piece = *it; if (piece->maxPlaceCount > 0 && piece->placeCount < piece->maxPlaceCount) { hasAnyPieces = true; @@ -158,13 +157,11 @@ VillagePieces::VillagePiece *VillagePieces::generatePieceFromSmallDoor(StartPiec numAttempts++; int weightSelection = random->nextInt(totalWeight); - for( AUTO_VAR(it, startPiece->pieceSet->begin()); it != startPiece->pieceSet->end(); it++ ) - { - PieceWeight *piece = *it; + for ( PieceWeight *piece : *startPiece->pieceSet ) + { weightSelection -= piece->weight; if (weightSelection < 0) { - if (!piece->doPlace(depth) || (piece == startPiece->previousPiece && startPiece->pieceSet->size() > 1)) { break; @@ -587,9 +584,9 @@ VillagePieces::StartPiece::StartPiece(BiomeSource *biomeSource, int genDepth, Ra VillagePieces::StartPiece::~StartPiece() { - for(AUTO_VAR(it, pieceSet->begin()); it != pieceSet->end(); it++ ) + for(auto& it : *pieceSet) { - delete (*it); + delete it; } delete pieceSet; } @@ -677,14 +674,14 @@ void VillagePieces::StraightRoad::addChildren(StructurePiece *startPiece, list<S { case Direction::NORTH: generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, boundingBox->z0, Direction::EAST, getGenDepth()); - break; - case Direction::SOUTH: + break; + case Direction::SOUTH: generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 + 1, boundingBox->y0, boundingBox->z1 - 2, Direction::EAST, getGenDepth()); - break; - case Direction::EAST: + break; + case Direction::EAST: generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x1 - 2, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); - break; - case Direction::WEST: + break; + case Direction::WEST: generateAndAddRoadPiece((StartPiece *) startPiece, pieces, random, boundingBox->x0, boundingBox->y0, boundingBox->z1 + 1, Direction::SOUTH, getGenDepth()); break; } @@ -989,7 +986,7 @@ bool VillagePieces::SmallTemple::postProcess(Level *level, Random *random, Bound } - for (int z = 0; z < depth; z++) + for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { diff --git a/Minecraft.World/VillageSiege.cpp b/Minecraft.World/VillageSiege.cpp index 0f967595..e3d20ef3 100644 --- a/Minecraft.World/VillageSiege.cpp +++ b/Minecraft.World/VillageSiege.cpp @@ -78,10 +78,8 @@ void VillageSiege::tick() bool VillageSiege::tryToSetupSiege() { vector<shared_ptr<Player> > *players = &level->players; - //for (Player player : players) - for(AUTO_VAR(it, players->begin()); it != players->end(); ++it) + for(auto& player : *players) { - shared_ptr<Player> player = *it; shared_ptr<Village> _village = level->villages->getClosestVillage((int) player->x, (int) player->y, (int) player->z, 1); village = _village; @@ -103,9 +101,8 @@ bool VillageSiege::tryToSetupSiege() overlaps = false; vector<shared_ptr<Village> > *villages = level->villages->getVillages(); //for (Village v : level.villages.getVillages()) - for(AUTO_VAR(itV, villages->begin()); itV != villages->end(); ++itV) + for(auto& v : *villages) { - shared_ptr<Village>v = *itV; if (v == _village) continue; if (v->isInside(spawnX, spawnY, spawnZ)) { @@ -132,16 +129,11 @@ bool VillageSiege::trySpawn() Vec3 *spawnPos = findRandomSpawnPos(spawnX, spawnY, spawnZ); if (spawnPos == NULL) return false; shared_ptr<Zombie> mob; - //try { mob = shared_ptr<Zombie>( new Zombie(level) ); mob->finalizeMobSpawn(NULL); mob->setVillager(false); } - //catch (Exception e) { - // e.printStackTrace(); - // return false; - //} mob->moveTo(spawnPos->x, spawnPos->y, spawnPos->z, level->random->nextFloat() * 360, 0); level->addEntity(mob); shared_ptr<Village> _village = village.lock(); diff --git a/Minecraft.World/Villager.cpp b/Minecraft.World/Villager.cpp index 1fe32a12..18ed7178 100644 --- a/Minecraft.World/Villager.cpp +++ b/Minecraft.World/Villager.cpp @@ -125,9 +125,8 @@ void Villager::serverAiMobStep() if (offers->size() > 0) { //for (MerchantRecipe recipe : offers) - for(AUTO_VAR(it, offers->begin()); it != offers->end(); ++it) + for(auto& recipe : *offers) { - MerchantRecipe *recipe = *it; if (recipe->isDeprecated()) { recipe->increaseMaxUses(random->nextInt(6) + random->nextInt(6) + 2); @@ -615,8 +614,8 @@ shared_ptr<ItemInstance> Villager::getItemTradeInValue(int itemId, Random *rando int Villager::getTradeInValue(int itemId, Random *random) { - AUTO_VAR(it,MIN_MAX_VALUES.find(itemId)); - if (it == MIN_MAX_VALUES.end()) + auto it = MIN_MAX_VALUES.find(itemId); + if (it == MIN_MAX_VALUES.end()) { return 1; } @@ -660,8 +659,8 @@ void Villager::addItemForPurchase(MerchantRecipeList *list, int itemId, Random * int Villager::getPurchaseCost(int itemId, Random *random) { - AUTO_VAR(it,MIN_MAX_PRICES.find(itemId)); - if (it == MIN_MAX_PRICES.end()) + auto it = MIN_MAX_PRICES.find(itemId); + if (it == MIN_MAX_PRICES.end()) { return 1; } @@ -677,7 +676,7 @@ void Villager::handleEntityEvent(byte id) { if (id == EntityEvent::LOVE_HEARTS) { - addParticlesAroundSelf(eParticleType_heart); + addParticlesAroundSelf(eParticleType_heart); } else if (id == EntityEvent::VILLAGER_ANGRY) { diff --git a/Minecraft.World/Villages.cpp b/Minecraft.World/Villages.cpp index ddb0e7dc..e636ed74 100644 --- a/Minecraft.World/Villages.cpp +++ b/Minecraft.World/Villages.cpp @@ -22,17 +22,16 @@ Villages::Villages(Level *level) : SavedData(VILLAGE_FILE_ID) Villages::~Villages() { - for(AUTO_VAR(it,queries.begin()); it != queries.end(); ++it) delete *it; + for(auto& querie : queries) + delete querie; } void Villages::setLevel(Level *level) { this->level = level; - //for (Village village : villages) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) + for(auto& village : villages) { - shared_ptr<Village> village = *it; village->setLevel(level); } } @@ -47,9 +46,8 @@ void Villages::tick() { ++_tick; //for (Village village : villages) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) + for(auto& village : villages) { - shared_ptr<Village> village = *it; village->tick(_tick); } removeVillages(); @@ -64,8 +62,8 @@ void Villages::tick() void Villages::removeVillages() { - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ) - { + for (auto it = villages.begin(); it != villages.end();) + { shared_ptr<Village> village = *it; if (village->canRemove()) { @@ -88,9 +86,8 @@ shared_ptr<Village> Villages::getClosestVillage(int x, int y, int z, int maxDist { shared_ptr<Village> closest = nullptr; float closestDistSqr = Float::MAX_VALUE; - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) + for(auto& village : villages) { - shared_ptr<Village> village = *it; float distSqr = village->getCenter()->distSqr(x, y, z); if (distSqr >= closestDistSqr) continue; @@ -115,14 +112,11 @@ void Villages::processNextQuery() void Villages::cluster() { // note doesn't merge or split existing villages - for(AUTO_VAR(it, unclustered.begin()); it != unclustered.end(); ++it) + for(auto& di : unclustered) { - shared_ptr<DoorInfo> di = *it; - bool found = false; - for(AUTO_VAR(itV, villages.begin()); itV != villages.end(); ++itV) + for(auto& village : villages) { - shared_ptr<Village> village = *itV; int dist = (int) village->getCenter()->distSqr(di->x, di->y, di->z); int radius = MaxDoorDist + village->getRadius(); if (dist > radius * radius) continue; @@ -164,17 +158,15 @@ void Villages::addDoorInfos(Pos *pos) shared_ptr<DoorInfo> Villages::getDoorInfo(int x, int y, int z) { //for (DoorInfo di : unclustered) - for(AUTO_VAR(it,unclustered.begin()); it != unclustered.end(); ++it) + for( const auto& di : unclustered) { - shared_ptr<DoorInfo> di = *it; if (di->x == x && di->z == z && abs(di->y - y) <= 1) return di; } //for (Village v : villages) - for(AUTO_VAR(it,villages.begin()); it != villages.end(); ++it) + for(auto& v : villages) { - shared_ptr<Village> v = *it; shared_ptr<DoorInfo> di = v->getDoorInfo(x, y, z); - if (di != NULL) return di; + if (di != nullptr) return di; } return nullptr; } @@ -205,10 +197,10 @@ void Villages::createDoorInfo(int x, int y, int z) bool Villages::hasQuery(int x, int y, int z) { //for (Pos pos : queries) - for(AUTO_VAR(it, queries.begin()); it != queries.end(); ++it) + for(const Pos* pos : queries) { - Pos *pos = *it; - if (pos->x == x && pos->y == y && pos->z == z) return true; + if (pos->x == x && pos->y == y && pos->z == z) + return true; } return false; } @@ -237,9 +229,8 @@ void Villages::save(CompoundTag *tag) tag->putInt(L"Tick", _tick); ListTag<CompoundTag> *villageTags = new ListTag<CompoundTag>(L"Villages"); //for (Village village : villages) - for(AUTO_VAR(it, villages.begin()); it != villages.end(); ++it) + for(auto& village : villages) { - shared_ptr<Village> village = *it; CompoundTag *villageTag = new CompoundTag(L"Village"); village->addAdditonalSaveData(villageTag); villageTags->add(villageTag); diff --git a/Minecraft.World/WeighedRandom.cpp b/Minecraft.World/WeighedRandom.cpp index 8839b0c5..0c27bf32 100644 --- a/Minecraft.World/WeighedRandom.cpp +++ b/Minecraft.World/WeighedRandom.cpp @@ -4,9 +4,9 @@ int WeighedRandom::getTotalWeight(vector<WeighedRandomItem *> *items) { int totalWeight = 0; - for( AUTO_VAR(it, items->begin()); it != items->end(); it++ ) + for( const auto& item : *items) { - totalWeight += (*it)->randomWeight; + totalWeight += item->randomWeight; } return totalWeight; } @@ -20,12 +20,12 @@ WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, vector<WeighedRa int selection = random->nextInt(totalWeight); - for( AUTO_VAR(it, items->begin()); it != items->end(); it++ ) + for(const auto& item : *items) { - selection -= (*it)->randomWeight; + selection -= item->randomWeight; if (selection < 0) { - return *it; + return item; } } return NULL; diff --git a/Minecraft.World/Witch.cpp b/Minecraft.World/Witch.cpp index c73e9198..c697d467 100644 --- a/Minecraft.World/Witch.cpp +++ b/Minecraft.World/Witch.cpp @@ -101,9 +101,9 @@ void Witch::aiStep() vector<MobEffectInstance *> *effects = Item::potion->getMobEffects(item); if (effects != NULL) { - for(AUTO_VAR(it, effects->begin()); it != effects->end(); ++it) + for(auto& effect : *effects) { - addEffect(new MobEffectInstance(*it)); + addEffect(new MobEffectInstance(effect)); } } delete effects; diff --git a/Minecraft.World/ZonedChunkStorage.cpp b/Minecraft.World/ZonedChunkStorage.cpp index b4ee8585..5c6bf192 100644 --- a/Minecraft.World/ZonedChunkStorage.cpp +++ b/Minecraft.World/ZonedChunkStorage.cpp @@ -11,7 +11,7 @@ // 4J Stu - There are changes to this class for 1.8.2, but since we never use it anyway lets not worry about it const int ZonedChunkStorage::BIT_TERRAIN_POPULATED = 0x0000001; - + const int ZonedChunkStorage::CHUNKS_PER_ZONE_BITS = 5; // = 32 const int ZonedChunkStorage::CHUNKS_PER_ZONE = 1 << ZonedChunkStorage::CHUNKS_PER_ZONE_BITS; // ^2 @@ -54,11 +54,11 @@ ZoneFile *ZonedChunkStorage::getZoneFile(int x, int z, bool create) // 4J - was !zoneFiles.containsKey(key) if (zoneFiles.find(key) == zoneFiles.end()) { - wchar_t xRadix36[64]; - wchar_t zRadix36[64]; - _itow(x,xRadix36,36); - _itow(z,zRadix36,36); - File file = File(dir, wstring( L"zone_") + _toString( xRadix36 ) + L"_" + _toString( zRadix36 ) + L".dat" ); + wchar_t xRadix36[64] {}; + wchar_t zRadix36[64] {}; + _itow_s(x,xRadix36,36); + _itow_s(z,zRadix36,36); + File file = File(dir, wstring( L"zone_") + std::wstring( xRadix36 ) + L"_" + std::wstring( zRadix36 ) + L".dat" ); if ( !file.exists() ) { @@ -67,7 +67,7 @@ ZoneFile *ZonedChunkStorage::getZoneFile(int x, int z, bool create) CloseHandle(ch); } - File entityFile = File(dir, wstring( L"entities_") + _toString( xRadix36 ) + L"_" + _toString( zRadix36 ) + L".dat" ); + File entityFile = File(dir, wstring( L"entities_") + std::wstring( xRadix36 ) + L"_" + std::wstring( zRadix36 ) + L".dat" ); zoneFiles[key] = new ZoneFile(key, file, entityFile); } @@ -147,32 +147,24 @@ void ZonedChunkStorage::tick() tickCount++; if (tickCount % (20 * 10) == 4) { - vector<__int64> toClose; + std::vector<int64_t> toClose; - AUTO_VAR(itEndZF, zoneFiles.end()); - for( unordered_map<__int64, ZoneFile *>::iterator it = zoneFiles.begin(); it != itEndZF; it++ ) + for ( auto& it : zoneFiles ) { - ZoneFile *zoneFile = it->second; - if (tickCount - zoneFile->lastUse > 20 * 60) + ZoneFile *zoneFile = it.second; + if ( zoneFile && tickCount - zoneFile->lastUse > 20 * 60) { toClose.push_back(zoneFile->key); } } - - AUTO_VAR(itEndTC, toClose.end()); - for (AUTO_VAR(it, toClose.begin()); it != itEndTC; it++) + + for ( int64_t key : toClose ) { - __int64 key = *it ; //toClose[i]; - // 4J - removed try/catch -// try { char buf[256]; sprintf(buf,"Closing zone %I64d\n",key); app.DebugPrintf(buf); zoneFiles[key]->close(); zoneFiles.erase(zoneFiles.find(key)); -// } catch (IOException e) { -// e.printStackTrace(); -// } } } } @@ -180,16 +172,12 @@ void ZonedChunkStorage::tick() void ZonedChunkStorage::flush() { - AUTO_VAR(itEnd, zoneFiles.end()); - for( unordered_map<__int64, ZoneFile *>::iterator it = zoneFiles.begin(); it != itEnd; it++ ) + auto itEnd = zoneFiles.end(); + for ( auto& it : zoneFiles ) { - ZoneFile *zoneFile = it->second; - // 4J - removed try/catch -// try { + ZoneFile *zoneFile = it.second; + if ( zoneFile ) zoneFile->close(); -// } catch (IOException e) { -// e.printStackTrace(); -// } } zoneFiles.clear(); } @@ -200,20 +188,18 @@ void ZonedChunkStorage::loadEntities(Level *level, LevelChunk *lc) ZoneFile *zoneFile = getZoneFile(lc->x, lc->z, true); vector<CompoundTag *> *tags = zoneFile->entityFile->readAll(slot); - AUTO_VAR(itEnd, tags->end()); - for (AUTO_VAR(it, tags->begin()); it != itEnd; it++) + for ( CompoundTag *tag : *tags ) { - CompoundTag *tag = *it; //tags->at(i); int type = tag->getInt(L"_TYPE"); if (type == 0) { shared_ptr<Entity> e = EntityIO::loadStatic(tag, level); - if (e != NULL) lc->addEntity(e); + if (e != nullptr) lc->addEntity(e); } else if (type == 1) { shared_ptr<TileEntity> te = TileEntity::loadStatic(tag); - if (te != NULL) lc->addTileEntity(te); + if (te != nullptr) lc->addTileEntity(te); } } } @@ -234,10 +220,8 @@ void ZonedChunkStorage::saveEntities(Level *level, LevelChunk *lc) { vector<shared_ptr<Entity> > *entities = lc->entityBlocks[i]; - AUTO_VAR(itEndTags, entities->end()); - for (AUTO_VAR(it, entities->begin()); it != itEndTags; it++) + for ( auto& e : *entities ) { - shared_ptr<Entity> e = *it; //entities->at(j); CompoundTag *cp = new CompoundTag(); cp->putInt(L"_TYPE", 0); e->save(cp); diff --git a/Minecraft.World/compile_flags.txt b/Minecraft.World/compile_flags.txt new file mode 100644 index 00000000..57863c77 --- /dev/null +++ b/Minecraft.World/compile_flags.txt @@ -0,0 +1,18 @@ +-xc++ +-m64 +-std=c++14 +-Wno-unused-includes +-Wno-unsafe-buffer-usage-in-libc-call +-Wno-unsafe-buffer-usage +-Wno-unused-macros +-Wno-c++98-compat +-Wno-c++98-compat-pedantic +-Wno-pre-c++14-compat +-D_LARGE_WORLDS +-D_DEBUG_MENUS_ENABLED +-D_LIB +-D_CRT_NON_CONFORMING_SWPRINTFS +-D_CRT_SECURE_NO_WARNINGS +-D_WINDOWS64 +-I +./x64headers
\ No newline at end of file diff --git a/Minecraft.World/stdafx.h b/Minecraft.World/stdafx.h index 48e52544..37c3960c 100644 --- a/Minecraft.World/stdafx.h +++ b/Minecraft.World/stdafx.h @@ -6,7 +6,6 @@ #ifdef __PS3__ #else -#define AUTO_VAR(_var, _val) auto _var = _val #endif #if ( defined _XBOX || defined _WINDOWS64 || defined _DURANGO ) |
